rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if self.state('waitToMagDown'): self.status('ready')
if not self.state('schedulingActive'): self.status('ready to mag down')
def cycle(self): """ this function should get called after the server finishes connecting. it doesn't return. each of the statuses will have a sleep for a given amount of time (usually 1s or rampWaitTime). """ self.state('alive', True) while self.state('alive'): # check to see if we should start recording temp #print "...
self.psMaxCurrent() elif self.currentStatus == 'waiting to mag up':
self.psMaxCurrent() elif self.currentStatus == 'ready to mag down':
def cycle(self): """ this function should get called after the server finishes connecting. it doesn't return. each of the statuses will have a sleep for a given amount of time (usually 1s or rampWaitTime). """ self.state('alive', True) while self.state('alive'): # check to see if we should start recording temp #print "...
if time.time() > self.state('scheduledMagUpTime') and (yield self.atBase()): self.status('magging up') elif self.currentStatus == 'magging up': yield util.wakeupCall(self.state('rampWaitTime')) self.clear('timeMaggedDown') (quenched, targetReached) = yield self.adrMagStep(True) self.log("%s mag step! Quenched: %s -- Ta...
self.psMaxCurrent()
def cycle(self): """ this function should get called after the server finishes connecting. it doesn't return. each of the statuses will have a sleep for a given amount of time (usually 1s or rampWaitTime). """ self.state('alive', True) while self.state('alive'): # check to see if we should start recording temp #print "...
self.clear('scheduledMagDownTime')
def cycle(self): """ this function should get called after the server finishes connecting. it doesn't return. each of the statuses will have a sleep for a given amount of time (usually 1s or rampWaitTime). """ self.state('alive', True) while self.state('alive'): # check to see if we should start recording temp #print "...
self.state('timeMaggedDown', time.time())
self.state('magDownCompletedTime', time.time())
def cycle(self): """ this function should get called after the server finishes connecting. it doesn't return. each of the statuses will have a sleep for a given amount of time (usually 1s or rampWaitTime). """ self.state('alive', True) while self.state('alive'): # check to see if we should start recording temp #print "...
elif self.currentStatus == 'ready to mag down': yield util.wakeupCall(self.sleepTime) self.psMaxCurrent()
def cycle(self): """ this function should get called after the server finishes connecting. it doesn't return. each of the statuses will have a sleep for a given amount of time (usually 1s or rampWaitTime). """ self.state('alive', True) while self.state('alive'): # check to see if we should start recording temp #print "...
print " volts[6]: %s\n volts[7]: %s\n voltageLimit: %s" % (volts[6].value, volts[7].value, self.state('voltageLimit')) if (not quenched) and (not targetReached) and abs(volts[6] < self.state('voltageLimit')) and abs(volts[7] < self.state('voltageLimit')): print "changing voltage" if up: newVoltage += self.stat...
if (not quenched) and (not targetReached) and abs(volts[6]) < self.state('voltageLimit') and abs(volts[7]) < self.state('voltageLimit'): print "changing voltage" if up: newVoltage += self.state('voltageStepUp') else: newVoltage -= self.state('voltageStepDown') else: print "not changing voltage"
def adrMagStep(self, up): """ If up is True, mags up a step. If up is False, mags down a step. """ ls = self.peripheralsConnected['lakeshore'] temps = yield ls.server.temperatures(context = ls.ctxt) volts = yield ls.server.voltages(context = ls.ctxt) ps = self.peripheralsConnected['magnet'] current = (yield ps.server.c...
if var == 'scheduledMagUpTime' and self.currentStatus == 'ready': self.status('waiting to mag up')
def state(self, var, newValue = None): if newValue is not None: self.stateVars[var] = newValue # check for scheduled mag up time if var == 'scheduledMagUpTime' and self.currentStatus == 'ready': self.status('waiting to mag up') self.log('Set %s to %s' % (var, str(newValue))) return self.stateVars[var]
elif newStatus == 'ready': if self.state('scheduledMagUpTime') > time.time(): self.status('waiting to mag up') elif newStatus == 'waiting at field': self.scheduledMagDownTime = time.time() + self.state("fieldWaitTime") * 60
def status(self, newStatus = None): if (newStatus is not None) and (newStatus not in self.possibleStatuses): self.log("ERROR: status %s not in possibleStatuses!" % newStatus) elif (newStatus is not None) and not (newStatus == self.currentStatus): self.currentStatus = newStatus if newStatus == 'magging up': if self.stat...
calib = self.voltToResCalibs[self.state('switchPosition') - 1]
calib = self.state('voltToResCalibs')[self.state('switchPosition') - 1]
def ruoxStatus(self): try: calib = self.voltToResCalibs[self.state('switchPosition') - 1] ls = self.peripheralsConnected['lakeshore'] voltage = (yield ls.server.voltages(context=ls.ctxt))[self.ruoxChannel].value resistance = voltage / (calib)* 10**6 # may or may not need this factor of 10^6 temp = 0.0 if resistance < s...
voltage = (yield ls.server.voltages(context=ls.ctxt))[self.ruoxChannel].value
voltage = (yield ls.server.voltages(context=ls.ctxt))[self.state('ruoxChannel')].value
def ruoxStatus(self): try: calib = self.voltToResCalibs[self.state('switchPosition') - 1] ls = self.peripheralsConnected['lakeshore'] voltage = (yield ls.server.voltages(context=ls.ctxt))[self.ruoxChannel].value resistance = voltage / (calib)* 10**6 # may or may not need this factor of 10^6 temp = 0.0 if resistance < s...
if resistance < self.resistanceCutoff:
if resistance < self.state('resistanceCutoff'):
def ruoxStatus(self): try: calib = self.voltToResCalibs[self.state('switchPosition') - 1] ls = self.peripheralsConnected['lakeshore'] voltage = (yield ls.server.voltages(context=ls.ctxt))[self.ruoxChannel].value resistance = voltage / (calib)* 10**6 # may or may not need this factor of 10^6 temp = 0.0 if resistance < s...
temp = self.highTempRuoxCurve(resistance, self.ruoxCoefsHigh)
temp = self.state('highTempRuoxCurve')(resistance, self.state('ruoxCoefsHigh'))
def ruoxStatus(self): try: calib = self.voltToResCalibs[self.state('switchPosition') - 1] ls = self.peripheralsConnected['lakeshore'] voltage = (yield ls.server.voltages(context=ls.ctxt))[self.ruoxChannel].value resistance = voltage / (calib)* 10**6 # may or may not need this factor of 10^6 temp = 0.0 if resistance < s...
temp = self.lowTempRuoxCurve(resistance, self.ruoxCoefsLow)
temp = self.state('lowTempRuoxCurve')(resistance, self.state('ruoxCoefsLow'))
def ruoxStatus(self): try: calib = self.voltToResCalibs[self.state('switchPosition') - 1] ls = self.peripheralsConnected['lakeshore'] voltage = (yield ls.server.voltages(context=ls.ctxt))[self.ruoxChannel].value resistance = voltage / (calib)* 10**6 # may or may not need this factor of 10^6 temp = 0.0 if resistance < s...
try: time = numpy.linspace(0,HORZ_DIVISIONS*secPerDiv*recordLength*(1.0/2500),recordLength) except: time = secPerDiv
time = numpy.linspace(0,HORZ_DIVISIONS*secPerDiv*recordLength*(1.0/2500),recordLength)
def get_trace(self, c, channel, start=1, stop=2500): """Get a trace from the scope. OUTPUT - (array voltage in volts, array time in seconds) """
self.WaysPassed = []
self.WaysPassed = set([])
def __init__(self, filename): #self.db = db self.useless = ('', 'created_by', 'source', 'editor', 'ele', 'time', 'editor', 'author', 'hdop', 'pdop', 'sat', 'speed', 'fix', 'course', 'converted_by', 'attribution', 'upload_tag', 'history') self.User = {} self.currentId = 0 self.goodUser = ('') self.TilesCreated = 0 self....
htmltablestart = "<table class=\"sortable\" sytle=\"width: 100%; border: 1px solid gray\" border=1 width=100%>"
htmltablestart = "<table class=\"sortable\" style=\"width: 100%; border: 1px solid gray\" border=1 width=100%>"
def __init__(self, filename): #self.db = db self.useless = ('', 'created_by', 'source', 'editor', 'ele', 'time', 'editor', 'author', 'hdop', 'pdop', 'sat', 'speed', 'fix', 'course', 'converted_by', 'attribution', 'upload_tag', 'history') self.User = {} self.currentId = 0 self.goodUser = ('') self.TilesCreated = 0 self....
self.WaysPassed.append(top)
self.WaysPassed.add(top)
def AddrTreeRecurse (top, wayback="» "):
filename.write(linkWay(child))
filename.write(linkWay(child)+" ")
def AddrTreeRecurse (top, wayback="» "):
for aaaaa in self.Address.keys():
for aaaaa in self.WaysPassed:
def AddrTreeRecurse (top, wayback="» "):
</head><body><div id="mess" style="visibility: hidden; position:absolute; background-color:white; border:1px dotted red; width:400px; height: 350px; overflow:auto "></div><table class="sortable" sytle="width: 100%; border: 1px solid gray" border=1 width=100%>
</head><body><div id="mess" style="visibility: hidden; position:absolute; background-color:white; border:1px dotted red; width:400px; height: 350px; overflow:auto "></div><table class="sortable" style="width: 100%; border: 1px solid gray" border=1 width=100%>
def AddrTreeRecurse (top, wayback="» "):
alpha = k[0]
if k: alpha = k[0] else: alpha = ""
def AddrTreeRecurse (top, wayback="» "):
if sys.platform != 'darwin': from sponsors.Sponsors import PermissionDialog permdialog = PermissionDialog(foo) if permdialog.needToAsk: permdialog.exec_() permdialog.start()
def startup_script( main_globals): """ This is the main startup script for NE1. It is intended to be run only once, and only by the code in main.py. When this function returns, the caller is intended to immediately exit normally. Parameter main_globals should be the value of globals() in __main__, which is needed in ca...
glTexCoord2fv(tex_origin + px * tex_dx + py * tex_dy) glVertex3fv(origin + px * dx + py * dy)
glTexCoord2fv((tex_origin + px * tex_dx + py * tex_dy).tolist())
def draw_textured_rect_subtriangle(origin, dx, dy, tex_origin, tex_dx, tex_dy, points): #070404 modified from draw_textured_rect """ Like draw_textured_rect, but draw only the sub-triangle of the same rect (textured in the same way), where the subtriangle has relative 2d vertices as specified inside that rect (treating...
return json.loads(value)
return value and json.loads(value) or {}
def process_result_value(self, value, dialect): return json.loads(value)
if (not url.startswith('http://')):
u = urlparse(url) if not u.scheme:
def shorten(self): if not request.POST: # XXX should be a 405 return { 'code': constants.INVALID_REQUEST, 'message': "must be POST call"} try: url = request.POST.get('url') #_from = request.POST.get('from') #_to = request.POST.get('to') except KeyError, what: error = { 'code': constants.INVALID_PARAMS, 'message': "'%s'...
json_attributes = Column(Json)
json_attributes = Column(Json())
def process_result_value(self, value, dialect): return value and json.loads(value) or {}
self.json_attributes = self.json_attributes or {} self.json_attributes[name] = value
self.__dict__['json_attributes'] = self.json_attributes or {} self.__dict__['json_attributes'][name] = value
def __setattr__(self, name, value): if name.startswith("_") or name in self.__dict__ or hasattr(self.__class__, name): object.__setattr__(self, name, value) return # assume it is an 'expando' object # Set json attributes to itself simply so the object is marked as # 'dirty' for subsequent updates. self.json_attributes ...
'message': "not logged in or no user account for that domain",
'message': str(e),
def send(self): result = {} error = None # If we don't have a key in our session we bail early with a # 401 domain = request.POST.get('domain') message = request.POST.get('message', '') username = request.POST.get('username') longurl = request.POST.get('link') shorten = asbool(request.POST.get('shorten', 0)) shorturl =...
if hasattr('message', info):
if hasattr(info, 'message'):
def verify(self): """Handle incoming redirect from OpenID Provider""" log_debug = self.log_debug if log_debug: log.debug('Handling processing of response from server') openid_session = session['openid_session'] if not openid_session: raise AccessException("openid session missing") # Setup the consumer and parse the i...
if len(h) < 3:
if len(h) >= 2:
def extract_fb_data(data): #import sys; print >> sys.stderr, data # Setup the normalized poco contact object nick = None # Setup the nick and preferred username to the last portion of the # FB link URL if its not their ID # if a user sets up their personal link, they get a url that looks like: # https://www.facebook.c...
body = """To: %s
body = u"""To: %s
def sendmessage(self, message, options={}): result = error = None from_ = self.account.get('profile',{}).get('verifiedEmail') url = "https://mail.google.com/mail/b/%s/smtp/" % from_ to_ = options['to'] server = SMTP(self.host, self.port) server.set_debuglevel(True) subject = options.get('subject') # XXX TODO: fix hea...
server.sendmail(from_, to_, body)
server.sendmail(from_, to_, body.encode('utf-8'))
def sendmessage(self, message, options={}): result = error = None from_ = self.account.get('profile',{}).get('verifiedEmail') url = "https://mail.google.com/mail/b/%s/smtp/" % from_ to_ = options['to'] server = SMTP(self.host, self.port) server.set_debuglevel(True) subject = options.get('subject') # XXX TODO: fix hea...
s = select([func.date(Account.created), Account.domain, func.count(Account.id)])
s = select([func.date_format(History.published, "%Y-%m-%d"), Account.domain, func.count(Account.id)])
def accounts(self): start = request.params.get('start',None) end = request.params.get('end',None) limit = int(request.params.get('days','0')) opts = request.params.get('opts','').split(',') groupby = [] whereclause = [] if limit and not start and not end: whereclause.append(Account.created >= UTCDateTime.now() - timede...
s = select([func.date(Account.created), func.count(Account.id)])
s = select([func.date_format(History.published, "%Y-%m-%d"), func.count(Account.id)])
def accounts(self): start = request.params.get('start',None) end = request.params.get('end',None) limit = int(request.params.get('days','0')) opts = request.params.get('opts','').split(',') groupby = [] whereclause = [] if limit and not start and not end: whereclause.append(Account.created >= UTCDateTime.now() - timede...
params={} for k,v in request.params.items(): params[k]=str(v) info = oidconsumer.complete(params, return_to)
info = oidconsumer.complete(request.params, return_to)
def verify(self): """Handle incoming redirect from OpenID Provider""" log_debug = self.log_debug if log_debug: log.debug('Handling processing of response from server') openid_session = session['openid_session'] if not openid_session: raise Exception("openid session missing") # Setup the consumer and parse the informa...
self.return_to_query = {}
def __init__(self, provider): self.log_debug = logging.DEBUG >= log.getEffectiveLevel()
qualified=True)
qualified=True, **self.return_to_query)
def request_access(self): log_debug = self.log_debug if log_debug: log.debug('Handling OpenID login') # Load default parameters that all Auth Responders take session['end_point_success'] = request.POST['end_point_success'] session['end_point_auth_failure'] = request.POST['end_point_auth_failure'] openid_url = request....
return redirect(redirect_url)
def request_access(self): log_debug = self.log_debug if log_debug: log.debug('Handling OpenID login') # Load default parameters that all Auth Responders take session['end_point_success'] = request.POST['end_point_success'] session['end_point_auth_failure'] = request.POST['end_point_auth_failure'] openid_url = request....
html = authrequest.htmlMarkup(realm=request.application_url, return_to=return_to,
return authrequest.htmlMarkup(realm=request.application_url, return_to=return_to,
def request_access(self): log_debug = self.log_debug if log_debug: log.debug('Handling OpenID login') # Load default parameters that all Auth Responders take session['end_point_success'] = request.POST['end_point_success'] session['end_point_auth_failure'] = request.POST['end_point_auth_failure'] openid_url = request....
return response(body=html)
def request_access(self): log_debug = self.log_debug if log_debug: log.debug('Handling OpenID login') # Load default parameters that all Auth Responders take session['end_point_success'] = request.POST['end_point_success'] session['end_point_auth_failure'] = request.POST['end_point_auth_failure'] openid_url = request....
info = oidconsumer.complete(request.params, return_to)
params={} for k,v in request.params.items(): params[k]=str(v) info = oidconsumer.complete(params, return_to)
def verify(self): """Handle incoming redirect from OpenID Provider""" log_debug = self.log_debug if log_debug: log.debug('Handling processing of response from server') openid_session = session['openid_session'] if not openid_session: raise Exception("openid session missing") # Setup the consumer and parse the informa...
raise Exception("consumer failure")
raise Exception("consumer failure: "+info.message)
def verify(self): """Handle incoming redirect from OpenID Provider""" log_debug = self.log_debug if log_debug: log.debug('Handling processing of response from server') openid_session = session['openid_session'] if not openid_session: raise Exception("openid session missing") # Setup the consumer and parse the informa...
raise Exception("consumer canceled")
raise Exception("consumer canceled: "+info.message)
def verify(self): """Handle incoming redirect from OpenID Provider""" log_debug = self.log_debug if log_debug: log.debug('Handling processing of response from server') openid_session = session['openid_session'] if not openid_session: raise Exception("openid session missing") # Setup the consumer and parse the informa...
resp.setcookie('csrf', csrf_token, expires=3600)
resp.set_cookie('csrf', csrf_token, expires=3600)
def __call__(self, environ, start_response): request = Request(environ) session = environ['beaker.session'] csrf_token = session.get('csrf') if not csrf_token: csrf_token = session['csrf'] = str(random.getrandbits(128)) session.save()
shorturl = Link.get_or_create(longurl)
shorturl = Link.get_or_create(longurl).short_url
def send(self): result = {} error = None # If we don't have a key in our session we bail early with a # 401 domain = request.POST.get('domain') message = request.POST.get('message', '') username = request.POST.get('username') longurl = request.POST.get('link') shorten = asbool(request.POST.get('shorten', 0)) shorturl =...
error = copy.copy(error)
error = copy.copy(response['error'])
def rawcall(self, url, method, args, options={}): headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } if options.get('HumanVerification'): headers['X-HumanVerification-ImageUrl'] = options.get('HumanVerificationImage') headers['X-HumanVerification-Answer'] = options.get('HumanVerification') #...
to_ = options['to']
to_addrs = AddressList(options['to'])
def sendmessage(self, message, options={}): result = error = None
"from":{"email":from_}, "to":[{"email":to_}],
"from":{"name": fullname, "email":from_}, "to":to_,
def sendmessage(self, message, options={}): result = error = None
if not userkey: error = {'provider': domain, 'reason': "no session for that domain", 'code': 401 } return {'result': result, 'error': error}
def send(self): result = {} error = None # If we don't have a userkey in our session we bail early with a # 401 userkey = session.get('userkey') if not userkey: error = {'provider': domain, 'reason': "no session for that domain", 'code': 401 } return {'result': result, 'error': error} try: domain = request.POST.get('do...
val = val.isoformat().split('.')[0]+'Z'
val = val.isoformat().split('.')[0].replace('+00:00','')+'Z'
def to_dict(self, fields=None): propdict = {} for prop in object_mapper(self).iterate_properties: if isinstance(prop, (ColumnProperty)):# or isinstance(prop, RelationProperty) and prop.secondary: if fields and prop.key not in fields: continue val = getattr(self, prop.key) if val: if isinstance(val, datetime): val = val...
return content_type, body
return content_type, body.encode('utf-8')
def encode_multipart_formdata(body): BOUNDARY = '----------$_BOUNDARY_' + str(random.getrandbits(128)) + '_$' CRLF = '\r\n' L = [] for key in body: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(body[key]) L.append('--' + BOUNDARY + '--') L.append('') body = ...
poco['urls'] = [ { 'type': u'profile', "primary" : False, "value" : user['publicProfileUrl']['url'] }]
poco['urls'] = [ { 'type': u'profile', "primary" : False, "value" : user['publicProfileUrl'] }]
def extract_li_data(user): poco = { 'displayName': "%s %s" % (user.get('firstName'), user.get('lastName'),), } if user.get('publicProfileUrl', False): poco['urls'] = [ { 'type': u'profile', "primary" : False, "value" : user['publicProfileUrl']['url'] }] if user.get('siteStandardProfileRequest', False): poco['urls'] = [...
'verifiedEmail': data['verified'] and data.get('email'),
'verifiedEmail': data.get('verified') and data.get('email'),
def extract_fb_data(data): # Setup the normalized poco contact object nick = None # Setup the nick and preferred username to the last portion of the # FB link URL if its not their ID link = data.get('link') if link: last = link.split('/')[-1] if last != data['id']: nick = last profile = { 'providerName': 'Facebook', ...
profile['birthday'] = '-'.join(yr, mth, day)
profile['birthday'] = '-'.join([yr, mth, day])
def extract_fb_data(data): # Setup the normalized poco contact object nick = None # Setup the nick and preferred username to the last portion of the # FB link URL if its not their ID link = data.get('link') if link: last = link.split('/')[-1] if last != data['id']: nick = last profile = { 'providerName': 'Facebook', ...
import sys; print >> sys.stderr, request.path_info
def __call__(self, environ, start_response): request = Request(environ) session = environ['beaker.session'] csrf_token = session.get('csrf') if not csrf_token: csrf_token = session['csrf'] = str(random.getrandbits(128)) session.save()
import sys; print >> sys.stderr, "unprotected path!"
def __call__(self, environ, start_response): request = Request(environ) session = environ['beaker.session'] csrf_token = session.get('csrf') if not csrf_token: csrf_token = session['csrf'] = str(random.getrandbits(128)) session.save()
if not hasattr(_f, '_prof_wrapped'): f = _profiler(_f) f._prof_wrapped = True return f(*args, **kwds)
if _profiler: if not hasattr(_f, '_prof_wrapped'): f = _profiler(_f) f._prof_wrapped = True return f(*args, **kwds) return _f(*args, **kwds)
def wrap(_f, *args, **kwds): if not hasattr(_f, '_prof_wrapped'): f = _profiler(_f) f._prof_wrapped = True return f(*args, **kwds)
if 'www-authenticate' in resp:
if 'invalid_token' in resp.get('www-authenticate',''):
def _make_error(self, data, resp): # Facebook makes error handling fun! So much for standards. # handle the various error mechanisms they deliver and hope # something works. (this is in part, proper oauth2 error # handling, in part facebook oauth error handling and facebook # rest api error handling).
BOUNDARY = '----------$_BOUNDARY_' + str(random.random) + '_$'
BOUNDARY = '----------$_BOUNDARY_' + str(random.getrandbits(128)) + '_$'
def encode_multipart_formdata(body): BOUNDARY = '----------$_BOUNDARY_' + str(random.random) + '_$' CRLF = '\r\n' L = [] for key in body: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(body[key]) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(...
keys = session.get('account_keys', '').split(',')
keys = [k for k in session.get('account_keys', '').split(',') if k]
def get(self, domain=None): keys = session.get('account_keys', '').split(',') accts = Session.query(Account).filter(Account.key.in_(keys)).all() return [a.profile for a in accts]
keys = session.get('account_keys', '').split(',') q = Session.query(Account.key).filter(Account.key.in_(keys)).filter(Account.domain!=domain)
keys = [k for k in session.get('account_keys', '').split(',') if k] _and = [Account.domain==domain]
def signout(self): domain = request.params.get('domain') username = request.params.get('username') userid = request.params.get('userid') if domain and username or userid: try: keys = session.get('account_keys', '').split(',') q = Session.query(Account.key).filter(Account.key.in_(keys)).filter(Account.domain!=domain) if...
q = q.filter(Account.username==username)
_and.append(Account.username==username)
def signout(self): domain = request.params.get('domain') username = request.params.get('username') userid = request.params.get('userid') if domain and username or userid: try: keys = session.get('account_keys', '').split(',') q = Session.query(Account.key).filter(Account.key.in_(keys)).filter(Account.domain!=domain) if...
q = q.filter(Account.userid==userid) session['account_keys'] = ','.join(q.all())
_and.append(Account.userid==userid) new_keys = Session.query(Account.key).filter(Account.key.in_(keys)).filter(not_(and_(*_and))).all() session['account_keys'] = ','.join([k[0] for k in new_keys])
def signout(self): domain = request.params.get('domain') username = request.params.get('username') userid = request.params.get('userid') if domain and username or userid: try: keys = session.get('account_keys', '').split(',') q = Session.query(Account.key).filter(Account.key.in_(keys)).filter(Account.domain!=domain) if...
keys = session.get('account_keys', '').split(',')
keys = [k for k in session.get('account_keys', '').split(',') if k]
def _get_or_create_account(self, domain, userid, username): keys = session.get('account_keys', '').split(',') # Find or create an account try: acct = Session.query(Account).filter(and_(Account.domain==domain, Account.userid==userid)).one() except NoResultFound: acct = Account() acct.domain = domain acct.userid = userid...
from_email = ("%s <%s>" % (fullname, from_)).encode('utf-8')
from_email = '"%s" <%s>' % (Header(fullname, 'utf-8').encode(), from_,)
def sendmessage(self, message, options={}): result = error = None
msg['Subject'] = subject msg['From'] = from_email msg['To'] = to_
def sendmessage(self, message, options={}): result = error = None
val = val.isoformat().split('.')[0].replace('+00:00','Z')
val = val.isoformat().split('.')[0]+'Z'
def to_dict(self, fields=None): propdict = {} for prop in object_mapper(self).iterate_properties: if isinstance(prop, (ColumnProperty)):# or isinstance(prop, RelationProperty) and prop.secondary: if fields and prop.key not in fields: continue val = getattr(self, prop.key) if val: if isinstance(val, datetime): val = val...
result, error = provider.api(acct).sendmessage(message, args)
try: result, error = provider.api(acct).sendmessage(message, args) except ValueError, e: error = {'provider': domain, 'message': "not logged in or no user account for that domain", 'status': 401 } return {'result': result, 'error': error}
def send(self): result = {} error = None # If we don't have a key in our session we bail early with a # 401 domain = request.POST.get('domain') message = request.POST.get('message', '') username = request.POST.get('username') longurl = request.POST.get('link') shorten = asbool(request.POST.get('shorten', 0)) shorturl =...
def empty_profiler(f): return f
def profile_wrapper(func): from decorator import decorator def wrap(_f, *args, **kwds): if not hasattr(_f, '_prof_wrapped'): f = _profiler(_f) f._prof_wrapped = True return f(*args, **kwds) return decorator(wrap, func)
def empty_profiler(f): return f
__builtin__.__dict__['profile'] = empty_profiler
__builtin__.__dict__['_profiler'] = None __builtin__.__dict__['profile'] = profile_wrapper
def empty_profiler(f): return f
p = __builtin__.__dict__.get('profile', None) if not p or p == empty_profiler: p = __builtin__.__dict__['profile'] = prof
__builtin__.__dict__['_profiler'] = p
def run_app(): app_iter = self.app(environ, replace_start_response) try: body.extend(app_iter) finally: if hasattr(app_iter, 'close'): app_iter.close()
from_ = self.account.get('profile',{}).get('verifiedEmail')
profile = self.account.get('profile', {}) from_email = from_ = profile.get('verifiedEmail') fullname = profile.get('displayName', None) if fullname: from_email = '"%s" <%s>' % (Header(fullname, 'utf-8').encode(), from_,)
def sendmessage(self, message, options={}): result = error = None from_ = self.account.get('profile',{}).get('verifiedEmail') to_ = options['to'] subject = options.get('subject')
link = Column(RDUnicode(128))
link = Column(UnicodeText)
def annotated_insert(insert, compiler, **kw): if getattr(insert.table, 'insert_prefix', None): insert = insert.prefix_with('%s' % insert.table.insert_prefix) return compiler.visit_insert(insert, **kw)
self.__dict__['json_attributes'] = self.json_attributes or {} self.__dict__['json_attributes'][name] = value
self.json_attributes = self.json_attributes or {} self.json_attributes[name] = value
def __setattr__(self, name, value): if name.startswith("_") or name in self.__dict__ or hasattr(self.__class__, name): object.__setattr__(self, name, value) return # assume it is an 'expando' object # Set json attributes to itself simply so the object is marked as # 'dirty' for subsequent updates. self.__dict__['json_a...
self.bitrate = 64
self.bit_rate = 64
def __init__(self): self.__parse_args() self.__setup_logging()
chapter_name = unicode(re.sub(re_sub, '', (self.custom_name % values).replace('/', '-')), 'utf-8')
chapter_name = re_sub.sub('', (self.custom_name % values).replace('/', '-')) if not isinstance(chapter_name, unicode): chapter_name = unicode(chapter_name, 'utf-8')
def split(self): re_format = re.compile(r'%\(([A-Za-z0-9]+)\)') re_sub = re.compile(r'[\\\*\?\"\<\>\|]+')
self.end = round(int(end)/1000., 3)
self.end = round(int(end)/1000.0, 3)
def __init__(self, title=None, start=None, end=None, num=None): self.title = title self.start = round(int(start)/1000.0, 3) self.end = round(int(end)/1000., 3) self.num = num
re_format = re.compile('%\(([A-Za-z0-9]+)\)')
re_format = re.compile(r'%\(([A-Za-z0-9]+)\)') re_sub = re.compile(r'[\\\*\?\"\<\>\|]+')
def split(self): if self.skip_splitting: return None re_format = re.compile('%\(([A-Za-z0-9]+)\)')
chapter_name = self.custom_name % values
chapter_name = re.sub(re_sub, '', (self.custom_name % values).replace('/', '-'))
def split(self): if self.skip_splitting: return None re_format = re.compile('%\(([A-Za-z0-9]+)\)')
self.output_dir = os.path.join(os.path.dirname(__file__),
args.output_dir = os.path.join(os.path.dirname(__file__),
def __parse_args(self): parser = argparse.ArgumentParser( description='Convert m4b audio book to mp3 file(s).')
else: self.output_dir = args.output_dir
self.output_dir = args.output_dir
def __parse_args(self): parser = argparse.ArgumentParser( description='Convert m4b audio book to mp3 file(s).')
self.log.debug('Specified arguments:')
if self.debug: s = ['Options:'] for k, v in self.args.__dict__.items(): s.append(' %s: %s' % (k, v)) self.log.debug('\n'.join(s))
def __setup_logging(self): logger = logging.getLogger('m4b')
for filename in os.listdir(tex_dir): os.remove(os.path.join(tex_dir, filename)) os.rmdir(tex_dir)
shutil.rmtree(tex_dir)
def convert(tex_source, input_format, output_format, max_runs=5): '''Convert LaTeX or TeX source to PDF or DVI.''' # check arguments assert isinstance(tex_source, unicode) try: (tex_cmd, output_suffix) = { ('tex', 'dvi'): ('tex', '.dvi'), ('latex', 'dvi'): ('latex', '.dvi'), ('tex', 'pdf'): ('pdftex', '.p...
return filter(lambda arg: not arg.haschild('RibValue'), argList)
return filter(lambda arg: not arg.findall('RibValue'), argList)
def ribArgs(argList): return filter(lambda arg: not arg.haschild('RibValue'), argList)
if procXml.haschild('CName'):
if procXml.findall('CName'):
def cName(procXml): if procXml.haschild('CName'): return procXml.findtext('CName') else: return 'Ri' + procXml.findtext('Name')
if procXml.haschild('Arguments/ParamList'):
if procXml.findall('Arguments/ParamList'):
def riCxxMethodDecl(procXml, className=None): args = [formalArg(arg) for arg in ribArgs(procXml.findall('Arguments/Argument'))] if procXml.haschild('Arguments/ParamList'): args += ['const ParamList& pList'] procName = procXml.findtext('Name') if className is not None: procName = className + '::' + procName return '%s %...
if procXml.haschild('Arguments/ParamList'):
if procXml.findall('Arguments/ParamList'):
def wrapperCallArgList(procXml): args = [arg.findtext('Name') for arg in ribArgs(procXml.findall('Arguments/Argument'))] if procXml.haschild('Arguments/ParamList'): args += ['pList'] return args
tDist = fabs(tuv1[...,0] - tuv2[...,0]) uvDist = eucDist(tuv1[...,1:],tuv2[...,1:]) return 2*tDist + uvDist
dt = tuv1[...,0] - tuv2[...,0] du = tuv1[...,1] - tuv2[...,1] dv = tuv1[...,2] - tuv2[...,2] return sqrt(4*dt*dt + du*du + dv*dv)
def sampleDist(tuv1, tuv2): ''' Get the distance between (t,u,v) tuples when optimizing. Optimizing involves choosing a (t,u,v) triple which is well separated from the other triples in the spatial neighbourhood. This function determines what "well-separated" means. tuv1 and tuv2 should be arrays which are broadcasta...
def ribArgs(argList): return filter(lambda arg: not arg.findall('RibValue'), argList)
def ribArgs(procXml): return [a for a in procXml.findall('Arguments/Argument') if not a.findall('RibValue')] def cArgs(procXml): return [a for a in procXml.findall('Arguments/Argument') if not a.findall('RibOnly')]
def ribArgs(argList): return filter(lambda arg: not arg.findall('RibValue'), argList)
args = [formalArg(arg) for arg in ribArgs(procXml.findall('Arguments/Argument'))]
args = [formalArg(arg) for arg in ribArgs(procXml)]
def riCxxMethodDecl(procXml, className=None): args = [formalArg(arg) for arg in ribArgs(procXml.findall('Arguments/Argument'))] if procXml.findall('Arguments/ParamList'): args += ['const ParamList& pList'] procName = procXml.findtext('Name') if className is not None: procName = className + '::' + procName return '%s %s...
return '%s %s(%s)' % (procXml.findtext('ReturnType'), procName, ', '.join(args))
return 'RtVoid %s(%s)' % (procName, ', '.join(args))
def riCxxMethodDecl(procXml, className=None): args = [formalArg(arg) for arg in ribArgs(procXml.findall('Arguments/Argument'))] if procXml.findall('Arguments/ParamList'): args += ['const ParamList& pList'] procName = procXml.findtext('Name') if className is not None: procName = className + '::' + procName return '%s %s...
args = [arg.findtext('Name') for arg in ribArgs(procXml.findall('Arguments/Argument'))]
args = [arg.findtext('Name') for arg in ribArgs(procXml)]
def wrapperCallArgList(procXml): args = [arg.findtext('Name') for arg in ribArgs(procXml.findall('Arguments/Argument'))] if procXml.findall('Arguments/ParamList'): args += ['pList'] return args
def __init__(self, tableSize=None, ncolors=2):
def __init__(self, ncolors, tableSize=None):
def __init__(self, tableSize=None, ncolors=2): if tableSize is None: self.N = 256 # Relatively "nice" permutation table for ncolors=2 generated with # findGoodHashPerm() self.P = array( [221, 248, 55, 65, 162, 184, 16, 217, 141, 24, 78, 34, 131, 164, 98, 127, 128, 229, 142, 70, 176, 192, 51, 1, 230, 235, 232...
self.P = array( [221, 248, 55, 65, 162, 184, 16, 217, 141, 24, 78, 34, 131, 164, 98, 127, 128, 229, 142, 70, 176, 192, 51, 1, 230, 235, 232, 124, 121, 6, 107, 85, 233, 175, 144, 202, 122, 200, 254, 167, 8, 196, 158, 63, 88, 102, 153, 170, 120, 149, 29, 13, 183, 7, 194, 241, 255, 15, 112, 126, 173...
self.P = array([ 41, 52, 248, 166, 162, 92, 95, 11, 3, 94, 219, 198, 170, 165, 80, 231, 75, 19, 20, 240, 169, 105, 15, 51, 45, 84, 85, 157, 232, 23, 97, 14, 174, 0, 82, 42, 145, 69, 111, 178, 158, 138, 17, 70, 238, 137, 179, 64, 172, 61, 53, 177, 91, 73, 234, 18, 148, 223, 68, 187, 123, ...
def __init__(self, tableSize=None, ncolors=2): if tableSize is None: self.N = 256 # Relatively "nice" permutation table for ncolors=2 generated with # findGoodHashPerm() self.P = array( [221, 248, 55, 65, 162, 184, 16, 217, 141, 24, 78, 34, 131, 164, 98, 127, 128, 229, 142, 70, 176, 192, 51, 1, 230, 235, 232...
c1 = cornerHash(tx, ty) c2 = cornerHash(tx+1, ty) c3 = cornerHash(tx, ty+1) c4 = cornerHash(tx+1, ty+1)
c1 = h[tx, ty] c2 = h[tx+1, ty] c3 = h[tx, ty+1] c4 = h[tx+1, ty+1]
def applyTileSet(width, tileSet, cornerHash): ''' Use a set of tiles to tile the plane. width is the width and height of the tiling in number of tiles. cornerHash represents a spatial hash function with which to compute colors for the tile corners; this determines the particular tile placement used. ''' tWidth = tileS...
h = SpatialHash(tableSize=tableSize, ncolors=ncol)
h = SpatialHash(ncol, tableSize=tableSize)
def findGoodHashPerm(tableSize, ncol): ''' Find a hash function permutation table which is "nice" in the sense that it results in few adjacent repititions of the same tile. ''' while True: h = SpatialHash(tableSize=tableSize, ncolors=ncol) ind = hashTilingInds(tableSize, h) goodness0 = sum(diff(ind, axis=0) == 0) / flo...
def riCxxMethodDecl(procXml, className=None):
def riCxxMethodDecl(procXml, className=None, useDefaults=False):
def riCxxMethodDecl(procXml, className=None): args = [formalArg(arg) for arg in ribArgs(procXml)] if procXml.findall('Arguments/ParamList'): args += ['const ParamList& pList'] procName = procXml.findtext('Name') if className is not None: procName = className + '::' + procName return 'RtVoid %s(%s)' % (procName, ', '.jo...
args += ['const ParamList& pList']
if procXml.findall('Arguments/ParamList/Optional') and useDefaults: args += ['const ParamList& pList = ParamList()'] else: args += ['const ParamList& pList']
def riCxxMethodDecl(procXml, className=None): args = [formalArg(arg) for arg in ribArgs(procXml)] if procXml.findall('Arguments/ParamList'): args += ['const ParamList& pList'] procName = procXml.findtext('Name') if className is not None: procName = className + '::' + procName return 'RtVoid %s(%s)' % (procName, ', '.jo...
type = type.replace('RtToken', 'RtConstToken') type = type.replace('RtString', 'RtConstString')
type = re.sub('Rt(Token|String|Color|Point(?!er)|Matrix|Bound)', r'RtConst\1', type)
def formalArg(arg): type = arg.findtext('Type') name = arg.findtext('Name') if type is None: return name type = type.replace('RtToken', 'RtConstToken') type = type.replace('RtString', 'RtConstString') if type.endswith('Array'): return 'const Array<%s>& %s' % (type[:-5], name) return '%s %s' % (type, name)