Programming2015. 9. 30. 10:28

주식시세 query

webservicex는 response가 간단해서 빠른편인데, data 자체는 realtime도 아니고 15-20분에 한번씩 update는것 같음.

Google finance는 response자체가 너무 복잡함. 시간이 좀 걸림. 개인적인 용도로는 상관없지만.

간단하게 빠르게 update되는 서버는 무료는 없을듯. Nasdaq에서 한달에 얼마씩 내면 준다고 함.

-------------

http://www.webservicex.net/stockquote.asmx/GetQuote?symbol=aapl


XML response example)

<string xmlns="http://www.webserviceX.NET/">

<StockQuotes>

<Stock>

<Symbol>aapl</Symbol>

<Last>109.06</Last>

<Date>9/29/2015</Date>

<Time>4:00pm</Time>

<Change>-3.38</Change>

<Open>112.79</Open>

<High>113.51</High>

<Low>107.86</Low>

<Volume>73365384</Volume>

<MktCap>621.94B</MktCap>

<PreviousClose>112.44</PreviousClose>

<PercentageChange>-3.01%</PercentageChange>

<AnnRange>92.00 - 134.54</AnnRange>

<Earns>8.65</Earns>

<P-E>12.62</P-E>

<Name>Apple Inc.</Name>

</Stock>

</StockQuotes>


*but from urllib2 read, all tags are UTF-9 encoded(llike corrupted) like below ==> HTML parser로 escape문자를 바꿔줘야함

<?xml version="1.0" encoding="utf-8"?>

<string xmlns="http://www.webserviceX.NET/">&lt;StockQuotes&gt;&lt;Stock&gt;&lt;Symbol&gt;AAPL&lt;/Symbol&gt;&lt;Last&gt

;109.06&lt;/Last&gt;&lt;Date&gt;9/29/2015&lt;/Date&gt;&lt;Time&gt;4:00pm&lt;/Time&gt;&lt;Change&gt;-3.38&lt;/Change&gt;&

lt;Open&gt;112.79&lt;/Open&gt;&lt;High&gt;113.51&lt;/High&gt;&lt;Low&gt;107.86&lt;/Low&gt;&lt;Volume&gt;73365384&lt;/Vol

ume&gt;&lt;MktCap&gt;621.94B&lt;/MktCap&gt;&lt;PreviousClose&gt;112.44&lt;/PreviousClose&gt;&lt;PercentageChange&gt;-3.0

1%&lt;/PercentageChange&gt;&lt;AnnRange&gt;92.00 - 134.54&lt;/AnnRange&gt;&lt;Earns&gt;8.65&lt;/Earns&gt;&lt;P-E&gt;12.6

2&lt;/P-E&gt;&lt;Name&gt;Apple Inc.&lt;/Name&gt;&lt;/Stock&gt;&lt;/StockQuotes&gt;</string>

-------------

Pattern matching in XML

import urllib2, time, os, re
import HTMLParser
def fetchStockPrice(ticker):
	url="http://www.webservicex.net/stockquote.asmx/GetQuote?symbol="
	txt=urllib2.urlopen(url+ticker).read()
	html_parser = HTMLParser.HTMLParser()
	parsed = html_parser.unescape(txt)
	#print parsed
	#unicode =  txt.encode('utf-8')
	#print unicode

	#result=re.search('(.*?)',parsed)
	result=re.search('([0-9]+\.[0-9]+)', parsed)
	if result:
		stockprice = result.group(1)
		cur_date = re.search('(.*?)',parsed)
		cur_time = re.search('',parsed)
		ret = stockprice + " " + cur_date.group(1) + " " + cur_time.group(1)
	else:
		stockprice = "Nothing found for: " + ticker
		ret = "Nothing found for: " + ticker
	return ret

print ("NOW = " + time.ctime())
print "Stock Price is " + fetchStockPrice("AAPL") 

-------------

Just Pattern Matching Python code
import  urllib2, time, os, re
def fetchStockPrice(ticker):
	url="http://www.webservicex.net/stockquote.asmx/GetQuote?symbol="
	txt=urllib2.urlopen(url+ticker).read()
	#f=open("sample.xml")
	#txt = f.read()
	#print txt
	#result=re.search('(.*?)',txt)
	result=re.search('([0-9]+\.[0-9]+)',txt)
	#result=re.search("Last\>(\d+\.\d+)\</Last", txt)
	if result:
		stockprice = result.group(1)
	else:
		stockprice = "Nothing found for: " + ticker
	return stockprice

print(time.ctime())
print fetchStockPrice("AAPL") 


-------------

XML parsing example

https://docs.python.org/2/library/xml.dom.minidom.html?highlight=xml.dom.minidom#module-xml.dom.minidom

import xml.dom.minidom

document = """\

	
		aapl
		109.06
		9/29/2015
		
		-3.38
		112.79
		113.51
		107.86
		73365384
		621.94B
		112.44
		-3.01%
		92.00 - 134.54
		8.65
		12.62
		Apple Inc.
	

"""

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

def getStockPrice(quote):
	 print "Last Stock Price is :" % getText(quote.childNodes)

def handleToc(stocks):
    for stock in stocks:
		symbol = stock.getElementsByTagName("Symbol")[0]
		print "

%s

" % getText(symbol.childNodes) last = stock.getElementsByTagName("Last")[0] print "

%s

" % getText(last.childNodes) date = stock.getElementsByTagName("Date")[0] print "

%s

" % getText(date.childNodes) time = stock.getElementsByTagName("Time")[0] print "

%s

" % getText(time.childNodes) dom = xml.dom.minidom.parseString(document) stocks = dom.getElementsByTagName("Stock") handleToc(stocks)

-------------

Stock Quote from Google finance

import urllib2, time, os, re, csv
 
def fetchGF(googleticker):
	url="http://www.google.com/finance?&q="
	txt=urllib2.urlopen(url+googleticker).read()
	#print txt
	#search phase 112.44
	k=re.search('id="ref_(.*?)">(.*?)<',txt)
	#print k
	if k:
		tmp1=k.group(0)
		tmp2=k.group(1)
		#print tmp1
		#print tmp2
		tmp=k.group(2)
		#print tmp
		q=tmp.replace(',','')
		#print q
	else:
		q="Nothing found for: "+googleticker
	return q
	
print(time.ctime())
print fetchGF("AAPL")
#print fetchGF("NASDAQ:AAPL")

-------------

Stock Portfolio를 query하려면

#file에서 읽어도 좋겠다.
tickers=["NASDAQ:AAPL","NASDAQ:GOOG","NASDAQ:BIDU","NYSE:IBM", \
         "NASDAQ:INTC","NASDAQ:MSFT","NYSEARCA:SPY"]

for ticker in tickers:
	data=combine(ticker)
	print(data)

-------------

 xmlparsing_finished.py


-------------

import urllib2, time, os, re
import HTMLParser
def fetchStockPrice(ticker):
    url="http://www.webservicex.net/stockquote.asmx/GetQuote?symbol="
    txt=urllib2.urlopen(url+ticker).read()
    html_parser = HTMLParser.HTMLParser()
    parsed = html_parser.unescape(txt)
    #print parsed
    #unicode =  txt.encode('utf-8')
    #print unicode
 
    #result=re.search('(.*?)',parsed)
    result=re.search('([0-9]+\.[0-9]+)', parsed)
    if result:
        stockprice = result.group(1)
        cur_date = re.search('(.*?)',parsed)
        cur_time = re.search('',parsed)
        cur_percent = re.search('(.*?)',parsed)
        #Text formatting
        ret = '{:4s}: {:7s} {:7s} - {:10s} {:7s}'.format(ticker, stockprice, cur_percent.group(1), cur_date.group(1), cur_time.group(1))
        #ret =  '{:4s}'.format(ticker) + ": " +stockprice + " " + cur_percent.group(1) + " " + cur_date.group(1) + " " + cur_time.group(1)
    else:
        stockprice = "Nothing found for: " + ticker
        ret = "Nothing found for: " + ticker
    return ret
 
print(time.ctime())

#tickers=["NASDAQ:AAPL","NASDAQ:GOOG","NASDAQ:QCOM","NYSE:NUAN", \
#         "NASDAQ:INTC","NYSE:DAL","NYSE:F", "NYSE:SMI", "NASDAQ:HQCL", "NYSEARCA:UCO"]
tickers=["AAPL","GOOG","QCOM","NUAN", \
         "INTC","DAL","F", "SMI", "HQCL", "UCO"]
print ("--------------------------")
#print fetchStockPrice("AAPL")
for ticker in tickers:
    data=fetchStockPrice(ticker)
    print(data)
print ("--------------------------") 

-------------


stockprices.py


'Programming' 카테고리의 다른 글

VM Virtualbox에 Ubuntu설치후  (0) 2015.10.01
Python - String, File, Regular Expression  (0) 2015.09.30
VIM resource file  (0) 2015.09.30
Python - Date, Time  (0) 2015.09.29
Python with Django  (0) 2015.09.26
Posted by 쁘레드
Programming2015. 9. 30. 09:46

vim with ctags, cscope

------------

Download VIM plug-ins from vim.org

Source Explorer

Nerd Tree

Tag list


unzip copy to vim plugins folder

~/.vim/plugins

------------


"VI env"
set nu
set ai
set ts=4
set bg=dark

ctag db"
set tags=/home/fred/host/kernel-3.10/linux-3.10.89/tags

"cscope db"
set csprg=/usr/bin/cscope
set csto=0
set cst
set nocsverb
cs add /home/fred/host/kernel-3.10/linux-3.10.89/cscope.out /home/fred/host/kernel-3.10/linux-3.10.89
set csverb

"tag list"
filetype on
nmap  :TlistToggle
let Tlist_Ctags_Cmd = "/usr/bin/ctags"
let Tlist_Inc_Winwidth = 0
let Tlist_Exit_OnlyWindow = 0
let Tlist_Auto_Open = 0
let Tlist_Use_Right_Window = 1

"Source Explorer"
nmap  :SrcExplToggle
nmap  h
nmap  j
nmap  k
nmap  l

let g:SrcExpl_winHeight = 8
let g:SrcExpl_refreshTime = 100
let g:SrcExpl_jumpKey = ""
let g:SrcExpl_gobackKey = ""
let g:SrcExpl_isUpdateTags = 0

"Nerd Tree"
let NERDTreeWinPos = "left"
nmap  :NERDTreeToggle"

------------------

make ARCH=x86 COMPILED_SOURCE=1 cscope tags

cscope -d  ; do not update cross reference

------------------

F7, F8, F9 ;open plugins


CRTL + H J K L ; windows switching

SPACEBAR ; previous window

CTRL + ] ; jump to definition

CTRL + t ; back to previous code


cscope command

:CS find s <SYMBOL_NAME>



'Programming' 카테고리의 다른 글

Python - String, File, Regular Expression  (0) 2015.09.30
Python - Stock Price Quote  (0) 2015.09.30
Python - Date, Time  (0) 2015.09.29
Python with Django  (0) 2015.09.26
Regular Expression  (0) 2015.09.25
Posted by 쁘레드
Programming2015. 9. 29. 21:59


----------------

http://www.tutorialspoint.com/python/python_date_time.htm

https://docs.python.org/2/library/datetime.html


----------------

TimeZone and Local time

import os, time

print(time.ctime())

#FRED : doesn't work in Windows, only UNIX/Linux
# Set local time zone to NYC
os.environ['TZ']='America/New_York'
time.tzset()
print time.strftime('%X %x %Z')

os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
time.tzset()
print time.strftime('%X %x %Z')

t=time.localtime() # string
print(time.ctime())

----------------

from datetime import date
from datetime import time
from datetime import datetime

def main():
  ## DATE OBJECTS
  # Get today's date from the simple today() method from the date class
  today = date.today()
  print "Today's date is ", today
  
  # print out the date's individual components
  print "Date Components: ", today.day, today.month, today.year
  
  # retrieve today's weekday (0=Monday, 6=Sunday)
  print "Today's Weekday #: ", today.weekday()
  
  ## DATETIME OBJECTS
  # Get today's date from the datetime class
  today = datetime.now()
  print  "The current date and time is ", today
  
  # Get the current time
  t = datetime.time(datetime.now())
  print "The current time is ", t
  
  # weekday returns 0 (monday) through 6 (sunday)
  wd = date.weekday(today)  
  # Days start at 0 for Monday 
  days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
  print "Today is day number %d" % wd
  print "Which is a " + days[wd]
  
  
if __name__ == "__main__":
  main();
 

----------------

Formatting

http://www.tutorialspoint.com/python/time_strftime.htm

from datetime import datetime

def main():
  # Times and dates can be formatted using a set of predefined string
  # control codes 
  now = datetime.now() # get the current date and time
  
  #### Date Formatting ####
  
  # %y/%Y - Year, %a/%A - weekday, %b/%B - month, %d - day of month
  print now.strftime("%Y") # full year with century
  print now.strftime("%a, %d %B, %y") # abbreviated day, num, full month, abbreviated year
  
  # %c - locale's date and time, %x - locale's date, %X - locale's time
  print now.strftime("%c")
  print now.strftime("%x")
  print now.strftime("%X")
  
  #### Time Formatting ####
  
  # %I/%H - 12/24 Hour, %M - minute, %S - second, %p - locale's AM/PM
  print now.strftime("%I:%M:%S %p") # 12-Hour:Minute:Second:AM
  print now.strftime("%H:%M") # 24-Hour:Minute

  ## Fred's preference
  print now.strftime("FRED date_time format: %Y%m%d_%H%M%S")

if __name__ == "__main__":
  main();

----------------

Diff, counting date, time

from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

# construct a basic timedelta and print it
print timedelta(days=365, hours=5, minutes=1)

# print today's date
print "today is: " + str(datetime.now())

# print today's date one year from now
print "one year from now it will be: " + str(datetime.now() + timedelta(days=365))

# create a timedelta that uses more than one argument
print "in two weeks and 3 days it will be: " + str(datetime.now() + timedelta(weeks=2, days=3))

# calculate the date 1 week ago, formatted as a string
t = datetime.now() - timedelta(weeks=1)
s = t.strftime("%A %B %d, %Y")
print "one week ago it was " + s

### How many days until April Fools' Day?

today = date.today()  # get today's date
afd = date(today.year, 4, 1)  # get April Fool's for the same year
# use date comparison to see if April Fool's has already gone for this year
# if it has, use the replace() function to get the date for next year
if afd < today:
  print "April Fool's day already went by %d days ago" % ((today-afd).days)
  afd = afd.replace(year=today.year + 1)  # if so, get the date for next year

# Now calculate the amount of time until April Fool's Day  
time_to_afd = abs(afd - today)
print time_to_afd.days, "days until next April Fools' Day!"


----------------

import calendar

# create a plain text calendar
c = calendar.TextCalendar(calendar.SUNDAY)
str = c.formatmonth(2015, 1, 0, 0)
print str

# create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.SUNDAY)
str = hc.formatmonth(2015, 1)
print str

# loop over the days of a month
# zeroes mean that the day of the week is in an overlapping month
for i in c.itermonthdays(2015, 8):
  print i

# The Calendar module provides useful utilities for the given locale,
# such as the names of days and months in both full and abbreviated forms
for name in calendar.month_name:
  print name

for day in calendar.day_name:
  print day

# Calculate days based on a rule: For example, consider
# a team meeting on the first Friday of every month.
# To figure out what days that would be for each month,
# we can use this script:
for m in range(1,13):
  # returns an array of weeks that represent the month
  cal = calendar.monthcalendar(2015, m)
  # The first Friday has to be within the first two weeks
  weekone = cal[0]
  weektwo = cal[1]
   
  if weekone[calendar.FRIDAY] != 0:
    meetday = weekone[calendar.FRIDAY]
  else:
    # if the first friday isn't in the first week, it must be in the second
    meetday = weektwo[calendar.FRIDAY]
      
  print "%10s %2d" % (calendar.month_name[m], meetday)


----------------


----------------


----------------

'Programming' 카테고리의 다른 글

Python - Stock Price Quote  (0) 2015.09.30
VIM resource file  (0) 2015.09.30
Python with Django  (0) 2015.09.26
Regular Expression  (0) 2015.09.25
Book - EXCEL Hacks  (0) 2015.09.24
Posted by 쁘레드
IT이야기2015. 9. 26. 10:34

IPhone6s가 발매됨에 따라 첫 주말에 얼마나 팔리느냐가 관건입니다.

Iphone6가 첫주말에 10M대를 팔았다고 하는데, 이번에는 13-15M을 팔수 있을거란 예측도 있습니다. 1차 발매국에 중국도 포함되고 여자들은 환장하는 핑크가 포함되어 있어 13M은 쉽게 달성할것 같습니다.


Google trends를 보면 역시 어제 오늘 Iphone서치가 폭발하네요. 기대됩니다.


https://www.google.com/trends/explore#q=apple%2C%20iphone&date=now%207-d&cmpt=q&tz=Etc%2FGMT%2B7

Posted by 쁘레드
IT이야기2015. 9. 26. 08:30

재밌는 Smart폰 자동화 App

IFTTT회사가 만드는 app들은 공짜이면서 응용분야가 엄청난다.

-------------

IFTTT

IF This Then That

 Top Developer

IF by IFTTT

Everyone Everyone
This app is compatible with all of your devices.


같은 회사에서 만든 IF조건이 없는 그냥 DO, 버튼을 만들어 누를때마다 실행.

 Top Developer

DO Button by IFTTT

Everyone Everyone
This app is compatible with all of your devices.

-------------

Trigger

Trigger

Everyone Everyone
Offers in-app purchases
This app is compatible with all of your devices.

-------------

Sweet Home - 집 WIFI를 잡으면 사진과 비디오를 NAS에다 backup

Sweet Home WiFi Picture Backup

Everyone Everyone
This app is compatible with all of your devices.


Posted by 쁘레드
Programming2015. 9. 26. 07:38

Python으로 website를 돌리는것을 배우려고 강좌를 하나 봤는데 꽤 재밌고 빠르고 짧다.

문제는 python language가 그렇듯 high level abstraction이 쉬운것처럼 보이지만 반대로 상당히 이해하기 어렵다. 말은 쉬운데 진짜로 만들기 어려운것 처럼. 하여간 output을 만들면 짧고 간견하세 maintenance는 쉬울듯.

이번에 Python으로 inventory check하는 프로그램을 만들려고 하는데 이것으로 하면 재밌겠다.



------------

Up and Running with Python and Django

http://www.lynda.com/Developer-Web-Development-tutorials/Up-Running-Python-Django/386287-2.html


https://www.djangoproject.com/

http://djangogirls.com


*Need pip

sudo apt-get install python-pip


django-admin startproject <project_name>

manage.py runserver


*FIles

__init__.py

wggi.py : hook for web

urls.py

settings.py : DEBUG, Database

- Models - data layer

model.py


-Migration

manage.py

manage.py migrate --list

manage.py makemigration

manage.py migrate



*SQL browser

http://sqlitebrowser.org/ 

 

 URL Patterns  -> Views -> Templates

                                  |

                                  |

                                  |

                              Models


*New text editor

http://www.sublimetext.com/2


------------

Barcode scanner

https://play.google.com/store/apps/details?id=com.google.zxing.client.android&hl=en

https://github.com/zxing/zxing


ZXing-based third-party open source projects

ModuleDescription
QZXingport to Qt framework
zxing-cppport to C++ (forked from the deprecated official C++ port)
zxing_cpp.rbbindings for Ruby (not just JRuby), powered by zxing-cpp
python-zxingbindings for Python
ZXing .NETport to .NET and C#, and related Windows platform

Other related third-party open source projects


ModuleDescription
Barcode4JGenerator library in Java
ZBarReader library in C99
OkapiBarcode


'Programming' 카테고리의 다른 글

VIM resource file  (0) 2015.09.30
Python - Date, Time  (0) 2015.09.29
Regular Expression  (0) 2015.09.25
Book - EXCEL Hacks  (0) 2015.09.24
file/directory 비교 tool - Meld  (0) 2015.09.24
Posted by 쁘레드
Programming2015. 9. 25. 03:23

Javascript based regular expression engine.

http://regexpal.com/ - save it to file and enable global checkmark which is enabled by default.


Python reqular expression test

http://pythex.org/

------------

grep

egrep = grep -e

awk, vi, emacs

POSIX

BRE - Basic R.E.

ERE - Extended R.E.

-------------


\ : excape character

\t : tab

\r, \n, \r\n : new lines


------------

[aeiou] : any of vowel

[0-9] : - is range character

[A-Za-z] : all alphabet

[^aeiou] : non vowel

------------

[\d\s] : digit and space

[^\d\s] : non digit and non space

[\D\S] : all ==> don't use multiple capital characters


*POSIX expressions are not popular



------------

#Year

(19|20)\d\d

/(19[5-9]\d|20[0-4]\d)/

------------

# Does first letter have to be capitalized?

Regex:  /^[A-Z][A-Za-z]+$/m


# Capture first, middle, and last name

Regex:  /^([A-Z][A-Za-z.'\-]+) (?:([A-Z][A-Za-z.'\-]+) )?([A-Z][A-Za-z.'\-]+)$/m

------------

# U.S. postal codes

Regex:  /^\d{5}(-\d{4})?$/m


# Canada postal codes

Regex:  /^[A-Z]\d[A-Z] \d[A-Z]\d$/m

------------

# Email and domain specifications allow other characters

Regex:  /^[\w.%+\-]+@[\w.\-]+\.[A-Za-z]{2,3}$/


Regex:  /^[\w.%+\-]+@[\w.\-]+\.[A-Za-z]{2,6}$/

String: "someone@somewhere.museum"

------------

# Query string portion

Regex:  /^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+.*$/

Regex:  /^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+[/?#]?.*$/

Regex:  /^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+[\w\-.,@?^=%&:/~\\+#]*$/


# Make groups non-capturing

Regex:  /^(?:http|https):\/\/[\w\-_]+(?:\.[\w\-_]+)+[\w\-.,@?^=%&:/~\\+#]*$/

------------

# Decimal numbers

Regex:  /^\d+\.\d+$/m

Regex:  /^\d?\.\d+$/m

Regex:  /^\d*\.?\d*$/m


# U.S. Dollar

Regex:  /^\$(\d*\.\d{2}|\d+)$/m

------------

# 12 hour time

Regex:  /^(0?[1-9]|1[0-2]):[0-5][0-9]$/m


# Optional am/pm


Regex:  /^(0?[1-9]|1[0-2]):[0-5][0-9](am|pm|AM|PM)?$/m

Regex:  /^(0?[1-9]|1[0-2]):[0-5][0-9]([aApP][mM])?$/m


Timezone


Regex:  /^([0-1]?[0-9]|[2][0-3]):[0-5][0-9](:[0-5][0-9])?( [A-Z]{3})?$/m

Regex:  /^([0-1]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?( ([A-Z]{3}|GMT [-+]([0-9]|1[0-2])))?$/m

------------

.Any character except newline.
\.A period (and so on for \*, \(, \\, etc.)
^The start of the string.
$The end of the string.
\d,\w,\sA digit, word character [A-Za-z0-9_], or whitespace.
\D,\W,\SAnything except a digit, word character, or whitespace.
[abc]Character a, b, or c.
[a-z]a through z.
[^abc]Any character except a, b, or c.
aa|bbEither aa or bb.
?Zero or one of the preceding element.
*Zero or more of the preceding element.
+One or more of the preceding element.
{n}Exactly n of the preceding element.
{n,}n or more of the preceding element.
{m,n}Between m and n of the preceding element.
??,*?,+?,
{n}?, etc.
Same as above, but as few as possible.
(expr)Capture expr for use with \1, etc.
(?:expr)Non-capturing group.
(?=expr)Followed by expr.
(?!expr)Not followed by expr.

------------

Regular expression cheat sheet

Special characters

\escape special characters
.matches any character
^matches beginning of string
$matches end of string
[5b-d]matches any chars '5', 'b', 'c' or 'd'
[^a-c6]matches any char except 'a', 'b', 'c' or '6'
R|Smatches either regex R or regex S
()creates a capture group and indicates precedence

Quantifiers

*0 or more (append ? for non-greedy)
+1 or more (append ? for non-greedy)
?0 or 1 (append ? for non-greedy)
{m}exactly mm occurrences
{m, n}from m to nm defaults to 0, n to infinity
{m, n}?from m to n, as few as possible

Special sequences

\Astart of string
\bmatches empty string at word boundary (between \wand \W)
\Bmatches empty string not at word boundary
\ddigit
\Dnon-digit
\swhitespace: [ \t\n\r\f\v]
\Snon-whitespace
\walphanumeric: [0-9a-zA-Z_]
\Wnon-alphanumeric
\Zend of string
\g<id>matches a previously defined group

Special sequences

(?iLmsux)matches empty string, sets re.X flags
(?:...)non-capturing version of regular parentheses
(?P...)matches whatever matched previously named group
(?P=)digit
(?#...)a comment; ignored
(?=...)lookahead assertion: matches without consuming
(?!...)negative lookahead assertion
(?<=...)lookbehind assertion: matches if preceded
(?<!...)negative lookbehind assertion
(?(id)yes|no)match 'yes' if group 'id' matched, else 'no'


------------

Unicode

Unicode indicator: \u

caf\u00E9 = cafe (e is unicode)


Unicode wildcard : \X (only for Perl and PHP)


------------


-----------


-----------

'Programming' 카테고리의 다른 글

Python - Date, Time  (0) 2015.09.29
Python with Django  (0) 2015.09.26
Book - EXCEL Hacks  (0) 2015.09.24
file/directory 비교 tool - Meld  (0) 2015.09.24
git 과 repo  (0) 2015.09.19
Posted by 쁘레드
Programming2015. 9. 24. 10:49

EXCEL하면

  • Finding/removing duplicates
  • Sorting
  • Filtering
  • Conditional formatting
  • Pivot table
  • vlookup() 응용


오늘은 EXCEL Hacks 라는 책을 봤습니다. 오래 볼것은 아니고 스스로 필요한 부분만 빨리 습득하면 될만한 책인데, 상당히 유용한 tip들을 많이가지고 있습니다.


------------

EXCEL conditional formatting이라는 메뉴가 있습니다. 이미 free define되어 있는 기능도 있는데 duplicate를 highlight해주는게 있습니다

Data에서 remove duplicates과는 다르게 유용합니다.


conditional formatting으로 every row마다 다른 background도 표시할수 있고

------------

두 table차이 비교하기

1. =A1=A19 처럼TRUE or FALSE로 찾기

2. Conditional formatting으로 =NOT(A1=A9) 때 color표시하기

------------

VLOOKUP 으로 이전 리스트와 비교하기

=VLOOKUP(VALUE, TABLE_RANGE, COLUME_from_the_table, 0)

=VLOOKUP(C1,F1:H13,1,0)


TIP: drag해도 range를 변하지 않게 하려면 절대 range를 넣어준다.

L1:L5 vs $L$1:$L$5

------------

이미 순서 정해진 array에서 그 subset이 주어지면 그 mother array의 순서에 맞게 sub-array를 sorting

==>이것도 VLOOKUP을 이용해서

=VLOOKUP(K2, $L$2:$L$6,1,0)


기준 subset 결과 모범답
Fred Joe Fred Fred
Joe Fred Joe Dave
Dave Dave Dave Joe
James Tania #N/A Mett
Joe Mett Joe Tania
Minsu #N/A
Mett Mett
Robyn #N/A
Marlene #N/A
Tania Tania
Jill #N/A
Jill #N/A

------------


------------

'Programming' 카테고리의 다른 글

Python with Django  (0) 2015.09.26
Regular Expression  (0) 2015.09.25
file/directory 비교 tool - Meld  (0) 2015.09.24
git 과 repo  (0) 2015.09.19
bash alias  (0) 2015.09.19
Posted by 쁘레드
Programming2015. 9. 24. 02:24

Windows에서는 Beyond Compare를 오래동안 썼는데,

Meld는 open source로 된 tool인데 상당히 좋네요. Linux, WIndows지원

윈도우즈는 설치파일로 잘 될것 같은데, 리눅스는 이놈의 GTK+ 버전때문에 오래된 리눅스는 안되고 아주 복잡하네요. Open Source/Linux가 더 크게 성장못하는 좋은 예이기도 한네요. 엄청좋은데 사용자를 계속 짜증나게 하는것이죠.

http://meldmerge.org/


Requirements

  • Python 2.7 (Python 3 not yet supported)
  • GTK+ 3.12
  • GLib 2.36
  • PyGObject 3.8
  • GtkSourceView 3.10

-----------


'Programming' 카테고리의 다른 글

Regular Expression  (0) 2015.09.25
Book - EXCEL Hacks  (0) 2015.09.24
git 과 repo  (0) 2015.09.19
bash alias  (0) 2015.09.19
codeaurora.org and linaro.org  (0) 2015.09.13
Posted by 쁘레드

폭시바겐 자동차 사태로 폭스바겐 자동차 주가가 떨어지는것은 물론 관련 자동차 산업 전체가 내려가고 있고, 연관된 부품업체도 추락하고 있습니다.

플래티넘 가격이 폭락한다고 해서 읽어보니 디젤 엔진에 플레티넘이 많이 들어간다고 하네요. 헐~




Update: 6개월간 주가가 반토막 됐네요. 아래 그림은 폭스바겐 몇달동안 주가 그래프와 토요타와 비교

전체 자동차 섹터가 이번 사태로 떨어지고 있습니다. 밥맛떨어졌으니 다들 밥먹고 싶은 생각이 없는거지요.

예전에 삼성 갤럭시폰이 성능을 조작하려고 벤치마크 프로그램이 돌때는 클락을 올려는 치팅을 하다가 걸렸지만 신뢰성은 또 타격입었지만 주가가 반토막 된다든지 큰 별일없었지요. 사실 모든 업체들이 그런 보이지 않는 치팅에 대해서 연구를 하는데 폭스바겐은 이번 치팅이 소비자를 우롱한것과 환경에 치명타를 줬다는 것, 관련법규를 어겼다는 것 때문에 리콜/벌금 비용이 상상을 초월할듯. 그래서 50%주가하락에도 짧은 시간에 회복되기가 싶지 않을것 같네요.



---------

LONDON—The price of platinum, widely used in diesel car engines, could fall below $900 a troy ounce for the first time since the financial crisis in the wake of the emissions scandal at VolkswagenAG, according to some metals investors and analysts.

Spot platinum fell heavily on Tuesday and hit a near seven-year low on Wednesday at $929.08 a troy ounce, before recovering slightly to $932.25, as some questioned whether the affair would have a lasting effect on demand for diesel cars.

Investors are worried that car buyers will switch from diesel engines to gasoline or electric cars, hitting demand for platinum, said David Govett, head of precious metals trading at Marex Spectron. Gasoline engines typically don’t use platinum.

Posted by 쁘레드