text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def create_or_update(sender, **kwargs):
"""
Create or update an Activity Monitor item from some instance.
"""
now = datetime.datetime.now()
# I can't explain why this import fails unless it's here.
from activity_monitor.models import Activity
instance = kwargs['instance']
# Find this o... | [
"def",
"create_or_update",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"# I can't explain why this import fails unless it's here.",
"from",
"activity_monitor",
".",
"models",
"import",
"Activity",
... | 43.061947 | 24.053097 |
def add_select(self, *column):
"""
Add a new select column to query
:param column: The column to add
:type column: str
:return: The current QueryBuilder instance
:rtype: QueryBuilder
"""
if not column:
column = []
self.columns += lis... | [
"def",
"add_select",
"(",
"self",
",",
"*",
"column",
")",
":",
"if",
"not",
"column",
":",
"column",
"=",
"[",
"]",
"self",
".",
"columns",
"+=",
"list",
"(",
"column",
")",
"return",
"self"
] | 20.9375 | 16.6875 |
def delete_list_item(self, item_id):
""" Delete an existing list item
:param item_id: Id of the item to be delted
"""
url = self.build_url(self._endpoints.get('get_item_by_id').format(item_id=item_id))
response = self.con.delete(url)
return bool(response) | [
"def",
"delete_list_item",
"(",
"self",
",",
"item_id",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'get_item_by_id'",
")",
".",
"format",
"(",
"item_id",
"=",
"item_id",
")",
")",
"response",
"=",
... | 27 | 21.636364 |
def __driver_completer(self, toks, text, state):
"""Driver level completer.
Arguments:
toks: A list of tokens, tokenized from the original input line.
text: A string, the text to be replaced if a completion candidate is
chosen.
state: An integer, the ... | [
"def",
"__driver_completer",
"(",
"self",
",",
"toks",
",",
"text",
",",
"state",
")",
":",
"if",
"state",
"!=",
"0",
":",
"return",
"self",
".",
"__completion_candidates",
"[",
"state",
"]",
"# Update the cache when this method is first called, i.e., state == 0.",
... | 37.604167 | 21.125 |
def import_url(self, url=None, force=None):
"""
Read a list of host entries from a URL, convert them into instances of HostsEntry and
then append to the list of entries in Hosts
:param url: The URL of where to download a hosts file
:return: Counts reflecting the attempted additio... | [
"def",
"import_url",
"(",
"self",
",",
"url",
"=",
"None",
",",
"force",
"=",
"None",
")",
":",
"file_contents",
"=",
"self",
".",
"get_hosts_by_url",
"(",
"url",
"=",
"url",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"file_contents",
"=",
"file_contents",... | 44.586207 | 14.103448 |
def solve_simple_captcha(self, pathfile=None, filedata=None, filename=None):
"""
Upload a image (from disk or a bytearray), and then
block until the captcha has been solved.
Return value is the captcha result.
either pathfile OR filedata should be specified. Filename is ignored (and is
only kept for compat... | [
"def",
"solve_simple_captcha",
"(",
"self",
",",
"pathfile",
"=",
"None",
",",
"filedata",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"if",
"pathfile",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"pathfile",
")",
":",
"fp",
"=",
"open",
"... | 30.441176 | 23.970588 |
def init_app(self, app, url='/hooks'):
"""Register the URL route to the application.
:param app: the optional :class:`~flask.Flask` instance to
register the extension
:param url: the url that events will be posted to
"""
app.config.setdefault('VALIDATE_IP', True)... | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"url",
"=",
"'/hooks'",
")",
":",
"app",
".",
"config",
".",
"setdefault",
"(",
"'VALIDATE_IP'",
",",
"True",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'VALIDATE_SIGNATURE'",
",",
"True",
")",
... | 36.979592 | 18 |
def get_order_book(self, code):
"""
获取实时摆盘数据
:param code: 股票代码
:return: (ret, data)
ret == RET_OK 返回字典,数据格式如下
ret != RET_OK 返回错误字符串
{‘code’: 股票代码
‘Ask’:[ (ask_price1, ask_volume1,order_num), (ask_price2, ask_volume2, ord... | [
"def",
"get_order_book",
"(",
"self",
",",
"code",
")",
":",
"if",
"code",
"is",
"None",
"or",
"is_str",
"(",
"code",
")",
"is",
"False",
":",
"error_str",
"=",
"ERROR_STR_PREFIX",
"+",
"\"the type of code param is wrong\"",
"return",
"RET_ERROR",
",",
"error_... | 29.555556 | 21.555556 |
def get_fabric_tasks(self, project):
"""
Generate a list of fabric tasks that are available
"""
cache_key = 'project_{}_fabfile_tasks'.format(project.pk)
cached_result = cache.get(cache_key)
if cached_result:
return cached_result
try:
fa... | [
"def",
"get_fabric_tasks",
"(",
"self",
",",
"project",
")",
":",
"cache_key",
"=",
"'project_{}_fabfile_tasks'",
".",
"format",
"(",
"project",
".",
"pk",
")",
"cached_result",
"=",
"cache",
".",
"get",
"(",
"cache_key",
")",
"if",
"cached_result",
":",
"re... | 33.478261 | 22.086957 |
def listener(self):
"""Helper for mt_interact() -- this executes in the other thread."""
while 1:
try:
data = self.read_eager()
except EOFError:
print('*** Connection closed by remote host ***')
return
if data:
... | [
"def",
"listener",
"(",
"self",
")",
":",
"while",
"1",
":",
"try",
":",
"data",
"=",
"self",
".",
"read_eager",
"(",
")",
"except",
"EOFError",
":",
"print",
"(",
"'*** Connection closed by remote host ***'",
")",
"return",
"if",
"data",
":",
"self",
".",... | 32.75 | 14.416667 |
def zncc(ts1,ts2):
"""Zero mean normalised cross-correlation (ZNCC)
This function does ZNCC of two signals, ts1 and ts2
Normalisation by very small values is avoided by doing
max(nmin,nvalue)
Parameters
--------------
ts1 : ndarray
Input signal 1 to be aligned with
ts2 : nd... | [
"def",
"zncc",
"(",
"ts1",
",",
"ts2",
")",
":",
"# Output is the same size as ts1",
"Ns1",
"=",
"np",
".",
"size",
"(",
"ts1",
")",
"Ns2",
"=",
"np",
".",
"size",
"(",
"ts2",
")",
"ts_out",
"=",
"np",
".",
"zeros",
"(",
"(",
"Ns1",
",",
"1",
")"... | 29.258621 | 18.206897 |
def fast_clone(self, VM, clone_name, mem=None):
"""
Create a 'fast' clone of a VM. This means we make
a snapshot of the disk and copy some of the settings
and then create a new VM based on the snapshot and settings
The VM is transient so when it is shutdown it deletes itself
... | [
"def",
"fast_clone",
"(",
"self",
",",
"VM",
",",
"clone_name",
",",
"mem",
"=",
"None",
")",
":",
"disks",
"=",
"VM",
".",
"get_disks",
"(",
")",
"ints",
"=",
"VM",
".",
"get_interfaces",
"(",
")",
"count",
"=",
"0",
"new_disks",
"=",
"[",
"]",
... | 35.085714 | 15.428571 |
def export(self, class_name, method_name, export_data=False,
export_dir='.', export_filename='data.json',
export_append_checksum=False, **kwargs):
"""
Port a trained estimator to the syntax of a chosen programming language.
Parameters
----------
:pa... | [
"def",
"export",
"(",
"self",
",",
"class_name",
",",
"method_name",
",",
"export_data",
"=",
"False",
",",
"export_dir",
"=",
"'.'",
",",
"export_filename",
"=",
"'data.json'",
",",
"export_append_checksum",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
... | 38.974359 | 17.538462 |
def _get_option(self, settings, find_key):
""" Return index for provided key """
# This is used as in IAR template, everything
# is as an array with random positions. We look for key with an index
for option in settings:
if option['name'] == find_key:
return ... | [
"def",
"_get_option",
"(",
"self",
",",
"settings",
",",
"find_key",
")",
":",
"# This is used as in IAR template, everything ",
"# is as an array with random positions. We look for key with an index",
"for",
"option",
"in",
"settings",
":",
"if",
"option",
"[",
"'name'",
"... | 48 | 9.857143 |
def _is_axis_allowed(self, axis):
"""Check if axis are allowed.
In case the calculation is requested over CA items dimension, it is not
valid. It's valid in all other cases.
"""
if axis is None:
# If table direction was requested, we must ensure that each slice
... | [
"def",
"_is_axis_allowed",
"(",
"self",
",",
"axis",
")",
":",
"if",
"axis",
"is",
"None",
":",
"# If table direction was requested, we must ensure that each slice",
"# doesn't have the CA items dimension (thus the [-2:] part). It's",
"# OK for the 0th dimension to be items, since no c... | 37.870968 | 18.83871 |
def __filename_to_modname(self, pathname):
"""
@type pathname: str
@param pathname: Pathname to a module.
@rtype: str
@return: Module name.
"""
filename = PathOperations.pathname_to_filename(pathname)
if filename:
filename = filename.lower()... | [
"def",
"__filename_to_modname",
"(",
"self",
",",
"pathname",
")",
":",
"filename",
"=",
"PathOperations",
".",
"pathname_to_filename",
"(",
"pathname",
")",
"if",
"filename",
":",
"filename",
"=",
"filename",
".",
"lower",
"(",
")",
"filepart",
",",
"extpart"... | 29.894737 | 13.789474 |
def ekdelr(handle, segno, recno):
"""
Delete a specified record from a specified E-kernel segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekdelr_c.html
:param handle: File handle.
:type handle: int
:param segno: Segment number.
:type segno: int
:param recno: Record num... | [
"def",
"ekdelr",
"(",
"handle",
",",
"segno",
",",
"recno",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
"handle",
")",
"segno",
"=",
"ctypes",
".",
"c_int",
"(",
"segno",
")",
"recno",
"=",
"ctypes",
".",
"c_int",
"(",
"recno",
")",
"libs... | 28.176471 | 15 |
def remove_users_from_account_group(self, account_id, group_id, **kwargs): # noqa: E501
"""Remove users from a group. # noqa: E501
An endpoint for removing users from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/policy-groups/{groupID}/users... | [
"def",
"remove_users_from_account_group",
"(",
"self",
",",
"account_id",
",",
"group_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
"... | 60.826087 | 35.347826 |
def load_model(self, tid, custom_objects=None):
"""Load saved keras model of the trial.
If tid = None, get the best model
Not applicable for trials ran in cross validion (i.e. not applicable
for `CompileFN.cv_n_folds is None`
"""
if tid is None:
tid = self.b... | [
"def",
"load_model",
"(",
"self",
",",
"tid",
",",
"custom_objects",
"=",
"None",
")",
":",
"if",
"tid",
"is",
"None",
":",
"tid",
"=",
"self",
".",
"best_trial_tid",
"(",
")",
"model_path",
"=",
"self",
".",
"get_trial",
"(",
"tid",
")",
"[",
"\"res... | 35.461538 | 18.384615 |
def __replace(config, wildcards, config_file):
"""For each kvp in config, do wildcard substitution on the values"""
for config_key in config:
config_value = config[config_key]
original_value = config_value
if isinstance(config_value, str):
for token in wildcards:
if wildcards[token]:
... | [
"def",
"__replace",
"(",
"config",
",",
"wildcards",
",",
"config_file",
")",
":",
"for",
"config_key",
"in",
"config",
":",
"config_value",
"=",
"config",
"[",
"config_key",
"]",
"original_value",
"=",
"config_value",
"if",
"isinstance",
"(",
"config_value",
... | 45.333333 | 16.666667 |
def update(self, E=None, **F):
'''flatten nested dictionaries to update pathwise
>>> Config({'foo': {'bar': 'glork'}}).update({'foo': {'blub': 'bla'}})
{'foo': {'bar': 'glork', 'blub': 'bla'}
In contrast to:
>>> {'foo': {'bar': 'glork'}}.update({'foo': {'blub': 'bla'}})
... | [
"def",
"update",
"(",
"self",
",",
"E",
"=",
"None",
",",
"*",
"*",
"F",
")",
":",
"def",
"_update",
"(",
"D",
")",
":",
"for",
"k",
",",
"v",
"in",
"D",
".",
"items",
"(",
")",
":",
"if",
"super",
"(",
"ConfigDict",
",",
"self",
")",
".",
... | 29.033333 | 21.033333 |
def query_raw(self, query, order_by=None, limit=None, offset=0):
"""
Do a full-text query on the OpenSearch API using the format specified in
https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch
DEPRECATED: use :meth:`query(raw=...) <.query>` instead. This method w... | [
"def",
"query_raw",
"(",
"self",
",",
"query",
",",
"order_by",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"0",
")",
":",
"warnings",
".",
"warn",
"(",
"\"query_raw() has been merged with query(). use query(raw=...) instead.\"",
",",
"PendingDepre... | 44.0625 | 27.375 |
def wait_for_resource_value_changes(self, wait: int=10):
"""
Long polling for changes and return a dictionary with resource:value
for changes
"""
changes = {}
payload = """<waitForResourceValueChanges1
xmlns=\"utcs\">{timeout}</waitForResourceValueCha... | [
"def",
"wait_for_resource_value_changes",
"(",
"self",
",",
"wait",
":",
"int",
"=",
"10",
")",
":",
"changes",
"=",
"{",
"}",
"payload",
"=",
"\"\"\"<waitForResourceValueChanges1\n xmlns=\\\"utcs\\\">{timeout}</waitForResourceValueChanges1>\n ... | 44.289474 | 17.868421 |
def days_to_hmsm(days):
"""
Convert fractional days to hours, minutes, seconds, and microseconds.
Precision beyond microseconds is rounded to the nearest microsecond.
Parameters
----------
days : float
A fractional number of days. Must be less than 1.
Returns
-------
hour :... | [
"def",
"days_to_hmsm",
"(",
"days",
")",
":",
"hours",
"=",
"days",
"*",
"24.",
"hours",
",",
"hour",
"=",
"math",
".",
"modf",
"(",
"hours",
")",
"mins",
"=",
"hours",
"*",
"60.",
"mins",
",",
"min",
"=",
"math",
".",
"modf",
"(",
"mins",
")",
... | 17.446809 | 25.148936 |
def get_events(self, from_=None, to=None):
"""Query a slice of the events.
Events are always returned in the order the were added.
Parameters:
from_ -- if not None, return only events added after the event with
id `from_`. If None, return from the start of history.... | [
"def",
"get_events",
"(",
"self",
",",
"from_",
"=",
"None",
",",
"to",
"=",
"None",
")",
":",
"assert",
"from_",
"is",
"None",
"or",
"isinstance",
"(",
"from_",
",",
"str",
")",
"assert",
"to",
"is",
"None",
"or",
"isinstance",
"(",
"to",
",",
"st... | 42.585366 | 18.926829 |
def add_group_email_grant(self, permission, email_address, headers=None):
"""
Convenience method that provides a quick way to add an email group
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
... | [
"def",
"add_group_email_grant",
"(",
"self",
",",
"permission",
",",
"email_address",
",",
"headers",
"=",
"None",
")",
":",
"acl",
"=",
"self",
".",
"get_acl",
"(",
"headers",
"=",
"headers",
")",
"acl",
".",
"add_group_email_grant",
"(",
"permission",
",",... | 47.45 | 20.75 |
def get_all_tweets(screen_name, api, since_id):
""" Get all tweets for the givens screen_name. Returns list of text/created_at pairs. """
# Twitter only allows access to a users most recent 3240 tweets with this method
all_tweets = []
# initial request for most recent tweets (200 is the maximum allowed ... | [
"def",
"get_all_tweets",
"(",
"screen_name",
",",
"api",
",",
"since_id",
")",
":",
"# Twitter only allows access to a users most recent 3240 tweets with this method",
"all_tweets",
"=",
"[",
"]",
"# initial request for most recent tweets (200 is the maximum allowed count)",
"new_twe... | 58.764706 | 22.823529 |
def new_text_and_position(self):
"""
Return (new_text, new_cursor_position) for this completion.
"""
if self.complete_index is None:
return self.original_document.text, self.original_document.cursor_position
else:
original_text_before_cursor = self.origina... | [
"def",
"new_text_and_position",
"(",
"self",
")",
":",
"if",
"self",
".",
"complete_index",
"is",
"None",
":",
"return",
"self",
".",
"original_document",
".",
"text",
",",
"self",
".",
"original_document",
".",
"cursor_position",
"else",
":",
"original_text_bef... | 43.947368 | 21.947368 |
def gap_to_sorl(time_gap):
"""
P1D to +1DAY
:param time_gap:
:return: solr's format duration.
"""
quantity, unit = parse_ISO8601(time_gap)
if unit[0] == "WEEKS":
return "+{0}DAYS".format(quantity * 7)
else:
return "+{0}{1}".format(quantity, unit[0]) | [
"def",
"gap_to_sorl",
"(",
"time_gap",
")",
":",
"quantity",
",",
"unit",
"=",
"parse_ISO8601",
"(",
"time_gap",
")",
"if",
"unit",
"[",
"0",
"]",
"==",
"\"WEEKS\"",
":",
"return",
"\"+{0}DAYS\"",
".",
"format",
"(",
"quantity",
"*",
"7",
")",
"else",
... | 26.090909 | 11.545455 |
def method2pos(method):
''' Returns a list of valid POS-tags for a given method. '''
if method in ('articles', 'plural', 'miniaturize', 'gender'):
pos = ['NN']
elif method in ('conjugate',):
pos = ['VB']
elif method in ('comparative, superlative'):
pos = ['JJ']
else:
pos = ['*']
return pos | [
"def",
"method2pos",
"(",
"method",
")",
":",
"if",
"method",
"in",
"(",
"'articles'",
",",
"'plural'",
",",
"'miniaturize'",
",",
"'gender'",
")",
":",
"pos",
"=",
"[",
"'NN'",
"]",
"elif",
"method",
"in",
"(",
"'conjugate'",
",",
")",
":",
"pos",
"... | 24.5 | 23.5 |
def __assert_field_mapping(self, mapping):
"""Assert that mapping.keys() == FIELDS.
The programmer is not supposed to pass extra/less number of fields
"""
passed_keys = set(mapping.keys())
class_fields = set(self.FIELDS)
if passed_keys != class_fields:
raise... | [
"def",
"__assert_field_mapping",
"(",
"self",
",",
"mapping",
")",
":",
"passed_keys",
"=",
"set",
"(",
"mapping",
".",
"keys",
"(",
")",
")",
"class_fields",
"=",
"set",
"(",
"self",
".",
"FIELDS",
")",
"if",
"passed_keys",
"!=",
"class_fields",
":",
"r... | 40.928571 | 14.714286 |
def create_tfs_project_analysis_client(url, token=None):
"""
Create a project_analysis_client.py client for a Team Foundation Server Enterprise connection instance.
This is helpful for understanding project languages, but currently blank for all our test conditions.
If token is not provided, will attem... | [
"def",
"create_tfs_project_analysis_client",
"(",
"url",
",",
"token",
"=",
"None",
")",
":",
"if",
"token",
"is",
"None",
":",
"token",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TFS_API_TOKEN'",
",",
"None",
")",
"tfs_connection",
"=",
"create_tfs_conne... | 43.684211 | 27.578947 |
def should_update(stack):
"""Tests whether a stack should be submitted for updates to CF.
Args:
stack (:class:`stacker.stack.Stack`): The stack object to check.
Returns:
bool: If the stack should be updated, return True.
"""
if stack.locked:
if not stack.force:
... | [
"def",
"should_update",
"(",
"stack",
")",
":",
"if",
"stack",
".",
"locked",
":",
"if",
"not",
"stack",
".",
"force",
":",
"logger",
".",
"debug",
"(",
"\"Stack %s locked and not in --force list. \"",
"\"Refusing to update.\"",
",",
"stack",
".",
"name",
")",
... | 30.684211 | 22.052632 |
def unpickle_dict(items):
'''Returns a dict pickled with pickle_dict'''
pickled_keys = items.pop('_pickled', '').split(',')
ret = {}
for key, val in items.items():
if key in pickled_keys:
ret[key] = pickle.loads(val)
else:
ret[key] = val
return ret | [
"def",
"unpickle_dict",
"(",
"items",
")",
":",
"pickled_keys",
"=",
"items",
".",
"pop",
"(",
"'_pickled'",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
"ret",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"items",
".",
"items",
"(",
")",
":"... | 29.9 | 14.9 |
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
if not isinstance(self.console, wxconsole.MessageConsole):
return
if not self.console.is_alive():
self.mpstate.console = textconsole.SimpleConsole()
return
type = msg.get_type()
... | [
"def",
"mavlink_packet",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"console",
",",
"wxconsole",
".",
"MessageConsole",
")",
":",
"return",
"if",
"not",
"self",
".",
"console",
".",
"is_alive",
"(",
")",
":",
"self"... | 49.886957 | 21.434783 |
def get_response(self):
"""Get the original response of requests"""
request = getattr(requests, self.request_method, None)
if request is None and self._request_method is None:
raise ValueError("A effective http request method must be set")
if self.request_url is None:
... | [
"def",
"get_response",
"(",
"self",
")",
":",
"request",
"=",
"getattr",
"(",
"requests",
",",
"self",
".",
"request_method",
",",
"None",
")",
"if",
"request",
"is",
"None",
"and",
"self",
".",
"_request_method",
"is",
"None",
":",
"raise",
"ValueError",
... | 48.461538 | 19.692308 |
def already_downloaded(filename):
"""
Verify that the file has not already been downloaded.
"""
cur_file = os.path.join(c.bview_dir, filename)
old_file = os.path.join(c.bview_dir, 'old', filename)
if not os.path.exists(cur_file) and not os.path.exists(old_file):
return False
retu... | [
"def",
"already_downloaded",
"(",
"filename",
")",
":",
"cur_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"c",
".",
"bview_dir",
",",
"filename",
")",
"old_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"c",
".",
"bview_dir",
",",
"'old'",
",",... | 35.444444 | 14.333333 |
def create_feature_map(features, feature_indices, output_dir):
"""Returns feature_map about the transformed features.
feature_map includes information such as:
1, cat1=0
2, cat1=1
3, numeric1
...
Returns:
List in the from
[(index, feature_description)]
"""
feature_map = []
for name,... | [
"def",
"create_feature_map",
"(",
"features",
",",
"feature_indices",
",",
"output_dir",
")",
":",
"feature_map",
"=",
"[",
"]",
"for",
"name",
",",
"info",
"in",
"feature_indices",
":",
"transform_name",
"=",
"features",
"[",
"name",
"]",
"[",
"'transform'",
... | 39.774194 | 20.258065 |
def read_single_xso(src, type_):
"""
Read a single :class:`~.XSO` of the given `type_` from the binary file-like
input `src` and return the instance.
"""
result = None
def cb(instance):
nonlocal result
result = instance
read_xso(src, {type_: cb})
return result | [
"def",
"read_single_xso",
"(",
"src",
",",
"type_",
")",
":",
"result",
"=",
"None",
"def",
"cb",
"(",
"instance",
")",
":",
"nonlocal",
"result",
"result",
"=",
"instance",
"read_xso",
"(",
"src",
",",
"{",
"type_",
":",
"cb",
"}",
")",
"return",
"r... | 19.866667 | 20.933333 |
def getWorkerQte(hosts):
"""Return the number of workers to launch depending on the environment"""
if "SLURM_NTASKS" in os.environ:
return int(os.environ["SLURM_NTASKS"])
elif "PBS_NP" in os.environ:
return int(os.environ["PBS_NP"])
elif "NSLOTS" in os.environ:
return int(os.envi... | [
"def",
"getWorkerQte",
"(",
"hosts",
")",
":",
"if",
"\"SLURM_NTASKS\"",
"in",
"os",
".",
"environ",
":",
"return",
"int",
"(",
"os",
".",
"environ",
"[",
"\"SLURM_NTASKS\"",
"]",
")",
"elif",
"\"PBS_NP\"",
"in",
"os",
".",
"environ",
":",
"return",
"int... | 38.1 | 7.8 |
def patch(destination, name=None, settings=None):
"""Decorator to create a patch.
The object being decorated becomes the :attr:`~Patch.obj` attribute of the
patch.
Parameters
----------
destination : object
Patch destination.
name : str
Name of the attribute at the destinat... | [
"def",
"patch",
"(",
"destination",
",",
"name",
"=",
"None",
",",
"settings",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"wrapped",
")",
":",
"base",
"=",
"_get_base",
"(",
"wrapped",
")",
"name_",
"=",
"base",
".",
"__name__",
"if",
"name",
"i... | 24.5 | 21.5 |
def delete(username):
"""Delete a user.
Example:
\b
```bash
$ polyaxon user delete david
```
"""
try:
PolyaxonClient().user.delete_user(username)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could not delete... | [
"def",
"delete",
"(",
"username",
")",
":",
"try",
":",
"PolyaxonClient",
"(",
")",
".",
"user",
".",
"delete_user",
"(",
"username",
")",
"except",
"(",
"PolyaxonHTTPError",
",",
"PolyaxonShouldExitError",
",",
"PolyaxonClientException",
")",
"as",
"e",
":",
... | 27.611111 | 26.5 |
def fullfill_descendants_info(desc_matrix):
'''
flat_offset
'''
pathloc_mapping = {}
locpath_mapping = {}
#def leaf_handler(desc,pdesc,offset):
def leaf_handler(desc,pdesc):
#desc['flat_offset'] = (offset,offset+1)
desc['non_leaf_son_paths'] = []
desc['leaf_son_pat... | [
"def",
"fullfill_descendants_info",
"(",
"desc_matrix",
")",
":",
"pathloc_mapping",
"=",
"{",
"}",
"locpath_mapping",
"=",
"{",
"}",
"#def leaf_handler(desc,pdesc,offset):",
"def",
"leaf_handler",
"(",
"desc",
",",
"pdesc",
")",
":",
"#desc['flat_offset'] = (offset,off... | 37.467532 | 11.181818 |
def read_sif(cls, path):
"""
Creates a graph from a `simple interaction format (SIF)`_ file
Parameters
----------
path : str
Absolute path to a SIF file
Returns
-------
caspo.core.graph.Graph
Created object instance
.. _... | [
"def",
"read_sif",
"(",
"cls",
",",
"path",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"path",
",",
"delim_whitespace",
"=",
"True",
",",
"names",
"=",
"[",
"'source'",
",",
"'sign'",
",",
"'target'",
"]",
")",
".",
"drop_duplicates",
"(",
")",... | 32.3 | 27 |
def send(tag, data=None):
'''
Send an event with the given tag and data.
This is useful for sending events directly to the master from the shell
with salt-run. It is also quite useful for sending events in orchestration
states where the ``fire_event`` requisite isn't sufficient because it does
... | [
"def",
"send",
"(",
"tag",
",",
"data",
"=",
"None",
")",
":",
"data",
"=",
"data",
"or",
"{",
"}",
"event",
"=",
"salt",
".",
"utils",
".",
"event",
".",
"get_master_event",
"(",
"__opts__",
",",
"__opts__",
"[",
"'sock_dir'",
"]",
",",
"listen",
... | 30.453125 | 23.890625 |
def surface_area(self):
r"""Calculate all atomic surface area.
:rtype: [float]
"""
return [self.atomic_sa(i) for i in range(len(self.rads))] | [
"def",
"surface_area",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"atomic_sa",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"rads",
")",
")",
"]"
] | 28 | 16.5 |
def get_serializer(serializer_format):
""" Get the serializer for a specific format """
if serializer_format == Format.JSON:
return _serialize_json
if serializer_format == Format.PICKLE:
return _serialize_pickle | [
"def",
"get_serializer",
"(",
"serializer_format",
")",
":",
"if",
"serializer_format",
"==",
"Format",
".",
"JSON",
":",
"return",
"_serialize_json",
"if",
"serializer_format",
"==",
"Format",
".",
"PICKLE",
":",
"return",
"_serialize_pickle"
] | 39 | 3.666667 |
def pypsa_id(self):
#TODO: docstring
""" Description
"""
return '_'.join(['MV', str(
self.grid.grid_district.lv_load_area.mv_grid_district.mv_grid.\
id_db), 'tru', str(self.id_db)]) | [
"def",
"pypsa_id",
"(",
"self",
")",
":",
"#TODO: docstring",
"return",
"'_'",
".",
"join",
"(",
"[",
"'MV'",
",",
"str",
"(",
"self",
".",
"grid",
".",
"grid_district",
".",
"lv_load_area",
".",
"mv_grid_district",
".",
"mv_grid",
".",
"id_db",
")",
","... | 34.142857 | 12.142857 |
def install(client, force):
"""Install Git hooks."""
import pkg_resources
from git.index.fun import hook_path as get_hook_path
for hook in HOOKS:
hook_path = Path(get_hook_path(hook, client.repo.git_dir))
if hook_path.exists():
if not force:
click.echo(
... | [
"def",
"install",
"(",
"client",
",",
"force",
")",
":",
"import",
"pkg_resources",
"from",
"git",
".",
"index",
".",
"fun",
"import",
"hook_path",
"as",
"get_hook_path",
"for",
"hook",
"in",
"HOOKS",
":",
"hook_path",
"=",
"Path",
"(",
"get_hook_path",
"(... | 32.038462 | 19.192308 |
def _adapt_WSDateTime(dt):
"""Return unix timestamp of the datetime like input.
If conversion overflows high, return sint64_max ,
if underflows, return 0
"""
try:
ts = int(
(dt.replace(tzinfo=pytz.utc)
- datetime(1970,1,1,tzinfo=pytz.utc)
).total_seconds()... | [
"def",
"_adapt_WSDateTime",
"(",
"dt",
")",
":",
"try",
":",
"ts",
"=",
"int",
"(",
"(",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"pytz",
".",
"utc"... | 26.705882 | 14.764706 |
def is_in(self, point_x, point_y):
""" Test if the point is within this ellipse """
x = self.x_origin
y = self.y_origin
a = self.e_width#/2 # FIXME: Why divide by two
b = self.e_height#/2
return ((point_x-x)**2/(a**2)) + ((point_y-y)**2/(b**2)) < 1.0 | [
"def",
"is_in",
"(",
"self",
",",
"point_x",
",",
"point_y",
")",
":",
"x",
"=",
"self",
".",
"x_origin",
"y",
"=",
"self",
".",
"y_origin",
"a",
"=",
"self",
".",
"e_width",
"#/2 # FIXME: Why divide by two",
"b",
"=",
"self",
".",
"e_height",
"#/2",
"... | 32.444444 | 19.111111 |
def get_value_index(self, indices):
"""Converts a list of dimensions’ indices into a numeric value index.
Args:
indices(list): list of dimension's indices.
Returns:
num(int): numeric value index.
"""
size = self['size'] if self.get('size') else self['dim... | [
"def",
"get_value_index",
"(",
"self",
",",
"indices",
")",
":",
"size",
"=",
"self",
"[",
"'size'",
"]",
"if",
"self",
".",
"get",
"(",
"'size'",
")",
"else",
"self",
"[",
"'dimension'",
"]",
"[",
"'size'",
"]",
"ndims",
"=",
"len",
"(",
"size",
"... | 30.388889 | 19.055556 |
def load_cookie(cls, request, key='session', secret_key=None):
"""Loads a :class:`SecureCookie` from a cookie in request. If the
cookie is not set, a new :class:`SecureCookie` instanced is
returned.
:param request: a request object that has a `cookies` attribute
... | [
"def",
"load_cookie",
"(",
"cls",
",",
"request",
",",
"key",
"=",
"'session'",
",",
"secret_key",
"=",
"None",
")",
":",
"data",
"=",
"request",
".",
"cookies",
".",
"get",
"(",
"key",
")",
"if",
"not",
"data",
":",
"return",
"cls",
"(",
"secret_key... | 45.9375 | 16.375 |
def validate_log_format(self, log):
'''
>>> lc = LogCollector('file=/path/to/file.log:formatter=logagg.formatters.basescript', 30)
>>> incomplete_log = {'data' : {'x' : 1, 'y' : 2},
... 'raw' : 'Not all keys present'}
>>> lc.validate_log_format(incomplete_log... | [
"def",
"validate_log_format",
"(",
"self",
",",
"log",
")",
":",
"keys_in_log",
"=",
"set",
"(",
"log",
")",
"keys_in_log_structure",
"=",
"set",
"(",
"self",
".",
"LOG_STRUCTURE",
")",
"try",
":",
"assert",
"(",
"keys_in_log",
"==",
"keys_in_log_structure",
... | 39.257576 | 18.5 |
def create_model(config: dict, output_dir: Optional[str], dataset: AbstractDataset,
restore_from: Optional[str]=None) -> AbstractModel:
"""
Create a model object either from scratch of from the checkpoint in ``resume_dir``.
Cxflow allows the following scenarios
1. Create model: leave ... | [
"def",
"create_model",
"(",
"config",
":",
"dict",
",",
"output_dir",
":",
"Optional",
"[",
"str",
"]",
",",
"dataset",
":",
"AbstractDataset",
",",
"restore_from",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"AbstractModel",
":",
"logging",
... | 49.796296 | 32.944444 |
def _static(self, target, value):
"""PHP's "static"
"""
return 'static ' + self.__p(ast.Assign(targets=[target],value=value)) | [
"def",
"_static",
"(",
"self",
",",
"target",
",",
"value",
")",
":",
"return",
"'static '",
"+",
"self",
".",
"__p",
"(",
"ast",
".",
"Assign",
"(",
"targets",
"=",
"[",
"target",
"]",
",",
"value",
"=",
"value",
")",
")"
] | 29.2 | 16.8 |
def substitute_minor_for_major(progression, substitute_index,
ignore_suffix=False):
"""Substitute minor chords for its major equivalent.
'm' and 'm7' suffixes recognized, and ['II', 'III', 'VI'] if there is no
suffix.
Examples:
>>> substitute_minor_for_major(['VI'], 0)
['I']
>>> su... | [
"def",
"substitute_minor_for_major",
"(",
"progression",
",",
"substitute_index",
",",
"ignore_suffix",
"=",
"False",
")",
":",
"(",
"roman",
",",
"acc",
",",
"suff",
")",
"=",
"parse_string",
"(",
"progression",
"[",
"substitute_index",
"]",
")",
"res",
"=",
... | 33.7 | 18.133333 |
def from_json(cls, json_info):
"""Build a Trial instance from a json string."""
if json_info is None:
return None
return TrialRecord(
trial_id=json_info["trial_id"],
job_id=json_info["job_id"],
trial_status=json_info["status"],
start_ti... | [
"def",
"from_json",
"(",
"cls",
",",
"json_info",
")",
":",
"if",
"json_info",
"is",
"None",
":",
"return",
"None",
"return",
"TrialRecord",
"(",
"trial_id",
"=",
"json_info",
"[",
"\"trial_id\"",
"]",
",",
"job_id",
"=",
"json_info",
"[",
"\"job_id\"",
"]... | 37.8 | 6.8 |
def _read_erd(erd_file, begsam, endsam):
"""Read the raw data and return a matrix, converted to microvolts.
Parameters
----------
erd_file : str
one of the .erd files to read
begsam : int
index of the first sample to read
endsam : int
index of the last sample (excluded, ... | [
"def",
"_read_erd",
"(",
"erd_file",
",",
"begsam",
",",
"endsam",
")",
":",
"hdr",
"=",
"_read_hdr_file",
"(",
"erd_file",
")",
"n_allchan",
"=",
"hdr",
"[",
"'num_channels'",
"]",
"shorted",
"=",
"hdr",
"[",
"'shorted'",
"]",
"# does this exist for Schema 7 ... | 34.698276 | 22.327586 |
def no_selenium_errors(func):
"""
Decorator to create an `EmptyPromise` check function that is satisfied
only when `func` executes without a Selenium error.
This protects against many common test failures due to timing issues.
For example, accessing an element after it has been modified by JavaScri... | [
"def",
"no_selenium_errors",
"(",
"func",
")",
":",
"def",
"_inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=missing-docstring",
"try",
":",
"return_val",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"excep... | 35.074074 | 25.592593 |
def export_data(filename_or_fobj, data, mode="w"):
"""Return the object ready to be exported or only data if filename_or_fobj is not passed."""
if filename_or_fobj is None:
return data
_, fobj = get_filename_and_fobj(filename_or_fobj, mode=mode)
source = Source.from_file(filename_or_fobj, mode... | [
"def",
"export_data",
"(",
"filename_or_fobj",
",",
"data",
",",
"mode",
"=",
"\"w\"",
")",
":",
"if",
"filename_or_fobj",
"is",
"None",
":",
"return",
"data",
"_",
",",
"fobj",
"=",
"get_filename_and_fobj",
"(",
"filename_or_fobj",
",",
"mode",
"=",
"mode",... | 37.181818 | 20.636364 |
def print_difftext(text, other=None):
"""
Args:
text (str):
CommandLine:
#python -m utool.util_print --test-print_difftext
#autopep8 ingest_data.py --diff | python -m utool.util_print --test-print_difftext
"""
if other is not None:
# hack
text = util_str.dif... | [
"def",
"print_difftext",
"(",
"text",
",",
"other",
"=",
"None",
")",
":",
"if",
"other",
"is",
"not",
"None",
":",
"# hack",
"text",
"=",
"util_str",
".",
"difftext",
"(",
"text",
",",
"other",
")",
"colortext",
"=",
"util_str",
".",
"color_diff_text",
... | 29.2 | 20.3 |
def running(self, offset=0, count=25):
'''Return all the currently-running jobs'''
return self.client('jobs', 'running', self.name, offset, count) | [
"def",
"running",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"count",
"=",
"25",
")",
":",
"return",
"self",
".",
"client",
"(",
"'jobs'",
",",
"'running'",
",",
"self",
".",
"name",
",",
"offset",
",",
"count",
")"
] | 53.333333 | 14.666667 |
def BVirial_Pitzer_Curl(T, Tc, Pc, omega, order=0):
r'''Calculates the second virial coefficient using the model in [1]_.
Designed for simple calculations.
.. math::
B_r=B^{(0)}+\omega B^{(1)}
B^{(0)}=0.1445-0.33/T_r-0.1385/T_r^2-0.0121/T_r^3
B^{(1)} = 0.073+0.46/T_r-0.5/T_r^2 -0.... | [
"def",
"BVirial_Pitzer_Curl",
"(",
"T",
",",
"Tc",
",",
"Pc",
",",
"omega",
",",
"order",
"=",
"0",
")",
":",
"Tr",
"=",
"T",
"/",
"Tc",
"if",
"order",
"==",
"0",
":",
"B0",
"=",
"0.1445",
"-",
"0.33",
"/",
"Tr",
"-",
"0.1385",
"/",
"Tr",
"**... | 44.315315 | 36.567568 |
def get_resources(cls):
"""Returns Ext Resources."""
plugin = directory.get_plugin()
controller = MacAddressRangesController(plugin)
return [extensions.ResourceExtension(Mac_address_ranges.get_alias(),
controller)] | [
"def",
"get_resources",
"(",
"cls",
")",
":",
"plugin",
"=",
"directory",
".",
"get_plugin",
"(",
")",
"controller",
"=",
"MacAddressRangesController",
"(",
"plugin",
")",
"return",
"[",
"extensions",
".",
"ResourceExtension",
"(",
"Mac_address_ranges",
".",
"ge... | 47.666667 | 14.333333 |
def getAsGrassAsciiRaster(self, tableName, rasterId=1, rasterIdFieldName='id', rasterFieldName='raster', newSRID=None):
"""
Returns a string representation of the raster in GRASS ASCII raster format.
"""
# Get raster in ArcInfo Grid format
arcInfoGrid = self.getAsGdalRaster(raste... | [
"def",
"getAsGrassAsciiRaster",
"(",
"self",
",",
"tableName",
",",
"rasterId",
"=",
"1",
",",
"rasterIdFieldName",
"=",
"'id'",
",",
"rasterFieldName",
"=",
"'raster'",
",",
"newSRID",
"=",
"None",
")",
":",
"# Get raster in ArcInfo Grid format",
"arcInfoGrid",
"... | 37.033333 | 18.066667 |
def fwd(self, astr_startPath, **kwargs):
"""
Return the files-in-working-directory in treeRecurse
compatible format.
:return: Return the cwd in treeRecurse compatible format.
"""
status = self.cd(astr_startPath)['status']
if status:
... | [
"def",
"fwd",
"(",
"self",
",",
"astr_startPath",
",",
"*",
"*",
"kwargs",
")",
":",
"status",
"=",
"self",
".",
"cd",
"(",
"astr_startPath",
")",
"[",
"'status'",
"]",
"if",
"status",
":",
"l",
"=",
"self",
".",
"lsf",
"(",
")",
"if",
"len",
"("... | 37.533333 | 13.666667 |
def increment(self, kwargs):
"""
Increments the counter for the given *kwargs*.
The counter index is computed from *kwargs*.
*kwargs* is an optional dict of vars captured by the
:class:`filter.Filter` that match the log entry. An immutable version
of *kwargs* is used as... | [
"def",
"increment",
"(",
"self",
",",
"kwargs",
")",
":",
"index",
"=",
"None",
"if",
"kwargs",
":",
"# index = hash(tuple(sorted(kwargs.items())))",
"# Better keep something readable so we can output it.",
"index",
"=",
"tuple",
"(",
"sorted",
"(",
"kwargs",
".",
"it... | 31.565217 | 22.782609 |
def group_associations_types(self, group_type, api_entity=None, api_branch=None, params=None):
"""
Gets the group association from a Indicator/Group/Victim
Args:
group_type:
api_entity:
api_branch:
params:
Returns:
"""
if... | [
"def",
"group_associations_types",
"(",
"self",
",",
"group_type",
",",
"api_entity",
"=",
"None",
",",
"api_branch",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"not",
"self",
".... | 25.709677 | 20.16129 |
def RSA(im: array, radius: int, volume_fraction: int = 1,
mode: str = 'extended'):
r"""
Generates a sphere or disk packing using Random Sequential Addition
This which ensures that spheres do not overlap but does not guarantee they
are tightly packed.
Parameters
----------
im : ND-a... | [
"def",
"RSA",
"(",
"im",
":",
"array",
",",
"radius",
":",
"int",
",",
"volume_fraction",
":",
"int",
"=",
"1",
",",
"mode",
":",
"str",
"=",
"'extended'",
")",
":",
"# Note: The 2D vs 3D splitting of this just me being lazy...I can't be",
"# bothered to figure it o... | 37.893204 | 23.631068 |
def find_all_globals(node, globs):
"""Search Syntax Tree node to find variable names that are global."""
for n in node:
if isinstance(n, SyntaxTree):
globs = find_all_globals(n, globs)
elif n.kind in read_write_global_ops:
globs.add(n.pattr)
return globs | [
"def",
"find_all_globals",
"(",
"node",
",",
"globs",
")",
":",
"for",
"n",
"in",
"node",
":",
"if",
"isinstance",
"(",
"n",
",",
"SyntaxTree",
")",
":",
"globs",
"=",
"find_all_globals",
"(",
"n",
",",
"globs",
")",
"elif",
"n",
".",
"kind",
"in",
... | 37.375 | 9.5 |
def NewFile(self, filename, encoding, options):
"""parse an XML file from the filesystem or the network. The
parsing flags @options are a combination of
xmlParserOption. This reuses the existing @reader
xmlTextReader. """
ret = libxml2mod.xmlReaderNewFile(self._o, filename... | [
"def",
"NewFile",
"(",
"self",
",",
"filename",
",",
"encoding",
",",
"options",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlReaderNewFile",
"(",
"self",
".",
"_o",
",",
"filename",
",",
"encoding",
",",
"options",
")",
"return",
"ret"
] | 50.428571 | 14.285714 |
def interpolate(self, factor, minGlyph, maxGlyph,
round=True, suppressError=True):
"""
Interpolate the contents of this glyph at location ``factor``
in a linear interpolation between ``minGlyph`` and ``maxGlyph``.
>>> glyph.interpolate(0.5, otherGlyph1, otherGlyp... | [
"def",
"interpolate",
"(",
"self",
",",
"factor",
",",
"minGlyph",
",",
"maxGlyph",
",",
"round",
"=",
"True",
",",
"suppressError",
"=",
"True",
")",
":",
"factor",
"=",
"normalizers",
".",
"normalizeInterpolationFactor",
"(",
"factor",
")",
"if",
"not",
... | 52.214286 | 26.166667 |
def FanOut(self, obj, parent=None):
"""Expand values from various attribute types.
Strings are returned as is.
Dictionaries are returned with a key string, and an expanded set of values.
Other iterables are expanded until they flatten out.
Other items are returned in string format.
Args:
... | [
"def",
"FanOut",
"(",
"self",
",",
"obj",
",",
"parent",
"=",
"None",
")",
":",
"# Catch cases where RDFs are iterable but return themselves.",
"if",
"parent",
"and",
"obj",
"==",
"parent",
":",
"results",
"=",
"[",
"utils",
".",
"SmartUnicode",
"(",
"obj",
")... | 39.944444 | 18.416667 |
def set_data(self, data):
"""
Fills form with data
Args:
data (dict): Data to assign form fields.
Returns:
Self. Form object.
"""
for name in self._fields:
setattr(self, name, data.get(name))
return self | [
"def",
"set_data",
"(",
"self",
",",
"data",
")",
":",
"for",
"name",
"in",
"self",
".",
"_fields",
":",
"setattr",
"(",
"self",
",",
"name",
",",
"data",
".",
"get",
"(",
"name",
")",
")",
"return",
"self"
] | 20.357143 | 18.214286 |
def _psed(text,
before,
after,
limit,
flags):
'''
Does the actual work for file.psed, so that single lines can be passed in
'''
atext = text
if limit:
limit = re.compile(limit)
comps = text.split(limit)
atext = ''.join(comps[1:])
c... | [
"def",
"_psed",
"(",
"text",
",",
"before",
",",
"after",
",",
"limit",
",",
"flags",
")",
":",
"atext",
"=",
"text",
"if",
"limit",
":",
"limit",
"=",
"re",
".",
"compile",
"(",
"limit",
")",
"comps",
"=",
"text",
".",
"split",
"(",
"limit",
")"... | 21.259259 | 22.740741 |
def add_version_pattern(self, m):
"""For QR codes with a version 7 or higher, a special pattern
specifying the code's version is required.
For further information see:
http://www.thonky.com/qr-code-tutorial/format-version-information/#example-of-version-7-information-string
"""
... | [
"def",
"add_version_pattern",
"(",
"self",
",",
"m",
")",
":",
"if",
"self",
".",
"version",
"<",
"7",
":",
"return",
"#Get the bit fields for this code's version",
"#We will iterate across the string, the bit string",
"#needs the least significant digit in the zero-th position",... | 33.896552 | 18.862069 |
def date_decimal_hook(dct):
'''The default JSON decoder hook. It is the inverse of
:class:`stdnet.utils.jsontools.JSONDateDecimalEncoder`.'''
if '__datetime__' in dct:
return todatetime(dct['__datetime__'])
elif '__date__' in dct:
return todatetime(dct['__date__']).date()
elif '__decimal... | [
"def",
"date_decimal_hook",
"(",
"dct",
")",
":",
"if",
"'__datetime__'",
"in",
"dct",
":",
"return",
"todatetime",
"(",
"dct",
"[",
"'__datetime__'",
"]",
")",
"elif",
"'__date__'",
"in",
"dct",
":",
"return",
"todatetime",
"(",
"dct",
"[",
"'__date__'",
... | 35.727273 | 13.909091 |
def _apply_cn_keys_patch():
"""
apply this patch due to an issue in http.client.parse_headers
when there're multi-bytes in headers. it will truncate some headers.
https://github.com/aliyun/aliyun-log-python-sdk/issues/79
"""
import sys
if sys.version_info[:2] == (3, 5):
impor... | [
"def",
"_apply_cn_keys_patch",
"(",
")",
":",
"import",
"sys",
"if",
"sys",
".",
"version_info",
"[",
":",
"2",
"]",
"==",
"(",
"3",
",",
"5",
")",
":",
"import",
"http",
".",
"client",
"as",
"hc",
"old_parse",
"=",
"hc",
".",
"parse_headers",
"def",... | 32.222222 | 16.148148 |
def sum_of_squares(simulated_trajectories, observed_trajectories_lookup):
"""
Returns the sum-of-squares distance between the simulated_trajectories and observed_trajectories
:param simulated_trajectories: Simulated trajectories
:type simulated_trajectories: list[:class:`means.simulation.Trajectory`]
... | [
"def",
"sum_of_squares",
"(",
"simulated_trajectories",
",",
"observed_trajectories_lookup",
")",
":",
"dist",
"=",
"0",
"for",
"simulated_trajectory",
"in",
"simulated_trajectories",
":",
"observed_trajectory",
"=",
"None",
"try",
":",
"observed_trajectory",
"=",
"obse... | 40.884615 | 26.961538 |
def delete_webhook(self, scaling_group, policy, webhook):
"""
Deletes the specified webhook from the policy.
"""
return self._manager.delete_webhook(scaling_group, policy, webhook) | [
"def",
"delete_webhook",
"(",
"self",
",",
"scaling_group",
",",
"policy",
",",
"webhook",
")",
":",
"return",
"self",
".",
"_manager",
".",
"delete_webhook",
"(",
"scaling_group",
",",
"policy",
",",
"webhook",
")"
] | 41.6 | 13.2 |
def _listen(self, uuid=None, session=None):
""" Listen a connection uuid """
if self.url is None:
raise Exception("NURESTPushCenter needs to have a valid URL. please use setURL: before starting it.")
events_url = "%s/events" % self.url
if uuid:
events_url = "%s?... | [
"def",
"_listen",
"(",
"self",
",",
"uuid",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"if",
"self",
".",
"url",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"NURESTPushCenter needs to have a valid URL. please use setURL: before starting it.\"",
")",
"... | 39.185185 | 30.740741 |
def store(self):
'''
Record the current value of each variable X named in track_vars in an
attribute named X_hist.
Parameters
----------
none
Returns
-------
none
'''
for var_name in self.track_vars:
value_now = getatt... | [
"def",
"store",
"(",
"self",
")",
":",
"for",
"var_name",
"in",
"self",
".",
"track_vars",
":",
"value_now",
"=",
"getattr",
"(",
"self",
",",
"var_name",
")",
"getattr",
"(",
"self",
",",
"var_name",
"+",
"'_hist'",
")",
".",
"append",
"(",
"value_now... | 24 | 24.125 |
async def process_message(self, message, wait=True):
"""Process a message to see if it wakes any waiters.
This will check waiters registered to see if they match the given
message. If so, they are awoken and passed the message. All matching
waiters will be woken.
This method ... | [
"async",
"def",
"process_message",
"(",
"self",
",",
"message",
",",
"wait",
"=",
"True",
")",
":",
"to_check",
"=",
"deque",
"(",
"[",
"self",
".",
"_waiters",
"]",
")",
"ignored",
"=",
"True",
"while",
"len",
"(",
"to_check",
")",
">",
"0",
":",
... | 39.948276 | 25.206897 |
def get_family_lookup_session(self):
"""Gets the ``OsidSession`` associated with the family lookup service.
return: (osid.relationship.FamilyLookupSession) - a
``FamilyLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports... | [
"def",
"get_family_lookup_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_family_lookup",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"ImportError",
":",
"raise",
"OperationFa... | 39.478261 | 18.217391 |
def get_lyrics_threaded(song, l_sources=None):
"""
Launches a pool of threads to search for the lyrics of a single song.
The optional parameter 'sources' specifies an alternative list of sources.
If not present, the main list will be used.
"""
if l_sources is None:
l_sources = sources
... | [
"def",
"get_lyrics_threaded",
"(",
"song",
",",
"l_sources",
"=",
"None",
")",
":",
"if",
"l_sources",
"is",
"None",
":",
"l_sources",
"=",
"sources",
"if",
"song",
".",
"lyrics",
"and",
"not",
"CONFIG",
"[",
"'overwrite'",
"]",
":",
"logger",
".",
"debu... | 27.484848 | 19.787879 |
def get(self, node=None):
"""Run basic healthchecks against the current node, or against a given
node.
Example response:
> {"status":"ok"}
> {"status":"failed","reason":"string"}
:param node: Node name
:raises ApiError: Raises if the remote ... | [
"def",
"get",
"(",
"self",
",",
"node",
"=",
"None",
")",
":",
"if",
"not",
"node",
":",
"return",
"self",
".",
"http_client",
".",
"get",
"(",
"HEALTHCHECKS",
")",
"return",
"self",
".",
"http_client",
".",
"get",
"(",
"HEALTHCHECKS_NODE",
"%",
"node"... | 32.222222 | 21.722222 |
def envelop(self, begin, end=None):
"""
Returns the set of all intervals fully contained in the range
[begin, end).
Completes in O(m + k*log n) time, where:
* n = size of the tree
* m = number of matches
* k = size of the search range
:rtype: set of... | [
"def",
"envelop",
"(",
"self",
",",
"begin",
",",
"end",
"=",
"None",
")",
":",
"root",
"=",
"self",
".",
"top_node",
"if",
"not",
"root",
":",
"return",
"set",
"(",
")",
"if",
"end",
"is",
"None",
":",
"iv",
"=",
"begin",
"return",
"self",
".",
... | 35.558824 | 17.794118 |
def sync_skills_data(self):
""" Update internal skill_data_structure from disk. """
self.skills_data = self.load_skills_data()
if 'upgraded' in self.skills_data:
self.skills_data.pop('upgraded')
else:
self.skills_data_hash = skills_data_hash(self.skills_data) | [
"def",
"sync_skills_data",
"(",
"self",
")",
":",
"self",
".",
"skills_data",
"=",
"self",
".",
"load_skills_data",
"(",
")",
"if",
"'upgraded'",
"in",
"self",
".",
"skills_data",
":",
"self",
".",
"skills_data",
".",
"pop",
"(",
"'upgraded'",
")",
"else",... | 44.142857 | 12.285714 |
def standardize_cell(cell,
to_primitive=False,
no_idealize=False,
symprec=1e-5,
angle_tolerance=-1.0):
"""Return standardized cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
... | [
"def",
"standardize_cell",
"(",
"cell",
",",
"to_primitive",
"=",
"False",
",",
"no_idealize",
"=",
"False",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"_positions",
",",
"_num... | 38.244898 | 17.897959 |
def field_metadata(self, well_row=0, well_column=0,
field_row=0, field_column=0):
"""Get OME-XML metadata of given field.
Parameters
----------
well_row : int
Y well coordinate. Same as --V in files.
well_column : int
X well coordin... | [
"def",
"field_metadata",
"(",
"self",
",",
"well_row",
"=",
"0",
",",
"well_column",
"=",
"0",
",",
"field_row",
"=",
"0",
",",
"field_column",
"=",
"0",
")",
":",
"def",
"condition",
"(",
"path",
")",
":",
"attrs",
"=",
"attributes",
"(",
"path",
")... | 35.909091 | 18.939394 |
def _split_horizontal(self, section, width, height):
"""For an horizontal split the rectangle is placed in the lower
left corner of the section (section's xy coordinates), the top
most side of the rectangle and its horizontal continuation,
marks the line of division for the split.
... | [
"def",
"_split_horizontal",
"(",
"self",
",",
"section",
",",
"width",
",",
"height",
")",
":",
"# First remove the section we are splitting so it doesn't ",
"# interfere when later we try to merge the resulting split",
"# rectangles, with the rest of free sections.",
"#self._sections.... | 44.264706 | 18.5 |
def _format_date_param(params, key, format="%Y-%m-%d %H:%M:%S"):
"""
Utility function to convert datetime values to strings.
If the value is already a str, or is not in the dict, no change is made.
:param params: A `dict` of params that may contain a `datetime` value.
:param key: The datetime valu... | [
"def",
"_format_date_param",
"(",
"params",
",",
"key",
",",
"format",
"=",
"\"%Y-%m-%d %H:%M:%S\"",
")",
":",
"if",
"key",
"in",
"params",
":",
"param",
"=",
"params",
"[",
"key",
"]",
"if",
"hasattr",
"(",
"param",
",",
"\"strftime\"",
")",
":",
"param... | 42.428571 | 23.428571 |
def transition_matrix_reversible_pisym(C, return_statdist=False, **kwargs):
r"""
Estimates reversible transition matrix as follows:
..:math:
p_{ij} = c_{ij} / c_i where c_i = sum_j c_{ij}
\pi_j = \sum_j \pi_i p_{ij}
x_{ij} = \pi_i p_{ij} + \pi_j p_{ji}
p^{rev}_{ij} = x_{ij} ... | [
"def",
"transition_matrix_reversible_pisym",
"(",
"C",
",",
"return_statdist",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# nonreversible estimate",
"T_nonrev",
"=",
"transition_matrix_non_reversible",
"(",
"C",
")",
"from",
"msmtools",
".",
"analysis",
"impo... | 31.307692 | 20.717949 |
def _convert_choices(self, choices):
"""Auto create db values then call super method"""
final_choices = []
for choice in choices:
if isinstance(choice, ChoiceEntry):
final_choices.append(choice)
continue
original_choice = choice
... | [
"def",
"_convert_choices",
"(",
"self",
",",
"choices",
")",
":",
"final_choices",
"=",
"[",
"]",
"for",
"choice",
"in",
"choices",
":",
"if",
"isinstance",
"(",
"choice",
",",
"ChoiceEntry",
")",
":",
"final_choices",
".",
"append",
"(",
"choice",
")",
... | 34.811321 | 19.943396 |
def _forceInt(x,y,z,a2,b2,c2,n,i):
"""Integral involved in the force at (x,y,z)
integrates 1/A B^n (x_i/(tau+a_i)) where
A = sqrt((tau+a)(tau+b)(tau+c)) and B = (1-x^2/(tau+a)-y^2/(tau+b)-z^2/(tau+c))
from lambda to infty with respect to tau.
The lower limit lambda is given by lowerlim function.
... | [
"def",
"_forceInt",
"(",
"x",
",",
"y",
",",
"z",
",",
"a2",
",",
"b2",
",",
"c2",
",",
"n",
",",
"i",
")",
":",
"def",
"integrand",
"(",
"tau",
")",
":",
"return",
"(",
"x",
"*",
"(",
"i",
"==",
"0",
")",
"+",
"y",
"*",
"(",
"i",
"==",... | 53.090909 | 19.545455 |
def _read_string(self, cpu, buf):
"""
Reads a null terminated concrete buffer form memory
:todo: FIX. move to cpu or memory
"""
filename = ""
for i in range(0, 1024):
c = Operators.CHR(cpu.read_int(buf + i, 8))
if c == '\x00':
break... | [
"def",
"_read_string",
"(",
"self",
",",
"cpu",
",",
"buf",
")",
":",
"filename",
"=",
"\"\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"1024",
")",
":",
"c",
"=",
"Operators",
".",
"CHR",
"(",
"cpu",
".",
"read_int",
"(",
"buf",
"+",
"i",
","... | 29.916667 | 11.083333 |
def validate_commit_index(func):
"""Apply to State Machine everything up to commit index"""
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
for not_applied in range(self.log.last_applied + 1, self.log.commit_index + 1):
self.state_machine.apply(self.log[not_applied]['command'... | [
"def",
"validate_commit_index",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"not_applied",
"in",
"range",
"(",
"self",
".",
"log",... | 36.125 | 21.125 |
def delete(self, **kwargs):
"""Delete a resource by issuing a DELETE http request against it."""
self.method = 'delete'
if len(kwargs) > 0:
self.load(self.client.delete(self.url, params=kwargs))
else:
self.load(self.client.delete(self.url))
self.parent.rem... | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"method",
"=",
"'delete'",
"if",
"len",
"(",
"kwargs",
")",
">",
"0",
":",
"self",
".",
"load",
"(",
"self",
".",
"client",
".",
"delete",
"(",
"self",
".",
"url",
",... | 37.333333 | 14.888889 |
def header(self, item0, *items):
"""print string item0 to the current position and next strings to defined positions
example: .header("Name", 75, "Quantity", 100, "Unit")
"""
self.txt(item0)
at_x = None
for item in items:
if at_x is None:
at_x ... | [
"def",
"header",
"(",
"self",
",",
"item0",
",",
"*",
"items",
")",
":",
"self",
".",
"txt",
"(",
"item0",
")",
"at_x",
"=",
"None",
"for",
"item",
"in",
"items",
":",
"if",
"at_x",
"is",
"None",
":",
"at_x",
"=",
"item",
"else",
":",
"self",
"... | 33.583333 | 11.916667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.