2017년 6월 29일 목요일

[C#] Task.WhenAll , WhenAny

Task.WhenAll(task1 , task2 )를 풀어서 쓰면 다음과 같다.

var exceptions = new List();
try{ task1.Wait() ;} catch ( AggregateException ex) { exceptions.Add(ex) ;}
try{ task2.Wait() ;} catch ( AggregateException ex) { exceptions.Add(ex) ;}
if(exceptions.Count > 0 ) throw new AggregateException (exceptions )

 따라서  WhenAll에 task1,task2를 넣기 전에 task1,task2는 미리 실행이 되어 있어야 한다.

[c#] Continuewith 추가 설명

Task task1 = Task.Run(() => Console.Write("task1"));
Task task2 = task1.ContinueWith(() => Console.Write("task1"));

1. task2 는 task1이 완료,실패,취소 되자마나 실행됨.

2. 2번째 라인에 진입하기전에 이미  task1이 완료된 상태라면 task2는 바로 실행된다.

2017년 6월 28일 수요일

[c#] Task Cancel token

public class CancelationTokenTest
    {
        public void testmethod2_multicancel()
        {
            var cancelsrc = new CancellationTokenSource();

            Task k1 = Task.Run( async ()=>
            {
                while(true)
                {
                    await Task.Delay(1200);
                    Console.WriteLine("k1 Done");
                    cancelsrc.Token.ThrowIfCancellationRequested(); // 여시서 토큰 상태 확인
                }
            }, cancelsrc.Token );

            Task k2 = Task.Run( async ()=>
            {
                while(true)
                {
                    await Task.Delay(1100);
                    Console.WriteLine("k2 Done");
                    cancelsrc.Token.ThrowIfCancellationRequested();
                }
            }, cancelsrc.Token );

            //await Task.Delay( 5000 );
            Thread.Sleep( 5000 );
            Console.WriteLine("cancel is started");
            cancelsrc.Cancel(); // 여기서 토큰 상태 취소로 바꿈.
            Console.WriteLine("Cancel done");
            Thread.Sleep( 5000 );
        }

        public void testmethod()
        {
            var cancelSource = new  CancellationTokenSource();
            Task foo = Foo(cancelSource.Token);
            Thread.Sleep( 3000 );
            Console.WriteLine( "cancel" );
            cancelSource.Cancel();
            Thread.Sleep( 3000 );
        }

        async Task Foo( CancellationToken cancellationToken )
        {
            int counter = 0;
            try
            {
                for ( int i = 0 ; i < 10 ; i++ )
                {
                    Console.WriteLine( i );
                    await Task.Delay( 500 );
                    cancellationToken.ThrowIfCancellationRequested();
                }
            }
            catch ( Exception ex )
            {
                Console.WriteLine( "Exception" );
                Console.WriteLine( counter );
                counter++;
            }
        }
    }

[C#] Task Tip

1. Task testtask = Task.Run( () => 3); 시 

int result =  testtask .Result;  는 테스크가 끝나서 결과를 반환할 때까지 대기를 탄다.

2. 테스크 끝난후 다른 테스크 실행하기 .

방법은 두가지

2-1 . GetAwaiter사용

 Task task = Task.Run( () => 3);

var awaiter = testtask.GetAwaiter(); // 이 awaiter는 테스크가 끝난건지 알수 있는 상태자체이다.

awaiteer.OnCompleted(  () =>
{
 Console.Writeline("Second Done")
 int result = awaiter.GetResult(); // testask의 결과값은 awaiter.GetResult() 이다.
Console.Writeline(result ) ;
});

** 선행 작업에서 예외 발생시 awaiter.GetResult()에서 그 예외가 그대로 발생.
** 비제네릭시 awaiter.GetResult()는 void반환. 오직 예외만 전달받는다는 기능이 있는거임.

** 선행 테스크와 같은 쓰레드에서 실행을 시키고 싶을때는

var awaiter = testask.ConfigureAwait(False).GetAwaiter();
이렇게 쓰면 된다. 이러면 단순히 선행 테스크와 코드가 합쳐지는 거라고 보면 된다.


2-2 ContinueWith

testtask.ContinueWith( firsttask =>
{
   int result = firsttask.Result;
  Console.Writeline(result ) ;
})

**여기서는 익셉션이 전파가 안된다. 따로 작성을 해줘야 한다. (선행 테스크에서 예외 발생시 그걸 따로 처리해서 전달을 하던지 해야 한다. )

** 같은 쓰레드에서 실행시키려고 하면 TaskCOntinueousOption 으로 ExecuteSynchronously를 지정해 줘야 한다.
Task t2= testtask.ContinueWith( firsttask =>
{
       int result = firsttask.Result;
       Console.Writeline(result ) ;
}
 , TaskContinuationOptions.ExecuteSynchronously);

3. Delay

Task.Delay(400).GetAwaiter().OnComplete( () => Console.Writeline(""));

Task.Delay(400).ContinueWith( ftask => Console.Writeline(""));

4. await async - TaskCompletionSource 로 작업의 연결, 완료 등을 관리해야 하면 힘들어서 이것들이 등장했다.

 var result = await 표현식;
문장들

은 원래는 다음과 같다.

var awaiter = 표현식.GetAwaiter();
awaiter.ConCompleted(()=>
{
  var result = awaiter.GetResult();
문장들
})

2017년 6월 27일 화요일

[C#] Collection Speed

Speed

Array  가장 빠름 

list queue stack 추가는 O(1) . list는 검색은 O(n) =>  Capacity로 용량을 미리 지정시 오버헤드 피할 수 있다.  queue stack 검색은 O(1)

linkedlist 추가는 O(1) , 검색은O(1)



http://flystone.tistory.com/154

http://game-secret.tistory.com/entry/C-%EA%B8%B0%EB%B3%B8%EA%B8%B0-II-%EC%9E%90%EB%A3%8C-%EA%B5%AC%EC%A1%B0%EC%9D%98-%EA%B8%B0%EB%B3%B8

[C#] WPFUserControl

1. UserControl  생성 : 반드시 네임을 지정한다. 아래는 네임 스페이스가 Menu이다.
             Name="user1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Menu"
             mc:Ignorable="d"
             Width="Auto" Height="Auto" d:DesignWidth="307.031" d:DesignHeight="395.312"
             >
   
       
           
           
       


       
           
           
       
       
           
       
       
   



2. 메인 폼에서 
xmlns:local="clr-namespace:Menu"


3.만약 네임스페이스가 다를경우 : Menu.UC 이다

             Name="Ucin1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Menu.UC"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
   
       
           
           
       

       
       


   

4. 메인폼에서 다음을 추가한다. : local2 
xmlns:local2="clr-namespace:Menu.UC"



[C#] Wpf Style 사용법

1.  styleDictionary.xmal 만듬.

--




--


2. App.xaml 에서 다음을 추가.
--

           
               
           

       
   

--

3. Form에서는 다음과 같이 사용
--




--






2017년 6월 26일 월요일

[WPF] Grid Line

http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&pageno=0&wid=739&rssMode=1&wtype=0

[c#] wpf startup wpf window

https://stackoverflow.com/questions/18138934/startup-code-in-a-windows-presentation-form-application


[C#] event Propagate

//In winform
// event is propagated c3 => c2 => c1 => winform

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EventPropagate
{
    public partial class Form1 : Form
   
{

        c1 cc1 = new c1();
        public Form1()
        {
            InitializeComponent();
            cc1.evtcc1 += new ff( test );
        }

        private void button1_Click( object sender , EventArgs e )
        {
            cc1.fire();
        }

        void test( int input )
        {
            label1.Text = input.ToString();
        }

    }


    public class c1
    {
        c2 cc2 = new c2();

        public void fire() { cc2.fire(); }

        public event ff evtcc1
        {
            add
            {
                Debug.WriteLine("c1");
                cc2.evtcc2 += value;
            }
            remove { }

        }

    }

    public class c2
    {
        c3 cc3 = new c3();
        public void fire() { cc3.fire(); }

        public event ff evtcc2
        {
            add
            {
                Debug.WriteLine("c2");
                cc3.evt += value;
            }
            remove { }

        }

    }

    public delegate void ff( int input );
    public class c3
    {
        public event ff evt ;

        public void fire()
        {
            Debug.WriteLine( "c3" );
            evt( 10000 );
        }
    }

}

2017년 6월 22일 목요일

[C#] casting

1. (int)3.4 =: InvalidCastException.
2.  as : null faster


[C#] Attribute

1. GetMethod()

-> 반환되는 메소드는 알파벳 순서로 나열이 된다.
-> bindingFlag 로 필터링해 메소드를 얻을 수 있다.

가져오는것은 다음과 같다.

https://msdn.microsoft.com/ko-kr/library/system.reflection.methodinfo(v=vs.110).aspx

2017년 6월 21일 수요일

2017년 6월 19일 월요일

[C#] Create Method Flow and Run Flow

        static void Main( string [ ] args )
        {
            Func temp = new Func(x =>
            {
                Console.WriteLine("temp done // input is : " +  x.ToString());
                return "g0";

            } );
            Func temp1 = new Func(x =>  {
                Console.WriteLine("temp1 done");
                return "g1";

            } );
            Func temp2 = new Func(x =>  {
                Console.WriteLine("temp2 done");
                return 4.5;

            } );
            List any = new List();
            any.Add( temp );
            any.Add( temp1 );
            any.Add( temp2 );

            Console.WriteLine( "anycount = " + any.Count.ToString() );
            var result = runme( 0, any , 10 );
            Console.WriteLine( result );
            Console.ReadLine();
        }


        static object runme( int idx , List list , object input  )
        {
            Console.WriteLine( idx );
            if ( idx == list.Count )
            {
                return input;
            }
            var output =  list [ idx ].DynamicInvoke( input );
            return runme( idx + 1 , list , output );
        }

2017년 6월 15일 목요일

[ Python] Tensorflow on windows10 and vision lib setting

Install Anadonda Installer 4.2.1

Install Tensorflow

Install keras (option)

Install opencv3

-- conda install -c https://conda.binstar.org/menpo opencv3





[TF] tensor to ndarray

https://stackoverflow.com/questions/34097281/how-can-i-convert-a-tensor-into-a-numpy-array-in-tensorflow


predict =   tf.argmax(model, 1)
result =    sess.run(predict , feed_dict = {
    X: x_data,
    Y: y_data,
    keep_prob: 1
    })

print(type(result)) << ndarray
print( 'Predict' , result)

2017년 6월 14일 수요일

[keras] image generater

from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import cv2
import numpy as np


datagen = ImageDataGenerator(
        rotation_range=180,
        width_shift_range=0.5,
        height_shift_range=0.5,
        shear_range=0.3,
        zoom_range=0.6,
        horizontal_flip=True,
        vertical_flip = True,
        fill_mode = "wrap")


img = cv2.imread(r"C:\image data\test\defect 001.jpg", 0)

#tensorflow backend
x = img_to_array(img)  # this is a Numpy array with shape (150, 150 , 1)

x = x.reshape( (1,) + x.shape )  # this is a Numpy array with shape (1, 150, 150 , 1~3(ch) )
i = 0
for batch in datagen.flow_from_directory( directory= r"C:\image data\defect"
                                         , target_size = (64,64)
                                         , color_mode = "grayscale"
                                         , batch_size=1
                                         , shuffle = True
                                         , save_to_dir=r'C:\image data\test\result'
                                         , save_prefix='defect'
                                         ):
    i += 1
    if i > 50000:
        break






new keras install

I uninstalled Keras using 

pip uninstall keras

Then I executed the following commands.
1. C:\Users\tjhau>conda create -n keras_tensorflow python=3.5.2 anaconda=4.3
2. C:\Users\tjhau>activate keras_tensorflow
3. C:\Users\tjhau>conda install -c conda-forge tensorflow keras

I understand that keras will be available in a directory after I execute the command 
 C:\Users\tjhau>activate keras_tensorflow
Thanks for your help.

[python] keras image dim converting


keras image dim convert

tensorflow image <-> theano image

https://github.com/fchollet/keras/issues/3994