code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
s = i = 0
while True:
term = 1.0 / (i*2+1)
s += term * ((-1)**i)
if term < 1e-6: break
i += 1
print "%.6lf" % s
| Python |
from sys import stdin
from decimal import *
a, b, c = map(int, stdin.readline().strip().split())
getcontext().prec = c
print Decimal(a) / Decimal(b)
| Python |
from sys import stdin
n = int(stdin.readline().strip())
print "%.3lf" % sum([1.0/x for x in range(1,n+1)])
| Python |
from sys import stdin
print len(stdin.readline().strip())
| Python |
from itertools import product
from math import *
def issqrt(n):
s = int(floor(sqrt(n)))
return s*s == n
aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))]
print ' '.join(map(str, filter(issqrt, aabb)))
| Python |
from sys import stdin
a = map(int, stdin.readline().strip().split())
print "%d %d %.3lf" % (min(a), max(a), float(sum(a)) / len(a))
| Python |
from sys import stdin
def cycle(n):
if n == 1: return 0
elif n % 2 == 1: return cycle(n*3+1) + 1
else: return cycle(n/2) + 1
n = int(stdin.readline().strip())
print cycle(n)
| Python |
from sys import stdin
n = int(stdin.readline().strip())
count = n*2-1
for i in range(n):
print ' '*i + '#'*count
count -= 2
| Python |
for abc in range(123, 329):
big = str(abc) + str(abc*2) + str(abc*3)
if(''.join(sorted(big)) == '123456789'): print abc, abc*2, abc*3
| Python |
from sys import stdin
n, m = map(int, stdin.readline().strip().split())
print "%.5lf" % sum([1.0/i/i for i in range(n,m+1)])
| Python |
from sys import stdin
data = map(int, stdin.readline().strip().split())
n, m = data[0], data[-1]
data = data[1:-1]
print len(filter(lambda x: x < m, data))
| Python |
from sys import stdin
def solve(a, b, c):
for i in range(10, 101):
if i % 3 == a and i % 5 == b and i % 7 == c:
print i
return
print 'No answer'
a, b, c = map(int, stdin.readline().strip().split())
solve(a, b, c)
| Python |
from itertools import product
sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c]
print '\n'.join(map(str, sol))
| Python |
from sys import stdin
from math import *
n = int(stdin.readline().strip())
print sum(map(factorial, range(1,n+1))) % (10**6)
| Python |
from sys import stdin
a, b, c = map(int, stdin.readline().strip().split())
print "%.3lf" % ((a+b+c)/3.0)
| Python |
from sys import stdin
from math import *
r, h = map(float, stdin.readline().strip().split())
print "Area = %.3lf" % (pi*r*r*2 + 2*pi*r*h)
| Python |
from sys import stdin
from math import *
n, = map(int, stdin.readline().strip().split())
rad = radians(n)
print "%.3lf %.3lf" % (sin(rad), cos(rad))
| Python |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
print n*(n+1)/2
| Python |
from sys import stdin
a, b = map(int, stdin.readline().strip().split())
print b, a
| Python |
from sys import stdin
n, m = map(int, stdin.readline().strip().split())
a = (4*n-m)/2
b = n-a
if m % 2 == 1 or a < 0 or b < 0: print "No answer"
else: print a, b
| Python |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
money = n * 95
if money >= 300: money *= 0.85
print "%.2lf" % money
| Python |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
print ["yes", "no"][n % 2]
| Python |
from sys import stdin
from math import *
x1, y1, x2, y2 = map(float, stdin.readline().strip().split())
print "%.3lf" % hypot((x1-x2), (y1-y2))
| Python |
from sys import stdin
n = stdin.readline().strip().split()[0]
print '%c%c%c' % (n[2], n[1], n[0])
| Python |
from sys import stdin
x, = map(float, stdin.readline().strip().split())
print abs(x)
| Python |
from sys import stdin
from calendar import isleap
year, = map(int, stdin.readline().strip().split())
if isleap(year): print "yes"
else: print "no"
| Python |
from sys import stdin
f, = map(float, stdin.readline().strip().split())
print "%.3lf" % (5*(f-32)/9)
| Python |
from sys import stdin
a, b, c = map(int, stdin.readline().strip().split())
if a*a + b*b == c*c or a*a + c*c == b*b or b*b + c*c == a*a: print "yes"
elif a + b <= c or a + c <= b or b + c <= a: print "not a triangle"
else: print "no"
| Python |
from sys import stdin
a = map(int, stdin.readline().strip().split())
a.sort()
print a[0], a[1], a[2]
| Python |
s = i = 0
while True:
term = 1.0 / (i*2+1)
s += term * ((-1)**i)
if term < 1e-6: break
i += 1
print "%.6lf" % s
| Python |
from sys import stdin
from decimal import *
a, b, c = map(int, stdin.readline().strip().split())
getcontext().prec = c
print Decimal(a) / Decimal(b)
| Python |
from sys import stdin
n = int(stdin.readline().strip())
print "%.3lf" % sum([1.0/x for x in range(1,n+1)])
| Python |
from sys import stdin
print len(stdin.readline().strip())
| Python |
from itertools import product
from math import *
def issqrt(n):
s = int(floor(sqrt(n)))
return s*s == n
aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))]
print ' '.join(map(str, filter(issqrt, aabb)))
| Python |
from sys import stdin
a = map(int, stdin.readline().strip().split())
print "%d %d %.3lf" % (min(a), max(a), float(sum(a)) / len(a))
| Python |
from sys import stdin
def cycle(n):
if n == 1: return 0
elif n % 2 == 1: return cycle(n*3+1) + 1
else: return cycle(n/2) + 1
n = int(stdin.readline().strip())
print cycle(n)
| Python |
from sys import stdin
n = int(stdin.readline().strip())
count = n*2-1
for i in range(n):
print ' '*i + '#'*count
count -= 2
| Python |
for abc in range(123, 329):
big = str(abc) + str(abc*2) + str(abc*3)
if(''.join(sorted(big)) == '123456789'): print abc, abc*2, abc*3
| Python |
from sys import stdin
n, m = map(int, stdin.readline().strip().split())
print "%.5lf" % sum([1.0/i/i for i in range(n,m+1)])
| Python |
from sys import stdin
data = map(int, stdin.readline().strip().split())
n, m = data[0], data[-1]
data = data[1:-1]
print len(filter(lambda x: x < m, data))
| Python |
from sys import stdin
def solve(a, b, c):
for i in range(10, 101):
if i % 3 == a and i % 5 == b and i % 7 == c:
print i
return
print 'No answer'
a, b, c = map(int, stdin.readline().strip().split())
solve(a, b, c)
| Python |
from itertools import product
sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c]
print '\n'.join(map(str, sol))
| Python |
from sys import stdin
from math import *
n = int(stdin.readline().strip())
print sum(map(factorial, range(1,n+1))) % (10**6)
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
# @author Sam Pullara, samp@yahoo-inc.com
import logging
import wsgiref.handlers
import os
from google.appengine.ext.webapp import template
from datetime import datetime
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import users
from yos.boss.ysearch import search
from yos.boss.ysearch import suggest
from yos.boss.ysearch import glue
from yos.crawl.rest import load_json
from yos.crawl.rest import load_xml
from django.utils import simplejson
from urllib import quote_plus
from types import *
from google.appengine.api import memcache
class Search(webapp.RequestHandler):
def get(self):
q = self.request.get("q")
m = self.request.get("m")
if q:
start = self.request.get("p")
query = q
if m:
query = m
if start:
result = search(query, count=10, start=int(start))
images = search(query, vertical="images", count=1, start=int(start), filter="yes")
else:
result = search(query, count=10)
images = search(query, vertical="images", count=1, filter="yes")
resultset_glue = glue(q)
ysr = result['ysearchresponse']
if ysr.has_key('resultset_web'):
results = ysr['resultset_web']
template_values = {
'query': q,
'totalhits': int(ysr['totalhits']) + int(ysr['deephits']),
'results': results,
'stats': memcache.get_stats()
}
if images:
image_response = images['ysearchresponse']
if int(image_response['count']) > 0:
template_values['image'] = image_response['resultset_images'][0]
if resultset_glue:
categories = []
if resultset_glue.has_key('glue') and resultset_glue['glue'].has_key('navbar'):
navbars = resultset_glue['glue']['navbar']
if navbars:
for navbar in navbars:
if isinstance(navbar, DictType):
if navbar.has_key('navEntry'):
if navbar['type'] == 'disambiguation':
navEntries = navbar['navEntry']
if isinstance(navEntries, DictType):
categories.append(navEntries)
else:
for navEntry in navEntries:
categories.append(navEntry)
template_values['categories'] = categories
if m:
template_values['category'] = m.replace(" ", "%20")
if start and int(start) != 0:
template_values['start'] = start
template_values['prev'] = int(start) - 10
template_values['next'] = int(start) + 10
else:
template_values['next'] = 10
path = os.path.join(os.path.dirname(__file__), "search.html")
self.response.out.write(template.render(path, template_values))
else:
template_values = {
'query': q,
}
path = os.path.join(os.path.dirname(__file__), "empty.html")
self.response.out.write(template.render(path, template_values))
else:
self.redirect("/")
class Suggest(webapp.RequestHandler):
def get(self):
q = self.request.get("q")
if q:
suggests = suggest(q)
self.response.headers['Content-Type'] = 'application/json'
resultset = suggests['ResultSet']
if isinstance(resultset, DictType):
self.response.out.write("{ 'Results':[")
results = resultset['Result']
for result in results:
self.response.out.write("{'v':'" + result + "'},")
self.response.out.write("{}] }")
else:
self.response.out.write("{ 'Results':[]}")
class Index(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), "index.html")
self.response.out.write(template.render(path, None))
def main():
application = webapp.WSGIApplication([('/', Index),
('/search', Search),
('/suggest', Suggest)
],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == "__main__":
main()
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
""" A simple text library for normalizing, cleaning, and overlapping strings """
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
STOPWORDS = set(["I", "a", "about", "an", "are", "as", "at", "be", "by", "com", "de", "en", "for", "from",
"how", "in", "is", "it", "it's", "la", "of", "on", "or", "that", "the", "this", "to", "was",
"what", "when", "where", "who", "will", "with", "und", "the", "to", "www", "your", "you're"])
def strip_enclosed_carrots(s):
i = s.find("<")
if i >= 0:
j = s.find(">", i)
if j > i:
j1 = j + 1
if j1 >= len(s):
return strip_enclosed_carrots(s[:i])
else:
return strip_enclosed_carrots(s[:i] + s[j1:])
return s
def filter_stops(words):
return filter(lambda w: w not in STOPWORDS, words)
def uniques(s):
return set( tokenize(s) )
def tokenize(s):
return filter_stops(map(lambda t: t.lower().strip("\'\"`,.;-!"), s.split()))
def norm(s):
return "".join( sorted( tokenize(s) ) )
def overlap(s1, s2):
return len(uniques(s1) & uniques(s2))
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__all__ = ["console", "text", "typechecks"]
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
from yos.crawl import object_dict
from types import DictType, ListType, TupleType
OBJ_DICT_TYPE = type(object_dict.object_dict())
def is_dict(td):
return td is DictType or td is OBJ_DICT_TYPE
def is_ordered(to):
return to is ListType or to is TupleType
def is_list(o):
return o is ListType
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
def strfix(msg):
"""
Copies this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523011
Constants out any characters that spew encoding errors
"""
goodchars = {}
try:
return str(msg)
except UnicodeEncodeError:
res=''
for i in list(msg):
if i not in goodchars:
try:
str(i)
goodchars[i] = i
except UnicodeEncodeError:
# format character as python string constant
code = ord(i)
t = None
if code < 256:
t ='\\x%02x' % code # 8-bit value
elif code < 65536:
t ='\\u%04x' % code # 16-bit value unicode
else:
t = '\\U%08x' % code # other values as 32-bit unicode
goodchars[i] = t # or '.' for readability ;-)
res += goodchars[i]
return res
def write(msg):
print strfix(msg)
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
"""
This is the Boss search API
search is the main function
Examples:
web_results = search("britney spears")
news_20_results = search("tiger woods", vertical="news", count=20)
"""
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
import types
import urllib
import datetime
from django.utils import simplejson
from yos.crawl import rest
from yos.crawl import xml2dict
from google.appengine.api import memcache
CONFIG = simplejson.load(open("config.json", "r"))
SEARCH_API_URL = CONFIG["uri"].rstrip("/") + "/%s/v%d/%s?start=%d&count=%d&lang=%s®ion=%s&filter=%s" + "&appid=" + CONFIG["appid"]
SUGGEST_API_URL = "http://search.yahooapis.com/WebSearchService/V1/relatedSuggestion?output=json&query=%s&appid=" + CONFIG["appid"]
GLUE_API_URL = glueurl = "http://glue.yahoo.com/template/index.php?query=%s"
def params(d):
""" Takes a dictionary of key, value pairs and generates a cgi parameter/argument string """
p = ""
for k, v in d.iteritems():
p += "&%s=%s" % (iri_to_uri(k), iri_to_uri(v))
return p
def search(command, vertical="web", version=1, start=0, count=10, lang="en", region="us", filter="-porn-hate", more={}):
"""
command is the query (not escaped)
vertical can be web, news, spelling, images
lang/region default to en/us - take a look at the the YDN Boss documentation for the supported lang/region values
"""
url = SEARCH_API_URL % (vertical, version, iri_to_uri(command), start, count, lang, region, filter) + params(more)
data = load(url)
if data:
return simplejson.loads(data)
def suggest(query):
url = SUGGEST_API_URL % iri_to_uri(query)
data = load(url)
if data:
return simplejson.loads(data)
def glue(query):
url = GLUE_API_URL % iri_to_uri(query)
data = load(url)
if data:
return xml2dict.fromstring(data)
def load(url):
data = memcache.get(url)
if data is not None:
return data
data = rest.download(url)
if data:
memcache.set(url, data, 3600)
return data
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if strings_only and isinstance(s, (types.NoneType, int)):
return s
elif not isinstance(s, basestring):
try:
return str(s)
except UnicodeEncodeError:
return unicode(s).encode(encoding, errors)
elif isinstance(s, unicode):
return s.encode(encoding, errors)
elif s and encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)
else:
return s
def iri_to_uri(iri):
"""
Convert an Internationalized Resource Identifier (IRI) portion to a URI
portion that is suitable for inclusion in a URL.
This is the algorithm from section 3.1 of RFC 3987. However, since we are
assuming input is either UTF-8 or unicode already, we can simplify things a
little from the full method.
Returns an ASCII string containing the encoded result.
"""
# The list of safe characters here is constructed from the printable ASCII
# characters that are not explicitly excluded by the list at the end of
# section 3.1 of RFC 3987.
if iri is None:
return iri
return urllib.quote(smart_str(iri), safe='/#%[]=:;$&()+,!?*')
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__all__ = ["ysearch"]
| Python |
#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-
""" Dictionary to XML - Library to convert a python dictionary to XML output
Copyleft (C) 2007 Pianfetti Maurizio <boymix81@gmail.com>
Package site : http://boymix81.altervista.org/files/dict2xml.tar.gz
Revision 1.0 2007/12/15 11:57:20 Maurizio
- First stable version
"""
__author__ = "Pianfetti Maurizio <boymix81@gmail.com>"
__contributors__ = []
__date__ = "$Date: 2007/12/15 11:57:20 $"
__credits__ = """..."""
__version__ = "$Revision: 1.0.0 $"
class Dict2XML:
#XML output
xml = ""
#Tab level
level = 0
def __init__(self):
self.xml = ""
self.level = 0
#end def
def __del__(self):
pass
#end def
def setXml(self,Xml):
self.xml = Xml
#end if
def setLevel(self,Level):
self.level = Level
#end if
def dict2xml(self,map):
if (str(type(map)) == "<class 'object_dict.object_dict'>" or str(type(map)) == "<type 'dict'>"):
for key, value in map.items():
if (str(type(value)) == "<class 'object_dict.object_dict'>" or str(type(value)) == "<type 'dict'>"):
if(len(value) > 0):
self.xml += "\t"*self.level
self.xml += "<%s>\n" % (key)
self.level += 1
self.dict2xml(value)
self.level -= 1
self.xml += "\t"*self.level
self.xml += "</%s>\n" % (key)
else:
self.xml += "\t"*(self.level)
self.xml += "<%s></%s>\n" % (key,key)
#end if
else:
self.xml += "\t"*(self.level)
self.xml += "<%s>%s</%s>\n" % (key,value, key)
#end if
else:
self.xml += "\t"*self.level
self.xml += "<%s>%s</%s>\n" % (key,value, key)
#end if
return self.xml
#end def
#end class
def createXML(dict,xml):
xmlout = Dict2XML()
xmlout.setXml(xml)
return xmlout.dict2xml(dict)
#end def
dict2Xml = createXML
if __name__ == "__main__":
#Define the dict
d={}
d['root'] = {}
d['root']['v1'] = "";
d['root']['v2'] = "hi";
d['root']['v3'] = {};
d['root']['v3']['v31']="hi";
#xml='<?xml version="1.0"?>\n'
xml = ""
print dict2Xml(d,xml)
#end if | Python |
#!/usr/local/bin/python25
# Thunder Chen<nkchenz@gmail.com> 2007.9.1
#
#
import xml.etree.ElementTree as ET
from object_dict import object_dict
def __parse_node(node):
tmp = object_dict()
# save attrs and text, hope there will not be a child with same name
if node.text:
tmp['value'] = node.text
for (k,v) in node.attrib.items():
tmp[k] = v
for ch in node.getchildren():
cht = ch.tag
chp = __parse_node(ch)
if cht not in tmp: # the first time, so store it in dict
tmp[cht] = chp
continue
old = tmp[cht]
if not isinstance(old, list):
tmp.pop(cht)
tmp[cht] = [old] # multi times, so change old dict to a list
tmp[cht].append(chp) # add the new one
return tmp
def parse(file):
"""parse a xml file to a dict"""
f = open(file, 'r')
t = ET.parse(f).getroot()
return object_dict({t.tag: __parse_node(t)})
def fromstring(s):
"""parse a string"""
t = ET.fromstring(s)
return object_dict({t.tag: __parse_node(t)})
if __name__ == '__main__':
s = """<?xml version="1.0" encoding="utf-8" ?>
<result>
<count n="1">10</count>
<data><id>491691</id><name>test</name></data>
<data><id>491692</id><name>test2</name></data>
<data><id>503938</id><name>hello, world</name></data>
</result>"""
r = fromstring(s)
import pprint
pprint.pprint(r)
print r.result.count.value
print r.result.count.n
for data in r.result.data:
print data.id, data.name
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
""" Functions for downloading REST API's and converting their responses into dictionaries """
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
import logging
import xml2dict
from django.utils import simplejson
from google.appengine.api import urlfetch
HEADERS = {"User-Agent": simplejson.load(open("config.json", "r"))["agent"]}
def download(url):
result = urlfetch.fetch(url)
if result.status_code == 200:
return result.content
def load_json(url):
return simplejson.loads(download(url))
def load_xml(url):
return xml2dict.fromstring(download(url))
def load(url):
dl = download(url)
try:
return simplejson.loads(dl)
except:
return xml2dict.fromstring(dl)
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__all__ = ["dict2xml", "object_dict", "rest", "xml2dict"]
| Python |
# object_dict
# Thunder Chen<nkchenz@gmail.com> 2007
# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
class object_dict(dict):
"""object view of dict, you can
>>> a = object_dict()
>>> a.fish = 'fish'
>>> a['fish']
'fish'
>>> a['water'] = 'water'
>>> a.water
'water'
>>> a.test = {'value': 1}
>>> a.test2 = object_dict({'name': 'test2', 'value': 2})
>>> a.test, a.test2.name, a.test2.value
(1, 'test2', 2)
"""
def __init__(self, initd=None):
if initd is None:
initd = {}
dict.__init__(self, initd)
def __getattr__(self, item):
d = self.__getitem__(item)
# if value is the only key in object, you can omit it
if isinstance(d, dict) and 'value' in d and len(d) == 1:
return d['value']
else:
return d
def __setattr__(self, item, value):
self.__setitem__(item, value)
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
| Python |
#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-
""" Dictionary to XML - Library to convert a python dictionary to XML output
Copyleft (C) 2007 Pianfetti Maurizio <boymix81@gmail.com>
Package site : http://boymix81.altervista.org/files/dict2xml.tar.gz
Revision 1.0 2007/12/15 11:57:20 Maurizio
- First stable version
"""
__author__ = "Pianfetti Maurizio <boymix81@gmail.com>"
__contributors__ = []
__date__ = "$Date: 2007/12/15 11:57:20 $"
__credits__ = """..."""
__version__ = "$Revision: 1.0.0 $"
class Dict2XML:
#XML output
xml = ""
#Tab level
level = 0
def __init__(self):
self.xml = ""
self.level = 0
#end def
def __del__(self):
pass
#end def
def setXml(self,Xml):
self.xml = Xml
#end if
def setLevel(self,Level):
self.level = Level
#end if
def dict2xml(self,map):
if (str(type(map)) == "<class 'object_dict.object_dict'>" or str(type(map)) == "<type 'dict'>"):
for key, value in map.items():
if (str(type(value)) == "<class 'object_dict.object_dict'>" or str(type(value)) == "<type 'dict'>"):
if(len(value) > 0):
self.xml += "\t"*self.level
self.xml += "<%s>\n" % (key)
self.level += 1
self.dict2xml(value)
self.level -= 1
self.xml += "\t"*self.level
self.xml += "</%s>\n" % (key)
else:
self.xml += "\t"*(self.level)
self.xml += "<%s></%s>\n" % (key,key)
#end if
else:
self.xml += "\t"*(self.level)
self.xml += "<%s>%s</%s>\n" % (key,value, key)
#end if
else:
self.xml += "\t"*self.level
self.xml += "<%s>%s</%s>\n" % (key,value, key)
#end if
return self.xml
#end def
#end class
def createXML(dict,xml):
xmlout = Dict2XML()
xmlout.setXml(xml)
return xmlout.dict2xml(dict)
#end def
dict2Xml = createXML
if __name__ == "__main__":
#Define the dict
d={}
d['root'] = {}
d['root']['v1'] = "";
d['root']['v2'] = "hi";
d['root']['v3'] = {};
d['root']['v3']['v31']="hi";
#xml='<?xml version="1.0"?>\n'
xml = ""
print dict2Xml(d,xml)
#end if | Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__all__ = ["boss", "crawl", "yql"]
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
"""
Make python more SQL like over REST responses
main entry functions are create and select
The goal here is to let the developer specify a data structure via a REST URI
or a list of dictionaries (lod) using select or create
These functions infer the structure automatically and converts the input into a unified data format (lod)
One can call on the result table the describe() method to see in stdout what the schema is to double check
If one has the data in lod format already, then pass it to the data parameter of create or select
This library provides functional libraries for doing
select, group, sort, inner_join, outer_join, cross, union, describe
on these resulting tables
See below for the join functions - more documentation there
A Quick Example (see examples directory for more involved ones)
from yos.yql import db
from yos.yql import udfs
dl = db.create(name="dl", url="http://del.icio.us/rss/popular/iphone")
dl.describe()
dl = db.select(udf=udfs.unnest_value, table=dl)
"""
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
import copy
from operator import itemgetter
import random
from asizeof import relsize
import simplejson
from util.typechecks import is_dict, is_list, is_ordered
from yos.crawl import dict2xml
from yos.crawl import rest
NAMESPACE_CHAR = "$"
def infer_collection_ordered_helper(l, cands):
for vo in l:
tv = type(vo)
if is_ordered(tv):
if is_list(vo) and is_dict(type(v[0])):
cands.append(vo)
else:
infer_collection_ordered_helper(vo, cands)
elif is_dict(tv):
infer_collection_dict_helper(vo, cands)
def infer_collection_dict_helper(d, cands):
for k, vd in d.iteritems():
tv = type(vd)
if is_ordered(tv):
if is_list(tv) and is_dict(type(vd[0])):
cands.append(vd)
else:
infer_collection_ordered_helper(vd, cands)
elif is_dict(tv):
infer_collection_dict_helper(vd, cands)
def infer_collection(d):
if is_list(type(d)):
return d
cands = []
for k, v in d.iteritems():
tv = type(v)
if is_ordered(tv):
if is_list(tv) and len(v) > 0 and is_dict(type(v[0])):
cands.append(v)
elif is_dict(tv):
infer_collection_dict_helper(v, cands)
if len(cands) > 0:
return sorted(map(lambda c: (c, relsize(c)), cands), key=itemgetter(1), reverse=True)[0][0]
else:
return []
def prep_name(name, c):
nc = []
for d in c:
results = {}
for k, v in d.iteritems():
if k.find(NAMESPACE_CHAR) >= 0:
results[k] = v
else:
results[name + NAMESPACE_CHAR + k] = v
nc.append(results)
return nc
def strip_prep(name):
ni = name.find(NAMESPACE_CHAR)
if ni > 0:
return name[ni+1:]
else:
return name
def strip_row(row):
rows = [{}]
for k, v in row.iteritems():
nn = strip_prep(k)
i = 0
while i < len(rows):
ri = rows[i]
if nn not in ri:
ri[nn] = v
break
elif i == len(rows):
rows.append({})
i += 1
return rows
STANDARDS_PREFIX = "{http://"
STANDARDS_SUFFIX = "}"
def remove_standards_prefix(k):
kp = k.find(STANDARDS_PREFIX)
if kp >= 0:
ks = k.find(STANDARDS_SUFFIX, kp + 1)
if ks >= 0 and ks < len(k) - 1:
return k[0:kp] + k[ks+1:]
return k
def standardize_tags_helper(d):
nd = {}
for k, v in d.iteritems():
if is_dict(type(v)):
cd = standardize_tags_helper(v)
else:
cd = v
nd[remove_standards_prefix(k)] = cd
return nd
def standardize_tags(collection):
nc = []
for d in collection:
nc.append(standardize_tags_helper(d))
return nc
class WebTable:
def __init__(self, name, d, keep_standards_prefix):
self.name = name.strip()
ic = infer_collection(d)
if not keep_standards_prefix:
ic = standardize_tags(ic)
if len(self.name) > 0:
ic = prep_name(name, ic)
self.rows = ic
def rename(self, before, after):
bn = self.name + NAMESPACE_CHAR + before
an = self.name + NAMESPACE_CHAR + after
for d in self.rows:
if bn in d:
value = copy.copy(d[bn])
del d[bn]
d[an] = value
def describe(self):
print "\n"
print "TABLENAME: %s, # RECORDS: %d" % (self.name, self.__len__())
if len(self.rows) == 0:
return
c = self.rows[0]
for k, v in c.iteritems():
print "\tOUTER KEY:", k
if is_dict(type(v)):
print "\t INNER KEYS:"
print "\t ", v.keys(), "\n"
def dumps(self, format="json"):
if format == "json":
return simplejson.dumps(self.rows)
elif format == "xml":
return dict2xml.dict2Xml({self.name: self.rows})
elif format == "opensearch":
raise Error, "opensearch dumps needs to be implemented!"
def dump(self, f, format="json"):
open(f, "w").write(self.dumps(format))
def __len__(self):
return len(self.rows)
def create(name="", data=None, url=None, keep_standards_prefix=False):
if data is not None:
return WebTable(name, d=data, keep_standards_prefix=keep_standards_prefix)
elif url is not None:
return WebTable(name, d=rest.load(url), keep_standards_prefix=keep_standards_prefix)
def postcreate(data):
return WebTable(name="", d=data, keep_standards_prefix=True)
def select(udf, name="", url=None, table=None, data=None, keep_standards_prefix=False):
if table is not None:
tb = table
keep_standards_prefix = True
if len(name) == 0:
name = tb.name
else:
tb = create(name, data=data, url=url, keep_standards_prefix=keep_standards_prefix)
results = []
for d in tb.rows:
try:
value = udf(d)
except KeyError:
try:
value = udf(strip_row(d)[0])
except KeyError:
continue
if is_dict(type(value)):
results.append(value)
return create(name=name, data=results, keep_standards_prefix=keep_standards_prefix)
def union(name, tables):
data = []
for t in tables:
rows = t.rows
for d in rows:
nd = {}
for k, v in d.iteritems():
nd[strip_prep(k)] = v
data.append(nd)
return create(name=name, data=data)
def sort(key, table, order="desc", count=None):
nc = []
for c in table.rows:
if key in c:
nc.append( (c, c[key]) )
else:
nc.append( (c, None) )
rv = True
if order == "asc":
rv = False
if count is None:
return postcreate(data=[c for c, s in sorted(nc, key=itemgetter(1), reverse=rv)])
else:
return postcreate(data=[c for c, s in sorted(nc, key=itemgetter(1), reverse=rv)[:count]])
def identity(x):
return x
def group(by, key, reducer, as, table, norm=identity, unique=True):
if not is_ordered(type(by)):
by = [by]
r = {}
for row in table.rows:
thk = []
for b in by:
if b in row:
thk.append(norm(row[b]))
else:
thk.append(None)
thk = tuple(thk)
if thk in r:
r[thk].append(row)
else:
r[thk] = [row]
answer = []
for thk, rows in r.iteritems():
try:
nr = []
for r in rows:
if key in r:
nr.append(r[key])
asv = reduce(reducer, nr)
except:
asv = None
if unique:
r = rows[0]
r[as] = asv
answer.append(r)
else:
for r in rows:
r[as] = asv
answer.append(r)
return postcreate(data=answer)
"""
When using yos.yql.db, keep in mind that for join calls
like join (inner_join), outer_join (left_outer_join)
that the first parameter (predicate function) should operate on row keys assuming no namespacing
like row['yn$title'] => should be row['title'] within the predicate function code
This is because the predicate function is being applied like a map function,
so the order of the tables input (second parameter) does not matter
It also doesn't make sense when the number of tables exceeds 2
as a predicate function only operates on records from two tables at a time
A commutative, functional, map like join seems to make joining lots of tables more concise and easier
"""
def join_check(f, r1, r2):
try:
stripped_r1 = strip_row(r1)
stripped_r2 = strip_row(r2)
for sr1 in stripped_r1:
for sr2 in stripped_r2:
if f(sr1, sr2):
return True
return False
except KeyError:
return False
def inner_match(f, c1, c2):
answer = []
for r1 in c1:
nr1 = copy.copy(r1)
for r2 in c2:
if join_check(f, r1, r2):
nr1.update(r2)
if r1 != nr1:
answer.append(nr1)
return answer
def outer_match(f, c1, c2):
answer = []
for r1 in c1:
m = False
for r2 in c2:
if join_check(f, r1, r2):
nr1 = copy.copy(r1)
nr1.update(r2)
answer.append(nr1)
m = True
if not m:
answer.append(r1)
return answer
def inner_join(f, tbs):
results = tbs[0].rows
ld = len(tbs)
if ld > 1:
for i in xrange(1, ld):
next = tbs[i].rows
results = inner_match(f, results, next)
return postcreate(results)
join = inner_join
def left_outer_join(f, tbs):
results = tbs[0].rows
ld = len(tbs)
if ld > 1:
for i in xrange(1, ld):
next = tbs[i].rows
results = outer_match(f, results, next)
return postcreate(results)
outer_join = left_outer_join
def cross_match(rows1, rows2):
r = []
for r1 in rows1:
for r2 in rows2:
nr = copy.copy(r1)
nr.update(r2)
r.append(nr)
return r
def cross(tbs):
results = tbs[0].rows
ld = len(tbs)
if ld > 1:
for i in xrange(1, ld):
results = cross_match(results, tbs[i].rows)
return postcreate(results)
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
""" Some handy user defined functions to plug in db.select """
__author__ = "Vik Singh (viksi@yahoo-inc.com)"
from util.typechecks import is_dict
def unnest_value(row):
"""
For data collections which have nested value parameters (like RSS)
this function will unnest the value to the higher level.
For example, say the row is {"title":{"value":"yahoo wins search"}}
This function will take that row and return the following row {"title": "yahoo wins search"}
"""
nr = {}
for k, v in row.iteritems():
if is_dict(type(v)) and "value" in v:
nr[k] = v["value"]
else:
nr[k] = v
return nr
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
__all__ = ["asizeof", "db", "udfs"]
| Python |
# Copyright (c) 2008 Yahoo! Inc. All rights reserved.
# Licensed under the Yahoo! Search BOSS Terms of Use
# (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html)
"""
Calculate the size of an object in python
This code used to be very complicated, and then realized in certain cases it failed
Given the structures handled in this framework, string'ing it and computing the length works fine
Especially since the # of bytes is not important - just need the relative sizes between objects
relsize is used to rank candidate collections of objects inferred from a REST response
The largest sized one wins
"""
__author__ = "Vik Singh (viksi@yahoo-inc)"
def relsize(o):
return len(str(o))
| Python |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| Python |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| Python |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| Python |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| Python |
#!/usr/bin/python
import sys, hashlib
def write_file(fn, buf):
fp = open(fn, "wb")
fp.write(buf)
fp.close()
def usage():
print ("Usage: " + sys.argv[0] + " infile outfile label")
def main():
if( len(sys.argv) != 4):
usage()
sys.exit()
fp = open( sys.argv[1] , "rb")
hash_str = hashlib.md5( fp.read() ).hexdigest()
fp.close()
out_str = "u8 " + sys.argv[3] + "[16] = { "
i=0
for str in hash_str:
if i % 2 == 0:
out_str += "0x" + str
else:
out_str += str
if i < 31:
out_str += ", "
i += 1
out_str += " };"
print out_str
write_file( sys.argv[2] , out_str )
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, re, os
def write_file(fn, buf):
fp = open(fn, "wb")
fp.write(buf)
fp.close()
def usage():
print ("Usage: " + os.path.split(__file__)[1] + " version outfile")
def crete_version_str(ver):
base = list("0.00")
version = str(ver)
ret = []
base[0] = version[0]
base[2] = version[1]
base[3] = version[2]
ret.append("".join(base))
version = str(int(ver) + 1)
base[0] = version[0]
base[2] = version[1]
base[3] = version[2]
ret.append("".join(base))
return ret
def main():
if( len(sys.argv) != 3):
usage()
sys.exit()
if len( sys.argv[1]) != 3:
print sys.argv[1] + ":Version error."
sys.exit()
fp = open( os.path.dirname(os.path.abspath(__file__)) + "/update_base.sfo" , "rb")
sfo_buf = fp.read()
fp.close()
after_str = crete_version_str(sys.argv[1])
print "Target version:" + after_str[0]
sfo_buf = re.sub("X.YZ", after_str[0], sfo_buf )
sfo_buf = re.sub("Z.YX", after_str[1], sfo_buf )
write_file( sys.argv[2] , sfo_buf )
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
""" PRO build script"""
import os, shutil, sys
NIGHTLY=0
VERSION="B9"
PRO_BUILD = [
{ "fn": "620PRO-%s.rar", "config": "CONFIG_620=1" },
{ "fn": "635PRO-%s.rar", "config": "CONFIG_635=1" },
{ "fn": "639PRO-%s.rar", "config": "CONFIG_639=1" },
{ "fn": "660PRO-%s.rar", "config": "CONFIG_660=1" },
# { "fn": "620PRO-%s.zip", "config": "CONFIG_620=1" },
# { "fn": "635PRO-%s.zip", "config": "CONFIG_635=1" },
# { "fn": "639PRO-%s.zip", "config": "CONFIG_639=1" },
# { "fn": "660PRO-%s.zip", "config": "CONFIG_660=1" },
# { "fn": "620PRO-%s.tar.gz", "config": "CONFIG_620=1" },
# { "fn": "635PRO-%s.tar.gz", "config": "CONFIG_635=1" },
# { "fn": "639PRO-%s.tar.gz", "config": "CONFIG_639=1" },
# { "fn": "660PRO-%s.tar.gz", "config": "CONFIG_660=1" },
# { "fn": "620PRO-%s.tar.bz2", "config": "CONFIG_620=1" },
# { "fn": "635PRO-%s.tar.bz2", "config": "CONFIG_635=1" },
# { "fn": "639PRO-%s.tar.bz2", "config": "CONFIG_639=1" },
# { "fn": "660PRO-%s.tar.bz2", "config": "CONFIG_660=1" },
]
OPT_FLAG = ""
def build_pro(build_conf):
global OPT_FLAG
if NIGHTLY:
build_conf += " " + "NIGHTLY=1"
build_conf += " " + OPT_FLAG
os.system("make clean %s" % (build_conf))
os.system("make deps %s" % (build_conf))
build_conf = "make " + build_conf
os.system(build_conf)
def copy_sdk():
try:
os.mkdir("dist/sdk")
os.mkdir("dist/sdk/lib")
os.mkdir("dist/sdk/include")
except OSError:
pass
shutil.copytree("kuBridgeTest", "dist/sdk/kuBridgeTest")
shutil.copy("include/kubridge.h", "dist/sdk/include")
shutil.copy("include/systemctrl.h", "dist/sdk/include")
shutil.copy("include/systemctrl_se.h", "dist/sdk/include")
shutil.copy("include/pspvshbridge.h", "dist/sdk/include")
shutil.copy("libs/libpspkubridge.a", "dist/sdk/lib")
shutil.copy("libs/libpspsystemctrl_kernel.a", "dist/sdk/lib")
shutil.copy("libs/libpspsystemctrl_user.a", "dist/sdk/lib")
def restore_chdir():
os.chdir(os.path.join(os.path.dirname(sys.argv[0]), ".."))
def make_archive(fn):
shutil.copy("credit.txt", "dist")
copy_sdk()
ext = os.path.splitext(fn)[-1].lower()
try:
os.remove(fn)
except OSError:
pass
path = os.getcwd()
os.chdir("dist");
if ext == ".rar":
os.system("rar a -r ../%s ." % (fn))
elif ext == ".gz":
os.system("tar -zcvf ../%s ." % (fn))
elif ext == ".bz2":
os.system("tar -jcvf ../%s ." % (fn))
elif ext == ".zip":
os.system("zip -r ../%s ." % (fn))
os.chdir(path)
def main():
global OPT_FLAG
OPT_FLAG = os.getenv("PRO_OPT_FLAG", "")
restore_chdir()
for conf in PRO_BUILD:
build_pro(conf["config"])
make_archive(conf["fn"] % (VERSION))
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, os, gzip, StringIO
def dump_binary(fn, data):
f = open(fn, "wb")
f.write(data)
f.close()
def dec_prx(fn):
f = open(fn, "rb")
f.seek(0x150)
dat = f.read()
f.close()
temp=StringIO.StringIO(dat)
f=gzip.GzipFile(fileobj=temp, mode='rb')
dec = f.read(f)
f.close()
fn = "%s.dec.prx" % os.path.splitext(fn)[0]
print ("Decompressed to %s" %(fn))
dump_binary(fn, dec)
def main():
if len(sys.argv) < 2:
print ("Usage: %s <file>" % (sys.argv[0]))
sys.exit(-1)
dec_prx(sys.argv[1])
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
class FakeTime:
def time(self):
return 1225856967.109
import sys, os, struct, gzip, hashlib, StringIO
gzip.time = FakeTime()
def binary_replace(data, newdata, offset):
return data[0:offset] + newdata + data[offset+len(newdata):]
def prx_compress(output, hdr, input, mod_name="", mod_attr=0xFFFFFFFF):
a=open(hdr, "rb")
fileheader = a.read();
a.close()
a=open(input, "rb")
elf = a.read(4);
a.close()
if (elf != '\x7fELF'.encode()):
print ("not a ELF/PRX file!")
return -1
uncompsize = os.stat(input).st_size
f_in=open(input, 'rb')
temp=StringIO.StringIO()
f=gzip.GzipFile(fileobj=temp, mode='wb')
f.writelines(f_in)
f.close()
f_in.close()
prx=temp.getvalue()
temp.close()
digest=hashlib.md5(prx).digest()
filesize = len(fileheader) + len(prx)
if mod_name != "":
if len(mod_name) < 28:
mod_name += "\x00" * (28-len(mod_name))
else:
mod_name = mod_name[0:28]
fileheader = binary_replace(fileheader, mod_name.encode(), 0xA)
if mod_attr != 0xFFFFFFFF:
fileheader = binary_replace(fileheader, struct.pack('H', mod_attr), 0x4)
fileheader = binary_replace(fileheader, struct.pack('L', uncompsize), 0x28)
fileheader = binary_replace(fileheader, struct.pack('L', filesize), 0x2c)
fileheader = binary_replace(fileheader, struct.pack('L', len(prx)), 0xb0)
fileheader = binary_replace(fileheader, digest, 0x140)
a=open(output, "wb")
assert(len(fileheader) == 0x150)
a.write(fileheader)
a.write(prx)
a.close()
try:
os.remove("tmp.gz")
except OSError:
pass
return 0
def main():
if len(sys.argv) < 4:
print ("Usage: %s outfile prxhdr infile [modname] [modattr]\n"%(sys.argv[0]))
exit(-1)
if len(sys.argv) < 5:
prx_compress(sys.argv[1], sys.argv[2], sys.argv[3])
elif len(sys.argv) < 6:
prx_compress(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
else:
prx_compress(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5], 16))
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import sys, hashlib
def toNID(name):
hashstr = hashlib.sha1(name.encode()).hexdigest().upper()
return "0x" + hashstr[6:8] + hashstr[4:6] + hashstr[2:4] + hashstr[0:2]
if __name__ == "__main__":
assert(toNID("sceKernelCpuSuspendIntr") == "0x092968F4")
for name in sys.argv[1:]:
print ("%s: %s"%(name, toNID(name)))
| Python |
#!/usr/bin/python
from hashlib import *
import sys, struct
def sha512(psid):
if len(psid) != 16:
return "".encode()
for i in range(512):
psid = sha1(psid).digest()
return psid
def get_psid(str):
if len(str) != 32:
return "".encode()
b = "".encode()
for i in range(0, len(str), 2):
b += struct.pack('B', int(str[i] + str[i+1], 16))
return b
def main():
if len(sys.argv) < 2:
print ("Usage: sha512.py psid")
exit(0)
psid = get_psid(sys.argv[1])
xhash = sha512(psid)
if len(xhash) == 0:
print ("wrong PSID")
exit(0)
print ("{\n\t"),
for i in range(len(xhash)):
if i != 0 and i % 8 == 0:
print ("\n\t"),
print ("0x%02X, "%(struct.unpack('B', xhash[i])[0])),
print ("\n},")
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
"""
pspbtcnf_editor: An script that add modules from pspbtcnf
"""
import sys, os, re
from getopt import *
from struct import *
BTCNF_MAGIC=0x0F803001
verbose = False
def print_usage():
print ("%s: pspbtcnf.bin [-o output.bin] [-a add_module_name:before_module_name:flag]" %(os.path.split(sys.argv[0]))[-1])
def replace_binary(data, offset, newdata):
newdata = data[0:offset] + newdata + data[offset+len(newdata):]
assert(len(data) == len(newdata))
return newdata
def dump_binary(data, offset, size):
newdata = data[offset:offset+size]
assert(len(newdata) == size)
return newdata
def dump_binary_str(data, offset):
ch = data[offset]
tmp = b''
while ch != 0:
tmp += pack('b', ch)
offset += 1
ch = data[offset]
return tmp.decode()
def add_prx_to_bootconf(srcfn, before_modname, modname, modflag):
"Return new bootconf data"
fn=open(srcfn, "rb")
bootconf = fn.read()
fn.close()
if len(bootconf) < 64:
raise Exception("Bad bootconf")
signature, devkit, modestart, nmodes, modulestart, nmodules, modnamestart, modnameend = unpack('LL8xLL8xLL8xLL8x', bootconf[:64])
if verbose:
print ("Devkit: 0x%08X"%(devkit))
print ("modestart: 0x%08X"%(modestart))
print ("nmodes: %d"%(nmodes))
print ("modulestart: 0x%08X"%(modulestart))
print ("nmodules: 0x%08X"%(nmodules))
print ("modnamestart: 0x%08X"%(modnamestart))
print ("modnameend: 0x%08X"%(modnameend))
if signature != BTCNF_MAGIC or nmodules <= 0 or nmodes <= 0:
raise Exception("Bad bootconf")
bootconf = bootconf + modname.encode() + b'\0'
modnameend += len(modname) + 1
i=0
while i < nmodules:
module_path, module_flags = unpack('L4xL4x16x', bootconf[modulestart+i*32:modulestart+(i+1)*32])
module_name = dump_binary_str(bootconf, modnamestart+module_path)
if verbose:
print ("[%02d]: Module path: %s flag: 0x%08X"%(i, module_name, module_flags))
if before_modname == module_name:
break
i+=1
if i >= nmodules:
raise Exception("module %s not found"%(before_modname))
module_path = modnameend - len(modname) - 1 - modnamestart
module_flag = 0x80010000 | (modflag & 0xFFFF)
newmod = dump_binary(bootconf, modulestart+i*32, 32)
newmod = replace_binary(newmod, 0, pack('L', module_path))
newmod = replace_binary(newmod, 8, pack('L', module_flag))
bootconf = bootconf[0:modulestart+i*32] + newmod + bootconf[modulestart+i*32:]
nmodules+=1
bootconf = replace_binary(bootconf, 0x24, pack('L', nmodules))
modnamestart += 32
bootconf = replace_binary(bootconf, 0x30, pack('L', modnamestart))
modnameend += 32
bootconf = replace_binary(bootconf, 0x34, pack('L', modnameend))
i = 0
while i < nmodes:
num = unpack('H', bootconf[modestart+i*32:modestart+i*32+2])[0]
num += 1
bootconf = replace_binary(bootconf, modestart + i * 32, pack('H', num))
i += 1
return bootconf
def write_file(output_fn, data):
fn = open(output_fn, "wb")
fn.write(data)
fn.close()
def main():
global verbose
try:
optlist, args = gnu_getopt(sys.argv, "a:o:vh")
except GetoptError as err:
print(err)
print_usage()
sys.exit(1)
# default configure
verbose = False
dst_filename = "-"
add_module = ""
for o, a in optlist:
if o == "-v":
verbose = True
elif o == "-h":
print_usage()
sys.exit()
elif o == "-o":
dst_filename = a
elif o == "-a":
add_module = a
else:
assert False, "unhandled option"
if verbose:
print (optlist, args)
if len(args) < 2:
print ("Missing input pspbtcnf.bin")
sys.exit(1)
src_filename = args[1]
if verbose:
print ("src_filename: " + src_filename)
print ("dst_filename: " + dst_filename)
# check add_module
if add_module != "":
t = (re.split(":", add_module, re.I))
if len(t) != 3:
print ("Bad add_module input")
sys.exit(1)
add_module, before_module, add_module_flag = (re.split(":", add_module, re.I))
if verbose:
print ("add_module: " + add_module)
print ("before_module: " + before_module)
print ("add_module_flag: " + add_module_flag)
if add_module != "":
result = add_prx_to_bootconf(src_filename, before_module, add_module, int(add_module_flag, 16))
if dst_filename == "-":
# print("Bootconf result:")
# print(result)
pass
else:
write_file(dst_filename, result)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import os
def main():
lists = [
"ISODrivers/Galaxy/galaxy.prx",
"ISODrivers/March33/march33.prx",
"ISODrivers/March33/march33_620.prx",
"ISODrivers/March33/march33_660.prx",
"ISODrivers/Inferno/inferno.prx",
"Popcorn/popcorn.prx",
"Satelite/satelite.prx",
"Stargate/stargate.prx",
"SystemControl/systemctrl.prx",
"usbdevice/usbdevice.prx",
"Vshctrl/vshctrl.prx",
"Recovery/recovery.prx",
]
for fn in lists:
path = "../" + fn
name=os.path.split(fn)[-1]
name=os.path.splitext(name)[0]
ret = os.system("bin2c %s %s.h %s"%(path, name, name))
assert(ret == 0)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
class FakeTime:
def time(self):
return 1225856967.109
import os, gzip, StringIO
gzip.time = FakeTime()
def create_gzip(input, output):
f_in=open(input, 'rb')
temp=StringIO.StringIO()
f=gzip.GzipFile(fileobj=temp, mode='wb')
f.writelines(f_in)
f.close()
f_in.close()
fout=open(output, 'wb')
temp.seek(0)
fout.writelines(temp)
fout.close()
temp.close()
def cleanup():
del_list = [
"installer.prx.gz",
"Rebootex.prx.gz",
]
for file in del_list:
try:
os.remove(file)
except OSError:
pass
def main():
create_gzip("../../Installer/installer.prx", "installer.prx.gz")
create_gzip("../../Rebootex/Rebootex.prx", "Rebootex.prx.gz")
os.system("bin2c installer.prx.gz installer.h installer")
os.system("bin2c Rebootex.prx.gz Rebootex_prx.h Rebootex_prx")
cleanup()
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
import os, sys, getopt
def usage():
print ("Usage: %s [-l size ] basefile input output" % (sys.argv[0]))
def write_file(fn, buf):
fp = open(fn, "wb")
fp.write(buf)
fp.close()
def main():
inputsize = 0
try:
optlist, args = getopt.getopt(sys.argv[1:], 'l:h')
except getopt.GetoptError:
usage()
sys.exit(2)
for o, a in optlist:
if o == "-h":
usage()
sys.exit()
if o == "-l":
inputsize = int(a, 16)
inputsize = max(inputsize, 0x4000);
if len(args) < 3:
usage()
sys.exit(2)
basefile = args[0]
inputfile = args[1]
outputfile = args[2]
fp = open(basefile, "rb")
buf = fp.read(0x1000)
fp.close()
if len(buf) < inputsize:
buf += b'\0' * (inputsize - len(buf))
assert(len(buf) == inputsize)
fp = open(inputfile, "rb")
ins = fp.read(0x3000)
fp.close()
buf = buf[0:0x1000] + ins + buf[0x1000+len(ins):]
assert(len(buf) == inputsize)
write_file(outputfile, buf)
if __name__ == "__main__":
main()
| Python |
from sys import stdin
a, b, c = map(int, stdin.readline().strip().split())
print "%.3lf" % ((a+b+c)/3.0)
| Python |
from sys import stdin
from math import *
r, h = map(float, stdin.readline().strip().split())
print "Area = %.3lf" % (pi*r*r*2 + 2*pi*r*h)
| Python |
from sys import stdin
from math import *
n, = map(int, stdin.readline().strip().split())
rad = radians(n)
print "%.3lf %.3lf" % (sin(rad), cos(rad))
| Python |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
print n*(n+1)/2
| Python |
from sys import stdin
a, b = map(int, stdin.readline().strip().split())
print b, a
| Python |
from sys import stdin
n, m = map(int, stdin.readline().strip().split())
a = (4*n-m)/2
b = n-a
if m % 2 == 1 or a < 0 or b < 0: print "No answer"
else: print a, b
| Python |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
money = n * 95
if money >= 300: money *= 0.85
print "%.2lf" % money
| Python |
from sys import stdin
n, = map(int, stdin.readline().strip().split())
print ["yes", "no"][n % 2]
| Python |
from sys import stdin
from math import *
x1, y1, x2, y2 = map(float, stdin.readline().strip().split())
print "%.3lf" % hypot((x1-x2), (y1-y2))
| Python |
from sys import stdin
n = stdin.readline().strip().split()[0]
print '%c%c%c' % (n[2], n[1], n[0])
| Python |
from sys import stdin
x, = map(float, stdin.readline().strip().split())
print abs(x)
| Python |
from sys import stdin
from calendar import isleap
year, = map(int, stdin.readline().strip().split())
if isleap(year): print "yes"
else: print "no"
| Python |
from sys import stdin
f, = map(float, stdin.readline().strip().split())
print "%.3lf" % (5*(f-32)/9)
| Python |
from sys import stdin
a, b, c = map(int, stdin.readline().strip().split())
if a*a + b*b == c*c or a*a + c*c == b*b or b*b + c*c == a*a: print "yes"
elif a + b <= c or a + c <= b or b + c <= a: print "not a triangle"
else: print "no"
| Python |
from sys import stdin
a = map(int, stdin.readline().strip().split())
a.sort()
print a[0], a[1], a[2]
| Python |
s = i = 0
while True:
term = 1.0 / (i*2+1)
s += term * ((-1)**i)
if term < 1e-6: break
i += 1
print "%.6lf" % s
| Python |
from sys import stdin
from decimal import *
a, b, c = map(int, stdin.readline().strip().split())
getcontext().prec = c
print Decimal(a) / Decimal(b)
| Python |
from sys import stdin
n = int(stdin.readline().strip())
print "%.3lf" % sum([1.0/x for x in range(1,n+1)])
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.