code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''Calling this function finishes input of the current line, then moves the vertical
print position forward by x/300 inch.
Args:
amount: how far foward you want the position moved. Actual movement is calculated as
amount/300 inches.
Returns:
... | def forward_feed(self, amount) | Calling this function finishes input of the current line, then moves the vertical
print position forward by x/300 inch.
Args:
amount: how far foward you want the position moved. Actual movement is calculated as
amount/300 inches.
Returns:
None
... | 10.052003 | 2.207607 | 4.553347 |
'''Specify vertical print position from the top margin position.
Args:
amount: The distance from the top margin you'd like, from 0 to 32767
Returns:
None
Raises:
RuntimeError: Invalid vertical position.
'''
mL = amount%256
... | def abs_vert_pos(self, amount) | Specify vertical print position from the top margin position.
Args:
amount: The distance from the top margin you'd like, from 0 to 32767
Returns:
None
Raises:
RuntimeError: Invalid vertical position. | 6.661484 | 3.131803 | 2.127044 |
'''Calling this function sets the absoulte print position for the next data, this is
the position from the left margin.
Args:
amount: desired positioning. Can be a number from 0 to 2362. The actual positioning
is calculated as (amount/60)inches from the left marg... | def abs_horz_pos(self, amount) | Calling this function sets the absoulte print position for the next data, this is
the position from the left margin.
Args:
amount: desired positioning. Can be a number from 0 to 2362. The actual positioning
is calculated as (amount/60)inches from the left margin.
... | 7.93997 | 2.169451 | 3.659898 |
'''Calling this function sets the relative horizontal position for the next data, this is
the position from the current position. The next character will be printed (x/180)inches
away from the current position. The relative position CANNOT be specified to the left.
This command is only v... | def rel_horz_pos(self, amount) | Calling this function sets the relative horizontal position for the next data, this is
the position from the current position. The next character will be printed (x/180)inches
away from the current position. The relative position CANNOT be specified to the left.
This command is only valid with l... | 9.052499 | 1.949187 | 4.644242 |
'''Sets the alignment of the printer.
Args:
align: desired alignment. Options are 'left', 'center', 'right', and 'justified'. Anything else
will throw an error.
Returns:
None
Raises:
RuntimeError: Invalid alignment.
'''
... | def alignment(self, align) | Sets the alignment of the printer.
Args:
align: desired alignment. Options are 'left', 'center', 'right', and 'justified'. Anything else
will throw an error.
Returns:
None
Raises:
RuntimeError: Invalid alignment. | 3.521129 | 1.938049 | 1.816842 |
'''Places/removes frame around text
Args:
action -- Enable or disable frame. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action.
'''
choices = {'on': '1',
'off': '0'}
if act... | def frame(self, action) | Places/removes frame around text
Args:
action -- Enable or disable frame. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action. | 7.638567 | 3.358994 | 2.274064 |
'''Enable/cancel bold printing
Args:
action: Enable or disable bold printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action.
'''
if action =='on':
action = 'E'
elif action == ... | def bold(self, action) | Enable/cancel bold printing
Args:
action: Enable or disable bold printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action. | 5.166736 | 2.663322 | 1.939959 |
'''Enable/cancel italic printing
Args:
action: Enable or disable italic printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action.
'''
if action =='on':
action = '4'
elif action... | def italic(self, action) | Enable/cancel italic printing
Args:
action: Enable or disable italic printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action. | 5.91848 | 2.818051 | 2.100203 |
'''Enable/cancel doublestrike printing
Args:
action: Enable or disable doublestrike printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action.
'''
if action == 'on':
action = 'G'
... | def double_strike(self, action) | Enable/cancel doublestrike printing
Args:
action: Enable or disable doublestrike printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action. | 5.743931 | 2.600268 | 2.208977 |
'''Enable/cancel doublewidth printing
Args:
action: Enable or disable doublewidth printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action.
'''
if action == 'on':
action = '1'
... | def double_width(self, action) | Enable/cancel doublewidth printing
Args:
action: Enable or disable doublewidth printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action. | 5.021973 | 2.526001 | 1.988112 |
'''Enable/cancel compressed character printing
Args:
action: Enable or disable compressed character printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action.
'''
if action == 'on':
act... | def compressed_char(self, action) | Enable/cancel compressed character printing
Args:
action: Enable or disable compressed character printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action. | 4.823498 | 2.402785 | 2.007461 |
'''Enable/cancel underline printing
Args:
action -- Enable or disable underline printing. Options are '1' - '4' and 'cancel'
Returns:
None
Raises:
None
'''
if action == 'off':
action = '0'
self.send(chr(... | def underline(self, action) | Enable/cancel underline printing
Args:
action -- Enable or disable underline printing. Options are '1' - '4' and 'cancel'
Returns:
None
Raises:
None | 6.369916 | 2.487659 | 2.560607 |
'''Changes font size
Args:
size: change font size. Options are 24' '32' '48' for bitmap fonts
33, 38, 42, 46, 50, 58, 67, 75, 83, 92, 100, 117, 133, 150, 167, 200 233,
11, 44, 77, 111, 144 for outline fonts.
Returns:
None
Raises:... | def char_size(self, size) | Changes font size
Args:
size: change font size. Options are 24' '32' '48' for bitmap fonts
33, 38, 42, 46, 50, 58, 67, 75, 83, 92, 100, 117, 133, 150, 167, 200 233,
11, 44, 77, 111, 144 for outline fonts.
Returns:
None
Raises:
... | 2.77479 | 1.628031 | 1.704384 |
'''Select font type
Choices are:
<Bit map fonts>
'brougham'
'lettergothicbold'
'brusselsbit'
'helsinkibit'
'sandiego'
<Outline fonts>
'lettergothic'
'brusselsoutline'
'helsinkioutline'
Args:
... | def select_font(self, font) | Select font type
Choices are:
<Bit map fonts>
'brougham'
'lettergothicbold'
'brusselsbit'
'helsinkibit'
'sandiego'
<Outline fonts>
'lettergothic'
'brusselsoutline'
'helsinkioutline'
Args:
font:... | 3.917226 | 1.966426 | 1.992054 |
'''Sets the character style.
Args:
style: The desired character style. Choose from 'normal', 'outline', 'shadow', and 'outlineshadow'
Returns:
None
Raises:
RuntimeError: Invalid character style
'''
styleset = {'normal': 0,
... | def char_style(self, style) | Sets the character style.
Args:
style: The desired character style. Choose from 'normal', 'outline', 'shadow', and 'outlineshadow'
Returns:
None
Raises:
RuntimeError: Invalid character style | 3.773798 | 2.266033 | 1.665376 |
'''Specifies proportional characters. When turned on, the character spacing set
with charSpacing.
Args:
action: Turn proportional characters on or off.
Returns:
None
Raises:
RuntimeError: Invalid action.
'''
actions = {... | def proportional_char(self, action) | Specifies proportional characters. When turned on, the character spacing set
with charSpacing.
Args:
action: Turn proportional characters on or off.
Returns:
None
Raises:
RuntimeError: Invalid action. | 7.840472 | 2.94017 | 2.666673 |
'''Specifes character spacing in dots.
Args:
dots: the character spacing you desire, in dots
Returns:
None
Raises:
RuntimeError: Invalid dot amount.
'''
if dots in range(0,127):
self.send(chr(27)+chr(32)+chr(dots))
... | def char_spacing(self, dots) | Specifes character spacing in dots.
Args:
dots: the character spacing you desire, in dots
Returns:
None
Raises:
RuntimeError: Invalid dot amount. | 6.460435 | 2.982945 | 2.165791 |
'''Choose a template
Args:
template: String, choose which template you would like.
Returns:
None
Raises:
None
'''
n1 = int(template)/10
n2 = int(template)%10
self.send('^TS'+'0'+str(n1)+str(n2)) | def choose_template(self, template) | Choose a template
Args:
template: String, choose which template you would like.
Returns:
None
Raises:
None | 6.485827 | 4.004005 | 1.619835 |
'''Perform machine operations
Args:
operations: which operation you would like
Returns:
None
Raises:
RuntimeError: Invalid operation
'''
operations = {'feed2start': 1,
'feedone': 2,
'... | def machine_op(self, operation) | Perform machine operations
Args:
operations: which operation you would like
Returns:
None
Raises:
RuntimeError: Invalid operation | 8.628819 | 5.498971 | 1.56917 |
'''Set print start trigger.
Args:
type: The type of trigger you desire.
Returns:
None
Raises:
RuntimeError: Invalid type.
'''
types = {'recieved': 1,
'filled': 2,
'num_recieved': 3}
... | def print_start_trigger(self, type) | Set print start trigger.
Args:
type: The type of trigger you desire.
Returns:
None
Raises:
RuntimeError: Invalid type. | 5.732626 | 3.486745 | 1.64412 |
'''Set print command
Args:
command: the type of command you desire.
Returns:
None
Raises:
RuntimeError: Command too long.
'''
size = len(command)
if size > 20:
raise RuntimeError('Command too long')
... | def print_start_command(self, command) | Set print command
Args:
command: the type of command you desire.
Returns:
None
Raises:
RuntimeError: Command too long. | 5.673266 | 2.869964 | 1.976772 |
'''Set recieved char count limit
Args:
count: the amount of received characters you want to stop at.
Returns:
None
Raises:
None
'''
n1 = count/100
n2 = (count-(n1*100))/10
n3 = (count-((n1*100)+(n2*10)))
... | def received_char_count(self, count) | Set recieved char count limit
Args:
count: the amount of received characters you want to stop at.
Returns:
None
Raises:
None | 4.867808 | 2.759269 | 1.764166 |
'''Select desired delimeter
Args:
delim: The delimeter character you want.
Returns:
None
Raises:
RuntimeError: Delimeter too long.
'''
size = len(delim)
if size > 20:
raise RuntimeError('Delimeter too long')... | def select_delim(self, delim) | Select desired delimeter
Args:
delim: The delimeter character you want.
Returns:
None
Raises:
RuntimeError: Delimeter too long. | 5.758885 | 3.096931 | 1.859546 |
'''Insert text into selected object.
Args:
data: The data you want to insert.
Returns:
None
Raises:
None
'''
if not data:
data = ''
size = len(data)
n1 = size%256
n2 = size/256
... | def insert_into_obj(self, data) | Insert text into selected object.
Args:
data: The data you want to insert.
Returns:
None
Raises:
None | 5.595199 | 3.937783 | 1.420901 |
'''Combines selection and data insertion into one function
Args:
name: the name of the object you want to insert into
data: the data you want to insert
Returns:
None
Raises:
None
'''
self.select_obj(name)
se... | def select_and_insert(self, name, data) | Combines selection and data insertion into one function
Args:
name: the name of the object you want to insert into
data: the data you want to insert
Returns:
None
Raises:
None | 4.200866 | 2.277451 | 1.844547 |
db = Database(db_path)
if db.has_version() and db.version() == version:
return db.connection
return None | def connect_if_correct_version(db_path, version) | Return a sqlite3 database connection if the version in the database's
metadata matches the version argument.
Also implicitly checks for whether the data in this database has
been completely filled, since we set the version last.
TODO: Make an explicit 'complete' flag to the metadata. | 4.006772 | 4.003679 | 1.000772 |
require_string(db_path, "db_path")
require_iterable_of(tables, DatabaseTable)
require_integer(version, "version")
# if the database file doesn't already exist and we encounter an error
# later, delete the file before raising an exception
delete_on_error = not exists(db_path)
# if the ... | def _create_cached_db(
db_path,
tables,
version=1) | Either create or retrieve sqlite database.
Parameters
--------
db_path : str
Path to sqlite3 database file
tables : dict
Dictionary mapping table names to datacache.DatabaseTable objects
version : int, optional
Version acceptable as cached data.
Returns sqlite3 connec... | 3.149332 | 3.297274 | 0.955132 |
tables = []
for table_name, df in table_names_to_dataframes.items():
table_indices = table_names_to_indices.get(table_name, [])
primary_key = table_names_to_primary_keys.get(table_name)
table = DatabaseTable.from_dataframe(
name=table_name,
df=df,
... | def build_tables(
table_names_to_dataframes,
table_names_to_primary_keys={},
table_names_to_indices={}) | Parameters
----------
table_names_to_dataframes : dict
Dictionary mapping each table name to a DataFrame
table_names_to_primary_keys : dict
Dictionary mapping each table to its primary key
table_names_to_indices : dict
Dictionary mapping each table to a set of indices
Retu... | 1.685033 | 1.698503 | 0.99207 |
if overwrite and exists(db_path):
remove(db_path)
tables = build_tables(
table_names_to_dataframes,
table_names_to_primary_keys,
table_names_to_indices)
return _create_cached_db(
db_path,
tables=tables,
version=version) | def db_from_dataframes_with_absolute_path(
db_path,
table_names_to_dataframes,
table_names_to_primary_keys={},
table_names_to_indices={},
overwrite=False,
version=1) | Create a sqlite3 database from a collection of DataFrame objects
Parameters
----------
db_path : str
Path to database file to create
table_names_to_dataframes : dict
Dictionary from table names to DataFrame objects
table_names_to_primary_keys : dict, optional
Name of prima... | 2.334473 | 3.367331 | 0.693271 |
if not (subdir is None or isinstance(subdir, str)):
raise TypeError("Expected subdir to be None or str, got %s : %s" % (
subdir, type(subdir)))
db_path = build_path(db_filename, subdir)
return db_from_dataframes_with_absolute_path(
db_path,
table_names_to_dataframes=... | def db_from_dataframes(
db_filename,
dataframes,
primary_keys={},
indices={},
subdir=None,
overwrite=False,
version=1) | Create a sqlite3 database from a collection of DataFrame objects
Parameters
----------
db_filename : str
Name of database file to create
dataframes : dict
Dictionary from table names to DataFrame objects
primary_keys : dict, optional
Name of primary key column for each tab... | 2.603189 | 3.35075 | 0.776897 |
return db_from_dataframes(
db_filename=db_filename,
dataframes={table_name: df},
primary_keys={table_name: primary_key},
indices={table_name: indices},
subdir=subdir,
overwrite=overwrite,
version=version) | def db_from_dataframe(
db_filename,
table_name,
df,
primary_key=None,
subdir=None,
overwrite=False,
indices=(),
version=1) | Given a dataframe `df`, turn it into a sqlite3 database.
Store values in a table called `table_name`.
Returns full path to the sqlite database file. | 1.977692 | 2.611418 | 0.757325 |
db_filename = base_filename + ("_nrows%d" % len(df))
for column_name in df.columns:
column_db_type = db_type(df[column_name].dtype)
column_name = column_name.replace(" ", "_")
db_filename += ".%s_%s" % (column_name, column_db_type)
return db_filename + ".db" | def _db_filename_from_dataframe(base_filename, df) | Generate database filename for a sqlite3 database we're going to
fill with the contents of a DataFrame, using the DataFrame's
column names and types. | 2.832328 | 2.711364 | 1.044614 |
df = fetch_csv_dataframe(
download_url=download_url,
filename=csv_filename,
subdir=subdir,
**pandas_kwargs)
base_filename = splitext(csv_filename)[0]
if db_filename is None:
db_filename = _db_filename_from_dataframe(base_filename, df)
return db_from_dataframe... | def fetch_csv_db(
table_name,
download_url,
csv_filename=None,
db_filename=None,
subdir=None,
version=1,
**pandas_kwargs) | Download a remote CSV file and create a local sqlite3 database
from its contents | 2.540136 | 2.760936 | 0.920027 |
def get_all(self, security):
url = 'http://www.google.com/finance?q=%s' % security
page = self._request(url)
soup = BeautifulSoup(page)
snapData = soup.find("table", {"class": "snap-data"})
if snapData is None:
raise UfException(Errors.STOCK_SYMBOL_E... | Get all available quote data for the given ticker security.
Returns a dictionary. | null | null | null | |
def quotes(self, security, start, end):
try:
url = 'http://www.google.com/finance/historical?q=%s&startdate=%s&enddate=%s&output=csv' % (security.symbol, start, end)
try:
page = self._request(url)
except UfException as ufExcep:
... | Get historical prices for the given ticker security.
Date format is 'YYYYMMDD'
Returns a nested list. | null | null | null | |
def financials(self, security):
try:
url = 'http://www.google.com/finance?q=%s&fstype=ii' % security
try:
page = self._request(url).read()
except UfException as ufExcep:
# if symol is not right, will get 400
if ... | get financials:
google finance provide annual and quanter financials, if annual is true, we will use annual data
Up to four lastest year/quanter data will be provided by google
Refer to page as an example: http://www.google.com/finance?q=TSE:CVG&fstype=ii | null | null | null | |
def _parseTarget(self, target, keyTimeValue):
''' parse table for get financial '''
table = target.table
timestamps = self._getTimeStamps(table)
for tr in table.tbody.findChildren('tr'):
for i, td in enumerate(tr.findChildren('td')):
if 0 == i:
... | parse table for get financial | null | null | null | |
def _getTimeStamps(self, table):
''' get time stamps '''
timeStamps = []
for th in table.thead.tr.contents:
if '\n' != th:
timeStamps.append(th.getText())
return timeStamps[1:] | get time stamps | null | null | null | |
def ticks(self, security, start, end):
period = 1
# url = 'http://www.google.com/finance/getprices?q=%s&i=%s&p=%sd&f=d,o,h,l,c,v&ts=%s' % (security, interval, period, start)
url = 'http://www.google.com/finance/getprices?q=%s&i=61&p=%sd&f=d,o,h,l,c,v' % (security.symbol, period)
... | Get tick prices for the given ticker security.
@security: stock security
@interval: interval in mins(google finance only support query till 1 min)
@start: start date(YYYYMMDD)
@end: end date(YYYYMMDD)
start and end is disabled since only 15 days data will show
@... | null | null | null | |
schema = self.parent.get_schema(schema)
return Binding(schema, self.parent.resolver, data=data) | def get_binding(self, schema, data) | For a given schema, get a binding mediator providing links to the
RDF terms matching that schema. | 6.447557 | 6.578145 | 0.980148 |
uri = URIRef(id)
if schema is None:
for o in self.graph.objects(subject=uri, predicate=RDF.type):
schema = self.parent.get_schema(str(o))
if schema is not None:
break
else:
schema = self.parent.get_schema(schema... | def get(self, id, depth=3, schema=None) | Construct a single object based on its ID. | 3.672495 | 3.464365 | 1.060077 |
if binding.is_object:
obj = {'$schema': binding.path}
for (s, p, o) in self.graph.triples((node, None, None)):
prop = binding.get_property(p)
if prop is None or depth <= 1 or o in path:
continue
# This is slight... | def _objectify(self, node, binding, depth, path) | Given an RDF node URI (and it's associated schema), return an
object from the ``graph`` that represents the information available
about this node. | 3.620397 | 3.496466 | 1.035445 |
try:
text = tree.xpath(xpath_str, namespaces=self.namespaces)[0].text
return text_type(text) if text else ''
except IndexError: # pragma: nocover
return '' | def get_text_node(self, tree, xpath_str) | Return a text node from given XML tree given an lxml XPath. | 3.184727 | 3.251559 | 0.979446 |
return tree.xpath(xpath_str, namespaces=self.namespaces) | def get_subtree(self, tree, xpath_str) | Return a subtree given an lxml XPath. | 3.865862 | 3.088105 | 1.251856 |
try:
tree = self.get_subtree(tree, 'fundingtree')[0]
except IndexError: # pragma: nocover
pass
funder_node = self.get_subtree(tree, 'funder')
subfunder_node = self.get_subtree(tree, '//funding_level_0')
funder_id = self.get_text_node(funder_nod... | def fundertree2json(self, tree, oai_id) | Convert OpenAIRE's funder XML to JSON. | 2.906501 | 2.883036 | 1.008139 |
tree = etree.fromstring(grant_xml)
# XML harvested from OAI-PMH has a different format/structure
if tree.prefix == 'oai':
ptree = self.get_subtree(
tree, '/oai:record/oai:metadata/oaf:entity/oaf:project')[0]
header = self.get_subtree(tree, '/oai:r... | def grantxml2json(self, grant_xml) | Convert OpenAIRE grant XML into JSON. | 2.777991 | 2.752237 | 1.009357 |
self._connect()
result = self.db_connection.cursor().execute(
"SELECT data, format FROM grants"
)
for data, data_format in result:
if (not as_json) and data_format == 'json':
raise Exception("Cannot convert JSON source to XML output.")
... | def iter_grants(self, as_json=True) | Fetch records from the SQLite database. | 3.756469 | 3.571934 | 1.051662 |
records = self.client.ListRecords(metadataPrefix='oaf',
set=self.setspec)
for rec in records:
try:
grant_out = rec.raw # rec.raw is XML
if as_json:
grant_out = self.grantxml2json(grant_out... | def iter_grants(self, as_json=True) | Fetch grants from a remote OAI-PMH endpoint.
Return the Sickle-provided generator object. | 5.7998 | 5.272433 | 1.100023 |
connection = sqlite3.connect(self.destination)
format_ = 'json' if as_json else 'xml'
if not self._db_exists(connection):
connection.execute(
"CREATE TABLE grants (data text, format text)")
# This will call the RemoteOAIRELoader.iter_grants and fetch... | def dump(self, as_json=True, commit_batch_size=100) | Dump the grant information to a local storage.
:param as_json: Convert XML to JSON before saving (default: True). | 3.834269 | 3.908699 | 0.980958 |
prefix, attrib = prefixed_attrib.split(':')
return et_node.get('{{{0}}}{1}'.format(self.namespaces[prefix],
attrib)) | def get_attrib(self, et_node, prefixed_attrib) | Get a prefixed attribute like 'rdf:resource' from ET node. | 3.619183 | 3.31166 | 1.092861 |
doi = FundRefDOIResolver.strip_doi_host(self.get_attrib(node,
'rdf:about'))
oaf_id = FundRefDOIResolver().resolve_by_doi(
"http://dx.doi.org/" + doi)
name = node.find('./skosxl:prefLabel/skosxl:Label/skosxl:literalForm',
... | def fundrefxml2json(self, node) | Convert a FundRef 'skos:Concept' node into JSON. | 2.729355 | 2.662531 | 1.025098 |
root = self.doc_root
funders = root.findall('./skos:Concept', namespaces=self.namespaces)
for funder in funders:
funder_json = self.fundrefxml2json(funder)
yield funder_json | def iter_funders(self) | Get a converted list of Funders as JSON dict. | 5.379097 | 4.519811 | 1.190115 |
if oai_id.startswith('oai:dnet:'):
oai_id = oai_id[len('oai:dnet:'):]
prefix = oai_id.split("::")[0]
suffix = prefix.replace("_", "").upper()
oaf = "{0}::{1}".format(prefix, suffix)
return self.data.get(oaf) | def resolve_by_oai_id(self, oai_id) | Resolve the funder from the OpenAIRE OAI record id.
Hack for when funder is not provided in OpenAIRE. | 3.91751 | 3.789294 | 1.033836 |
pieces = []
for piece in resource.split('/'):
if path.sep in piece \
or (path.altsep and path.altsep in piece) or \
piece == path.pardir:
raise ResourceNotFound(resource)
elif piece and piece != '.':
pieces.append(piece)
return pieces | def split_resource_path(resource) | Split a path into segments and perform a sanity check. If it detects
'..' in the path it will raise a `TemplateNotFound` error. | 3.952022 | 3.515114 | 1.124294 |
seen = set()
def _traverse(binding):
if binding.path in seen:
return
seen.add(binding.path)
if binding.is_object:
for prop in binding.properties:
yield (binding.path, prop.name, tuple(prop.types))
for pred in _traverse(prop):... | def predicates(graph) | Return a listing of all known predicates in the registered schemata,
including the schema path they associate with, their name and allowed
types. | 3.256138 | 2.876341 | 1.132042 |
new = old.upgradeVersion(old.typeName, 1, 2, installedOn=None)
for iface in new.store.interfacesFor(new):
new.store.powerDown(new, iface)
new.deleteFromStore() | def passwordReset1to2(old) | Power down and delete the item | 10.586744 | 10.442623 | 1.013801 |
newUserInfo = oldUserInfo.upgradeVersion(
UserInfo.typeName, 1, 2,
realName=oldUserInfo.firstName + u" " + oldUserInfo.lastName)
return newUserInfo | def upgradeUserInfo1to2(oldUserInfo) | Concatenate the I{firstName} and I{lastName} attributes from the old user
info item and set the result as the I{realName} attribute of the upgraded
item. | 7.260801 | 6.317157 | 1.149378 |
if isinstance(old.benefactor, Multifactor):
types = list(chain(*[b.powerupNames for b in
old.benefactor.benefactors('ascending')]))
elif isinstance(old.benefactor, InitializerBenefactor):
#oh man what a mess
types = list(chain(*[b.powerupNames for b in
... | def ticket1to2(old) | change Ticket to refer to Products and not benefactor factories. | 6.65379 | 6.002692 | 1.108468 |
# Note the underscore; this _should_ be a public API but it is currently an
# unfortunate hack; there should be a different powerup interface that
# requires prompt and prefixURL attributes rather than _SignupTracker.
# -glyph
for tr in siteStore.query(_SignupTracker):
si = tr.signupI... | def _getPublicSignupInfo(siteStore) | Get information about public web-based signup mechanisms.
@param siteStore: a store with some signups installed on it (as indicated
by _SignupTracker instances).
@return: a generator which yields 2-tuples of (prompt, url) where 'prompt'
is unicode briefly describing the signup mechanism (e.g. "Sign Up... | 14.914084 | 11.148705 | 1.337741 |
if len(segments) == 1:
attempt = self.attemptByKey(unicode(segments[0]))
if attempt is not None:
self.attempt = attempt
return (self, ())
return NotFound | def locateChild(self, ctx, segments) | Initialize self with the given key's L{_PasswordResetAttempt}, if any.
@param segments: a L{_PasswordResetAttempt} key (hopefully)
@return: C{(self, ())} with C{self.attempt} initialized, or L{NotFound}
@see: L{attemptByKey} | 6.421635 | 2.921867 | 2.197785 |
req = inevow.IRequest(ctx)
if req.method == 'POST':
if req.args.get('username', [''])[0]:
user = unicode(usernameFromRequest(req), 'ascii')
self.handleRequestForUser(user, URL.fromContext(ctx))
self.fragment = self.templateResolver.ge... | def renderHTTP(self, ctx) | Handle the password reset form.
The following exchange describes the process:
S: Render C{reset}
C: POST C{username} or C{email}
S: L{handleRequestForUser}, render C{reset-check-email}
(User follows the emailed reset link)
S: Render C{reset-step-tw... | 4.483543 | 3.672625 | 1.220801 |
attempt = self.newAttemptForUser(username)
account = self.accountByAddress(username)
if account is None:
# do we want to disclose this to the user?
return
email = self.getExternalEmail(account)
if email is not None:
self.sendEmail(url,... | def handleRequestForUser(self, username, url) | User C{username} wants to reset their password. Create an attempt
item, and send them an email if the username is valid | 5.913257 | 5.480307 | 1.079001 |
host = url.netloc.split(':', 1)[0]
from_ = 'reset@' + host
body = file(sibpath(__file__, 'reset.rfc2822')).read()
body %= {'from': from_,
'to': email,
'date': rfc822.formatdate(),
'message-id': smtp.messageid(),
... | def sendEmail(self, url, attempt, email, _sendEmail=_sendEmail) | Send an email for the given L{_PasswordResetAttempt}.
@type url: L{URL}
@param url: The URL of the password reset page.
@type attempt: L{_PasswordResetAttempt}
@param attempt: An L{Item} representing a particular user's attempt to
reset their password.
@type email: C{s... | 6.258113 | 5.729305 | 1.092299 |
return self.store.findUnique(_PasswordResetAttempt,
_PasswordResetAttempt.key == key,
default=None) | def attemptByKey(self, key) | Locate the L{_PasswordResetAttempt} that corresponds to C{key} | 14.165992 | 4.217456 | 3.358895 |
return unicode(hashlib.md5(str((usern, time.time(), random.random()))).hexdigest()) | def _makeKey(self, usern) | Make a new, probably unique key. This key will be sent in an email to
the user and is used to access the password change form. | 5.596482 | 4.720192 | 1.185647 |
# we could query for other attempts by the same
# user within some timeframe and raise an exception,
# if we wanted
return _PasswordResetAttempt(store=self.store,
username=user,
timestamp=extime.Time(),
... | def newAttemptForUser(self, user) | Create an L{_PasswordResetAttempt} for the user whose username is C{user}
@param user: C{unicode} username | 14.065905 | 12.173789 | 1.155425 |
self.accountByAddress(attempt.username).password = newPassword
self.store.query(
PersistentSession,
PersistentSession.authenticatedAs == str(attempt.username)
).deleteFromStore()
attempt.deleteFromStore() | def resetPassword(self, attempt, newPassword) | @param attempt: L{_PasswordResetAttempt}
reset the password of the user who initiated C{attempt} to C{newPassword},
and afterward, delete the attempt and any persistent sessions that belong
to the user | 12.175303 | 7.606179 | 1.600712 |
ticket = self.createTicket(issuer,
unicode(email, 'ascii'),
product)
nonce = ticket.nonce
signupInfo = {'from': 'signup@'+domainName,
'to': email,
'date': rfc822.formatdat... | def issueViaEmail(self, issuer, email, product, templateData,
domainName, httpPort=80) | Send a ticket via email to the supplied address, which, when claimed, will
create an avatar and allow the given product to endow it with
things.
@param issuer: An object, preferably a user, to track who issued this
ticket.
@param email: a str, formatted as an rfc2821 email addr... | 6.413125 | 4.882035 | 1.313617 |
if len(username) < 2:
return [False, u"Username too short"]
for char in u"[ ,:;<>@()!\"'%&\\|\t\b":
if char in username:
return [False,
u"Username contains invalid character: '%s'" % char]
# The localpart is acceptable if ... | def usernameAvailable(self, username, domain) | Check to see if a username is available for the user to select. | 5.070418 | 5.160333 | 0.982576 |
# XXX This method should be called in a transaction, it shouldn't
# start a transaction itself.
def _():
loginsystem = self.store.findUnique(userbase.LoginSystem)
# Create an account with the credentials they specified,
# making it internal since it ... | def createUser(self, realName, username, domain, password, emailAddress) | Create a user, storing some associated metadata in the user's store,
i.e. their first and last names (as a L{UserInfo} item), and a
L{axiom.userbase.LoginMethod} allowing them to login with their email
address.
@param realName: the real name of the user.
@type realName: C{unicod... | 9.964159 | 9.254254 | 1.076711 |
siteStore = self.store.parent
booth = siteStore.findOrCreate(TicketBooth, lambda booth: installOn(booth, siteStore))
signupItem = signupClass(
store=siteStore,
booth=booth,
product=product,
emailTemplate=emailTemplate,
prompt... | def createSignup(self, creator, signupClass, signupConf,
product, emailTemplate, prompt) | Create a new signup facility in the site store's database.
@param creator: a unicode string describing the creator of the new
signup mechanism, for auditing purposes.
@param signupClass: the item type of the signup mechanism to create.
@param signupConf: a dictionary of keyword argume... | 5.156825 | 5.377154 | 0.959025 |
productPicker = liveform.LiveForm(
self.coerceProduct,
[liveform.Parameter(
str(id(product)),
liveform.FORM_INPUT,
liveform.LiveForm(
lambda selectedProduct, product=product: selectedProduct and product,
[live... | def makeProductPicker(self) | Make a LiveForm with radio buttons for each Product in the store. | 10.343099 | 8.718592 | 1.186327 |
for tracker in trackers:
if tracker.store is None:
# we're not updating the list of live signups client side, so
# we might get a signup that has already been deleted
continue
sig = tracker.signupItem
# XXX the only ... | def _deleteTrackers(self, trackers) | Delete the given signup trackers and their associated signup resources.
@param trackers: sequence of L{_SignupTrackers} | 13.743339 | 12.58055 | 1.092427 |
api = self.doapi_manager
return api._image(api.request(self.url)["image"]) | def fetch(self) | Fetch & return a new `Image` object representing the image's current
state
:rtype: Image
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the image no longer exists) | 43.342339 | 28.012697 | 1.547239 |
# The `_image` is to avoid conflicts with MutableMapping.update.
api = self.doapi_manager
return api._image(api.request(self.url, method='PUT',
data={"name": name})["image"]) | def update_image(self, name) | Update (i.e., rename) the image
:param str name: the new name for the image
:return: an updated `Image` object
:rtype: Image
:raises DOAPIError: if the API endpoint replies with an error | 23.222599 | 27.364338 | 0.848645 |
'''Pick a random name form a specified list of name parts'''
nameformat = nameformat or self.nameformat
capitalize = capitalize or self.capitalize
formatters = formatters or {}
lines = self._get_lines(kwargs)
names = dict((k, v['name']) for k, v in list(lines.items()))
... | def generate(self, nameformat=None, capitalize=None, formatters=None, **kwargs) | Pick a random name form a specified list of name parts | 3.337269 | 3.00127 | 1.111952 |
'''Given a numeric frequency, pick a line from a csv with a cumulative frequency field'''
if resource_exists('censusname', filename):
with closing(resource_stream('censusname', filename)) as b:
g = codecs.iterdecode(b, 'ascii')
return self._pick_frequency_line... | def pick_frequency_line(self, filename, frequency, cumulativefield='cumulative_frequency') | Given a numeric frequency, pick a line from a csv with a cumulative frequency field | 4.386017 | 3.410443 | 1.286055 |
project_name = git_repo()
if not project_name and sys.argv:
project_name = sys.argv[0]
if not project_name:
project_name = "unknown"
dirpath = os.path.join(DFL_DIR_PARENT, project_name)
return os.path.expanduser(dirpath) | def dfl_local_dir() | Infers a default local directory, which is DFL_DIR_PARENT/<project name>,
where the project name is guessed according to the following rules.
If we detect we're in a repository, the project name is the repository name
(git only for now).
If we're not in a repository, and the script file sys.argv[0] is... | 3.369544 | 2.711856 | 1.242523 |
try:
reldir = subprocess.check_output(
["git", "rev-parse", "--git-dir"])
reldir = reldir.decode("utf-8")
return os.path.basename(os.path.dirname(os.path.abspath(reldir)))
except subprocess.CalledProcessError:
return None | def git_repo() | Returns the git repository root if the cwd is in a repo, else None | 2.673156 | 2.529801 | 1.056666 |
if git_repo() is None:
return "unknown"
git_hash = subprocess.check_output(
["git", "rev-parse", "HEAD"])
# git_hash is a byte string; we want a string.
git_hash = git_hash.decode("utf-8")
# git_hash also comes with an extra \n at the end, which we remove.
git_hash = git_has... | def git_hash() | returns the current git hash or unknown if not in git repo | 3.072226 | 2.867166 | 1.07152 |
if git_repo() is None:
return "unknown"
pretty = subprocess.check_output(
["git", "log", "--pretty=format:%h %s", "-n", "1"])
pretty = pretty.decode("utf-8")
pretty = pretty.strip()
return pretty | def git_pretty() | returns a pretty summary of the commit or unkown if not in git repo | 3.189091 | 2.698361 | 1.181862 |
cmdargs = [sys.executable] + sys.argv[:]
invocation = " ".join(shlex.quote(s) for s in cmdargs)
return invocation | def invocation() | reconstructs the invocation for this python program | 4.388067 | 3.611839 | 1.214912 |
def wrapped(instance, req, resp, **kwargs):
assert not req.get_param("unicode") or req.get_param("unicode") == u"✓", "Unicode sanity check failed"
resp.set_header("Cache-Control", "no-cache, no-store, must-revalidate");
resp.set_header("Pragma", "no-cache");
resp.set_header("Exp... | def serialize(func) | Falcon response serialization | 2.47622 | 2.520363 | 0.982485 |
def readRow(self, row, startCol=0, endCol=-1):
''' read row '''
return self.__operation.readRow(row, startCol, endCol) | read row | null | null | null | |
def readCol(self, col, startRow=0, endRow=-1):
''' read col '''
return self.__operation.readCol(col, startRow, endRow) | read col | null | null | null | |
def writeCell(self, row, col, value):
''' write cell'''
self.__operation.writeCell(row, col, value) | write cell | null | null | null | |
def openSheet(self, name):
''' set a sheet to write '''
if name not in self.__sheetNameDict:
sheet = self.__workbook.add_sheet(name)
self.__sheetNameDict[name] = sheet
self.__sheet = self.__sheetNameDict[name] | set a sheet to write | null | null | null | |
def __getSheet(self, name):
''' get a sheet by name '''
if not self.sheetExsit(name):
raise UfException(Errors.SHEET_NAME_INVALID, "Can't find a sheet named %s" % name)
return self.__sheetNameDict[name] | get a sheet by name | null | null | null | |
def writeCell(self, row, col, value):
''' write a cell '''
if self.__sheet is None:
self.openSheet(super(ExcelWrite, self).DEFAULT_SHEET)
self.__sheet.write(row, col, value) | write a cell | null | null | null | |
def writeRow(self, row, values):
'''
write a row
Not sure whether xlwt support write the same cell multiple times
'''
if self.__sheet is None:
self.openSheet(super(ExcelWrite, self).DEFAULT_SHEET)
for index, value in enumerate(values):
se... | write a row
Not sure whether xlwt support write the same cell multiple times | null | null | null | |
def readCell(self, row, col):
''' read a cell'''
try:
if self.__sheet is None:
self.openSheet(super(ExcelRead, self).DEFAULT_SHEET)
return self.__sheet.cell(row, col).value
except BaseException as excp:
raise UfException(Errors.UNKNOWN... | read a cell | null | null | null | |
# file may exist locally in compressed and decompressed states
# delete both
for decompress in [False, True]:
key = (url, decompress)
if key in self._local_paths:
path = self._local_paths[key]
remove(path)
del self.... | def delete_url(self, url) | Delete local files downloaded from given URL | 6.34238 | 6.23491 | 1.017237 |
return download.file_exists(
url,
filename=filename,
decompress=decompress,
subdir=self.subdir) | def exists(self, url, filename=None, decompress=False) | Return True if a local file corresponding to these arguments
exists. | 5.06144 | 5.277839 | 0.958998 |
key = (url, decompress)
if not force and key in self._local_paths:
path = self._local_paths[key]
if exists(path):
return path
else:
del self._local_paths[key]
path = download.fetch_file(
url,
fil... | def fetch(
self,
url,
filename=None,
decompress=False,
force=False,
timeout=None,
use_wget_if_available=True) | Return the local path to the downloaded copy of a given URL.
Don't download the file again if it's already present,
unless `force` is True. | 2.191649 | 2.180896 | 1.004931 |
return common.build_local_filename(url, filename, decompress) | def local_filename(
self,
url=None,
filename=None,
decompress=False) | What local filename will we use within the cache directory
for the given URL/filename/decompress options. | 7.858397 | 8.702634 | 0.902991 |
if download:
return self.fetch(url=url, filename=filename, decompress=decompress)
else:
filename = self.local_filename(url, filename, decompress)
return join(self.cache_directory_path, filename) | def local_path(self, url, filename=None, decompress=False, download=False) | What will the full local path be if we download the given file? | 3.123982 | 2.894275 | 1.079366 |
return ConnectionManager.connect_redis(
redis_client=redis_client, name=name, transaction=transaction) | def connect_redis(redis_client, name=None, transaction=False) | Connect your redis-py instance to redpipe.
Example:
.. code:: python
redpipe.connect_redis(redis.StrictRedis(), name='users')
Do this during your application bootstrapping.
You can also pass a redis-py-cluster instance to this method.
.. code:: python
redpipe.connect_redis(re... | 4.573535 | 8.925415 | 0.512417 |
new_pool = pipeline_method().connection_pool
try:
if cls.get(name).connection_pool != new_pool:
raise AlreadyConnected("can't change connection for %s" % name)
except InvalidPipeline:
pass
cls.connections[name] = pipeline_method | def connect(cls, pipeline_method, name=None) | Low level logic to bind a callable method to a name.
Don't call this directly unless you know what you are doing.
:param pipeline_method: callable
:param name: str optional
:return: None | 6.374982 | 7.380797 | 0.863725 |
connection_pool = redis_client.connection_pool
if connection_pool.connection_kwargs.get('decode_responses', False):
raise InvalidPipeline('decode_responses set to True')
def pipeline_method():
return redis_client.pipeline(transaction=transaction)
... | def connect_redis(cls, redis_client, name=None, transaction=False) | Store the redis connection in our connector instance.
Do this during your application bootstrapping.
We call the pipeline method of the redis client.
The ``redis_client`` can be either a redis or rediscluster client.
We use the interface, not the actual class.
That means we c... | 4.880301 | 5.824365 | 0.837911 |
newIndexer = oldIndexer.upgradeVersion(
oldIndexer.typeName, 1, 2,
indexCount=oldIndexer.indexCount,
installedOn=oldIndexer.installedOn,
indexDirectory=oldIndexer.indexDirectory)
listeners = newIndexer.store.query(
batch._ReliableListener,
batch._ReliableLis... | def remoteIndexer1to2(oldIndexer) | Previously external application code was responsible for adding a
RemoteListener to a batch work source as a reliable listener. This
precluded the possibility of the RemoteListener resetting itself
unilaterally. With version 2, RemoteListener takes control of adding
itself as a reliable listener and k... | 6.981301 | 6.398025 | 1.091165 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.