레이블이 Python.인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Python.인 게시물을 표시합니다. 모든 게시물 표시

2020년 9월 25일 금요일

colour-demosaic python package

to execute demosaic example 

1. Find a proper source

    - Colour - Demosaicing 

        - Colour Science library install

            - when install modify setup.py (long_description = open('README.rst', encoding='UTF8').read())

        - pip install colour-demosaicing

2. example

    - in "colour-demosaicing" package

    - python folder\Lib\site-packages\colour_demosaicing\examples\examples_bayer.ipynb

    - add extention when read image -> colour.io.read_image(temp_path, format ='exr')

    - install freeimage binary


**1

this post give me the clue about reading image error

error message: Could not find a format to read the specified file in single-image mode

https://stackoverflow.com/questions/60713874/grayscale-image-not-a-jpeg

2018년 3월 1일 목요일

PyQt 사용간 메모

Python Code(Anaconda 환경) 에서는 문제없이 실행 되었는데 Pyinstaller로 exe 로 변형한 다음에는 출력 에러가 떴다.
문제는 PyQt의 plainTextEdit 에서 .toPlainText() 로 가져온 string format 이 QString 이었는데 이것이 처리되는것에 문제가 생긴 것이었고 str() 으로 변경한 후에는 문제가 사라졌다.

2017년 9월 11일 월요일

PyQt

PyQt Version: PyQt4-4.11.4-gpl-Py2.7-Qt4.8.7-x64.exe Python Version: 2.7.12 64bit IDE: Anaconda2 4.2.0 64bit String 콤보 박스의 string 을 str(combobox.Text()) 로 사용하고 있었고, 이것을 Anaconda Spider 에서 사용할 때는 문제가 없었으나. PyInstaller 로 Build 한 exe 에서 error 가 나서 확인해보니 str(combobox.Text()).excode('utf-8') 을 추가 해 주어야 했다. 동일한 Python 으로 한 것이 Build 한 전후에 이상이 생겨 그 이유를 아직은 모른다.

2016년 10월 29일 토요일

2016년 10월 27일 목요일

extract data(paragraph, table) from docx file

회사에서 사용하는 워드문서(docx) 파일을 자동으로 분석할 필요가 생겨 알아 보았습니다.

아래 "1. 분석 대상 문서" 의 내용처럼 heading 이 되어 있는 내용들이 있고 그 안에 Text("Table 1") 나 table 이 있는 문서 입니다.

인터넷 검색을 하면 paragraph 를 얻거나 table 을 얻는 것을 각각 할 수는 있지만 둘을 다 할 수 있는 기능은 찾지 못하였는데 결국 둘다 한번에 얻을 수 있는 코드를 찾아서 실행하니 원하는 결과를 얻을 수 있었습니다.

몇달간 조금씩 고민했던 내용이라 실행이 되어서 기쁘지만 이것보다 좋은 방법이 있는지 궁금 하네요.

혹시 더 좋은 방법을 아시면 소개 부탁 드립니다.



참조 Link

2016년 9월 3일 토요일

python 에서 다른 파일/패키지 를 참조할 때

다른 파일을 참조할 때 아래와 같이 3가지 경우가 있다.

1. import module_name

2. from module_name import specific_function

3. from module_name import *

2번이 나머지와 다른데 해당 모듈 중 특정 함수만 가져오겠다는 것이며,
다른 1, 3 은 모든 함수들을 가져오겠다는 것이다.

2번이 빠르다.

더 깊숙한 내용이 있겠지만 여기까지..



python에서 실행되는 순서

아래와 같은 코드가 있을 때,

total = 0

def add_total(n):
    total += n

add_total(1)
add_total(10)

print(total)


에러가 발생한다.

왜냐하면 이 코드가 실행되면 먼저 def 로 정의된 함수가 먼저 실행이 되는데
total 이라는 변수는 아직 정의가 되지 않은 상태에서 참조 되었기 때문이다.

total 이라는 변수가 위쪽에 위치하기 때문에 global variable 로 먼저 선언되어 있다고 생각할 수 있지만 실행은 def 가 먼저 되기 때문에 에러가 발생한다.

pythton 에서 list 와 tuple 의 차이점


선언
    list : list_name = []
    tuple: tuple_name = ()

다른 점
    tuple 은 내용물을 수정할 수 없다.
    tuple 은 list 보다 속도가 빠르다.

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년 8월 20일 토요일

Dynamic Test Scheduling in Hardware-In-theLoop Simulation of Commercial Vehicles

Hardware-In-the Loop Simulation of Commercial Vehicles
차량에 대한 HIL 시뮬레이션 자료

나의 결론은 테스트 효율화를 위해 스테이트 머신 형태로 테스트가 진행되고 있다는 것

---

ABSTRACT

Modern day commercial vehicles are controlled by various Electronic
Control Units (ECU). They are not only tested as single units, but also by
networking them in Controlled Area Network bus (CAN) to form a complete
electrical control system. This is achieved using Hardware In the Loop (HIL)
Integration Lab. In HIL, the electrical system is connected to a real time
mathematical model of the vehicle plus it’s environment so as to form a loop.

Testing functionality of the electrical system begins by defining functional
tests. An example would be testing cruise control activation. Executing each test
is made possible by parameterizing variables in the vehicle dynamic model and
externally controlling them.

HIL based Verification and Validation (V&V) is moving towards
automation.

This is because of the complexity of electrical control systems is increasing and manual V&V is time consuming. In an automated test environment, a Test Engineer develops test scripts to implement functional tests. These test scripts execute the vehicle model in real time, control parameterized variables, and observe the electrical system response. This is compared to the expected response to decide if a functional test passed or failed.
Tests are designed to remain independent of each other. Scheduling of tests is done by the Test Engineer, which is a difficult task owing to their large number and possible combinations. Hence, the normal practice is to execute tests in a predefined sequence.

To solve the test scheduling problem in Hardware In the Loop simulation,
two solutions are proposed. 
Both the solutions exploit relationship between test case and state of the vehicle in a dynamic simulation environment. An example of such relationship is engaging cruise control only when vehicle speed is above 20 km/h. It can be proved that a test process that is sensitive to the simulation environment will be more realistic and hence efficient.

 One solution is to model the test execution as a state machine. Tests are
treated as states. Entry conditions for each state are defined using state variables
of the dynamic model. When a simulation is run, state variables of the dynamic
model are sampled in real time. One sample of state variables trigger a transition
from one state to another in the state machine. When the state machine is in one
state, a test case corresponding to that state is selected and executed. A sequence
of these transitions results in a test process evolving in time.
The second proposed solution is functionally similar to a state machine but
it’s implementation is derived from logic design. Here, one sample of state
variables is compared with entry conditions of each test case. Test cases whose
entry conditions match with the current sample are selected for execution.

Both the solutions use Failure Mode Effective Analysis (FMEA) to resolve test selection conflicts, that is, situations where more than one test is selected.
Results show that test execution using this approach is sensitive to the simulation environment and comparable to that of a real test drive scenario. An
improvement in test efficiency both in Qualitative and Quantitative terms is also
achieved. Test runs show how the new method of test execution allows faults to
propagate from one test to another like in a real test drive.

django 기초 강좌 수강 기록

django 기초 강좌 수강기록

1.  python 설치 - anaconda 3 64 bit 설치
2. easy_install django, 최신버전 특정 버전 django==1.9
3. django-admin --version
참조 Link

4. core file 생성
5. django-admin startproject MyProjectName
6. pycham 설치 및 MyProjectName open
7. manage.py 파일은 사용하는 것이지 수정하는 것이 아니다.
8. __init__ 파일은 내용이 없으며 MyProjectName 이라는 폴더가 그냥 폴더가 아니라 python package 라는 것을 알려준다.
9. setting.py 는 웹싸이트에 필요한 것들을 설정해 놓은 것이다.
10. urls.py 웹싸이트의 내용들(contents)을 보여주는 테이블이다. 특정 url 을 연결해 준다.
11. wsgi.py 는 특별한 서버의 기능을 나타내며 긴 시간이 지난 후 배우니 신경쓰지 않아도 된다.
12. 처음에는 setting.py, urls.py 만보면 된다.
13. python manage.py runserver 를 쓰면 지금 첫 생성한 프로젝트를 서버레 올려준다.
14. 127.0.0.1:8000 에 웹브라우저로 접속하면 초기 화면을 볼 수 있다.
참조: Link

15. 서버가 돌아가고 있을 때 소스코드를 변경하여도 서버를 재시작 하는 것이 아니라 브라우저로 접속을 다시하면 업데이트 된 것을 볼 수 있다.
16. python manage.py startapp music 하면 새로운 app 이 나타난다.
 - app 을 만든다. app 은 하나의 일을 하는 단위이다.
참조: Link

17. music 폴더 속의 파일 이름들을 보면 전체를 그려볼 수 있다.
18. wesite 나 소스코드 들을 database 에 hook up 하는 것이며, django 에서는 한 줄이면 된다.
19. admin.py 은 admin 권한을 이야기 한다.
20. apps.py: 이 app의 configuration을 위한 파일이다.
21. model.py: database 에 대한 blueprint 이다.
22. tests.py 는 테스트를 작성할 수 있는 공간이란 뜻이다.
23. views.py 파이썬 함수들이 있는 곳이며, 유저의 요청을 받아 들여서 그 요청한 것에 대한 결과를 다시 보여주는 것이다. 95%의 확률로 어떤 웹페이지를 요청하고 그 웹페이지를 전달해 주는 것이다.
참조: Link

24. 어떤 웹페이지를 요청하게 되면 urls.py 를 확인하게 된다.
25. 아래와 같이 쓰면 music 으로 접근했을 때 music app의 아래에 있는 urls.py 에서 어떤 동작을 할 지를 찾게 된다.
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^music/', include('music.urls')),
]
26. music app urls.py 파일에서는 아래와 같이 해당 regular expression 일 대 view.py 에 선언되어 있는 index 함수를 부르게 된다.
urlpatterns = [
    url(r'^$', views.index),
]
27. index 함수는 "This is the music app homepage" 문장을 리턴해 주는 Http 문장이므로 이를 웹브라우저에 보여준다.
def index(request):
    return HttpResponse("<h1>This is the music app homepage")
참조: Link

28. 데이터 베이스를 만들려고 한다. 그러기 위해 django 에서 중요한 내용을 습득해야 한다.
29. django project를 만들면 default로 sqlite db 가 만들어진다.
30. 이것은 setting file의 77라인에 DATABASES 라는 구조로 만들어져 있다.
31. django 는 mysql 이나 XX 등 어떤 database 나 쓸 수 있지만 기본으로 되느 sqlite3 는 어려움 없이 사용할 수 있어서 테스트에 최적이다.
32. 기본으로 아래 APP 들이 설치되어 있다. 이 앱들은 데이터 베이스에 접근해야 동작하는 것들이 있다. 하지만 migration 이 되어있지 않아 앱이 제대로 실행되지 않은 상태이다.
INSTALLED_APPS = [
    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',]
33. 데이터베이스와 싱크가 맞지 않아서 벌어지는 것이다.
34. 콘솔에서 python manage.py migrate 누르면 싱크가 된다.
35. 각 앱이 실행하기 위한 테이블이 데이터베이스에 있고 앱과 데이터베이스가 싱크가 된 것이다.
36. 싱크한 후 python manage.py runserver 하면 이번에는 no issue 라고 뜬다.
참조: Link

37. 이제는 Model 을 만들려고 한다. Model 은 저장할 데이터에 대한 blueprint 이다.
38. 코드와 데이터베이스의 셋팅은 따로 떨어져 있지 않다. Model.py 에서 한번에 할 수 있다.
39. Model.py 파일에서 class 를 만들면 자동으로 데이터베이스 테이블로 만들어 준다.
40. 각 데이터끼리는 연결해 주고, 포함관계에 따라 지워질 수 있다.
class Album(models.Model):
    # 이것들은 컬럼    artist = models.CharField(max_length=250)
    album_title = models.CharField(max_length=500)
    genre = models.CharField(max_length=100)
    album_logo = models.CharField(max_length=1000)


class Song(models.Model):
    # 앨범을 지우면 그 앨범에 연결된 곡은 같이 지워진다.    album = models.foreinKey(Album, on_delete=models.CASCADE)
    file_type = models.CharField(max_length=10)
    song_title = models.CharField(max_length=250)
참조: Link


41. 새로 만든 앱은 setting.py 에서 추가해 준다.
INSTALLED_APPS = [
    'music.apps.MusicConfig',    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',]
42. models.py 에서 class 생성한 것을 데이터베이스에 연결 시키려면 python manage.py makemigrations music 이라고 명령을 주어야 한다.
43. migration 이라는 말은 데이터 베이스에 적용시킨다는 것이다.
44. python manage.py migrate 하면 적용 완료 시켜준다.
참조: Link

45. python manage.py shell 을 구동시켜서 데이터베이스에 데이터를 저장할 수 있다.
참조: Link

46. object를 읽을 때 __str__ 함수를 사용해서 object 가 아닌 문자열을 리턴할 수 있다.
47. filter 를 써서 필요한 정보만 읽을 수 있다.
참조: Link

48. python manage.py createsuperuser 를 하면 admin 계정을 만들 수 있다.
49. Music 폴더의 admin.py 에 Album 정보를 넣으면 admin.site.register(Album) 을 적으면 된다.
참조: Link

50. view 는 간단한 함수로서 html 을 리턴해 주는 것이다.
51. urls.py 에서 어떤 정규식과 같은 url이 불리면 views.py 의 특정 함수가 불리게 되고 그 함수의 return 값이 html 이다.
참조: Link

52. 가지고 있는 Album 정보를 모두 페이지에 디스플레이 하려고 한다.
53. views.py 에서 music page 를 보여주는 index 함수를 수정한다.
54. 아래와 같이 database 의 정보를 all_albums 라는 변수로 연결시켜 준다.
all_albums = Album.objects.all()
55. album 의 각 정보를 loop 돌면서 출력해 주면 music 페이지에서 해당 리스트를 볼 수 있다.
def index(request):
    all_albums = Album.objects.all()
    html = ''    for album in all_albums:
        url = '/music/' + str(album.id) + '/'        html += '<a href="' + url + '">' + album.album_title + '</a><br>'    return HttpResponse(html)
참조: Link

56. 데이터 베이스의 내용을 가지고 웹페이지에 쓰는 것 까진 했지만 웹페이지가 투박해서 꾸며야 한다.
57. template 를 만드는 방법을 생각해야 한다.
58. music 폴더에서 template 이라는 자식 폴더를 만들고, 그 자식으로 music 폴더를 만든다.
59. 그 안에 index 라는 이름의 html 파일을 만든다.
60. 아래와 같이 연결하면 자동으로 template 폴더의 내용물을 찾는다.
template = loader.get.get_template('music/index.html')
61. template 를 load 한 다음 내용을 render 하면 된다.
62. python 에서 있던 내용을 context 라고 하는 dictionary 로 만들어서 render 할 때 인자로 넣어주면 된다.
63. html template 안에  python 코드를 넣으면 된다. 넣는 방법은 {% 여기에 넣는 것 %} 이다. 그 때 html 속에서 사용되는 변수는 {{ 이것으로 둘러 쌓인다 }}
64. html 속에서 python if 문을 아래와 같이 쓸 수 있다.






참조: Link

65. django.shortcut 을 쓰면 경로를 단축시킬 수 있다(예를 들어 template.render -> render)

참조: Link

66.  앨범이 있는 것 없는 것 확인하여 없으면 404 에러를 띄울 수 있게 한다.

참조: 16 - Raising a 404 HTTP Error


참조: 17 - Adding Songs to our Database


참조: 18 - Related Objects Set

참조: 19 - Designing the Details Template

XX. url 구조를 dynamic 하게 만드는 법

참조: 20 - Removing Hardcoded URLs



참조: 21 - Namespace and HTTP 404 Shortcut

참조: 22 - Simple Form
참조: 23 - Adding Forms to the Template
참조: 24 - Favorite View Function
참조: 25 - Bootstrap and Static Files
참조:
참조:
참조:
참조:
참조:
참조:











2016년 8월 15일 월요일

PyCon APAC 2016 후기 - 이정우



개요
    1. 어떤 프로그램을 들었는지
    2. 후원사 부스 특이사항
    3. 파이콘에서 느낀 것

1. 어떤 프로그램을 들었는지
  • (1일)Wes McKinney 키노트 : 우리나라에 Pandas를 만든 사람이 왔다는 것 자체가 신기했습니다. Pandas 만든 사람이니 기본 내용보다 변경된 내용 알려줄 텐데 그것을 이해하려고 하면 머리가 아프겠다고 생각하고 집중하지 못했습니다.
  • (1일)나의 사진은 내가 지난 과거에 한 일을 알고 있다-최규민님: 사진에 있는 정보를 뽑아내고, 그 정보들을 조합해서 결과를 보여주는 것인데 실제로 해보고 싶다는 생각이 들었습니다. 많은 정보들을 보여주셨는데 그 중 집중 한 것은 이동한 경로를 사진의 위치 데이터 바탕으로 지도상에 찍어 준 것과, 사진 속 얼굴을 인식하여 얼마나 즐거웠는지 판단한 것 입니다. 직접 구현해보고 싶어 간단하게 진행(블로그링크) 하고 있습니다.
  • (1일)Introduction to deep learning for machine vision tasks using Keras-Michael Amy: Machine learning을 해야 하는데 몇번 시도해본 결과 머리가 아팠던 기억이 있어 이해는 미뤄두고 듣기만 했습니다..
  • (1일)뉴스를 재미있게 만드는 방법; 뉴스잼-김경훈님: 뉴스를 재미있게 보여주기 위해서 필요한 작업을 수집, 분석, 전달 로 나누고 각 세부적인 작업들에서 사용한 정말 다양한 라이브러리를 소개해 주셨습니다. 방대한 내용을 차근차근 설명해주시는 모습을 보고 회사 선배님이었으면 좋겠다라고 생각 했습니다;
  • (1일)The PSF and our community-김영근님: Python 의 김영근님이 커뮤니티를 어떻게 시작했고 어떤 마음으로 하고 있다는 것을 설명, 운영하는 분들의 노고를 많이 느낄 수 있었습니다. 
  • (1일)기계학습을 활용한 게임 어뷰징 검출-김정주님: 게임중 채팅창에 광고하는 어뷰징 프로그램을 감지하는 방법에 대한 고민하고, 기계학습을 사용해서 100% 검출을 할 수 있었다는 내용이었습니다. 역시 분석 할 데이터가 있고, 그 효과를 바로 느낄 수 있는 것이 가장 중요하다고 느꼈습니다. 게임에서는 채팅창이 도배되면 유저들이 대화를 못하고, 게임도 하기 싫어질 테니까요..
  • (2일)Django vs Flask, 까봅시다!-김도현님: Django 와 Flask 를 둘다 써본 사람으로써 어떤 장 단점이 있다고 느낀것을 공유해 주셨습니다. 1) Django는 암시적이지만 기능이 많고, Flask는 명시적이지만 기능이 적다. 2) Flask 가 간결하지만 구현 방법이 다양해서 초보자가 따라가기에 힘들다. 3) Django 구현방법이 사람마다 편차가 적어 초보자가 하는 것이 적당하다. 
  • (2일)Python으로 19대 국회 뽀개기-이홍주님: 머신러닝을 할 때는 attribute들을 vector로 만드는 작업(featurization)이 가장 중요하다. 
  • (2일)Debugging Tips and Tricks-Roy Hyunjin Han: 8가지 debug 하는 방법을 보여주었습니다. 제가 평소 사용하지 않는 디버깅 기술들을 빠르고 명확하게 끊김없이 하셔서 멋있어 보였습니다. 8가지 중 Jupyer notebook 에서 에러 발생 시 창에 'debug' 를 쓰면 바로 debug 모드로 들어가는 것이 이해도 잘 되고 바로 사용할 것 같았습니다. 세션이 끝나고 insight 를 얻고 싶어 뛰어나지 않은 개발자로서 할만 하고, 요즘 가장 hot 한 것이 무엇이 있냐고 물었는데 www.openai.com 싸이트를 소개시켜 주었습니다. 머신러닝 중 reinforcement 에 관련된 것이었습니다.    
2. 후원사 부스 특이사항
    JetBrain: PyCharm을 만드는 회사로 대기열이 가장 길었는데, JetBrain에 등록을 하면 추첨을 해서 PyCharm Pro 버전을 무료로 주기 때문이었습니다. 하지만 그 내용에 대한 공지가 따로 없었기 때문에 (저를 포함)많은 사람들이 제일 좋은 것을 준다고 생각해서 줄을 서 있었고, JetBrain Member에게 문의하니 몇명이 등록하는지 마지막날까지 확인해서 내부적으로 결정할 것이라고 결정된 것은 없다고 확인하였습니다.
    SmartStudy: 사진을 셀카포함 거의 안찍었는데 facebook에 셀카 찍어서 #PyConAPAC, #SmartStudy 공유하면 bottle 준다고 해서 찍음, 그 사진이 남아서 다행입니다.
    Elastic: Twitter 에 태그 남기면 Stress ball 을 주셨습니다. 개인적으로 건강에 관련된 아이템을 좋아해서 기분 좋았습니다.

3. 파이콘에서 느낀 것
    이렇게 수준높은 컨퍼런스를 5만원 내고 3일 동안 즐길 수 있어서 행운이었습니다.
    봉사하는 분들은 정말 세션 내용들을 못드는 것을 보고 죄송한 마음이 들었습니다..
    세션들을 듣는다고 해도 그 내용을 정말 기억하고 이해해서 내 업무에 쓰기는 정말 어렵다는 것을 느꼈고, 그래서 생각한 것은, 들었던 내용을 토론 형식으로 꾸준히 리뷰하면 각자 자기 수준을 뛰어넘는 인싸이트를 얻을 수 있을 것 같다는 것입니다.

2016년 7월 23일 토요일

Python으로 Binary 파일을 읽고 Hex 형으로 표현하기

계기: Hardware 팀에서 Sensor Setting 하는 것을 자동화 하고 싶어한다.
방법: 1. Teraterm 의 명령어를 Script로 작성해서 자동 실행 한다.
        2. 1번을 위해 Sensor Setting 해야 하는 메모리 주소, 값의 리스트를 Binary 파일로 받아 TeraTerm Script로 자동 생성한다.


관련 코드
import binascii

binAllString = ""

with open("C:\\Users\\ADMIN\\Downloads\\info-523.bin", "rb") as f:
    byte = f.read(1)
    binAllString = binAllString + binascii.b2a_hex(byte)
    while byte != "":
        # Do stuff with byte.
        byte = f.read(1)
        hex_str = binascii.b2a_hex(byte)
        binAllString = binAllString + " " + hex_str
        
#print binAllString


binStringList = []

for s in range(0, len(binAllString), 48):
    print binAllString[s:s+48] + ""

세부 설명
Convert between binary and ASCII

Open file with "rb" (read binary)

Use b2a_hex function to use hexadecimal representation of the binary data

use String List( binAllString[s:s+48] ) to write script line every 48(16 hex values, 2digits-16bytes-16spaces)





2016년 7월 20일 수요일

python serial library 사용기 - 1

serial port 를 python에서 사용하기 위한 serial library 간단 사용기
천천히라도 원리를 이해하기 위함

import serial
설치 되어 있는 serial library import
ser = serial.Serial('COM5',115200,timeout=1)
port를 사용하기 위한 instance 생성
COM5’ = 사용할 COM port의 이름
115200 = 사용할 baud rate
1 = timeout(반응 없을면 종료) 시간
ser.write("hello")
지정된 port“hello” 문자열 씀
ser.readline()
지정된 port에서 EOL 문자 까지 값 읽음

메모
1. baud rate: 컴퓨터와 통신 장비 간에 직렬 데이터의 전송 속도를 나타내는 단위이고, 1초당 불연속 상태의 데이터 전송의 수를 말한다. [컴퓨터인터넷IT용어대사전]
2. python에서는 각 함수에 인자의 순서가 정해져 있으나 이름(timeout 과 같은)을 명시해서 입력하면 순서에 상관없이 사용할 수 있다.

2016년 7월 14일 목요일

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년 6월 5일 일요일

(K, E)Python Module Dependency Graphs Example(종속성 그래프 예제)


Contents
    file1~5, Console Command, Result

file1
file2

file3

file4

file5

Console Command
python py2depgraph.py file1.py | python depgraph2dot.py | dot -T png -o result.png

Note
Some built in Libraries(ex> Serial) make py2depgraph.py script error. I don't know the root cause. In that case, that library need to be commented or replace to blank library which has same name to appear in dependency graph. I made another 20 scripts related dependency graph, so this method works file.
기본 라이브러리(예를 들어 Serial)들이 py2depgraph.py 스크립트를 실행하다 에러가 발생하는 경우가 있습니다. 정확한 이유는 모르지만 처리과정에 문제가 있는 것이고, 기본 라이브러리기 때문에 아예 주석으로 바꾸어서 그림에 안나타나게 하거나, 필요 시에는 같은 이름을 가진 .py를 만들어 주면 그림에서 나타나게 할 수 있습니다. 그리고 이 예시 말고 약 20개 python script 로도 dependency graph를 그려보아서 이 방법이 잘 되는 것은 확인 하였습니다.


Result

2016년 6월 4일 토요일

(E, K)Generating Python Module Dependency Graphs(종속성 그래프 생성하기)

I studied how to draw dependency graph from the website. I translated it below to understand correctly.
my own example is on another post.
python 파일들의 dependency graph를 그리기 위해서 인터넷 검색을 통해 잘 설명해 준 싸이트를 찾았고, 해 보았습니다. 아래는 이해를 제대로 하기 위해 번역해 놓은 글 입니다. 제가 직접 구현한 간단한 예제는 다른 포스트에 기록 했습니다.


Controlling physical dependencies is an important part of any software architecture. We noticed a shortage of tools for analyzing Python program when we started work on 'Tintag Explorer', and the tools described here were created as a result.
물리적인 의존관계를 파악하고 제어하는 것은 소프트웨어 구조에서 중요한 부분입니다. 우리는 Python 에서 이런 의존관계를 분석하는 툴이 부족한 것을 인지하여 Tintag Explorer 의 의존관계 분석하는 툴을 직접 만들어 보았습니다.

Below is a shrunken version of the dependency graph from several subsystems of the current development version of Tinytag Explorer; 4.3. The __main__ module is the small dark blue circle at the top. Other circles are other modules. The lines are arrows (although you cant see the arrow-heads in this shrunken version) that indicate that one module imports another. All arrows point down, unless there are cyclic imports.
아래는 Tinytag Explorer 4.3버전에 대한 의존그래프 입니다. __main__ 모듈은 위쪽에 작은 어두운 파란 동그라미 입니다. 보이는 선들은 화살표이며(비록 이 작은 그림들에서는 화살의 머리가 보이지 않아도) import 된 관계를 나타 냅니다.
모든 화살표는 아래를 향하게 됩니다. 단 cycle 관계여서 서로 import 하는게 아니라면...



We have obtained enormous value from studying automatically generated diagrams such as this. It often highlights:
우리는 자동 다이어그램 생성을 찾아 보면서 많은 것들을 얻었습니다. 이 dependency graph를 통해서 강조해서 알 수 있었던 것은.

● Ill-advised module iorts, as obtrusive diagonal lines across large distances of the diagram.
  문제가 될만한 먼 거리에 보기싫게 사선으로 연결된 관계.
● Modules that might be in the wrong package, as solitary circles on one color surrounded by those of another color.
   잘못된 패키지 안에 있는 모듈들, 예를 들어 혼자 연결되어 있는 것.
● Subsystems that are ideal for reuse in other systems because they have few dependencies. For example, the island of pink on the bottom left of the diagram above has already been reused from another project. [Hi Lawrence.... That's TSG!]
   의존 관계가 적어, 재 사용하기에 좋은 하위시스템들, 예를 들어 아래에서 왼쪽에 핑크색으로 표시된 것처럼.
● Close clusters of modules are often a suitable unit for code review.
   구분되어 져 있는 무리들은 코드 리뷰하기에 적당함

This diagram was generated from a three-step process:
이 다이어그램은 3개의 단계로 나누어 진행 되었습니다.

Step 1: Compute The Dependency Graph
Python's modulefinder module does all the heavy lifting here. modulefinder use bytecode inspection to find dependencies, and therefore is free from any side-effects that may be caused by importing the modules being studied.
파이썬의 modulefinder 모듈이 어려운 일들을 해 줍니다. modulefinder 는 바이트코드 단위에서 의존관계를 확인해 주었고, import 된 것을 확인하는 과정에서 부작용이 없도록 하였습니다.

This py2depgraph.py script will write to stdout the dependency graph raw data for the script named in its first parameter.
py2depgraph.py 스크립트 첫번째 파라미터가 된 파일에 대한 의존 관계를 간단한 text 버전으로 보여 줍니다.

Step 2: Format The Dependency Graph
In step 3 we will be passing our data into dot, part of graphviz In step 2 we need to convert the raw dependency data generated in step 1 into the correct format, and apply any presentation logic.
2번째 단계에서는 1단계에서 나온 의존관계를 그래프 그리기 알맞는 dot형태로 변경하고, 3번째 단계에서 dot 형태의 그래프를 graphviz로 보내 그림으로 보여질 수 있도록 합니다.

In simple cases you can use depgraph2dot.py as-is. It receives the raw data in standard input, and provides the generated dot file on standard output.
간단한 관계에선 depgraph2dot.py를 그대로 사용하면 됩니다. 입력값으로 기본 text 포맷을 받아들이며 dot파일의 형태로 아웃풋을 만들어 줍니다.

For the best presentation you will need a little programming. Create a subclass of the class defined in this module, override some methods that apply presentation logic, then call the main() method of one of those objects. The following aspects of the presentation can be customised:
최적으로 보여주기 위하여 약간의 프로그래밍이 필요 합니다. 여기서 만들어진 클래스에 대한 하위 클래스를 만들어서, 프레젠테이션 로직을 오버라이드 해 주고 main 함수를 부르면 됩니다. 프레젠테이션은 수정될 수도 있습니다.

1. Change which modules will be used on the diagram. By default it omits a number of very common modules such as sys that would add uninteresting clutter. It also omits packages (but not the modules within the package). The diagram above has been customized to show a group of application-specific packages.
 어떤 모듈을 그릴 것인지 선택 합니다. 정말 기본적인 모듈들 이나 package 들은 생략합니다(예를 들어 sys).  위의 다이어그램은 application 에 사용되는 것들만 보이도록 손 본 것입니다.

2. Pairs of modules that have a specially close relationship. These relationships are drawn with particularly short straight lines. By default any reference to a module whose name starts with an underscore carries this extra weight, because that usually indicates a special relationship (for example, as between random and _random)
   관계가 밀접한 모듈들은 짧은 라인으로 연결되게 됩니다. 모듈 이름에 밑줄이 그어져 잇는 것들은 특별히 중요한 것들입니다. 특별한 관계이기 때문 입니다.(예를 들어 random 과 _random)

3. Pairs of modules whose relationship should be drawn with an extra long line. This is a good way of separating subsystems - for example the module highlighted in red in the diagram above has extra space above.
   특별히 긴 라인으로 연결되어 있는 모듈들도 있습니다. 이 방법은 하위 시스템들을 구분하는 데 사용됩니다 - 빨간색으로 강조 되어 있는 부분이 그렇습니다.

4. A color. By default the color is assigned automatically with all modules in one package assigned the same color.
  색을 입힙니다. 기본 색은 자동으로 생성되며 같은 패키지것을 사용한 것은 같은 색이 됩니다.

5. A text label, by default the module name.
  텍스트를 모듈의 이름에 근거해서 생성합니다.

Step 3: Generate The Image
You need the dot tool from graphviz. This can generate most image formats. It can also generate postscript ideal for printing. If printing to a black and white printer the --mono switch to depgraph2dot.py will be helpful.
image를 만들기 위해서는 graphviz에 있는 dot 툴이 필요 합니다. 흑백의 출력이 필요하다면 --mono option 을 depgraph2dot.py 명령에 추가하면 됩니다.

Putting those three steps together gives something like:
위에 설명한 3개의 단계는 아래의 명령으로 구현 됩니다.

$ python py2depgraph.py path/to/my/script.py | python depgraph2dot.py | dot -T png -o depgraph.png
$

(Created 2004. Updated December 2009 with python 2.6 fixes)