레이블이 프로그래밍인 게시물을 표시합니다. 모든 게시물 표시
레이블이 프로그래밍인 게시물을 표시합니다. 모든 게시물 표시

2016년 10월 9일 일요일

Catch Game with Scratch language

Analysis for the Catch Game with Scratch language
    See game: Link
    1. Apple, Bowl(Sprite1)
    2. Apple does 2 works, Bowl does 1 work.
    3. Apple does
        3.1 Moving from the Up to Down 
        3.2 If apple is touched by bowl, move to Top again and add Score 1
    4. Bowl does
        4.1 Moving to left and right


Game Screen and Codes

2016년 8월 27일 토요일

python variable, attribute(instance attribute, class attribute)

-- 정리 계기 --

python을 사용할 때 변수(variable) 이라는 말과 속성(attribute)이라는 말이 혼란스럽기도 했고, attribute를 알아보니 class, instance attribute 가 따로 있어 정리했습니다.
지금은 간단히 class 안에 있는 것은 attribute 이고 class 로 만든 새로운 instance는 variable 이라고 이해하고 있습니다.


-- 내용 --

variable:  우리가 일반적으로 이야기하는 변수, class 로 새로운 instance 를 생성하면 그것이 변수
attribute: class 내에서 만들어진 변수


attribute 세부
    1. instance attribute
    2. class attribute

Beyond performance considerations, there is a significant semantic difference. In the class attribute case, there is just one object referred to. In the instance-attribute-set-at-instantiation, there can be multiple objects referred to.
성능에 대한 이야기를 떠나서, 확실하게 다른점이 있다. class attribute는 1개의 object 밖에 없다. 초기화를 통해 만들어진 instance attribute눈 여러개의 object 가 만들어진다.

For instance
예를 들면 아래와 같다.

1. class attribute 
class A:
    foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
[5]

-> class level 에서 작성, self.xxx 로 사용하지 않음


2. instance attribute
class C:
    def __init__(self):
        self.foo = []
c, d = C(), C()
c.foo.append(5)
d.foo
[]

-> instance level 에서 접근, self.xxx 로 사용

The difference is that the attribute on the class is shared by all instances. The attribute on an instance is unique to that instance.
class 의 attribute는 모든 instance 들이 공유하고, instance 의 attribute 는 각 attribute 마다 고유하다.



참조: Link







2016년 8월 26일 금요일

python 에서 밑줄 ('_', underline) 사용된 파일, 함수, 변수 List 및 그 의미

1. 파일
    폴더 아래의 __init__.py
        해당 폴더가 파이썬 package 라고 인식할 수 있게 한다.
        그 폴더가 package 이기 때문에 그 안에 있는 python 파일들을 import 할 수 있다.

2. 메서드(method, 클래스 내부 함수, 가장 아래 예시 코드)
    1) '_' 이 앞에 붙으면 외부 사용자는 사용하지 말라는 권유의 문법이고,
 a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself.

    2) '__' 이 앞에 붙으면 private 가 되어 외부에서 사용할 수 없고, 다른 클래스 에서 사용하거나 override 할 수 없다.
 it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

    3) __이름__ : __init__ 함수의 경우는 class 생성 시 자동으로 실행되는 생성자이다.
                  init 외의 __이름__ 는 그냥 함수이며 클래스 외부에서 call 할 수 있다.

3. 속성(Attribute, 클래스 내의 변수)
    위 2.메서드와 동일한 특성을 가진다.
    특별히 class 에서 default로 만들어진 attribute 이 있으며 각 사용법에 맞게 사용된다.
    __name__ : 해당 파일이 실행된 것이면 "__main__" 이 셋팅된다.
    __file__: 해당 파일의 이름
    그 외에도 종류가 있을 것이므로 확인 시 추가 예정


참조 : Link



2-예시 코드

1) 클래스 선언
class TestClass:
    def __init__(self):
        self.a = "a"
    def __dUnderscoreBothSide__(self):
        self.udb = "udb"
    def __dUnderscoreOneSide(self):
        self.udo = "udo"

2) 클래스 인스턴스 생성
t = TestClass()
 
3) attribute a 출력
t.a
'a'
 
4) attribute udb 출력  에러 확인
t.udb
AttributeError                            Traceback (most recent call last)
<ipython-input-4-12af1792c567> in <module>()
----> 1 t.udb
 
AttributeError: 'TestClass' object has no attribute 'udb'

5) attribute udo 출력  에러 확인
t.udo
AttributeError                            Traceback (most recent call last)
<ipython-input-5-89e092a247e5> in <module>()
----> 1 t.udo
 
AttributeError: 'TestClass' object has no attribute 'udo'
 
6) __dUnderscoreBothSide__ method함수 실행 확인 
t.__dUnderscoreBothSide__()
 
7) udb attribute 출력 확인
t.udb
'udb'
 
8) 클래스 외부에서__dUnderscoreOneSide 실행 시 에러 확인
t.__dUnderscoreOneSide()
AttributeError                            Traceback (most recent call last)
<ipython-input-8-58ea9d19081f> in <module>()
----> 1 t.__dUnderscoreOneSide()
 

AttributeError: 'TestClass' object has no attribute '__dUnderscoreOneSide'









2016년 7월 14일 목요일

Pandas 다루기 - Dataframe 값 접근/필터

Python에서 데이터 분석을 할 때 가장 편리한 것이 Pandas 라이브러리이고 가장 많이 사용하는 것이 Dataframe(2차원) 객체라고 이야기 하면서,
정작 필요할 때는 인터넷 검색으로 처음부터 다시 시작하고 있다는 것을 느끼고,
필수 적인것을 쓸 때마다 정리

1. Dataframe은 무엇인가: 2차원 배열로 row값(index), column값(header)를 가질 수 있는 자료구조, Pandas 라이브러리에 있다.

2. 어떻게 사용하는가 (  )
     'import pandas as pd' 라고 선언한 후에 사용한다.
     아래와 같이 df 를 만든다.

In [1]:
import pandas as pd
import numpy as np
In [2]:
dates = pd.date_range('7/14/2016', periods=8)
dates
Out[2]:
DatetimeIndex(['2016-07-14', '2016-07-15', '2016-07-16', '2016-07-17',
               '2016-07-18', '2016-07-19', '2016-07-20', '2016-07-21'],
              dtype='datetime64[ns]', freq='D')
In [3]:
df = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
df
Out[3]:
ABCD
2016-07-14-0.184950-0.8063921.494103-0.369560
2016-07-150.399724-0.063784-0.056321-0.007364
2016-07-16-0.626461-0.423751-0.0187030.087733
2016-07-171.198658-1.532482-0.2980020.634820
2016-07-180.312076-0.673361-0.141319-1.169763
2016-07-19-0.119623-0.293787-0.592312-1.167606
2016-07-20-0.1581412.5596730.949287-1.461863
2016-07-211.0424770.9689770.0507091.789358

     컬럼 A 에 접근하는 방법은 여러가지가 있다.
In [4]:
df['A']
Out[4]:
2016-07-14   -0.184950
2016-07-15    0.399724
2016-07-16   -0.626461
2016-07-17    1.198658
2016-07-18    0.312076
2016-07-19   -0.119623
2016-07-20   -0.158141
2016-07-21    1.042477
Freq: D, Name: A, dtype: float64
In [5]:
df.A
Out[5]:
2016-07-14   -0.184950
2016-07-15    0.399724
2016-07-16   -0.626461
2016-07-17    1.198658
2016-07-18    0.312076
2016-07-19   -0.119623
2016-07-20   -0.158141
2016-07-21    1.042477
Freq: D, Name: A, dtype: float64
In [6]:
df.ix[:, 0]
Out[6]:
2016-07-14   -0.184950
2016-07-15    0.399724
2016-07-16   -0.626461
2016-07-17    1.198658
2016-07-18    0.312076
2016-07-19   -0.119623
2016-07-20   -0.158141
2016-07-21    1.042477
Freq: D, Name: A, dtype: float64

     컬럼의 값으로 필터를 하려면 df 에 boolean(true, false) array를 주면 true만 볼 수 있다.
       아래 코드는 A 컬럼의 값이 0 보다 작을 경우만을 필터하여 보여준다.
In [7]:
df['A'] < 0
Out[7]:
2016-07-14     True
2016-07-15    False
2016-07-16     True
2016-07-17    False
2016-07-18    False
2016-07-19     True
2016-07-20     True
2016-07-21    False
Freq: D, Name: A, dtype: bool
In [8]:
df [ df['A'] < 0 ]
Out[8]:
ABCD
2016-07-14-0.184950-0.8063921.494103-0.369560
2016-07-16-0.626461-0.423751-0.0187030.087733
2016-07-19-0.119623-0.293787-0.592312-1.167606
2016-07-20-0.1581412.5596730.949287-1.461863





wxPython으로 여러개 파일 경로 가져오기(extract file paths with wxPython)

파일 여러개 가져오는 코드

The wx.App object must be created first!

배경: Anaconda 의 Spider IDE 에서 wxPython 코드 연습

연습 코드:
import wx

class Frame(wx.Frame):
    def __init__(self, title):
        wx.Frame.__init__(self, None, title=title, size=(350,200))

app = wx.App(redirect=True)
top = Frame("Hello World")
top.Show()
app.MainLoop()

에러 메시지: "The wx.App object must be created first!"

StackOverflow 에서 찾은 이유:
I suspect it's because you are attempting to run the example in an interactive interpreter session. The example is really a GUI application with an event loop, and it's not going to behave well when you repeatedly execute it in the same interactive session since cleanup of the previous app from the last run won't happen completely. Like you experienced, it will run once, but subsequent attempts fail. Such an example should definitely be run in its own dedicated interpreter that can completely exit when the GUI closes.
In Spyder, you can configure your script to run in a dedicated stand-alone interpreter without having to manually run in a separate external console. Open the file in the Spyder editor, hit F6 to open the Run Settings dialog, and then select the radio button for "Execute in a new dedicated Python interpreter". Now hit Run. Subsequent runs by using F5 will remember this configuration setting, and you'll get your example running in it's own interpreter with each repeated execution.

아마 당신은 연습코드를 interactive interpreter session(대화형 인터프리터 세션, 상호작용이 가능한 상태) 에서 실행한 것 같다. 예제는 루프문을 도는 GUI 응용 프로그램이고, 재 시작을 했을 때는 이전 실행 했던 것들이 아직 남아있는 상태 였을 것이다. 경험했던 대로, 한번을 잘 돌지만 다시 돌릴 때는 실패한다. 이런 프로그램을 실행할 때는 그 프로그램 만을 위한 인터프리터를 사용해야 한다.
스파이더 에서는, 하나의 프로그램만을 위한 인터프리터에서 실행할 수 있다. 스파이더 에디터에서, F6를 누르면 셋팅 다이얼로그가 열린다. 그리고 거기서  "Execute in a new dedicated Python interpreter" 라디오 버튼을 선택하면 된다. 이제부터 실행하는 것들은 그 프로그램만을 위한 인터프리터를 실행할 수 있는 것이다.

※ 기본 설정

※ dedicated Python interpreter 설정 후


2016년 5월 22일 일요일

임베디드 소프트웨어 설계 시 고려해야 할 사항(1/3) - 유연한(flexible) 소프트웨어의 필요성

1.
임베디드 시스템 엔지니어링에는 제약사항이 많다. 여러 제약 중 어떤 제약이 나중에 프로젝트 개발에 문젯거리가 될지를 파악하는 일은 쉽지 않다. 앞으로 발생할 변화를 예측해서 애플리케이션에 발생하는 변화를 충분히 수용할 수 있도록 소프트웨어를 유연하게(flexible) 설계해야 한다.

2.
소프트웨어를 설계할 때 시스템을 좀 더 유연하게 할 수 있는 몇몇 훌륭한 원칙이 있다.

모듈화 원칙을 이용해 하위 시스템별로 기능을 분리하고 각 하위시스템이 사용하는 데이터를 감출 수 있다.

캡슐화 원칙을 이용해 서로에 대해 알지 못하도록 하위 시스템 간의 인터페이스를 만들 수 있다. 하위시스템(또는 객체)의 결합을 약한 상태로 유지하면 한 부분을 고치더라도 다른 부분에 영향을 주지 않을 것이라는 확신을 가질 수 있으므로 쉽게 코드를 고칠 수 있다. 따라서 필요에 따라 일부 시스템을 분리했다가 수정하고 다시 제자리에 넣을 수 있다.

시스템을 어떻게 분리해야 하는지를 잘 판단하려면 연습이 필요하다. 최선의 방법은 독립적으로 변경될 수 있는 부분을 찾는 것이다.

3.
이 원칙들은 이론부터 나온 것이 아니라 컴퓨터나 만들어지고 프로그램을 만들면서 생긴 시행착오에 의해 적립이 된 것으로 이것들을 후에 체계적으로 정리한 것이 디자인 패턴 이다.

4.
디자인 패턴에 관심을 가진지는 오래 되었지만, 제대로 적용해 본적이 없었기 때문에 가장 대표적인 패턴인 MVC(Model, View, Controller) 를 간단한 프로그램을 통해 직접 구현해야 할 필요가 생겼다.


참조:
디자인 패턴을 적용한 임베디드 시스템


2016년 5월 18일 수요일

Robot Framework 이해를 위한 정리(2/3)

테스트 자동화 도입 시 얻을 수 있는 것들 및 경계해야 하는 것들
이해하기 쉽습니다.

1. Common test automation promises
테스트 자동화가 약속하는 것들.

1) Run existing regression tests on a new version of a program
새롭게 변경된 프로그램에 회귀 테스트를 실행할 수 있다.

Being able to run previously created tests without extra effort clearly makes testing more efficient.
이전에 만들어져 있는 테스트를 간단하게 실행할 수 있도록 하여 효율적으로 테스트를 수행할 수 있도록 한다.

2) Run more tests more often
많은 테스트들을 자주 실행할 수 있도록 해준다.

Automation means faster test execution which means more test rounds. Automation should also make creating new test cases easy and fast.
자동화는 빠른 테스트 실행을 의미하기 때문에 테스트를 여러번 할 수 있다는 것을 의미하며, 또한 자동화는 새로운 테스트 케이스를 쉽고 빠르게 만들 수 있도록 한다.

3) Perform tests which would be difficult or impossible to do manually
수동으로 할 때는 어렵거나 아예 못할 것 들도 수행할 수 있다.

For example performance and stress tests are nearly impossible to conduct without automation.
예를 들어 성능 테스트나 스트레스 테스트 같은 것들은 자동화가 없다면 하기 어렵다. 왜냐하면 정말 다양하고 많은 테스트를 수행해야 하기 때문이다.

4) Better use of resources
자원을 효율적으로 사용할 수 있게 된다.

Automating repeating and boring tasks releases test engineers for more demanding and rewarding work.
반복적이고 지루한 일을 자동화 하는 것은 테스트 엔지니어가 의미있는 일을 할 수 있도록 만들어 준다.

5) Consistency and repeatability of tests
일관적이고 반복적인 테스트가 가능하게 된다.

Tests are always run the same way so test results can be consistently compared to previous results from previous testing rounds. Tests can also be easily repeated on different environments.
테스트들은 항상 같은 방식으로 실행기 되기 때문에 그 결과는 이전의 테스트들과도 일관성이 있게 나타난다. 테스트들은 다른 환경에서도 쉽게 실행될 수 있다.

6) Reuse of tests
재 사용성이 높다.

Reusing tests from earlier projects gives a kick start to a new project.
재 사용성은 새 프로젝트의 빠른 출발을 돕는다.

7) Earlier time to market
빠른 출시

Reusing tests and shortening test execution time fastens feedback cycle to developers. In the end that shortens the time to market.
테스트 재사용과 빠른 실행은 개발 주기를 더욱 빠르게 한다. 그래서 시장에 빨리 출시할 수 있게 한다.

8) Increased confidence
자신감 상승

Running an extensive set of tests often, consistently and on different environments successfully increases the confidence that the product really is ready to be released.

넓은 범위의 테스트를 자주, 일관성 있게 그리고 다양한 환경에서 성공적으로 실행할 수 있다는 것은 제품의 출시에 대한 자신감을 만들어줄 수 있다.



2. Common test automation problems
테스트 자동화의 문제점

1) Unrealistic expectations
실현 가능하지 않은 기대
Managers may believe test automation will solve all their testing problems and magically make the software quality better. Automation experts should help managers setting their expectations right.
매니저들은 테스트 자동화가 모든 문제를 해결해 주고 마법처럼 소프트웨어의 품질을 향상시켜 줄 것이라고 믿는다. 자동화 전문가들은 매니저들이 기대치를 올바르게 가지도록 도와야 한다.

2) Poor testing practice
낮은 테스트 경험
If testing practices and processes are inadequate it is better to start improving them than bringing in test automation. Automating chaos just gives faster chaos.
테스트에 대한 경험이나 테스트 프로세스가 제대로 갖춰지지 않았다면 그것을 먼저 향상시킨 다음에 테스트 자동화를 논의하는 것이 낮다. 혼란을 자동화 한다면 이해할 시간이 없어 혼란이 먼저 빠르게 찾아올 것이다.

3) Expectation that automated tests will find a lot of new defects
자동화된 테스트가 새로운 문제점을 찾아낼 것이라는 기대
After automated test has been run successfully once it is not very likely to find new bugs unless the tested functionality changes. Automators normally find more defects while they are developing tests than when tests are re-executed.
테스트가 자동화 되고 성공적으로 실행되고 난 다음에는 기능이 변경되지 않는 한 새로운 버그를 찾을 가능성이 낮다. 자동화 하는 사람들은 이미 실행된 테스트를 재 테스트 할 때보다 새로운 테스트를 만들 때 문제점을 더 찾는다.

4) False sense of security
보안에 대한 잘못된 인식
Just seeing a test report with no failures does not mean that the SUT did not have any. Tests may be incomplete, either not testing all features or not able to see failures when they occur. Tests may also have defects and show wrong results.
테스트 리포트에 fail 항목이 없다고 해서 테스트 대상에 버그가 없다는 것은 아니다. 테스트는 완벽하지 않으며, 전체를 다 테스트 하지 못했거나 fail이 발생했을 때 제대로 보지 못했을 수도 있다. 테스트 자체가 문제가 있거나 결과가 잘못되었을 가능성이 있다.

5) Maintenance
유지보수
When the SUT changes also its tests change. Human test engineers are able to handle even major changes without problems but automated tests can fail after a slightest change. If maintaining test automation system takes more time than testing manually it will surely be abandoned. The same will happen also if adding new features to the automation system is too cumbersome.
테스트 대상에 변경사항이 생기면 테스트도 변해야 한다. 테스트 엔지니어 들은 중요한 변경사항을 문제없이 다룰 수 있다. 하지만 자동화된 테스트는 작은 차이점에도 문제가 생길 수 있다. 만약에 테스트 자동화 시스템을 유지보수 하는데 수동으로 하는 것보다 더 많은 시간이 들어간다면 자동화를 하지 않는것이 낮다. 테스트 대상에 새로운 기능이 들어갈 때 다루기가 어렵울 때도 자동화를 하지 않는 것이 낮다.

6) Technical problems
기술적 문제
Building and taking test automation system to use is a technical challenge which is unlikely to proceed without problems. Tools may be incompatible with the tested system and they also often have defects themselves.
테스트 자동화를 구축하고 실행하는 것은 문제점을 만날수 밖에 벗은 기술적인 도전이다. 기존에 만들어진 도구들은 테스트 되는 시스템들에 호환될 가능성이 적으며, 그 자체도 문제가 있을 수 있다.

7) Organizational issues
관리적인 이슈
Successful test automation project requires both high technical skills and support from management. Test automation has also big impact on the organization and requires changes in many processes.
성공적인 테스트 자동화 정착되기 위해서는 기술의 수준이 높아야 함은 물론이고 경영진의 지원이 필요하다. 테스트 자동화는 단체에 큰 영향을 주며 프로세스들의 변경을 초래하기 때문이다.

*단어의 뜻
regression test
회귀 테스트는 회귀 버그를 찾는 테스트를 의미한다.
회귀 버그는 이전에 제대로 작동하던 소프트웨어 기능에 문제가 생기는 것을 가리킨다. 일반적으로 회귀 버그는 프로그램 변경 중 뜻하지 않게 발생한다.
회귀 테스트로는 이전의 실행 테스트를 재 실행하며 이전에 고쳐졌던 오류가 재현되는지 검사하는 방법이 많이 사용된다.
 버그가 발생했을 경우 이를 수정하면서 해당 버그를 발견할 수 있는 테스트 케이스를 작성하고 이를 이용해 프로그램을 변경할 때마다 테스트를 다시 수행하는 것이 좋다. 수동으로 할 수도 있지만, 보통은 테스트 자동화 툴을 사용한다.

이전글
Robot Framework 이해를 위한 정리(1/3)

참조
1. Robot Framework의 첫 제안이었던 헬싱키 대학 Laukkanen, Pekka 의 석사논문