text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def returner(ret):
'''
Parse the return data and return metrics to AppOptics.
For each state that's provided in the configuration, return tagged metrics for
the result of that state if it's present.
'''
options = _get_options(ret)
states_to_report = ['state.highstate']
if options.get('... | [
"def",
"returner",
"(",
"ret",
")",
":",
"options",
"=",
"_get_options",
"(",
"ret",
")",
"states_to_report",
"=",
"[",
"'state.highstate'",
"]",
"if",
"options",
".",
"get",
"(",
"'sls_states'",
")",
":",
"states_to_report",
".",
"append",
"(",
"'state.sls'... | 40.666667 | 17.416667 |
def start_webhook(dispatcher, webhook_path, *, loop=None, skip_updates=None,
on_startup=None, on_shutdown=None, check_ip=False, retry_after=None, route_name=DEFAULT_ROUTE_NAME,
**kwargs):
"""
Start bot in webhook mode
:param dispatcher:
:param webhook_path:
:para... | [
"def",
"start_webhook",
"(",
"dispatcher",
",",
"webhook_path",
",",
"*",
",",
"loop",
"=",
"None",
",",
"skip_updates",
"=",
"None",
",",
"on_startup",
"=",
"None",
",",
"on_shutdown",
"=",
"None",
",",
"check_ip",
"=",
"False",
",",
"retry_after",
"=",
... | 34.592593 | 17.259259 |
def apply_async(f, args=(), kwargs=None, callback=None):
"""Apply a function but emulate the API of an asynchronous call.
Parameters
----------
f : callable
The function to call.
args : tuple, optional
The positional arguments.
kwargs : dict, opti... | [
"def",
"apply_async",
"(",
"f",
",",
"args",
"=",
"(",
")",
",",
"kwargs",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"try",
":",
"value",
"=",
"(",
"identity",
"if",
"callback",
"is",
"None",
"else",
"callback",
")",
"(",
"f",
"(",
"*"... | 30.333333 | 19.030303 |
def read_until_yieldable(self):
"""Read in additional chunks until it is yieldable."""
while not self.yieldable():
read_content, read_position = _get_next_chunk(self.fp, self.read_position, self.chunk_size)
self.add_to_buffer(read_content, read_position) | [
"def",
"read_until_yieldable",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"yieldable",
"(",
")",
":",
"read_content",
",",
"read_position",
"=",
"_get_next_chunk",
"(",
"self",
".",
"fp",
",",
"self",
".",
"read_position",
",",
"self",
".",
"chunk... | 58 | 19.2 |
def create_comment(self, comment, repository_id, pull_request_id, thread_id, project=None):
"""CreateComment.
[Preview API] Create a comment on a specific thread in a pull request (up to 500 comments can be created per thread).
:param :class:`<Comment> <azure.devops.v5_1.git.models.Comment>` com... | [
"def",
"create_comment",
"(",
"self",
",",
"comment",
",",
"repository_id",
",",
"pull_request_id",
",",
"thread_id",
",",
"project",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'pr... | 65.076923 | 29.461538 |
def filter_results(source, results, aggressive):
"""Filter out spurious reports from pycodestyle.
If aggressive is True, we allow possibly unsafe fixes (E711, E712).
"""
non_docstring_string_line_numbers = multiline_string_lines(
source, include_docstrings=False)
all_string_line_numbers = ... | [
"def",
"filter_results",
"(",
"source",
",",
"results",
",",
"aggressive",
")",
":",
"non_docstring_string_line_numbers",
"=",
"multiline_string_lines",
"(",
"source",
",",
"include_docstrings",
"=",
"False",
")",
"all_string_line_numbers",
"=",
"multiline_string_lines",
... | 33.293103 | 22.310345 |
def get_contacts(self):
"""Use this method to get contacts from your Telegram address book.
Returns:
On success, a list of :obj:`User` objects is returned.
Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
"""
while True:
... | [
"def",
"get_contacts",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"contacts",
"=",
"self",
".",
"send",
"(",
"functions",
".",
"contacts",
".",
"GetContacts",
"(",
"hash",
"=",
"0",
")",
")",
"except",
"FloodWait",
"as",
"e",
":",
"log"... | 40.277778 | 25.388889 |
def _ParseCshVariables(self, lines):
"""Extract env_var and path values from csh derivative shells.
Path attributes can be set several ways:
- setenv takes the form "setenv PATH_NAME COLON:SEPARATED:LIST"
- set takes the form "set path_name=(space separated list)" and is
automatically exported fo... | [
"def",
"_ParseCshVariables",
"(",
"self",
",",
"lines",
")",
":",
"paths",
"=",
"{",
"}",
"for",
"line",
"in",
"lines",
":",
"if",
"len",
"(",
"line",
")",
"<",
"2",
":",
"continue",
"action",
"=",
"line",
"[",
"0",
"]",
"if",
"action",
"==",
"\"... | 34.315789 | 18.710526 |
def get_schemaloc_string(self, ns_uris=None, sort=False, delim="\n"):
"""Constructs and returns a schemalocation attribute. If no
namespaces in this set have any schema locations defined, returns
an empty string.
Args:
ns_uris (iterable): The namespaces to include in the co... | [
"def",
"get_schemaloc_string",
"(",
"self",
",",
"ns_uris",
"=",
"None",
",",
"sort",
"=",
"False",
",",
"delim",
"=",
"\"\\n\"",
")",
":",
"if",
"not",
"ns_uris",
":",
"ns_uris",
"=",
"six",
".",
"iterkeys",
"(",
"self",
".",
"__ns_uri_map",
")",
"if"... | 33.371429 | 25 |
def get_subject_version_ids(self, subject):
"""
Return the list of schema version ids which have been registered
under the given subject.
"""
res = requests.get(self._url('/subjects/{}/versions', subject))
raise_if_failed(res)
return res.json() | [
"def",
"get_subject_version_ids",
"(",
"self",
",",
"subject",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_url",
"(",
"'/subjects/{}/versions'",
",",
"subject",
")",
")",
"raise_if_failed",
"(",
"res",
")",
"return",
"res",
".",
"json... | 36.625 | 12.625 |
def df(unit = 'GB'):
'''A wrapper for the df shell command.'''
details = {}
headers = ['Filesystem', 'Type', 'Size', 'Used', 'Available', 'Capacity', 'MountedOn']
n = len(headers)
unit = df_conversions[unit]
p = subprocess.Popen(args = ['df', '-TP'], stdout = subprocess.PIPE) # -P prevents line... | [
"def",
"df",
"(",
"unit",
"=",
"'GB'",
")",
":",
"details",
"=",
"{",
"}",
"headers",
"=",
"[",
"'Filesystem'",
",",
"'Type'",
",",
"'Size'",
",",
"'Used'",
",",
"'Available'",
",",
"'Capacity'",
",",
"'MountedOn'",
"]",
"n",
"=",
"len",
"(",
"header... | 36.386364 | 21.659091 |
def to_binary(self):
"""Convert N-ary operators to binary operators."""
node = self.node.to_binary()
if node is self.node:
return self
else:
return _expr(node) | [
"def",
"to_binary",
"(",
"self",
")",
":",
"node",
"=",
"self",
".",
"node",
".",
"to_binary",
"(",
")",
"if",
"node",
"is",
"self",
".",
"node",
":",
"return",
"self",
"else",
":",
"return",
"_expr",
"(",
"node",
")"
] | 29.857143 | 12.714286 |
def separable_series(h, N=1):
"""
finds the first N rank 1 tensors such that their sum approximates
the tensor h (2d or 3d) best
returns (e.g. for 3d case) res = (hx,hy,hz)[i]
s.t.
h \approx sum_i einsum("i,j,k",res[i,0],res[i,1],res[i,2])
Parameters
----------
h: ndarray
... | [
"def",
"separable_series",
"(",
"h",
",",
"N",
"=",
"1",
")",
":",
"if",
"h",
".",
"ndim",
"==",
"2",
":",
"return",
"_separable_series2",
"(",
"h",
",",
"N",
")",
"elif",
"h",
".",
"ndim",
"==",
"3",
":",
"return",
"_separable_series3",
"(",
"h",
... | 22.833333 | 22.033333 |
def isometric_remesh(script, SamplingRate=10):
"""Isometric parameterization: remeshing
"""
filter_xml = ''.join([
' <filter name="Iso Parametrization Remeshing">\n',
' <Param name="SamplingRate"',
'value="%d"' % SamplingRate,
'description="Sampling Rate"',
'type... | [
"def",
"isometric_remesh",
"(",
"script",
",",
"SamplingRate",
"=",
"10",
")",
":",
"filter_xml",
"=",
"''",
".",
"join",
"(",
"[",
"' <filter name=\"Iso Parametrization Remeshing\">\\n'",
",",
"' <Param name=\"SamplingRate\"'",
",",
"'value=\"%d\"'",
"%",
"Sampling... | 32.333333 | 12.933333 |
def list_preferences_communication_channel_id(self, user_id, communication_channel_id):
"""
List preferences.
Fetch all preferences for the given communication channel
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""... | [
"def",
"list_preferences_communication_channel_id",
"(",
"self",
",",
"user_id",
",",
"communication_channel_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - user_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"us... | 45.65 | 35.15 |
def allows_not_principal(self):
"""Find allowed not-principals."""
not_principals = []
for statement in self.statements:
if statement.not_principal and statement.effect == "Allow":
not_principals.append(statement)
return not_principals | [
"def",
"allows_not_principal",
"(",
"self",
")",
":",
"not_principals",
"=",
"[",
"]",
"for",
"statement",
"in",
"self",
".",
"statements",
":",
"if",
"statement",
".",
"not_principal",
"and",
"statement",
".",
"effect",
"==",
"\"Allow\"",
":",
"not_principals... | 36.125 | 14.125 |
def p_chr(p):
""" string : CHR arg_list
"""
if len(p[2]) < 1:
syntax_error(p.lineno(1), "CHR$ function need at less 1 parameter")
p[0] = None
return
for i in range(len(p[2])): # Convert every argument to 8bit unsigned
p[2][i].value = make_typecast(TYPE.ubyte, p[2][i].va... | [
"def",
"p_chr",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
"[",
"2",
"]",
")",
"<",
"1",
":",
"syntax_error",
"(",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"\"CHR$ function need at less 1 parameter\"",
")",
"p",
"[",
"0",
"]",
"=",
"None",
"return",... | 33 | 25.5 |
def publish(endpoint, purge_files, rebuild_manifest, skip_upload):
"""Publish the site"""
print("Publishing site to %s ..." % endpoint.upper())
yass = Yass(CWD)
target = endpoint.lower()
sitename = yass.sitename
if not sitename:
raise ValueError("Missing site name")
endpoint = yas... | [
"def",
"publish",
"(",
"endpoint",
",",
"purge_files",
",",
"rebuild_manifest",
",",
"skip_upload",
")",
":",
"print",
"(",
"\"Publishing site to %s ...\"",
"%",
"endpoint",
".",
"upper",
"(",
")",
")",
"yass",
"=",
"Yass",
"(",
"CWD",
")",
"target",
"=",
... | 34.854545 | 21.109091 |
def enqueue(self, name=None, action=None, method=None, wait_url=None,
wait_url_method=None, workflow_sid=None, **kwargs):
"""
Create a <Enqueue> element
:param name: Friendly name
:param action: Action URL
:param method: Action URL method
:param wait_url:... | [
"def",
"enqueue",
"(",
"self",
",",
"name",
"=",
"None",
",",
"action",
"=",
"None",
",",
"method",
"=",
"None",
",",
"wait_url",
"=",
"None",
",",
"wait_url_method",
"=",
"None",
",",
"workflow_sid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
... | 31.625 | 12.875 |
def _checkout(self):
""" check out the image filesystem on self.mount_point """
cmd = ["atomic", "mount", "--storage", "ostree", self.ref_image_name, self.mount_point]
# self.mount_point has to be created by us
self._run_and_log(cmd, self.ostree_path,
"Failed to... | [
"def",
"_checkout",
"(",
"self",
")",
":",
"cmd",
"=",
"[",
"\"atomic\"",
",",
"\"mount\"",
",",
"\"--storage\"",
",",
"\"ostree\"",
",",
"self",
".",
"ref_image_name",
",",
"self",
".",
"mount_point",
"]",
"# self.mount_point has to be created by us",
"self",
"... | 59.5 | 21.833333 |
def _var(ins):
""" Defines a memory variable.
"""
output = []
output.append('%s:' % ins.quad[1])
output.append('DEFB %s' % ((int(ins.quad[2]) - 1) * '00, ' + '00'))
return output | [
"def",
"_var",
"(",
"ins",
")",
":",
"output",
"=",
"[",
"]",
"output",
".",
"append",
"(",
"'%s:'",
"%",
"ins",
".",
"quad",
"[",
"1",
"]",
")",
"output",
".",
"append",
"(",
"'DEFB %s'",
"%",
"(",
"(",
"int",
"(",
"ins",
".",
"quad",
"[",
"... | 24.5 | 18.375 |
def navigation(self, id=None):
"""Function decorator for navbar registration.
Convenience function, calls :meth:`.register_element` with ``id`` and
the decorated function as ``elem``.
:param id: ID to pass on. If ``None``, uses the decorated functions
name.
"... | [
"def",
"navigation",
"(",
"self",
",",
"id",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"self",
".",
"register_element",
"(",
"id",
"or",
"f",
".",
"__name__",
",",
"f",
")",
"return",
"f",
"return",
"wrapper"
] | 28.866667 | 22 |
def schedule_task(self):
"""
Schedules this publish action as a Celery task.
"""
from .tasks import publish_task
publish_task.apply_async(kwargs={'pk': self.pk}, eta=self.scheduled_time) | [
"def",
"schedule_task",
"(",
"self",
")",
":",
"from",
".",
"tasks",
"import",
"publish_task",
"publish_task",
".",
"apply_async",
"(",
"kwargs",
"=",
"{",
"'pk'",
":",
"self",
".",
"pk",
"}",
",",
"eta",
"=",
"self",
".",
"scheduled_time",
")"
] | 31.571429 | 16.142857 |
def supplementary_material(soup):
"""
supplementary-material tags
"""
supplementary_material = []
supplementary_material_tags = raw_parser.supplementary_material(soup)
position = 1
for tag in supplementary_material_tags:
item = {}
copy_attribute(tag.attrs, 'id', item)
... | [
"def",
"supplementary_material",
"(",
"soup",
")",
":",
"supplementary_material",
"=",
"[",
"]",
"supplementary_material_tags",
"=",
"raw_parser",
".",
"supplementary_material",
"(",
"soup",
")",
"position",
"=",
"1",
"for",
"tag",
"in",
"supplementary_material_tags",... | 30.028571 | 18.942857 |
def levelize_smooth_or_improve_candidates(to_levelize, max_levels):
"""Turn parameter in to a list per level.
Helper function to preprocess the smooth and improve_candidates
parameters passed to smoothed_aggregation_solver and rootnode_solver.
Parameters
----------
to_levelize : {string, tuple... | [
"def",
"levelize_smooth_or_improve_candidates",
"(",
"to_levelize",
",",
"max_levels",
")",
":",
"if",
"isinstance",
"(",
"to_levelize",
",",
"tuple",
")",
"or",
"isinstance",
"(",
"to_levelize",
",",
"str",
")",
":",
"to_levelize",
"=",
"[",
"to_levelize",
"for... | 39.653846 | 24.807692 |
def delete(name, profile="splunk"):
'''
Delete a splunk search
CLI Example:
splunk_search.delete 'my search name'
'''
client = _get_splunk(profile)
try:
client.saved_searches.delete(name)
return True
except KeyError:
return None | [
"def",
"delete",
"(",
"name",
",",
"profile",
"=",
"\"splunk\"",
")",
":",
"client",
"=",
"_get_splunk",
"(",
"profile",
")",
"try",
":",
"client",
".",
"saved_searches",
".",
"delete",
"(",
"name",
")",
"return",
"True",
"except",
"KeyError",
":",
"retu... | 19.714286 | 21.142857 |
def partition_dict(items, key):
"""
Given an ordered dictionary of items and a key in that dict,
return an ordered dict of items before, the keyed item, and
an ordered dict of items after.
>>> od = collections.OrderedDict(zip(range(5), 'abcde'))
>>> before, item, after = partition_dict(od, 3)
>>> before
Ordere... | [
"def",
"partition_dict",
"(",
"items",
",",
"key",
")",
":",
"def",
"unmatched",
"(",
"pair",
")",
":",
"test_key",
",",
"item",
",",
"=",
"pair",
"return",
"test_key",
"!=",
"key",
"items_iter",
"=",
"iter",
"(",
"items",
".",
"items",
"(",
")",
")"... | 27.028571 | 19.885714 |
def _detect_timezone():
'''
Get timezone as set by the system
'''
default_timezone = 'America/New_York'
locale_code = locale.getdefaultlocale()
return default_timezone if not locale_code[0] else \
str(pytz.country_timezones[locale_code[0][-2:]][0]) | [
"def",
"_detect_timezone",
"(",
")",
":",
"default_timezone",
"=",
"'America/New_York'",
"locale_code",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"return",
"default_timezone",
"if",
"not",
"locale_code",
"[",
"0",
"]",
"else",
"str",
"(",
"pytz",
".",
... | 34.125 | 15.625 |
def minimum_needs_parameter(field=None, parameter_name=None):
"""Get minimum needs parameter from a given field.
:param field: Field provided
:type field: dict
:param parameter_name: Need parameter's name
:type parameter_name: str
:return: Need paramter
:rtype: ResourceParameter
"""
... | [
"def",
"minimum_needs_parameter",
"(",
"field",
"=",
"None",
",",
"parameter_name",
"=",
"None",
")",
":",
"try",
":",
"if",
"field",
"[",
"'key'",
"]",
":",
"for",
"need_field",
"in",
"minimum_needs_fields",
":",
"if",
"need_field",
"[",
"'key'",
"]",
"==... | 30.555556 | 18.666667 |
def for_all(*generators):
"""
Takes a list of generators and returns a closure which takes a property,
then tests the property against arbitrary instances of the generators.
"""
# Pass in n as an argument
n = 100
def test_property(property_function):
"""
A closure which take... | [
"def",
"for_all",
"(",
"*",
"generators",
")",
":",
"# Pass in n as an argument",
"n",
"=",
"100",
"def",
"test_property",
"(",
"property_function",
")",
":",
"\"\"\"\n A closure which takes a property and tests it against arbitrary\n instances of the generators in th... | 35.375 | 17.225 |
def listDataTiers(self, data_tier_name=""):
"""
API to list data tiers known to DBS.
:param data_tier_name: List details on that data tier (Optional)
:type data_tier_name: str
:returns: List of dictionaries containing the following keys (data_tier_id, data_tier_name, create_by, ... | [
"def",
"listDataTiers",
"(",
"self",
",",
"data_tier_name",
"=",
"\"\"",
")",
":",
"data_tier_name",
"=",
"data_tier_name",
".",
"replace",
"(",
"\"*\"",
",",
"\"%\"",
")",
"try",
":",
"conn",
"=",
"self",
".",
"dbi",
".",
"connection",
"(",
")",
"return... | 51.206897 | 30.586207 |
def set_assets(self, asset_ids):
"""Sets the assets.
arg: asset_ids (osid.id.Id[]): the asset ``Ids``
raise: InvalidArgument - ``asset_ids`` is invalid
raise: NullArgument - ``asset_ids`` is ``null``
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*complian... | [
"def",
"set_assets",
"(",
"self",
",",
"asset_ids",
")",
":",
"# Implemented from template for osid.learning.ActivityForm.set_assets_template",
"if",
"not",
"isinstance",
"(",
"asset_ids",
",",
"list",
")",
":",
"raise",
"errors",
".",
"InvalidArgument",
"(",
")",
"if... | 41.666667 | 14.619048 |
def add_static_path(prefix: str, path: str, no_watch: bool = False) -> None:
"""Add directory to serve static files.
First argument ``prefix`` is a URL prefix for the ``path``. ``path`` must
be a directory. If ``no_watch`` is True, any change of the files in the
path do not trigger restart if ``--autor... | [
"def",
"add_static_path",
"(",
"prefix",
":",
"str",
",",
"path",
":",
"str",
",",
"no_watch",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"app",
"=",
"get_app",
"(",
")",
"app",
".",
"add_static_path",
"(",
"prefix",
",",
"path",
")",
"if",
... | 40 | 21.090909 |
def balance_ions(anions, cations, anion_zs=None, cation_zs=None,
anion_concs=None, cation_concs=None, rho_w=997.1,
method='increase dominant', selected_ion=None):
r'''Performs an ion balance to adjust measured experimental ion
compositions to electroneutrality. Can accept ei... | [
"def",
"balance_ions",
"(",
"anions",
",",
"cations",
",",
"anion_zs",
"=",
"None",
",",
"cation_zs",
"=",
"None",
",",
"anion_concs",
"=",
"None",
",",
"cation_concs",
"=",
"None",
",",
"rho_w",
"=",
"997.1",
",",
"method",
"=",
"'increase dominant'",
","... | 46.468182 | 23.295455 |
def run( self ):
"""
Interact with the blockchain peer,
until we get a socket error or we
exit the loop explicitly.
The order of operations is:
* send version
* receive version
* send verack
* send getdata
* receive blocks
* for ea... | [
"def",
"run",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Segwit support: {}\"",
".",
"format",
"(",
"get_features",
"(",
"'segwit'",
")",
")",
")",
"self",
".",
"begin",
"(",
")",
"try",
":",
"self",
".",
"loop",
"(",
")",
"except",
"socket"... | 24.625 | 17.416667 |
def get_tan_mechanisms(self):
"""
Get the available TAN mechanisms.
Note: Only checks for HITANS versions listed in IMPLEMENTED_HKTAN_VERSIONS.
:return: Dictionary of security_function: TwoStepParameters objects.
"""
retval = OrderedDict()
for version in sorte... | [
"def",
"get_tan_mechanisms",
"(",
"self",
")",
":",
"retval",
"=",
"OrderedDict",
"(",
")",
"for",
"version",
"in",
"sorted",
"(",
"IMPLEMENTED_HKTAN_VERSIONS",
".",
"keys",
"(",
")",
")",
":",
"for",
"seg",
"in",
"self",
".",
"bpd",
".",
"find_segments",
... | 36.388889 | 26.277778 |
def keys_to_snake_case(camel_case_dict):
"""
Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on
each of the keys in the dictionary and returns a new dictionary.
:param camel_case_dict: Dictionary with the keys to convert.
:type camel_case_dict: Di... | [
"def",
"keys_to_snake_case",
"(",
"camel_case_dict",
")",
":",
"return",
"dict",
"(",
"(",
"to_snake_case",
"(",
"key",
")",
",",
"value",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"camel_case_dict",
".",
"items",
"(",
")",
")"
] | 43.636364 | 24.545455 |
def start(self, *args):
"""
Start the daemon
"""
if os.path.exists(self.pidfile):
msg = "pidfile exists. Exit.\n"
sys.stderr.write(msg % self.pidfile)
sys.exit(1)
self.daemonize()
self.run(*args) | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"pidfile",
")",
":",
"msg",
"=",
"\"pidfile exists. Exit.\\n\"",
"sys",
".",
"stderr",
".",
"write",
"(",
"msg",
"%",
"self",
".",
"p... | 22.583333 | 14.416667 |
def prepare(self, node):
"""
Initialise arguments effects as this analysis in inter-procedural.
Initialisation done for Pythonic functions and default values set for
user defined functions.
"""
super(ArgumentReadOnce, self).prepare(node)
# global functions init
... | [
"def",
"prepare",
"(",
"self",
",",
"node",
")",
":",
"super",
"(",
"ArgumentReadOnce",
",",
"self",
")",
".",
"prepare",
"(",
"node",
")",
"# global functions init",
"for",
"n",
"in",
"self",
".",
"global_declarations",
".",
"values",
"(",
")",
":",
"fe... | 39.310345 | 14.586207 |
def f_load(self, name=None, index=None, as_new=False, load_parameters=pypetconstants.LOAD_DATA,
load_derived_parameters=pypetconstants.LOAD_SKELETON,
load_results=pypetconstants.LOAD_SKELETON,
load_other_data=pypetconstants.LOAD_SKELETON,
recursive=True,
... | [
"def",
"f_load",
"(",
"self",
",",
"name",
"=",
"None",
",",
"index",
"=",
"None",
",",
"as_new",
"=",
"False",
",",
"load_parameters",
"=",
"pypetconstants",
".",
"LOAD_DATA",
",",
"load_derived_parameters",
"=",
"pypetconstants",
".",
"LOAD_SKELETON",
",",
... | 45.797872 | 30.601064 |
async def get_supported_playback_functions(
self, uri=""
) -> List[SupportedFunctions]:
"""Return list of inputs and their supported functions."""
return [
SupportedFunctions.make(**x)
for x in await self.services["avContent"]["getSupportedPlaybackFunction"](
... | [
"async",
"def",
"get_supported_playback_functions",
"(",
"self",
",",
"uri",
"=",
"\"\"",
")",
"->",
"List",
"[",
"SupportedFunctions",
"]",
":",
"return",
"[",
"SupportedFunctions",
".",
"make",
"(",
"*",
"*",
"x",
")",
"for",
"x",
"in",
"await",
"self",
... | 35 | 17.4 |
def create(self, handle=None, handle_type=None, **args):
"""
Creates an ontology based on a handle
Handle is one of the following
- `FILENAME.json` : creates an ontology from an obographs json file
- `obo:ONTID` : E.g. obo:pato - creates an ontology from obolibrary PURL (re... | [
"def",
"create",
"(",
"self",
",",
"handle",
"=",
"None",
",",
"handle_type",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"if",
"handle",
"is",
"None",
":",
"self",
".",
"test",
"=",
"self",
".",
"test",
"+",
"1",
"logging",
".",
"info",
"(",
... | 38.384615 | 20.384615 |
def subscribe_to_quorum_channel(self):
"""In case the experiment enforces a quorum, listen for notifications
before creating Partipant objects.
"""
from dallinger.experiment_server.sockets import chat_backend
self.log("Bot subscribing to quorum channel.")
chat_backend.su... | [
"def",
"subscribe_to_quorum_channel",
"(",
"self",
")",
":",
"from",
"dallinger",
".",
"experiment_server",
".",
"sockets",
"import",
"chat_backend",
"self",
".",
"log",
"(",
"\"Bot subscribing to quorum channel.\"",
")",
"chat_backend",
".",
"subscribe",
"(",
"self",... | 42 | 11.5 |
def _build_dictionary(self, results):
"""
Build model dictionary keyed by the relation's foreign key.
:param results: The results
:type results: Collection
:rtype: dict
"""
foreign = self._foreign_key
dictionary = {}
for result in results:
... | [
"def",
"_build_dictionary",
"(",
"self",
",",
"results",
")",
":",
"foreign",
"=",
"self",
".",
"_foreign_key",
"dictionary",
"=",
"{",
"}",
"for",
"result",
"in",
"results",
":",
"key",
"=",
"getattr",
"(",
"result",
".",
"pivot",
",",
"foreign",
")",
... | 23.333333 | 17.428571 |
def WheelUp(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Simulate mouse wheel up.
wheelTimes: int.
interval: float.
waitTime: float.
"""
for i in range(wheelTimes):
mouse_event(MouseEventFlag.Wheel, 0, 0, 120, 0) #WHEEL_DELTA=120
... | [
"def",
"WheelUp",
"(",
"wheelTimes",
":",
"int",
"=",
"1",
",",
"interval",
":",
"float",
"=",
"0.05",
",",
"waitTime",
":",
"float",
"=",
"OPERATION_WAIT_TIME",
")",
"->",
"None",
":",
"for",
"i",
"in",
"range",
"(",
"wheelTimes",
")",
":",
"mouse_eve... | 32.818182 | 18.636364 |
def read_queue(self):
"""
This is responsible for reading events off the queue, and sending
notifications to users, via email or SMS.
The following are necessary for AWS access:
RESTCLIENTS_AMAZON_AWS_ACCESS_KEY
RESTCLIENTS_AMAZON_AWS_SECRET_KEY
RESTCLIENTS_AMAZON... | [
"def",
"read_queue",
"(",
"self",
")",
":",
"queue",
"=",
"AmazonSQS",
"(",
")",
".",
"create_queue",
"(",
"settings",
".",
"RESTCLIENTS_AMAZON_QUEUE",
")",
"queue",
".",
"set_message_class",
"(",
"RawMessage",
")",
"message",
"=",
"queue",
".",
"read",
"(",... | 35.45 | 14.65 |
def get_converted(self, symbol, units='CAD', system=None, tag=None):
"""
Uses a Symbol's Dataframe, to build a new Dataframe,
with the data converted to the new units
Parameters
----------
symbol : str or tuple of the form (Dataframe, str)
Str... | [
"def",
"get_converted",
"(",
"self",
",",
"symbol",
",",
"units",
"=",
"'CAD'",
",",
"system",
"=",
"None",
",",
"tag",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"symbol",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"sym",
"=",
"self",
... | 40.214286 | 17.928571 |
def register(workflow_id, workflow_version):
"""Register an (empty) workflow definition in the database."""
name = "workflow_definitions:{}:{}".format(workflow_id, workflow_version)
workflow_definition = dict(id=workflow_id, version=workflow_version,
stages=[])
# DB.set_ha... | [
"def",
"register",
"(",
"workflow_id",
",",
"workflow_version",
")",
":",
"name",
"=",
"\"workflow_definitions:{}:{}\"",
".",
"format",
"(",
"workflow_id",
",",
"workflow_version",
")",
"workflow_definition",
"=",
"dict",
"(",
"id",
"=",
"workflow_id",
",",
"versi... | 59.142857 | 15.428571 |
def remove_all_listeners(self, event=None):
"""Remove all functions for all events, or one event if one is specifed.
:param event: Optional event you wish to remove all functions from
"""
if event is not None:
self._registered_events[event] = OrderedDict()
else:
... | [
"def",
"remove_all_listeners",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"if",
"event",
"is",
"not",
"None",
":",
"self",
".",
"_registered_events",
"[",
"event",
"]",
"=",
"OrderedDict",
"(",
")",
"else",
":",
"self",
".",
"_registered_events",
... | 41.111111 | 17.222222 |
def convertSequenceMachineSequence(generatedSequences):
"""
Convert a sequence from the SequenceMachine into a list of sequences, such
that each sequence is a list of set of SDRs.
"""
sequenceList = []
currentSequence = []
for s in generatedSequences:
if s is None:
sequenceList.append(currentSeq... | [
"def",
"convertSequenceMachineSequence",
"(",
"generatedSequences",
")",
":",
"sequenceList",
"=",
"[",
"]",
"currentSequence",
"=",
"[",
"]",
"for",
"s",
"in",
"generatedSequences",
":",
"if",
"s",
"is",
"None",
":",
"sequenceList",
".",
"append",
"(",
"curre... | 26.933333 | 16.266667 |
def cb_histogram(fastq, umi_histogram):
''' Counts the number of reads for each cellular barcode
Expects formatted fastq files.
'''
annotations = detect_fastq_annotations(fastq)
re_string = construct_transformed_regex(annotations)
parser_re = re.compile(re_string)
cb_counter = collections.... | [
"def",
"cb_histogram",
"(",
"fastq",
",",
"umi_histogram",
")",
":",
"annotations",
"=",
"detect_fastq_annotations",
"(",
"fastq",
")",
"re_string",
"=",
"construct_transformed_regex",
"(",
"annotations",
")",
"parser_re",
"=",
"re",
".",
"compile",
"(",
"re_strin... | 33.333333 | 17.555556 |
def runSharedFeatures(noiseLevel=None, profile=False):
"""
Runs a simple experiment where three objects share a number of location,
feature pairs.
Parameters:
----------------------------
@param noiseLevel (float)
Noise level to add to the locations and features during inference
@param ... | [
"def",
"runSharedFeatures",
"(",
"noiseLevel",
"=",
"None",
",",
"profile",
"=",
"False",
")",
":",
"exp",
"=",
"L4L2Experiment",
"(",
"\"shared_features\"",
",",
"enableLateralSP",
"=",
"True",
",",
"enableFeedForwardSP",
"=",
"True",
")",
"pairs",
"=",
"crea... | 22.764706 | 22.215686 |
def indentsize(line):
"""Return the indent size, in spaces, at the start of a line of text."""
expline = string.expandtabs(line)
return len(expline) - len(string.lstrip(expline)) | [
"def",
"indentsize",
"(",
"line",
")",
":",
"expline",
"=",
"string",
".",
"expandtabs",
"(",
"line",
")",
"return",
"len",
"(",
"expline",
")",
"-",
"len",
"(",
"string",
".",
"lstrip",
"(",
"expline",
")",
")"
] | 46.75 | 8.75 |
def uninstall(self):
'''
Uninstall the module finder. If not installed, this will do nothing.
After uninstallation, none of the newly loaded modules will be
decorated (that is, everything will be back to normal).
'''
if self.installed:
sys.meta_path.remove(se... | [
"def",
"uninstall",
"(",
"self",
")",
":",
"if",
"self",
".",
"installed",
":",
"sys",
".",
"meta_path",
".",
"remove",
"(",
"self",
")",
"# Reload all decorated items",
"import_list",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".",
"__loaded_modules",
":... | 28.4 | 20.7 |
def dummyListOfDicts(size=100):
"""
returns a list (of the given size) of dicts with fake data.
some dictionary keys are missing for some of the items.
"""
titles="ahp,halfwidth,peak,expT,expI,sweep".split(",")
ld=[] #list of dicts
for i in range(size):
d={}
for t in titles:
... | [
"def",
"dummyListOfDicts",
"(",
"size",
"=",
"100",
")",
":",
"titles",
"=",
"\"ahp,halfwidth,peak,expT,expI,sweep\"",
".",
"split",
"(",
"\",\"",
")",
"ld",
"=",
"[",
"]",
"#list of dicts",
"for",
"i",
"in",
"range",
"(",
"size",
")",
":",
"d",
"=",
"{"... | 35.4375 | 17.1875 |
def delete(self, value, key):
"""
Delete a value from a tree.
"""
# Base case: The empty tree cannot possibly have the desired value.
if self is NULL:
raise KeyError(value)
direction = cmp(key(value), key(self.value))
# Because we lean to the left, ... | [
"def",
"delete",
"(",
"self",
",",
"value",
",",
"key",
")",
":",
"# Base case: The empty tree cannot possibly have the desired value.",
"if",
"self",
"is",
"NULL",
":",
"raise",
"KeyError",
"(",
"value",
")",
"direction",
"=",
"cmp",
"(",
"key",
"(",
"value",
... | 41.271186 | 19.169492 |
def print_prediction (self, ptup, precision=2):
"""Print a summary of a predicted position.
The argument *ptup* is a tuple returned by :meth:`predict`. It is
printed to :data:`sys.stdout` in a reasonable format that uses Unicode
characters.
"""
from . import ellipses
... | [
"def",
"print_prediction",
"(",
"self",
",",
"ptup",
",",
"precision",
"=",
"2",
")",
":",
"from",
".",
"import",
"ellipses",
"bestra",
",",
"bestdec",
",",
"maj",
",",
"min",
",",
"pa",
"=",
"ptup",
"f",
"=",
"ellipses",
".",
"sigmascale",
"(",
"1",... | 35.263158 | 23.894737 |
def remove_selected_classification(self):
"""Remove selected item on hazard class form."""
removed_classes = self.hazard_class_form.selectedItems()
current_item = self.hazard_class_form.currentItem()
removed_index = self.hazard_class_form.indexFromItem(current_item)
del self.clas... | [
"def",
"remove_selected_classification",
"(",
"self",
")",
":",
"removed_classes",
"=",
"self",
".",
"hazard_class_form",
".",
"selectedItems",
"(",
")",
"current_item",
"=",
"self",
".",
"hazard_class_form",
".",
"currentItem",
"(",
")",
"removed_index",
"=",
"se... | 52.777778 | 11.888889 |
def getScriptLanguageSystems(feaFile):
"""Return dictionary keyed by Unicode script code containing lists of
(OT_SCRIPT_TAG, [OT_LANGUAGE_TAG, ...]) tuples (excluding "DFLT").
"""
languagesByScript = collections.OrderedDict()
for ls in [
st
for st in feaFile.statements
if isi... | [
"def",
"getScriptLanguageSystems",
"(",
"feaFile",
")",
":",
"languagesByScript",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"ls",
"in",
"[",
"st",
"for",
"st",
"in",
"feaFile",
".",
"statements",
"if",
"isinstance",
"(",
"st",
",",
"ast",
".... | 37.473684 | 16.736842 |
def get(cls, name, raise_exc=True):
"""
Get the element by name. Does an exact match by element type.
:param str name: name of element
:param bool raise_exc: optionally disable exception.
:raises ElementNotFound: if element does not exist
:rtype: Element
... | [
"def",
"get",
"(",
"cls",
",",
"name",
",",
"raise_exc",
"=",
"True",
")",
":",
"element",
"=",
"cls",
".",
"objects",
".",
"filter",
"(",
"name",
",",
"exact_match",
"=",
"True",
")",
".",
"first",
"(",
")",
"if",
"name",
"is",
"not",
"None",
"e... | 40.466667 | 14.6 |
def _dispatch_cmd(self, handler, argv):
"""Introspect sub-command handler signature to determine how to
dispatch the command. The raw handler provided by the base
'RawCmdln' class is still supported:
def do_foo(self, argv):
# 'argv' is the vector of command line args... | [
"def",
"_dispatch_cmd",
"(",
"self",
",",
"handler",
",",
"argv",
")",
":",
"co_argcount",
"=",
"handler",
".",
"__func__",
".",
"__code__",
".",
"co_argcount",
"if",
"co_argcount",
"==",
"2",
":",
"# handler ::= do_foo(self, argv)",
"return",
"handler",
"(",
... | 45.290323 | 20.387097 |
def interpretBitEncoding(bitEncoding):
"""Returns a floattype string and a numpy array type.
:param bitEncoding: Must be either '64' or '32'
:returns: (floattype, numpyType)
"""
if bitEncoding == '64':
floattype = 'd' # 64-bit
numpyType = numpy.float64
elif bitEncoding == '32':... | [
"def",
"interpretBitEncoding",
"(",
"bitEncoding",
")",
":",
"if",
"bitEncoding",
"==",
"'64'",
":",
"floattype",
"=",
"'d'",
"# 64-bit",
"numpyType",
"=",
"numpy",
".",
"float64",
"elif",
"bitEncoding",
"==",
"'32'",
":",
"floattype",
"=",
"'f'",
"# 32-bit",
... | 32.421053 | 13.578947 |
def _create_translation_file(feature_folder,
dataset_name,
translation,
formula_id2index):
"""
Write a loop-up file that contains the direct (record-wise) lookup
information.
Parameters
----------
feature_fol... | [
"def",
"_create_translation_file",
"(",
"feature_folder",
",",
"dataset_name",
",",
"translation",
",",
"formula_id2index",
")",
":",
"translationfilename",
"=",
"\"%s/translation-%s.csv\"",
"%",
"(",
"feature_folder",
",",
"dataset_name",
")",
"with",
"open",
"(",
"t... | 37.166667 | 15 |
def _add_debugging_fields(gelf_dict, record):
"""Add debugging fields to the given ``gelf_dict``
:param gelf_dict: dictionary representation of a GELF log.
:type gelf_dict: dict
:param record: :class:`logging.LogRecord` to extract debugging
fields from to insert into the gi... | [
"def",
"_add_debugging_fields",
"(",
"gelf_dict",
",",
"record",
")",
":",
"gelf_dict",
".",
"update",
"(",
"{",
"'file'",
":",
"record",
".",
"pathname",
",",
"'line'",
":",
"record",
".",
"lineno",
",",
"'_function'",
":",
"record",
".",
"funcName",
",",... | 37.190476 | 13.428571 |
def filled_contour(self, min=None, max=None):
"""Get contour polygons between the given levels.
Parameters
----------
min : numbers.Number or None
The minimum data level of the contour polygon. If :obj:`None`,
``numpy.finfo(numpy.float64).min`` will be used.
... | [
"def",
"filled_contour",
"(",
"self",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
")",
":",
"# pylint: disable=redefined-builtin,redefined-outer-name",
"# Get the contour vertices.",
"if",
"min",
"is",
"None",
":",
"min",
"=",
"np",
".",
"finfo",
"(",
"np"... | 36.571429 | 19.071429 |
def unlink_from(self, provider):
'''
解绑特定第三方平台
'''
if type(provider) != str:
raise TypeError('input should be a string')
self.link_with(provider, None)
# self._sync_auth_data(provider)
return self | [
"def",
"unlink_from",
"(",
"self",
",",
"provider",
")",
":",
"if",
"type",
"(",
"provider",
")",
"!=",
"str",
":",
"raise",
"TypeError",
"(",
"'input should be a string'",
")",
"self",
".",
"link_with",
"(",
"provider",
",",
"None",
")",
"# self._sync_auth_... | 28.444444 | 14.888889 |
def _get_job_collection_name(self, process_name):
"""jobs are stored in 4 collections: hourly, daily, monthly and yearly;
method looks for the proper job_collection base on process TIME_QUALIFIER"""
qualifier = context.process_context[process_name].time_qualifier
if qualifier == QUALIFI... | [
"def",
"_get_job_collection_name",
"(",
"self",
",",
"process_name",
")",
":",
"qualifier",
"=",
"context",
".",
"process_context",
"[",
"process_name",
"]",
".",
"time_qualifier",
"if",
"qualifier",
"==",
"QUALIFIER_HOURLY",
":",
"collection_name",
"=",
"COLLECTION... | 50 | 14.4375 |
def _add_metadata_as_attrs_da(data, units, description, dtype_out_vert):
"""Add metadata attributes to DataArray"""
if dtype_out_vert == 'vert_int':
if units != '':
units = '(vertical integral of {0}): {0} kg m^-2)'.format(units)
else:
units = '(vertical integral of quant... | [
"def",
"_add_metadata_as_attrs_da",
"(",
"data",
",",
"units",
",",
"description",
",",
"dtype_out_vert",
")",
":",
"if",
"dtype_out_vert",
"==",
"'vert_int'",
":",
"if",
"units",
"!=",
"''",
":",
"units",
"=",
"'(vertical integral of {0}): {0} kg m^-2)'",
".",
"f... | 43.1 | 18.9 |
def delete_orderrun(backend, orderrun_id):
"""
Delete the orderrun specified by the argument.
"""
click.secho('%s - Deleting orderrun %s' % (get_datetime(), orderrun_id), fg='green')
check_and_print(DKCloudCommandRunner.delete_orderrun(backend.dki, orderrun_id.strip())) | [
"def",
"delete_orderrun",
"(",
"backend",
",",
"orderrun_id",
")",
":",
"click",
".",
"secho",
"(",
"'%s - Deleting orderrun %s'",
"%",
"(",
"get_datetime",
"(",
")",
",",
"orderrun_id",
")",
",",
"fg",
"=",
"'green'",
")",
"check_and_print",
"(",
"DKCloudComm... | 47.5 | 18.5 |
def token_from_fragment(self, authorization_response):
"""Parse token from the URI fragment, used by MobileApplicationClients.
:param authorization_response: The full URL of the redirect back to you
:return: A token dict
"""
self._client.parse_request_uri_response(
a... | [
"def",
"token_from_fragment",
"(",
"self",
",",
"authorization_response",
")",
":",
"self",
".",
"_client",
".",
"parse_request_uri_response",
"(",
"authorization_response",
",",
"state",
"=",
"self",
".",
"_state",
")",
"self",
".",
"token",
"=",
"self",
".",
... | 38.727273 | 15.636364 |
def p_decl(self, p):
'decl : sigtypes declnamelist SEMICOLON'
decllist = []
for rname, rlength in p[2]:
decllist.extend(self.create_decl(p[1], rname, length=rlength,
lineno=p.lineno(2)))
p[0] = Decl(tuple(decllist), lineno=p.lineno... | [
"def",
"p_decl",
"(",
"self",
",",
"p",
")",
":",
"decllist",
"=",
"[",
"]",
"for",
"rname",
",",
"rlength",
"in",
"p",
"[",
"2",
"]",
":",
"decllist",
".",
"extend",
"(",
"self",
".",
"create_decl",
"(",
"p",
"[",
"1",
"]",
",",
"rname",
",",
... | 44.25 | 16.25 |
def _set_splits(self, split_dict):
"""Split setter (private method)."""
# Update the dictionary representation.
# Use from/to proto for a clean copy
self._splits = split_dict.copy()
# Update the proto
del self.as_proto.splits[:] # Clear previous
for split_info in split_dict.to_proto():
... | [
"def",
"_set_splits",
"(",
"self",
",",
"split_dict",
")",
":",
"# Update the dictionary representation.",
"# Use from/to proto for a clean copy",
"self",
".",
"_splits",
"=",
"split_dict",
".",
"copy",
"(",
")",
"# Update the proto",
"del",
"self",
".",
"as_proto",
"... | 36.1 | 9.7 |
def load_ssh_key(key_id, skip_priv_key=False):
"""
Load a local ssh private key (in PEM format). PEM format is the OpenSSH
default format for private keys.
See similar code in imgapi.js#loadSSHKey.
@param key_id {str} An ssh public key fingerprint or ssh private key path.
@param skip_priv_key ... | [
"def",
"load_ssh_key",
"(",
"key_id",
",",
"skip_priv_key",
"=",
"False",
")",
":",
"priv_key",
"=",
"None",
"# If `key_id` is already a private key path, then easy.",
"if",
"not",
"FINGERPRINT_RE",
".",
"match",
"(",
"key_id",
")",
":",
"if",
"not",
"skip_priv_key"... | 33.038095 | 19.342857 |
def _execute(self, request, **kwargs):
"""The top-level execute function for the endpoint.
This method is intended to remain as-is, and not be overridden.
It gets called by your HTTP framework's route handler, and performs
the following actions to process the request:
``authent... | [
"def",
"_execute",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
".",
"_create_context",
"(",
"request",
")",
"self",
".",
"_authenticate",
"(",
")",
"context",
"=",
"get_current_context",
"(",
")",
"self",
".",
"_... | 46.157576 | 23.515152 |
def rel_href(src, dst):
"""For src='foo/bar.html', dst='garply.html#frotz' return relative link '../garply.html#frotz'.
"""
src_dir = os.path.dirname(src)
return os.path.relpath(dst, src_dir) | [
"def",
"rel_href",
"(",
"src",
",",
"dst",
")",
":",
"src_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"src",
")",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"dst",
",",
"src_dir",
")"
] | 39 | 5.4 |
async def reply_voice(self, voice: typing.Union[base.InputFile, base.String],
caption: typing.Union[base.String, None] = None,
duration: typing.Union[base.Integer, None] = None,
disable_notification: typing.Union[base.Boolean, None] = None,
... | [
"async",
"def",
"reply_voice",
"(",
"self",
",",
"voice",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"InputFile",
",",
"base",
".",
"String",
"]",
",",
"caption",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"String",
",",
"None",
"]",
"=",
"... | 57.972973 | 26.459459 |
def device_sdr_entries(self):
"""A generator that returns the SDR list. Starting with ID=0x0000 and
end when ID=0xffff is returned.
"""
reservation_id = self.reserve_device_sdr_repository()
record_id = 0
while True:
record = self.get_device_sdr(record_id, res... | [
"def",
"device_sdr_entries",
"(",
"self",
")",
":",
"reservation_id",
"=",
"self",
".",
"reserve_device_sdr_repository",
"(",
")",
"record_id",
"=",
"0",
"while",
"True",
":",
"record",
"=",
"self",
".",
"get_device_sdr",
"(",
"record_id",
",",
"reservation_id",... | 34.384615 | 13.615385 |
def _nested_op(inputs, op): # pylint: disable=invalid-name
"""Helper: sum a list of arrays or nested arrays."""
# First the simple non-nested case.
if not isinstance(inputs[0], (list, tuple)):
return op(inputs)
# In the nested case, sum on each axis separately.
result_list = []
for i in range(len(input... | [
"def",
"_nested_op",
"(",
"inputs",
",",
"op",
")",
":",
"# pylint: disable=invalid-name",
"# First the simple non-nested case.",
"if",
"not",
"isinstance",
"(",
"inputs",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"op",
"(",
"in... | 38.916667 | 12.583333 |
def check_metadata(self):
'''Ensure that the metadata in our file is self-consistent.'''
assert self.header.point_count == self.point_used, (
'inconsistent point count! {} header != {} POINT:USED'.format(
self.header.point_count,
self.point_used,
)... | [
"def",
"check_metadata",
"(",
"self",
")",
":",
"assert",
"self",
".",
"header",
".",
"point_count",
"==",
"self",
".",
"point_used",
",",
"(",
"'inconsistent point count! {} header != {} POINT:USED'",
".",
"format",
"(",
"self",
".",
"header",
".",
"point_count",... | 41.755556 | 21 |
def set_version(self, version='0.0.0', save=True):
"""Set configuration (not application!) version"""
self.set(self.DEFAULT_SECTION_NAME, 'version', version, save=save) | [
"def",
"set_version",
"(",
"self",
",",
"version",
"=",
"'0.0.0'",
",",
"save",
"=",
"True",
")",
":",
"self",
".",
"set",
"(",
"self",
".",
"DEFAULT_SECTION_NAME",
",",
"'version'",
",",
"version",
",",
"save",
"=",
"save",
")"
] | 61.333333 | 15 |
def _log_debug(msg):
'''
Log at debug level
:param msg: message to log
'''
if _log_level <= DEBUG:
if _log_level == TRACE:
traceback.print_stack()
_log(msg) | [
"def",
"_log_debug",
"(",
"msg",
")",
":",
"if",
"_log_level",
"<=",
"DEBUG",
":",
"if",
"_log_level",
"==",
"TRACE",
":",
"traceback",
".",
"print_stack",
"(",
")",
"_log",
"(",
"msg",
")"
] | 21.777778 | 18.222222 |
def loadCats(self, ids=[]):
"""
Load cats with the specified ids.
:param ids (int array) : integer ids specifying cats
:return: cats (object array) : loaded cat objects
"""
if _isArrayLike(ids):
return [self.cats[id] for id in ids]
elif type(ids)... | [
"def",
"loadCats",
"(",
"self",
",",
"ids",
"=",
"[",
"]",
")",
":",
"if",
"_isArrayLike",
"(",
"ids",
")",
":",
"return",
"[",
"self",
".",
"cats",
"[",
"id",
"]",
"for",
"id",
"in",
"ids",
"]",
"elif",
"type",
"(",
"ids",
")",
"==",
"int",
... | 35.5 | 9.1 |
def exclude_time(self, start, end, days):
"""Added an excluded time by start, end times and the days.
``start`` and ``end`` are in military integer times (e.g. - 1200 1430).
``days`` is a collection of integers or strings of fully-spelt, lowercased days
of the week.
"""... | [
"def",
"exclude_time",
"(",
"self",
",",
"start",
",",
"end",
",",
"days",
")",
":",
"self",
".",
"_excluded_times",
".",
"append",
"(",
"TimeRange",
"(",
"start",
",",
"end",
",",
"days",
")",
")",
"return",
"self"
] | 44.111111 | 20.333333 |
def getNodeByName(node, name):
"""
Get the first child node matching a given local name
"""
if node is None:
raise Exception(
"Cannot search for a child '%s' in a None object" % (name,)
)
if not name:
raise Exception("Unspecified name to find node for.")
try:... | [
"def",
"getNodeByName",
"(",
"node",
",",
"name",
")",
":",
"if",
"node",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Cannot search for a child '%s' in a None object\"",
"%",
"(",
"name",
",",
")",
")",
"if",
"not",
"name",
":",
"raise",
"Exception",
"(... | 26.5625 | 21.0625 |
def shell(self, gui=0, command='', dryrun=None, shell_interactive_cmd_str=None):
"""
Opens an SSH connection.
"""
from burlap.common import get_hosts_for_site
if dryrun is not None:
self.dryrun = dryrun
r = self.local_renderer
if r.genv.SITE != r.ge... | [
"def",
"shell",
"(",
"self",
",",
"gui",
"=",
"0",
",",
"command",
"=",
"''",
",",
"dryrun",
"=",
"None",
",",
"shell_interactive_cmd_str",
"=",
"None",
")",
":",
"from",
"burlap",
".",
"common",
"import",
"get_hosts_for_site",
"if",
"dryrun",
"is",
"not... | 41.660714 | 24.803571 |
def validate(cls, mapper_spec):
"""Validate mapper specification.
Args:
mapper_spec: an instance of model.MapperSpec.
Raises:
BadWriterParamsError: if the specification is invalid for any reason such
as missing the bucket name or providing an invalid bucket name.
"""
writer_spe... | [
"def",
"validate",
"(",
"cls",
",",
"mapper_spec",
")",
":",
"writer_spec",
"=",
"cls",
".",
"get_params",
"(",
"mapper_spec",
",",
"allow_old",
"=",
"False",
")",
"# Bucket Name is required",
"if",
"cls",
".",
"BUCKET_NAME_PARAM",
"not",
"in",
"writer_spec",
... | 36.5 | 20.269231 |
def get_parameter(self, name):
"""
Gets a single parameter by its name.
:param str name: Either a fully-qualified XTCE name or an alias in the
format ``NAMESPACE/NAME``.
:rtype: .Parameter
"""
name = adapt_name_for_rest(name)
url = '/mdb/... | [
"def",
"get_parameter",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"adapt_name_for_rest",
"(",
"name",
")",
"url",
"=",
"'/mdb/{}/parameters{}'",
".",
"format",
"(",
"self",
".",
"_instance",
",",
"name",
")",
"response",
"=",
"self",
".",
"_client",... | 37.5 | 11.785714 |
def html_to_fc(html=None, clean_html=None, clean_visible=None, encoding=None, url=None,
timestamp=None, other_features=None):
'''`html` is expected to be a raw string received over the wire from a
remote webserver, and `encoding`, if provided, is used to decode
it. Typically, encoding comes ... | [
"def",
"html_to_fc",
"(",
"html",
"=",
"None",
",",
"clean_html",
"=",
"None",
",",
"clean_visible",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"url",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"other_features",
"=",
"None",
")",
":",
"def",... | 36.2875 | 20.7875 |
def from_dict(cls, parameters):
"""Set attributes with provided values.
Args:
parameters(dict): Dictionary containing instance parameters.
Returns:
Truncnorm: Instance populated with given parameters.
"""
instance = cls()
instance.fitted = parame... | [
"def",
"from_dict",
"(",
"cls",
",",
"parameters",
")",
":",
"instance",
"=",
"cls",
"(",
")",
"instance",
".",
"fitted",
"=",
"parameters",
"[",
"'fitted'",
"]",
"instance",
".",
"constant_value",
"=",
"parameters",
"[",
"'constant_value'",
"]",
"if",
"in... | 32.705882 | 23.764706 |
def dframe(self, dimensions=None, multi_index=False):
"""Convert dimension values to DataFrame.
Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.
Args:
dimensions: Dimensions to return as columns
mul... | [
"def",
"dframe",
"(",
"self",
",",
"dimensions",
"=",
"None",
",",
"multi_index",
"=",
"False",
")",
":",
"if",
"dimensions",
":",
"dimensions",
"=",
"[",
"self",
".",
"get_dimension",
"(",
"d",
",",
"strict",
"=",
"True",
")",
"for",
"d",
"in",
"dim... | 42.708333 | 23.875 |
def _writeConnectivity(self, links, fileObject):
"""
Write Connectivity Lines to File Method
"""
for link in links:
linkNum = link.linkNumber
downLink = link.downstreamLinkID
numUpLinks = link.numUpstreamLinks
upLinks = ''
for u... | [
"def",
"_writeConnectivity",
"(",
"self",
",",
"links",
",",
"fileObject",
")",
":",
"for",
"link",
"in",
"links",
":",
"linkNum",
"=",
"link",
".",
"linkNumber",
"downLink",
"=",
"link",
".",
"downstreamLinkID",
"numUpLinks",
"=",
"link",
".",
"numUpstreamL... | 38.4 | 14.133333 |
def execute(mp):
"""
Example process for testing.
Inputs:
-------
file1
raster file
Parameters:
-----------
Output:
-------
np.ndarray
"""
# Reading and writing data works like this:
with mp.open("file1", resampling="bilinear") as raster_file:
if ra... | [
"def",
"execute",
"(",
"mp",
")",
":",
"# Reading and writing data works like this:",
"with",
"mp",
".",
"open",
"(",
"\"file1\"",
",",
"resampling",
"=",
"\"bilinear\"",
")",
"as",
"raster_file",
":",
"if",
"raster_file",
".",
"is_empty",
"(",
")",
":",
"retu... | 21.708333 | 21.958333 |
def encrypt(self, sa, esp, key):
"""
Encrypt an ESP packet
@param sa: the SecurityAssociation associated with the ESP packet.
@param esp: an unencrypted _ESPPlain packet with valid padding
@param key: the secret key used for encryption
@return: a valid ESP packet... | [
"def",
"encrypt",
"(",
"self",
",",
"sa",
",",
"esp",
",",
"key",
")",
":",
"data",
"=",
"esp",
".",
"data_for_encryption",
"(",
")",
"if",
"self",
".",
"cipher",
":",
"mode_iv",
"=",
"self",
".",
"_format_mode_iv",
"(",
"algo",
"=",
"self",
",",
"... | 38.230769 | 21.307692 |
async def get_constraints(self):
"""Return the machine constraints dict for this application.
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(
'Getting constraints for %s', self.name)
result = (await app_facade.Get(self.name)).c... | [
"async",
"def",
"get_constraints",
"(",
"self",
")",
":",
"app_facade",
"=",
"client",
".",
"ApplicationFacade",
".",
"from_connection",
"(",
"self",
".",
"connection",
")",
"log",
".",
"debug",
"(",
"'Getting constraints for %s'",
",",
"self",
".",
"name",
")... | 33.636364 | 21 |
def install_sql(self, site=None, database='default', apps=None, stop_on_error=0, fn=None):
"""
Installs all custom SQL.
"""
#from burlap.db import load_db_set
stop_on_error = int(stop_on_error)
site = site or ALL
name = database
r = self.local_renderer... | [
"def",
"install_sql",
"(",
"self",
",",
"site",
"=",
"None",
",",
"database",
"=",
"'default'",
",",
"apps",
"=",
"None",
",",
"stop_on_error",
"=",
"0",
",",
"fn",
"=",
"None",
")",
":",
"#from burlap.db import load_db_set",
"stop_on_error",
"=",
"int",
"... | 38.12037 | 18.675926 |
def updateImage(self, imgdata, xaxis=None, yaxis=None):
"""Updates the Widget image directly.
:type imgdata: numpy.ndarray, see :meth:`pyqtgraph:pyqtgraph.ImageItem.setImage`
:param xaxis: x-axis values, length should match dimension 1 of imgdata
:param yaxis: y-axis values, length shou... | [
"def",
"updateImage",
"(",
"self",
",",
"imgdata",
",",
"xaxis",
"=",
"None",
",",
"yaxis",
"=",
"None",
")",
":",
"imgdata",
"=",
"imgdata",
".",
"T",
"self",
".",
"img",
".",
"setImage",
"(",
"imgdata",
")",
"if",
"xaxis",
"is",
"not",
"None",
"a... | 45.352941 | 15.352941 |
def getExperiments(uuid: str):
""" list active (running or completed) experiments"""
return jsonify([x.deserialize() for x in Experiment.query.all()]) | [
"def",
"getExperiments",
"(",
"uuid",
":",
"str",
")",
":",
"return",
"jsonify",
"(",
"[",
"x",
".",
"deserialize",
"(",
")",
"for",
"x",
"in",
"Experiment",
".",
"query",
".",
"all",
"(",
")",
"]",
")"
] | 52 | 13 |
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | [
"def",
"run_migrations_offline",
"(",
")",
":",
"url",
"=",
"winchester_config",
"[",
"'database'",
"]",
"[",
"'url'",
"]",
"context",
".",
"configure",
"(",
"url",
"=",
"url",
")",
"with",
"context",
".",
"begin_transaction",
"(",
")",
":",
"context",
"."... | 29.411765 | 16.529412 |
def ready_argument_list(self, arguments):
"""ready argument list to be passed to the kernel, allocates gpu mem
:param arguments: List of arguments to be passed to the kernel.
The order should match the argument list on the OpenCL kernel.
Allowed values are numpy.ndarray, and/or ... | [
"def",
"ready_argument_list",
"(",
"self",
",",
"arguments",
")",
":",
"gpu_args",
"=",
"[",
"]",
"for",
"arg",
"in",
"arguments",
":",
"# if arg i is a numpy array copy to device",
"if",
"isinstance",
"(",
"arg",
",",
"numpy",
".",
"ndarray",
")",
":",
"gpu_a... | 48.473684 | 21.894737 |
def next_frame_glow_shapes():
"""Hparams for qualitative and quantitative results on shapes dataset."""
hparams = next_frame_glow_bair_quant()
hparams.video_num_input_frames = 1
hparams.video_num_target_frames = 2
hparams.num_train_frames = 2
hparams.num_cond_latents = 1
hparams.coupling = "additive"
hp... | [
"def",
"next_frame_glow_shapes",
"(",
")",
":",
"hparams",
"=",
"next_frame_glow_bair_quant",
"(",
")",
"hparams",
".",
"video_num_input_frames",
"=",
"1",
"hparams",
".",
"video_num_target_frames",
"=",
"2",
"hparams",
".",
"num_train_frames",
"=",
"2",
"hparams",
... | 34.428571 | 8.071429 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.