2016年7月31日日曜日

Google検索でグラフが表示できる

Google検索で関数を入力すると、グラフを表示してくれる。 log(x),y=x,y=x^2と入力した場合の結果です。

2016年7月28日木曜日

c#文字列比較

c#では、Equalsではなく、==を使って文字列比較したほうが良さそうだね。
タイプセーフ、nullで比較した時に落ちない。Stringクラスの中で、==で比較できるように、Equalsを再定義してるようだ。
http://sinproject.blog47.fc2.com/blog-entry-38.html


C# == str1 == str2
VB.NE = str1 = str2
Java .equals str1.equals(str2)
VB6/VBA = str1 = str2
↑Option Compare {Binary|Text|Database}のモードによる
Binary  

バイナリ文字コード順によって並べ替え順序が決まります。
Option Compare ステートメントの記述がない場合はこの Binary モードが使用されます
Text  

50音順による並べ替え順になります。
ただし、大文字と小文字、文字幅、カタカナとひらがなは区別しません。

2016年7月21日木曜日

jQueryでKey Valueのテーブルから、KeyでValueを検索

1.Tableの要素を取得
2.find("td.class")でKeyが入ってるtdを取得
3.eachでごりごり回しながら、Keyとマッチ
4.マッチしたら、next()で隣の要素を取得
5. return false;でeachから抜ける

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>HTML5サンプル</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="   crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
//alert("hello");

 //検索ボタンクリック
 $(document).on("click", "[id='seach']", function() {
  $('#testTable').each(function () {
   $(this).find('td.code').each(function () {
    $(this).next().attr('style', '');
   });
   $(this).find('td.code').each(function () {
    if($(this).text() == $('#search_word').val()) {
    //alert($(this).next().text());
      $(this).next().attr('style', 'background-color:yellow');
      return false;
    } else {
     $(this).next().attr('style', '');
    }
   });
  });
 });


/*
 // grep
 $(document).on("click", "[id='seach']", function() {
  $('#testTable').each(function () {
   $(this).find('td').each(function () {
    if($(this).text().match(new RegExp($('#search_word').val(),"g"))) {
     $(this).attr('style', 'background-color:yellow');
    } else {
     $(this).attr('style', '');
    }
   });
  });
 });
*/
});
</script>
</head>
<body>
<br />
テキストボックスに検索したい文字を入力&#12289;検索ボタンをクリックすると&#12289;
<br />
入力した文字列が含まれるセルの背景色が黄色に変わります&#12290;<br />
<br />
<input type="text" id="search_word"">
<button type="button" id="seach"> Search </button>
<table id="testTable" border ="1">
<tr>
<th>Key</th><th>Value</th>
</tr>
<script type="text/javascript">
for (i=0; i<=10;i++){
    document.write("<tr>");
    document.write("<td class=\"code\">" + i + "</td>");
    document.write("<td>" + Math.floor(Math.random() *1000) + "</td>");
    document.write("</tr>");
}
</script>
</table>
</body>
</html>

LINQ Where句動的 AsQueryable()を使う。と可読性が増す

int? categoryID = null;
string categoryName = string.Empty;
string description = string.Empty;

// nullチェックとORでくっつけてやる
from c in ctx.Categories
where (categoryID == null || c.CategoryID == categoryID)
&& (string.IsNullOrEmpty(categoryName) || c.CategoryName == categoryName)
&& (string.IsNullOrEmpty(description) || c.Description == description)
select c;
↓でWhere句を動的に書ける。
var q = ctx.Categories.AsQueryable();
if (categoryID != null)
{
    q = q.Where(c => c.CategoryID == categoryID);
}
if (!string.IsNullOrEmpty(categoryName))
{
    q = q.Where(c => c.CategoryName == categoryName);
}

2016年7月20日水曜日

LINQ 条件文でフィルタをかける

// To run this sample, first specify an integer value of 1 to 4 for the command
// line. This number will be converted to a GradeLevel value that specifies which
// set of students to query. 
// Call the method: QueryByYear(args[0]);

static void QueryByYear(string level)
{
    GradeLevel year = (GradeLevel)Convert.ToInt32(level);
    IEnumerable<Student> studentQuery = null;
    switch (year)
    {
        case GradeLevel.FirstYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.FirstYear
                           select student;
            break;
        case GradeLevel.SecondYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.SecondYear
                           select student;
            break;
        case GradeLevel.ThirdYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.ThirdYear
                           select student;
            break;
        case GradeLevel.FourthYear:
            studentQuery = from student in students
                           where student.Year == GradeLevel.FourthYear
                           select student;
            break;

        default:
            break;
    }
    Console.WriteLine("The following students are at level {0}", year.ToString());
    foreach (Student name in studentQuery)
    {
        Console.WriteLine("{0}: {1}", name.LastName, name.ID);
    }
}

LINQ Contains

class DynamicPredicates : StudentClass
{
    static void Main(string[] args)
    {
        string[] ids = { "111", "114", "112" };

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    static void QueryByID(string[] ids)
    {
        var queryNames =
            from student in students
            let i = student.ID.ToString()
            where ids.Contains(i)
            select new { student.LastName, student.ID };

        foreach (var name in queryNames)
        {
            Console.WriteLine("{0}: {1}", name.LastName, name.ID);
        }
    }
}

2016年7月10日日曜日

LINQ TO SQL でのINSERT

//自動採番の場合は、以下のプロパティ設定
//Auto Generated Value:True
//Auto-Sync:OnInsert
 var devDb2 = new DevDataClassesDataContext(devCon);
 User UserObj = new User();
      

// UserObj.UserID = 1;//自動採番するように設定されてるのでいらない
  UserObj.FirstName = "Hiroshi";
  UserObj.LastName = "Igarashi";
  UserObj.NickName = "IgaChan";

   devDb2.Users.InsertOnSubmit(UserObj);
   devDb2.SubmitChanges();

Auto Increment (SQL Server)

IDENTITY [ (seed , increment) ]

seed
テーブルに読み込まれる最初の行に使用される値です。
increment
既に読み込まれている前の行の ID 値に加算される増分の値です。
seed と increment の両方を指定するか、またはどちらも指定しないでください。
どちらも指定しないときの既定値は (1,1) です。


CREATE TABLE [dbo].[Users](
    [UserID] [int] IDENTITY(1,1) NOT NULL ,
    [FirstName] [nvarchar](50) NULL,
    [LastName] [nvarchar](50) NULL,
    [NickName] [nvarchar](50) NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
    [UserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
)

2016年7月7日木曜日

Threading

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Thread1
{

    class TestThread
    {
        // THREAD_NUM個のスレッドを立てる。
        // それぞれのスレッドの中でnumをROOP_NUM回インクリメントする。
        static void Main()
        {
            const int ThreadNum = 20;
            const int LoopNum = 20;

            int num = 0;//複数のスレッドから同時にアクセスされる

            var syncObject = new object();

            Parallel.For(0, ThreadNum, i =>
            {
                for (int j = 0; j < LoopNum; j++)
                {
                    //Monitorクラスを簡略化
                    lock (syncObject)
                    {
                        //クリティカルセクション
                        int tmp = num;
                        Thread.Sleep(1);
                        num = tmp + 1;

                    }



                    /*
                                        Monitor.Enter(syncObject);//MonitorクラスのEnterでロックを取得
                                        try
                                        {
                                            //クリティカルセクション
                                            int tmp = num;
                                            Thread.Sleep(1);
                                            num = tmp + 1;
                                        }
                                        finally
                                        {
                                            //ロック解放
                                            Monitor.Exit(syncObject);
                                        }
                                        */

                }
            });

            Console.Write("{0} (期待値{1})\n", num, ThreadNum * LoopNum);
            Console.ReadLine();
        }
    }

    //class TaskSample
    //{
    //    static void Main(string[] args)
    //    {
    //        const int N = 3;
    //        //並列処理が行われる
    //        //idの箇所は、デリゲート。名前はなんでもよい。
    //        Parallel.For(0, N, id =>
    //        {
    //            Random rnd = new Random();
    //            for (int i = 0; i < 10; ++i)
    //            {
    //                // ランダムな間隔で処理を一時中断
    //                Thread.Sleep(rnd.Next(50, 100));
    //                Console.Write("{0} (ID: {1})\n", i, id);
    //            }
    //        });
    //        // 並行して動かしている処理がすべて終わるまで、自動的に待つ
    //    }
    //}
}

オブジェクトを生成し、戻り値を返す

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReturnObject
{
    class Customer
    {
        public int ID;
        public string Name;

    }
    //構造体も返せるが、値コピーになるので、数が多いとコピーが多くなり、パフォーマンスでない
    //struct Customer
    //{
    //    public int ID;
    //    public string Name;

    //}


    class Program
    {

        private static Customer getData() {

            return new Customer()
            {
                ID = 1,
                Name = "Hiroshi"

            };
        }

        static void Main(string[] args)
        {
            var dt = getData();
            Console.WriteLine("Name={0}, ID={1}", dt.Name,dt.Name);
        }
    }
}

デリゲートいろいろ

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace definedLamda2
{
    class Program
    {
        static void Main(string[] args)
        {
            Action<string> act = (x) => { Console.WriteLine(x); };
            act("Hello!");
            act("wowowow");

            int i = 100;double d = 3.14159;

            //Func<Σパラメータの型, 戻り値の型> 名前 =(Σパラメータ)=>{return 戻り値 }
            //Func<int, double, double> func = (x, y) =>
            //{
            //    return x * y;
            //};

            //{return ;}は省略できる
            Func<int, double, double> func = (x, y) => ( x * y );

            double ret = func(i, d);
            Console.WriteLine(ret);


            Console.ReadLine();
        }
    }
}

デリゲート書き方いろいろ

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DefinedDelegate
{
    class Program
    {

        ////その1
        //private static void Disp() {
        //    Console.WriteLine("Disp()");

        //}

        ////定義済みdelegate
        //private static void a(Action call) {
        //    call();
        //}

        //static void Main(string[] args)
        //{

        //    a(Disp);
        //    Console.ReadLine();
        //}


        ////その2
        //private static void Disp()
        //{
        //    Console.WriteLine("Disp()");

        //}
        //static void Main(string[] args) {
        //    Action act = Disp;
        //    act();
        //    Console.ReadLine();

        //}


            //その3
        static void Main(string[] args) {
            //デリゲートactに代入
            Action act = () => { Console.WriteLine("Hello lamda Expression"); };
            //act実行
            act();

        }
    }
}

LINQ 結合

MSDNサンプル

LEFT OUTER JOIN(左外部結合)

LINQのほぼ全部を使ってみた

LINQ TO SQL SQLデバック

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;


namespace LINS_Samples
{
#if DEBUG
    class OutputWriter : System.IO.TextWriter
    {
        public override System.Text.Encoding Encoding
        {
            get { return null; }
        }

        public override void WriteLine(string value)
        {
            // [出力]ウィンドウに表示
            System.Diagnostics.Debug.WriteLine(value);
        }
    }
#endif


    class Program
    {
        static void Main(string[] args)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            Console.WriteLine("{0}", connectionString);
            Console.ReadLine();


            using (var db = new DataClasses1DataContext())
            {
               
                db.Log = Console.Out;//Oupput windowに表示する設定
                var q = from orders in db.Orders
                        select new { orders.OrderDate,orders.ShipName  };

                var q2 = from orDetail in db.Order_Details
                        select new { orDetail.ProductID,orDetail.Quantity };

                //Debug!
                System.Diagnostics.Debug.WriteLine(q);
                System.Diagnostics.Debug.WriteLine(q2);


                Console.WriteLine(q);
                Console.WriteLine(q2);

            }

            //http://blogs.bitlan.net/ito/?p=1474

        }
    }
}

LINQ サンプル いろいろ

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;


namespace LINQ_Query
{
    class Fruit {
        public string code;
        public string name;
        public int price;

    }
    class Program
    {

        static string[] getString(string[] str) {
            return (from s in str where s.StartsWith("A") select s).ToArray();

        }

        static void Main(string[] args)
        {
            int[] numbers = { 1, 2, 3, 4, 5 };
            //クエリ式バージョン
            var query = from x in numbers
                        where x>= 2 && x <= 5
                        select x;
            foreach (var o in query) {
                Debug.WriteLine(o);

            }
          
            //ラムダ式バージョン
            var lamdaQuery = numbers.Where((x) => x >= 3 && x <= 4);
            foreach (var o in lamdaQuery)
            {
                Debug.WriteLine(o);//B

            }
            Debug.WriteLine("test");
            Console.ReadLine();


            string str = "ABC";
            var qSkip = str.Skip(1);
            foreach (var o in qSkip)
            {
                Debug.WriteLine(o);//BC
            }

            var qSkipTake = str.Skip(1).Take(1);
            foreach (var o in qSkipTake)
            {
                Debug.WriteLine(o);//BC
            }




            Debug.WriteLine("test");
            //Console.ReadLine();
              
         

            string[] fruit = { "Orange", "Apple", "Grape"};
            string[] result = getString(fruit);
            foreach (var name in result) Debug.WriteLine(name);


            int[] num = { 50, 200, 15, 43, 41, 333, };
            int qCount = num.Select(x=>x).Count();
            Debug.WriteLine(qCount);//6

            int qSum = num.Select(x => x).Sum();
            Debug.WriteLine(qSum);//682


            var r = from n in num
                    where n >= 100
                    orderby n
                    select n ;
            foreach (var n in r) Debug.WriteLine(n);
            Debug.WriteLine("test");
         

            var r2 = num.Where((n) => n >= 10).OrderBy((n) => n);
            foreach (var n in r2) Debug.WriteLine(n);


            Debug.WriteLine("test");
          
            var r3 = from n in num
                     select n * 100 / 30;
            foreach (var n in r3) Debug.WriteLine(n);

            Debug.WriteLine("test");
         

            var r4 = num.Select(n => n * 100 / 20);
            foreach (var n in r4) Debug.WriteLine(n);



            Debug.WriteLine("test");
     

            Fruit[] f = {
                new Fruit() { code="A100" , name ="Apple1", price=100},
                new Fruit() { code="A200" , name ="Apple2", price=200},
                new Fruit() { code="A300" , name ="Apple3", price=300},
                new Fruit() { code="A400" , name ="Apple4", price=400},

            };

            var q = from x in f
                    select x;
            foreach (var a in q) {
                Debug.WriteLine(a);
                Debug.WriteLine("code={0},name={1},price={2}", a.code, a.name, a.price);
                   
            };

//匿名オブジェクト
            var lamda_q = f.Select((n) => new { N=n.name,P=n.price});
            foreach (var a in lamda_q)
            {
                Console.WriteLine(a);
                Console.WriteLine("name={0},price={1}", a.N, a.P);

            };
            Debug.WriteLine("test");
            Console.ReadLine();

//匿名オブジェクト
            var q2 = from n in f
                     select new { N = n.name, P =n.price};

            foreach (var a in q2)
            {
                Debug.WriteLine(a);
                Debug.WriteLine("name={0},price={1}",  a.N, a.P);

            };


            Debug.WriteLine("test");
            //Console.ReadLine();

        }
    }
}
退避でわかりやすい
クエリ式とラムダ式サンプル多し