text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _get_valid_fill_mask(arr, dim, limit):
'''helper function to determine values that can be filled when limit is not
None'''
kw = {dim: limit + 1}
# we explicitly use construct method to avoid copy.
new_dim = utils.get_temp_dimname(arr.dims, '_window')
return (arr.isnull().rolling(min_periods=... | [
"def",
"_get_valid_fill_mask",
"(",
"arr",
",",
"dim",
",",
"limit",
")",
":",
"kw",
"=",
"{",
"dim",
":",
"limit",
"+",
"1",
"}",
"# we explicitly use construct method to avoid copy.",
"new_dim",
"=",
"utils",
".",
"get_temp_dimname",
"(",
"arr",
".",
"dims",... | 46.666667 | 16.444444 |
def process_exception_message(exception):
"""
Process an exception message.
Args:
exception: The exception to process.
Returns:
A filtered string summarizing the exception.
"""
exception_message = str(exception)
for replace_char in ['\t',... | [
"def",
"process_exception_message",
"(",
"exception",
")",
":",
"exception_message",
"=",
"str",
"(",
"exception",
")",
"for",
"replace_char",
"in",
"[",
"'\\t'",
",",
"'\\n'",
",",
"'\\\\n'",
"]",
":",
"exception_message",
"=",
"exception_message",
".",
"replac... | 35.071429 | 18.357143 |
def showroom_get_roomid_by_room_url_key(room_url_key):
"""str->str"""
fake_headers_mobile = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'UTF-8,*;q=0.5',
'Accept-Encoding': 'gzip,deflate,sdch',
'Accept-Language': 'en-US,en;q=0.8... | [
"def",
"showroom_get_roomid_by_room_url_key",
"(",
"room_url_key",
")",
":",
"fake_headers_mobile",
"=",
"{",
"'Accept'",
":",
"'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'",
",",
"'Accept-Charset'",
":",
"'UTF-8,*;q=0.5'",
",",
"'Accept-Encoding'",
":",
"'... | 49.785714 | 24.785714 |
def by_col(cls, df, e, b, t=None, geom_col='geometry', inplace=False, **kwargs):
"""
Compute smoothing by columns in a dataframe. The bounding box and point
information is computed from the geometry column.
Parameters
-----------
df : pandas.DataFrame
... | [
"def",
"by_col",
"(",
"cls",
",",
"df",
",",
"e",
",",
"b",
",",
"t",
"=",
"None",
",",
"geom_col",
"=",
"'geometry'",
",",
"inplace",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"pandas",
"as",
"pd",
"if",
"not",
"inplace",
":",
... | 41.102564 | 20.769231 |
def setup(__pkg: str) -> jinja2.Environment:
"""Configure a new Jinja environment with our filters.
Args:
__pkg: Package name to use as base for templates searches
Returns:
Configured Jinja environment
"""
dirs = [path.join(d, 'templates')
for d in xdg_basedir.get_data_d... | [
"def",
"setup",
"(",
"__pkg",
":",
"str",
")",
"->",
"jinja2",
".",
"Environment",
":",
"dirs",
"=",
"[",
"path",
".",
"join",
"(",
"d",
",",
"'templates'",
")",
"for",
"d",
"in",
"xdg_basedir",
".",
"get_data_dirs",
"(",
"__pkg",
")",
"]",
"env",
... | 33.722222 | 20.333333 |
def open_with_encoding(filename, encoding, mode='r'):
"""Return opened file with a specific encoding."""
return io.open(filename, mode=mode, encoding=encoding,
newline='') | [
"def",
"open_with_encoding",
"(",
"filename",
",",
"encoding",
",",
"mode",
"=",
"'r'",
")",
":",
"return",
"io",
".",
"open",
"(",
"filename",
",",
"mode",
"=",
"mode",
",",
"encoding",
"=",
"encoding",
",",
"newline",
"=",
"''",
")"
] | 48.75 | 10.25 |
def clone_model(model_instance):
"""
Returns a copy of the given model with all objects cloned. This is equivalent to saving the model to
a file and reload it, but it doesn't require writing or reading to/from disk. The original model is not touched.
:param model: model to be cloned
:return: a clon... | [
"def",
"clone_model",
"(",
"model_instance",
")",
":",
"data",
"=",
"model_instance",
".",
"to_dict_with_types",
"(",
")",
"parser",
"=",
"ModelParser",
"(",
"model_dict",
"=",
"data",
")",
"return",
"parser",
".",
"get_model",
"(",
")"
] | 33.071429 | 23.928571 |
def VerifyStructure(self, parser_mediator, lines):
"""Verifies whether content corresponds to an SCCM log file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
lines (str): one or more lines from the text file.... | [
"def",
"VerifyStructure",
"(",
"self",
",",
"parser_mediator",
",",
"lines",
")",
":",
"# Identify the token to which we attempt a match.",
"match",
"=",
"self",
".",
"_PARSING_COMPONENTS",
"[",
"'msg_left_delimiter'",
"]",
".",
"match",
"# Because logs files can lead with ... | 39.210526 | 20.210526 |
def _get_verdict(result):
"""Gets verdict of the testcase."""
verdict = result.get("verdict")
if not verdict:
return None
verdict = verdict.strip().lower()
if verdict not in Verdicts.PASS + Verdicts.FAIL + Verdicts.SKIP + Verdicts.WAIT:
return None
... | [
"def",
"_get_verdict",
"(",
"result",
")",
":",
"verdict",
"=",
"result",
".",
"get",
"(",
"\"verdict\"",
")",
"if",
"not",
"verdict",
":",
"return",
"None",
"verdict",
"=",
"verdict",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"verdict",
... | 36.333333 | 14.888889 |
def draw_circle(self, center, radius, array, value, mode="set"):
"""
Draws a circle of specified radius on the input array and fills it with specified value
:param center: a tuple for the center of the circle
:type center: tuple (x,y)
:param radius: how many pixels in radius the ... | [
"def",
"draw_circle",
"(",
"self",
",",
"center",
",",
"radius",
",",
"array",
",",
"value",
",",
"mode",
"=",
"\"set\"",
")",
":",
"ri",
",",
"ci",
"=",
"draw",
".",
"circle",
"(",
"center",
"[",
"0",
"]",
",",
"center",
"[",
"1",
"]",
",",
"r... | 45.230769 | 16.307692 |
def parse_stdout(self, filelike):
"""Parse the content written by the script to standard out into a `CifData` object.
:param filelike: filelike object of stdout
:returns: an exit code in case of an error, None otherwise
"""
from CifFile import StarError
if not filelike.... | [
"def",
"parse_stdout",
"(",
"self",
",",
"filelike",
")",
":",
"from",
"CifFile",
"import",
"StarError",
"if",
"not",
"filelike",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
":",
"return",
"self",
".",
"exit_codes",
".",
"ERROR_EMPTY_OUTPUT_FILE",
"try"... | 34.238095 | 20.52381 |
def compute_pool(instance1, attribute1, relation1,
instance2, attribute2, relation2,
prefix1, prefix2, doinstance=True, doattribute=True, dorelation=True):
"""
compute all possible node mapping candidates and their weights (the triple matching number gain resulting from
map... | [
"def",
"compute_pool",
"(",
"instance1",
",",
"attribute1",
",",
"relation1",
",",
"instance2",
",",
"attribute2",
",",
"relation2",
",",
"prefix1",
",",
"prefix2",
",",
"doinstance",
"=",
"True",
",",
"doattribute",
"=",
"True",
",",
"dorelation",
"=",
"Tru... | 58.731481 | 26.157407 |
def add_javascripts(self, *js_files):
"""add javascripts files in HTML body"""
# create the script tag if don't exists
if self.main_soup.script is None:
script_tag = self.main_soup.new_tag('script')
self.main_soup.body.append(script_tag)
for js_file in js_files:
... | [
"def",
"add_javascripts",
"(",
"self",
",",
"*",
"js_files",
")",
":",
"# create the script tag if don't exists",
"if",
"self",
".",
"main_soup",
".",
"script",
"is",
"None",
":",
"script_tag",
"=",
"self",
".",
"main_soup",
".",
"new_tag",
"(",
"'script'",
")... | 42 | 12.444444 |
def get_task_subtask_positions_objs(client, task_id):
'''
Gets a list of the positions of a single task's subtasks
Each task should (will?) only have one positions object defining how its subtasks are laid out
'''
params = {
'task_id' : int(task_id)
}
response = client.a... | [
"def",
"get_task_subtask_positions_objs",
"(",
"client",
",",
"task_id",
")",
":",
"params",
"=",
"{",
"'task_id'",
":",
"int",
"(",
"task_id",
")",
"}",
"response",
"=",
"client",
".",
"authenticated_request",
"(",
"client",
".",
"api",
".",
"Endpoints",
".... | 37.454545 | 29.636364 |
def apply_mtlist_budget_obs(list_filename,gw_filename="mtlist_gw.dat",
sw_filename="mtlist_sw.dat",
start_datetime="1-1-1970"):
""" process an MT3D list file to extract mass budget entries.
Parameters
----------
list_filename : str
the mt3... | [
"def",
"apply_mtlist_budget_obs",
"(",
"list_filename",
",",
"gw_filename",
"=",
"\"mtlist_gw.dat\"",
",",
"sw_filename",
"=",
"\"mtlist_sw.dat\"",
",",
"start_datetime",
"=",
"\"1-1-1970\"",
")",
":",
"try",
":",
"import",
"flopy",
"except",
"Exception",
"as",
"e",... | 35.142857 | 21.55102 |
def maskedNanPercentile(maskedArray, percentiles, *args, **kwargs):
""" Calculates np.nanpercentile on the non-masked values
"""
#https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html#accessing-the-data
awm = ArrayWithMask.createFromMaskedArray(maskedArray)
maskIdx = awm.maskIndex()
... | [
"def",
"maskedNanPercentile",
"(",
"maskedArray",
",",
"percentiles",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html#accessing-the-data",
"awm",
"=",
"ArrayWithMask",
".",
"createFromMaskedArray",
"... | 36.45 | 25.5 |
def incoming_messages(self) -> t.List[t.Tuple[float, bytes]]:
"""Consume the receive buffer and return the messages.
If there are new messages added to the queue while this funciton is being
processed, they will not be returned. This ensures that this terminates in
a timely manner.
... | [
"def",
"incoming_messages",
"(",
"self",
")",
"->",
"t",
".",
"List",
"[",
"t",
".",
"Tuple",
"[",
"float",
",",
"bytes",
"]",
"]",
":",
"approximate_messages",
"=",
"self",
".",
"_receive_buffer",
".",
"qsize",
"(",
")",
"messages",
"=",
"[",
"]",
"... | 40.2 | 19.866667 |
def name(name, validator=None):
""" Set a name on a validator callable.
Useful for user-friendly reporting when using lambdas to populate the [`Invalid.expected`](#invalid) field:
```python
from good import Schema, name
Schema(lambda x: int(x))('a')
#-> Invalid: invalid literal for int(): exp... | [
"def",
"name",
"(",
"name",
",",
"validator",
"=",
"None",
")",
":",
"# Decorator mode",
"if",
"validator",
"is",
"None",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"f",
".",
"name",
"=",
"name",
"return",
"f",
"return",
"decorator",
"# Direct mode",
... | 27.44186 | 23.767442 |
def get_subject(self, identifier):
"""
Build a Subject XML block for a SAML 1.1
AuthenticationStatement or AttributeStatement.
"""
subject = etree.Element('Subject')
name = etree.SubElement(subject, 'NameIdentifier')
name.text = identifier
subject_confirma... | [
"def",
"get_subject",
"(",
"self",
",",
"identifier",
")",
":",
"subject",
"=",
"etree",
".",
"Element",
"(",
"'Subject'",
")",
"name",
"=",
"etree",
".",
"SubElement",
"(",
"subject",
",",
"'NameIdentifier'",
")",
"name",
".",
"text",
"=",
"identifier",
... | 42.666667 | 13.166667 |
def reissueOverLongJobs(self):
"""
Check each issued job - if it is running for longer than desirable
issue a kill instruction.
Wait for the job to die then we pass the job to processFinishedJob.
"""
maxJobDuration = self.config.maxJobDuration
jobsToKill = []
... | [
"def",
"reissueOverLongJobs",
"(",
"self",
")",
":",
"maxJobDuration",
"=",
"self",
".",
"config",
".",
"maxJobDuration",
"jobsToKill",
"=",
"[",
"]",
"if",
"maxJobDuration",
"<",
"10000000",
":",
"# We won't bother doing anything if rescue time > 16 weeks.",
"runningJo... | 56.473684 | 23.421053 |
def sql_string_literal(text: str) -> str:
"""
Transforms text into its ANSI SQL-quoted version, e.g. (in Python ``repr()``
format):
.. code-block:: none
"some string" -> "'some string'"
"Jack's dog" -> "'Jack''s dog'"
"""
# ANSI SQL: http://www.contrib.andrew.cmu.edu/~shad... | [
"def",
"sql_string_literal",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"# ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt",
"# <character string literal>",
"return",
"SQUOTE",
"+",
"text",
".",
"replace",
"(",
"SQUOTE",
",",
"DOUBLE_SQUOTE",
")",... | 32.615385 | 18 |
def euclidean_random_projection_split(data, indices, rng_state):
"""Given a set of ``indices`` for data points from ``data``, create
a random hyperplane to split the data, returning two arrays indices
that fall on either side of the hyperplane. This is the basis for a
random projection tree, which simpl... | [
"def",
"euclidean_random_projection_split",
"(",
"data",
",",
"indices",
",",
"rng_state",
")",
":",
"dim",
"=",
"data",
".",
"shape",
"[",
"1",
"]",
"# Select two random points, set the hyperplane between them",
"left_index",
"=",
"tau_rand_int",
"(",
"rng_state",
")... | 34.380435 | 21.228261 |
def _add_onchain_locksroot_to_channel_settled_state_changes(
raiden: RaidenService,
storage: SQLiteStorage,
) -> None:
""" Adds `our_onchain_locksroot` and `partner_onchain_locksroot` to
ContractReceiveChannelSettled. """
batch_size = 50
batch_query = storage.batch_query_state_changes(
... | [
"def",
"_add_onchain_locksroot_to_channel_settled_state_changes",
"(",
"raiden",
":",
"RaidenService",
",",
"storage",
":",
"SQLiteStorage",
",",
")",
"->",
"None",
":",
"batch_size",
"=",
"50",
"batch_query",
"=",
"storage",
".",
"batch_query_state_changes",
"(",
"ba... | 43.530303 | 24.515152 |
def pre_factor_kkt(Q, G, A):
""" Perform all one-time factorizations and cache relevant matrix products"""
nineq, nz, neq, _ = get_sizes(G, A)
# S = [ A Q^{-1} A^T A Q^{-1} G^T ]
# [ G Q^{-1} A^T G Q^{-1} G^T + D^{-1} ]
U_Q = torch.potrf(Q)
# partial cholesky of S m... | [
"def",
"pre_factor_kkt",
"(",
"Q",
",",
"G",
",",
"A",
")",
":",
"nineq",
",",
"nz",
",",
"neq",
",",
"_",
"=",
"get_sizes",
"(",
"G",
",",
"A",
")",
"# S = [ A Q^{-1} A^T A Q^{-1} G^T ]",
"# [ G Q^{-1} A^T G Q^{-1} G^T + D^{-1} ]",
"U_... | 34.342857 | 17.228571 |
def indicators_from_tag(self, indicator, tag_name, filters=None, params=None):
"""
Args:
indicator:
tag_name:
filters:
params:
Return:
"""
params = params or {}
for t in sel... | [
"def",
"indicators_from_tag",
"(",
"self",
",",
"indicator",
",",
"tag_name",
",",
"filters",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"params",
"or",
"{",
"}",
"for",
"t",
"in",
"self",
".",
"pivot_from_tag",
"(",
"indicator",
... | 26.4 | 21.466667 |
def create_issue(self, title, content, priority=None,
milestone=None, tags=None, assignee=None,
private=None):
"""
Create a new issue.
:param title: the title of the issue
:param content: the description of the issue
:param priority: the ... | [
"def",
"create_issue",
"(",
"self",
",",
"title",
",",
"content",
",",
"priority",
"=",
"None",
",",
"milestone",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"assignee",
"=",
"None",
",",
"private",
"=",
"None",
")",
":",
"request_url",
"=",
"\"{}new_i... | 36.939394 | 14.575758 |
def delete_ec2_role(self, role, mount_point='aws-ec2'):
"""DELETE /auth/<mount_point>/role/<role>
:param role:
:type role:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
return self._adapter.delete('/v1/auth/{0}/role/{1}'.format(mount... | [
"def",
"delete_ec2_role",
"(",
"self",
",",
"role",
",",
"mount_point",
"=",
"'aws-ec2'",
")",
":",
"return",
"self",
".",
"_adapter",
".",
"delete",
"(",
"'/v1/auth/{0}/role/{1}'",
".",
"format",
"(",
"mount_point",
",",
"role",
")",
")"
] | 29.454545 | 19.818182 |
def _parse(coord, _match=_regex.match):
"""Return match groups from single sheet coordinate.
>>> Coordinates._parse('A1')
('A', '1', None, None)
>>> Coordinates._parse('A'), Coordinates._parse('1')
((None, None, 'A', None), (None, None, None, '1'))
>>> Coordinates._par... | [
"def",
"_parse",
"(",
"coord",
",",
"_match",
"=",
"_regex",
".",
"match",
")",
":",
"try",
":",
"return",
"_match",
"(",
"coord",
")",
".",
"groups",
"(",
")",
"except",
"AttributeError",
":",
"raise",
"ValueError",
"(",
"coord",
")"
] | 29.5 | 14.555556 |
def loadSignalFromWav(inputSignalFile, calibrationRealWorldValue=None, calibrationSignalFile=None, start=None,
end=None) -> Signal:
""" reads a wav file into a Signal and scales the input so that the sample are expressed in real world values
(as defined by the calibration signal).
:par... | [
"def",
"loadSignalFromWav",
"(",
"inputSignalFile",
",",
"calibrationRealWorldValue",
"=",
"None",
",",
"calibrationSignalFile",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
"->",
"Signal",
":",
"inputSignal",
"=",
"readWav",
"(",
"inp... | 60.058824 | 25.117647 |
def all_label_values(self, label_list_ids=None):
"""
Return a set of all label-values occurring in this corpus.
Args:
label_list_ids (list): If not None, only labels from label-lists with an id contained in this list
are considered.
Return... | [
"def",
"all_label_values",
"(",
"self",
",",
"label_list_ids",
"=",
"None",
")",
":",
"values",
"=",
"set",
"(",
")",
"for",
"utterance",
"in",
"self",
".",
"utterances",
".",
"values",
"(",
")",
":",
"values",
"=",
"values",
".",
"union",
"(",
"uttera... | 33.411765 | 26 |
def check(self, **kwargs):
"""
In addition to parent class' checks, also ensure that MULTITENANT_STATICFILES_DIRS
is a tuple or a list.
"""
errors = super().check(**kwargs)
multitenant_staticfiles_dirs = settings.MULTITENANT_STATICFILES_DIRS
if not isinstance(mul... | [
"def",
"check",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"super",
"(",
")",
".",
"check",
"(",
"*",
"*",
"kwargs",
")",
"multitenant_staticfiles_dirs",
"=",
"settings",
".",
"MULTITENANT_STATICFILES_DIRS",
"if",
"not",
"isinstance",
"... | 35.588235 | 23.235294 |
def parameters_dict(self):
"""
Get the tool parameters as a simple dictionary
:return: The tool parameters
"""
d = {}
for k, v in self.__dict__.items():
if not k.startswith("_"):
d[k] = v
return d | [
"def",
"parameters_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"not",
"k",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"d",
"[",
"k",
"]",
"=",
"v",
... | 24.636364 | 13 |
def random_reseed(self, seed):
"""
Provide YubiHSM DRBG_CTR with a new seed.
@param seed: new seed -- must be exactly 32 bytes
@type seed: string
@returns: True on success
@rtype: bool
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random_Reseed}
"""
return p... | [
"def",
"random_reseed",
"(",
"self",
",",
"seed",
")",
":",
"return",
"pyhsm",
".",
"basic_cmd",
".",
"YHSM_Cmd_Random_Reseed",
"(",
"self",
".",
"stick",
",",
"seed",
")",
".",
"execute",
"(",
")"
] | 28.692308 | 19.461538 |
def getSampleTypes(self, active_only=True):
"""Return all sampletypes
"""
catalog = api.get_tool("bika_setup_catalog")
query = {
"portal_type": "SampleType",
# N.B. The `sortable_title` index sorts case sensitive. Since there
# is no sort key for ... | [
"def",
"getSampleTypes",
"(",
"self",
",",
"active_only",
"=",
"True",
")",
":",
"catalog",
"=",
"api",
".",
"get_tool",
"(",
"\"bika_setup_catalog\"",
")",
"query",
"=",
"{",
"\"portal_type\"",
":",
"\"SampleType\"",
",",
"# N.B. The `sortable_title` index sorts ca... | 39.888889 | 13.666667 |
def properties_changed(self, sender, changed_properties, invalidated_properties):
"""
Called when a device property has changed or got invalidated.
"""
if 'Connected' in changed_properties:
if changed_properties['Connected']:
self.connect_succeeded()
... | [
"def",
"properties_changed",
"(",
"self",
",",
"sender",
",",
"changed_properties",
",",
"invalidated_properties",
")",
":",
"if",
"'Connected'",
"in",
"changed_properties",
":",
"if",
"changed_properties",
"[",
"'Connected'",
"]",
":",
"self",
".",
"connect_succeed... | 41.461538 | 17 |
def create_quote(self, blogname, **kwargs):
"""
Create a quote post on a blog
:param blogname: a string, the url of the blog you want to post to.
:param state: a string, The state of the post.
:param tags: a list of tags that you want applied to the post
:param tweet: a ... | [
"def",
"create_quote",
"(",
"self",
",",
"blogname",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"type\"",
":",
"\"quote\"",
"}",
")",
"return",
"self",
".",
"_send_post",
"(",
"blogname",
",",
"kwargs",
")"
] | 47.444444 | 19.888889 |
def three_d_effect(img, **kwargs):
"""Create 3D effect using convolution"""
w = kwargs.get('weight', 1)
LOG.debug("Applying 3D effect with weight %.2f", w)
kernel = np.array([[-w, 0, w],
[-w, 1, w],
[-w, 0, w]])
mode = kwargs.get('convolve_mode', 'same')... | [
"def",
"three_d_effect",
"(",
"img",
",",
"*",
"*",
"kwargs",
")",
":",
"w",
"=",
"kwargs",
".",
"get",
"(",
"'weight'",
",",
"1",
")",
"LOG",
".",
"debug",
"(",
"\"Applying 3D effect with weight %.2f\"",
",",
"w",
")",
"kernel",
"=",
"np",
".",
"array... | 38.529412 | 20.882353 |
def _tool_to_dict(tool):
"""Parse a tool definition into a cwl2wdl style dictionary.
"""
out = {"name": _id_to_name(tool.tool["id"]),
"baseCommand": " ".join(tool.tool["baseCommand"]),
"arguments": [],
"inputs": [_input_to_dict(i) for i in tool.tool["inputs"]],
"o... | [
"def",
"_tool_to_dict",
"(",
"tool",
")",
":",
"out",
"=",
"{",
"\"name\"",
":",
"_id_to_name",
"(",
"tool",
".",
"tool",
"[",
"\"id\"",
"]",
")",
",",
"\"baseCommand\"",
":",
"\" \"",
".",
"join",
"(",
"tool",
".",
"tool",
"[",
"\"baseCommand\"",
"]",... | 46.272727 | 17.181818 |
def deprecated(func):
"""
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted
when the function is used.
:param func: The function to run
:return: function
"""
def deprecation_warning(*args, **kwargs):
warnings.warn('Call ... | [
"def",
"deprecated",
"(",
"func",
")",
":",
"def",
"deprecation_warning",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"'Call to deprecated function {name}. Please consult our documentation at '",
"'http://pyapi-gitlab.readthedocs.io/... | 44.411765 | 20.764706 |
def delete(self, client=None):
"""API call: delete a metric via a DELETE request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/delete
:type client: :class:`~google.cloud.logging.client.Client` or
``NoneType``
:param clien... | [
"def",
"delete",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"client",
".",
"metrics_api",
".",
"metric_delete",
"(",
"self",
".",
"project",
",",
"self",
".",
"name",
")"
] | 42.384615 | 22.461538 |
def on_balance_volume(close_data, volume):
"""
On Balance Volume.
Formula:
start = 1
if CLOSEt > CLOSEt-1
obv = obvt-1 + volumet
elif CLOSEt < CLOSEt-1
obv = obvt-1 - volumet
elif CLOSEt == CLOSTt-1
obv = obvt-1
"""
catch_errors.check_for_input_len_diff(close... | [
"def",
"on_balance_volume",
"(",
"close_data",
",",
"volume",
")",
":",
"catch_errors",
".",
"check_for_input_len_diff",
"(",
"close_data",
",",
"volume",
")",
"obv",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"volume",
")",
")",
"obv",
"[",
"0",
"]",
"="... | 28.625 | 13.875 |
def make_next_param(login_url, current_url):
'''
Reduces the scheme and host from a given URL so it can be passed to
the given `login` URL more efficiently.
:param login_url: The login URL being redirected to.
:type login_url: str
:param current_url: The URL to reduce.
:type current_url: st... | [
"def",
"make_next_param",
"(",
"login_url",
",",
"current_url",
")",
":",
"l",
"=",
"urlparse",
"(",
"login_url",
")",
"c",
"=",
"urlparse",
"(",
"current_url",
")",
"if",
"(",
"not",
"l",
".",
"scheme",
"or",
"l",
".",
"scheme",
"==",
"c",
".",
"sch... | 33.294118 | 18.941176 |
def to_native(self, value, context=None):
""" Schematics deserializer override
We return a phoenumbers.PhoneNumber object so any kind
of formatting can be trivially performed. Additionally,
some convenient properties have been added:
e164: string formatted '+11234567890'
... | [
"def",
"to_native",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"pn",
".",
"phonenumber",
".",
"PhoneNumber",
")",
":",
"return",
"value",
"try",
":",
"phone",
"=",
"pn",
".",
"parse",
"(",... | 34.354839 | 21.032258 |
def exponential_sleep_generator(initial, maximum, multiplier=_DEFAULT_DELAY_MULTIPLIER):
"""Generates sleep intervals based on the exponential back-off algorithm.
This implements the `Truncated Exponential Back-off`_ algorithm.
.. _Truncated Exponential Back-off:
https://cloud.google.com/storage/d... | [
"def",
"exponential_sleep_generator",
"(",
"initial",
",",
"maximum",
",",
"multiplier",
"=",
"_DEFAULT_DELAY_MULTIPLIER",
")",
":",
"delay",
"=",
"initial",
"while",
"True",
":",
"# Introduce jitter by yielding a delay that is uniformly distributed",
"# to average out to the d... | 38.130435 | 22.565217 |
def patch_ligotimegps(module="ligo.lw.lsctables"):
"""Context manager to on-the-fly patch LIGOTimeGPS to accept all int types
"""
module = import_module(module)
orig = module.LIGOTimeGPS
module.LIGOTimeGPS = _ligotimegps
try:
yield
finally:
module.LIGOTimeGPS = orig | [
"def",
"patch_ligotimegps",
"(",
"module",
"=",
"\"ligo.lw.lsctables\"",
")",
":",
"module",
"=",
"import_module",
"(",
"module",
")",
"orig",
"=",
"module",
".",
"LIGOTimeGPS",
"module",
".",
"LIGOTimeGPS",
"=",
"_ligotimegps",
"try",
":",
"yield",
"finally",
... | 30.1 | 12.4 |
def ipv4(self, network=False, address_class=None, private=None):
"""
Produce a random IPv4 address or network with a valid CIDR.
:param network: Network address
:param address_class: IPv4 address class (a, b, or c)
:param private: Public or private
:returns: IPv4
... | [
"def",
"ipv4",
"(",
"self",
",",
"network",
"=",
"False",
",",
"address_class",
"=",
"None",
",",
"private",
"=",
"None",
")",
":",
"if",
"private",
"is",
"True",
":",
"return",
"self",
".",
"ipv4_private",
"(",
"address_class",
"=",
"address_class",
","... | 38.441176 | 19.911765 |
def calculate_acf(data, delta_t=1.0, unbiased=False):
r"""Calculates the one-sided autocorrelation function.
Calculates the autocorrelation function (ACF) and returns the one-sided
ACF. The ACF is defined as the autocovariance divided by the variance. The
ACF can be estimated using
.. math::
... | [
"def",
"calculate_acf",
"(",
"data",
",",
"delta_t",
"=",
"1.0",
",",
"unbiased",
"=",
"False",
")",
":",
"# if given a TimeSeries instance then get numpy.array",
"if",
"isinstance",
"(",
"data",
",",
"TimeSeries",
")",
":",
"y",
"=",
"data",
".",
"numpy",
"("... | 31.6 | 24.653333 |
def process_tree(top, name='top'):
"""Creates a string representation of the process tree for process top.
This method uses the :func:`walk_processes` method to create the process tree.
:param top: top process for which process tree string should be
created
:typ... | [
"def",
"process_tree",
"(",
"top",
",",
"name",
"=",
"'top'",
")",
":",
"str1",
"=",
"''",
"for",
"name",
",",
"proc",
",",
"level",
"in",
"walk_processes",
"(",
"top",
",",
"name",
",",
"ignoreFlag",
"=",
"True",
")",
":",
"indent",
"=",
"' '",
"*... | 40.236842 | 25.078947 |
def load(self, items):
"""
Populate this section from an iteration of the parse_items call
"""
for k, vals in items:
self[k] = "".join(vals) | [
"def",
"load",
"(",
"self",
",",
"items",
")",
":",
"for",
"k",
",",
"vals",
"in",
"items",
":",
"self",
"[",
"k",
"]",
"=",
"\"\"",
".",
"join",
"(",
"vals",
")"
] | 25.571429 | 15 |
def int2str(num, radix=10, alphabet=BASE85):
"""helper function for quick base conversions from integers to strings"""
return NumConv(radix, alphabet).int2str(num) | [
"def",
"int2str",
"(",
"num",
",",
"radix",
"=",
"10",
",",
"alphabet",
"=",
"BASE85",
")",
":",
"return",
"NumConv",
"(",
"radix",
",",
"alphabet",
")",
".",
"int2str",
"(",
"num",
")"
] | 56.333333 | 4 |
def no_llvm(*args, uid=0, gid=0, **kwargs):
"""
Return a customizable uchroot command.
The command will be executed inside a uchroot environment.
Args:
args: List of additional arguments for uchroot (typical: mounts)
Return:
chroot_cmd
"""
uchroot_cmd = no_args()
uchroo... | [
"def",
"no_llvm",
"(",
"*",
"args",
",",
"uid",
"=",
"0",
",",
"gid",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"uchroot_cmd",
"=",
"no_args",
"(",
")",
"uchroot_cmd",
"=",
"uchroot_cmd",
"[",
"__default_opts__",
"(",
"uid",
",",
"gid",
")",
"]"... | 27.357143 | 18.785714 |
def dot_alignment(sequences, seq_field=None, name_field=None, root=None, root_name=None,
cluster_threshold=0.75, as_fasta=False, just_alignment=False):
'''
Creates a dot alignment (dots indicate identity, mismatches are represented by the mismatched
residue) for a list of sequences.
Args:
... | [
"def",
"dot_alignment",
"(",
"sequences",
",",
"seq_field",
"=",
"None",
",",
"name_field",
"=",
"None",
",",
"root",
"=",
"None",
",",
"root_name",
"=",
"None",
",",
"cluster_threshold",
"=",
"0.75",
",",
"as_fasta",
"=",
"False",
",",
"just_alignment",
"... | 43.530303 | 27.742424 |
def write_docstring_for_shortcut(self):
"""Write docstring to editor by shortcut of code editor."""
# cursor placed below function definition
result = self.get_function_definition_from_below_last_line()
if result is not None:
__, number_of_lines_of_function = result
... | [
"def",
"write_docstring_for_shortcut",
"(",
"self",
")",
":",
"# cursor placed below function definition\r",
"result",
"=",
"self",
".",
"get_function_definition_from_below_last_line",
"(",
")",
"if",
"result",
"is",
"not",
"None",
":",
"__",
",",
"number_of_lines_of_func... | 43.6875 | 17.6875 |
def indicator(self):
"""Produce the spinner."""
while self.run:
try:
size = self.work_q.qsize()
except Exception:
note = 'Please wait '
else:
note = 'Number of Jobs in Queue = %s ' % size
if self.msg:
... | [
"def",
"indicator",
"(",
"self",
")",
":",
"while",
"self",
".",
"run",
":",
"try",
":",
"size",
"=",
"self",
".",
"work_q",
".",
"qsize",
"(",
")",
"except",
"Exception",
":",
"note",
"=",
"'Please wait '",
"else",
":",
"note",
"=",
"'Number of Jobs i... | 30.263158 | 17.421053 |
def get_task(
self,
taskName):
"""*recursively scan this taskpaper object to find a descendant task by name*
**Key Arguments:**
- ``taskName`` -- the name, or title, of the task you want to return
**Return:**
- ``task`` -- the taskpaper task obje... | [
"def",
"get_task",
"(",
"self",
",",
"taskName",
")",
":",
"if",
"taskName",
"[",
":",
"2",
"]",
"!=",
"\"- \"",
":",
"taskName",
"=",
"\"- \"",
"+",
"taskName",
"task",
"=",
"None",
"try",
":",
"self",
".",
"refresh",
"except",
":",
"pass",
"# SEARC... | 25.87234 | 21.659574 |
def dispatch(self, key):
""" Get a seq of Commandchain objects that match key """
if key in self.strs:
yield self.strs[key]
for r, obj in self.regexs.items():
if re.match(r, key):
yield obj
else:
#print "nomatch",key # dbg
... | [
"def",
"dispatch",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"strs",
":",
"yield",
"self",
".",
"strs",
"[",
"key",
"]",
"for",
"r",
",",
"obj",
"in",
"self",
".",
"regexs",
".",
"items",
"(",
")",
":",
"if",
"re",
".... | 29.727273 | 13.363636 |
def change_mime(self, bucket, key, mime):
"""修改文件mimeType:
主动修改指定资源的文件类型,具体规格参考:
http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html
Args:
bucket: 待操作资源所在空间
key: 待操作资源文件名
mime: 待操作文件目标mimeType
"""
resource = entry(bucke... | [
"def",
"change_mime",
"(",
"self",
",",
"bucket",
",",
"key",
",",
"mime",
")",
":",
"resource",
"=",
"entry",
"(",
"bucket",
",",
"key",
")",
"encode_mime",
"=",
"urlsafe_base64_encode",
"(",
"mime",
")",
"return",
"self",
".",
"__rs_do",
"(",
"'chgm'",... | 31.571429 | 16.071429 |
def custom_auth(principal, credentials, realm, scheme, **parameters):
""" Generate a basic auth token for a given user and password.
:param principal: specifies who is being authenticated
:param credentials: authenticates the principal
:param realm: specifies the authentication provider
:param sche... | [
"def",
"custom_auth",
"(",
"principal",
",",
"credentials",
",",
"realm",
",",
"scheme",
",",
"*",
"*",
"parameters",
")",
":",
"from",
"neobolt",
".",
"security",
"import",
"AuthToken",
"return",
"AuthToken",
"(",
"scheme",
",",
"principal",
",",
"credentia... | 51.5 | 18.75 |
def ReadClientStartupInfo(self, client_id, cursor=None):
"""Reads the latest client startup record for a single client."""
query = (
"SELECT startup_info, UNIX_TIMESTAMP(timestamp) "
"FROM clients, client_startup_history "
"WHERE clients.last_startup_timestamp=client_startup_history.time... | [
"def",
"ReadClientStartupInfo",
"(",
"self",
",",
"client_id",
",",
"cursor",
"=",
"None",
")",
":",
"query",
"=",
"(",
"\"SELECT startup_info, UNIX_TIMESTAMP(timestamp) \"",
"\"FROM clients, client_startup_history \"",
"\"WHERE clients.last_startup_timestamp=client_startup_history... | 42.705882 | 20.058824 |
def get_docstring(filename, verbose=False):
"""
Search for assignment of the DOCUMENTATION variable in the given file.
Parse that from YAML and return the YAML doc or None.
"""
doc = None
try:
# Thank you, Habbie, for this bit of code :-)
M = ast.parse(''.join(open(filename)))
... | [
"def",
"get_docstring",
"(",
"filename",
",",
"verbose",
"=",
"False",
")",
":",
"doc",
"=",
"None",
"try",
":",
"# Thank you, Habbie, for this bit of code :-)",
"M",
"=",
"ast",
".",
"parse",
"(",
"''",
".",
"join",
"(",
"open",
"(",
"filename",
")",
")",... | 31.7 | 17.5 |
def as_iterable(value, wrap_maps=True, wrap_sets=False, itertype=tuple):
"""Wraps a single non-iterable value with a tuple (or other iterable type,
if ``itertype`` is provided.)
>>> as_iterable("abc")
("abc",)
>>> as_iterable(("abc",))
("abc",)
Equivalent to::
... | [
"def",
"as_iterable",
"(",
"value",
",",
"wrap_maps",
"=",
"True",
",",
"wrap_sets",
"=",
"False",
",",
"itertype",
"=",
"tuple",
")",
":",
"if",
"is_iterable",
"(",
"value",
",",
"not",
"wrap_maps",
",",
"not",
"wrap_sets",
")",
":",
"return",
"value",
... | 27.571429 | 19.190476 |
def _set_closed(self, future):
"""
Indicate that the instance is effectively closed.
:param future: The close future.
"""
logger.debug("%s[%s] closed.", self.__class__.__name__, id(self))
self.on_closed.emit(self)
self._closed_future.set_result(future.result()) | [
"def",
"_set_closed",
"(",
"self",
",",
"future",
")",
":",
"logger",
".",
"debug",
"(",
"\"%s[%s] closed.\"",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"id",
"(",
"self",
")",
")",
"self",
".",
"on_closed",
".",
"emit",
"(",
"self",
")",
... | 34.444444 | 13.555556 |
def _add_to_schema(self, field_name, schema):
"""Set the ``attribute`` attr to the field in question so this always
gets deserialzed into the field name without ``_id``.
Args:
field_name (str): The name of the field (the attribute name being
set in the schema).
... | [
"def",
"_add_to_schema",
"(",
"self",
",",
"field_name",
",",
"schema",
")",
":",
"super",
"(",
"ForeignKeyField",
",",
"self",
")",
".",
"_add_to_schema",
"(",
"field_name",
",",
"schema",
")",
"if",
"self",
".",
"get_field_value",
"(",
"'convert_fks'",
","... | 43.642857 | 21.071429 |
def run(self, incremental=None, run_id=None):
"""Queue the execution of a particular crawler."""
state = {
'crawler': self.name,
'run_id': run_id,
'incremental': settings.INCREMENTAL
}
if incremental is not None:
state['incremental'] = incr... | [
"def",
"run",
"(",
"self",
",",
"incremental",
"=",
"None",
",",
"run_id",
"=",
"None",
")",
":",
"state",
"=",
"{",
"'crawler'",
":",
"self",
".",
"name",
",",
"'run_id'",
":",
"run_id",
",",
"'incremental'",
":",
"settings",
".",
"INCREMENTAL",
"}",
... | 32 | 12.533333 |
def default_vsan_policy_configured(name, policy):
'''
Configures the default VSAN policy on a vCenter.
The state assumes there is only one default VSAN policy on a vCenter.
policy
Dict representation of a policy
'''
# TODO Refactor when recurse_differ supports list_differ
# It's goi... | [
"def",
"default_vsan_policy_configured",
"(",
"name",
",",
"policy",
")",
":",
"# TODO Refactor when recurse_differ supports list_differ",
"# It's going to make the whole thing much easier",
"policy_copy",
"=",
"copy",
".",
"deepcopy",
"(",
"policy",
")",
"proxy_type",
"=",
"... | 45.471014 | 17.688406 |
def _open_ftp(self):
# type: () -> FTP
"""Open an ftp object for the file."""
ftp = self.fs._open_ftp()
ftp.voidcmd(str("TYPE I"))
return ftp | [
"def",
"_open_ftp",
"(",
"self",
")",
":",
"# type: () -> FTP",
"ftp",
"=",
"self",
".",
"fs",
".",
"_open_ftp",
"(",
")",
"ftp",
".",
"voidcmd",
"(",
"str",
"(",
"\"TYPE I\"",
")",
")",
"return",
"ftp"
] | 29.333333 | 11.666667 |
def construct_zernike_polynomials(x, y, zernike_indexes, mask=None, weight=None):
"""Return the zerike polynomials for all objects in an image
x - the X distance of a point from the center of its object
y - the Y distance of a point from the center of its object
zernike_indexes - an Nx2 array of th... | [
"def",
"construct_zernike_polynomials",
"(",
"x",
",",
"y",
",",
"zernike_indexes",
",",
"mask",
"=",
"None",
",",
"weight",
"=",
"None",
")",
":",
"if",
"x",
".",
"shape",
"!=",
"y",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"\"X and Y must have the ... | 37.892308 | 19.384615 |
def connect_post_namespaced_pod_exec(self, name, namespace, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_exec # noqa: E501
connect POST requests to exec of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please... | [
"def",
"connect_post_namespaced_pod_exec",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"... | 64.535714 | 36.892857 |
def find_first_number(ll):
""" Returns nr of first entry parseable to float in ll, None otherwise"""
for nr, entry in enumerate(ll):
try:
float(entry)
except (ValueError, TypeError) as e:
pass
else:
return nr
return None | [
"def",
"find_first_number",
"(",
"ll",
")",
":",
"for",
"nr",
",",
"entry",
"in",
"enumerate",
"(",
"ll",
")",
":",
"try",
":",
"float",
"(",
"entry",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
"as",
"e",
":",
"pass",
"else",
":",
"re... | 28.3 | 16.2 |
async def create_stream_player(self, url, opts=ydl_opts):
"""Creates a streamer that plays from a URL"""
self.current_download_elapsed = 0
self.streamer = await self.vclient.create_ytdl_player(url, ytdl_options=opts, after=self.vafter_ts)
self.state = "ready"
await self.setup_s... | [
"async",
"def",
"create_stream_player",
"(",
"self",
",",
"url",
",",
"opts",
"=",
"ydl_opts",
")",
":",
"self",
".",
"current_download_elapsed",
"=",
"0",
"self",
".",
"streamer",
"=",
"await",
"self",
".",
"vclient",
".",
"create_ytdl_player",
"(",
"url",
... | 43.1 | 26.1 |
def build_status(namespace, name, branch='master') -> pin:
'''Returns the current status of the build'''
return ci_data(namespace, name, branch).get('build_success', None) | [
"def",
"build_status",
"(",
"namespace",
",",
"name",
",",
"branch",
"=",
"'master'",
")",
"->",
"pin",
":",
"return",
"ci_data",
"(",
"namespace",
",",
"name",
",",
"branch",
")",
".",
"get",
"(",
"'build_success'",
",",
"None",
")"
] | 59 | 19 |
def step_interpolation(x, xp, fp, **kwargs):
"""Multi-dimensional step interpolation.
Returns the multi-dimensional step interpolant to a function with
given discrete data points (xp, fp), evaluated at x.
Note that *N and *M indicate zero or more dimensions.
Args:
x: An array of shape [*N], the x-coord... | [
"def",
"step_interpolation",
"(",
"x",
",",
"xp",
",",
"fp",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"kwargs",
"# Unused.",
"xp",
"=",
"np",
".",
"expand_dims",
"(",
"xp",
",",
"-",
"1",
")",
"lower",
",",
"upper",
"=",
"xp",
"[",
":",
"-",
"... | 37.689655 | 20.965517 |
def antiscia(self):
""" Returns antiscia object. """
obj = self.copy()
obj.type = const.OBJ_GENERIC
obj.relocate(360 - obj.lon + 180)
return obj | [
"def",
"antiscia",
"(",
"self",
")",
":",
"obj",
"=",
"self",
".",
"copy",
"(",
")",
"obj",
".",
"type",
"=",
"const",
".",
"OBJ_GENERIC",
"obj",
".",
"relocate",
"(",
"360",
"-",
"obj",
".",
"lon",
"+",
"180",
")",
"return",
"obj"
] | 29.833333 | 10.5 |
def _synthesize(self):
"""
Assigns all placeholder labels to actual values and implicitly declares the ``ro``
register for backwards compatibility.
Changed in 1.9: Either all qubits must be defined or all undefined. If qubits are
undefined, this method will not help you. You mus... | [
"def",
"_synthesize",
"(",
"self",
")",
":",
"self",
".",
"_synthesized_instructions",
"=",
"instantiate_labels",
"(",
"self",
".",
"_instructions",
")",
"self",
".",
"_synthesized_instructions",
"=",
"implicitly_declare_ro",
"(",
"self",
".",
"_synthesized_instructio... | 47.190476 | 29.285714 |
def check_arg_compatibility(args: argparse.Namespace):
"""
Check if some arguments are incompatible with each other.
:param args: Arguments as returned by argparse.
"""
if args.lhuc is not None:
# Actually this check is a bit too strict
check_condition(args.encoder != C.CONVOLUTION... | [
"def",
"check_arg_compatibility",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
":",
"if",
"args",
".",
"lhuc",
"is",
"not",
"None",
":",
"# Actually this check is a bit too strict",
"check_condition",
"(",
"args",
".",
"encoder",
"!=",
"C",
".",
"CONVOLU... | 48.588235 | 29.647059 |
def _handle_offset_response(self, response):
"""
Handle responses to both OffsetRequest and OffsetFetchRequest, since
they are similar enough.
:param response:
A tuple of a single OffsetFetchResponse or OffsetResponse
"""
# Got a response, clear our outstandi... | [
"def",
"_handle_offset_response",
"(",
"self",
",",
"response",
")",
":",
"# Got a response, clear our outstanding request deferred",
"self",
".",
"_request_d",
"=",
"None",
"# Successful request, reset our retry delay, count, etc",
"self",
".",
"retry_delay",
"=",
"self",
".... | 39.172414 | 17.241379 |
def command_getkeys(self, command, *args, encoding='utf-8'):
"""Extract keys given a full Redis command."""
return self.execute(b'COMMAND', b'GETKEYS', command, *args,
encoding=encoding) | [
"def",
"command_getkeys",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"return",
"self",
".",
"execute",
"(",
"b'COMMAND'",
",",
"b'GETKEYS'",
",",
"command",
",",
"*",
"args",
",",
"encoding",
"=",
"encoding"... | 56.75 | 13.25 |
def get_object(self, cat, **kwargs):
"""
This method is used for retrieving objects from facebook. "cat", the category, must be
passed. When cat is "single", pass the "id "and desired "fields" of the single object. If the
cat is "multiple", only pass the... | [
"def",
"get_object",
"(",
"self",
",",
"cat",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'id'",
"not",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"kwargs",
"[",
"'id'",
"]",
"=",
"''",
"res",
"=",
"request",
".",
"get_object_cat1",
"(",
"self",
"... | 56 | 23.8 |
def evaluate(self, test_file, save_dir=None, logger=None, num_buckets_test=10, test_batch_size=5000):
"""Run evaluation on test set
Parameters
----------
test_file : str
path to test set
save_dir : str
where to store intermediate results and log
l... | [
"def",
"evaluate",
"(",
"self",
",",
"test_file",
",",
"save_dir",
"=",
"None",
",",
"logger",
"=",
"None",
",",
"num_buckets_test",
"=",
"10",
",",
"test_batch_size",
"=",
"5000",
")",
":",
"parser",
"=",
"self",
".",
"_parser",
"vocab",
"=",
"self",
... | 35.064516 | 21.903226 |
def _add_edge(self, idx, from_idx, from_lvec, to_idx, to_lvec):
"""
Add information about an edge linking two critical points.
This actually describes two edges:
from_idx ------ idx ------ to_idx
However, in practice, from_idx and to_idx will typically be
atom nuclei, ... | [
"def",
"_add_edge",
"(",
"self",
",",
"idx",
",",
"from_idx",
",",
"from_lvec",
",",
"to_idx",
",",
"to_lvec",
")",
":",
"self",
".",
"edges",
"[",
"idx",
"]",
"=",
"{",
"'from_idx'",
":",
"from_idx",
",",
"'from_lvec'",
":",
"from_lvec",
",",
"'to_idx... | 40.4 | 20.88 |
def to_pil_image(pic, mode=None):
"""Convert a tensor or an ndarray to PIL Image.
See :class:`~torchvision.transforms.ToPILImage` for more details.
Args:
pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
mode (`PIL.Image mode`_): color space and pixel depth of input data (... | [
"def",
"to_pil_image",
"(",
"pic",
",",
"mode",
"=",
"None",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"pic",
",",
"torch",
".",
"Tensor",
")",
"or",
"isinstance",
"(",
"pic",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"("... | 39.164706 | 23.611765 |
def ratio(self, ratio):
"""
The split ratio of the corporate action - i.e. the ratio of new shares to old shares
:param ratio: A tuple representing (original_count, new_count). For example (1, 2) is a doubling stock split.
(3, 1) is a 3:1 reverse stock split.
:return:
""... | [
"def",
"ratio",
"(",
"self",
",",
"ratio",
")",
":",
"if",
"isinstance",
"(",
"ratio",
",",
"tuple",
")",
":",
"self",
".",
"_ratio",
"=",
"ratio",
"else",
":",
"raise",
"TypeError",
"(",
"'Invalid ratio type: %s'",
"%",
"type",
"(",
"ratio",
")",
")"
... | 42 | 22 |
def create_stack(Name=None, Region=None, VpcId=None, Attributes=None, ServiceRoleArn=None, DefaultInstanceProfileArn=None, DefaultOs=None, HostnameTheme=None, DefaultAvailabilityZone=None, DefaultSubnetId=None, CustomJson=None, ConfigurationManager=None, ChefConfiguration=None, UseCustomCookbooks=None, UseOpsworksSecur... | [
"def",
"create_stack",
"(",
"Name",
"=",
"None",
",",
"Region",
"=",
"None",
",",
"VpcId",
"=",
"None",
",",
"Attributes",
"=",
"None",
",",
"ServiceRoleArn",
"=",
"None",
",",
"DefaultInstanceProfileArn",
"=",
"None",
",",
"DefaultOs",
"=",
"None",
",",
... | 71.147541 | 56.961749 |
def load_config(self, config=None):
''' loads a config file
Parameters:
config (str):
Optional name of manual config file to load
'''
# Read the config file
cfgname = (config or self.config_name)
cfgname = 'sdsswork' if cfgname is None else c... | [
"def",
"load_config",
"(",
"self",
",",
"config",
"=",
"None",
")",
":",
"# Read the config file",
"cfgname",
"=",
"(",
"config",
"or",
"self",
".",
"config_name",
")",
"cfgname",
"=",
"'sdsswork'",
"if",
"cfgname",
"is",
"None",
"else",
"cfgname",
"assert",... | 39.967742 | 24.032258 |
def nsmap(self):
"""
Returns the current namespace mapping as a dictionary
there are several problems with the map and we try to guess a few
things here:
1) a URI can be mapped by many prefixes, so it is to decide which one to take
2) a prefix might map to an empty stri... | [
"def",
"nsmap",
"(",
"self",
")",
":",
"NSMAP",
"=",
"dict",
"(",
")",
"# solve 3) by using a set",
"for",
"k",
",",
"v",
"in",
"set",
"(",
"self",
".",
"namespaces",
")",
":",
"s_prefix",
"=",
"self",
".",
"sb",
"[",
"k",
"]",
"s_uri",
"=",
"self"... | 33.416667 | 18.75 |
def on_menu_clear_interpretation(self, event):
'''
clear all current interpretations.
'''
# delete all previous interpretation
for sp in list(self.Data.keys()):
del self.Data[sp]['pars']
self.Data[sp]['pars'] = {}
self.Data[sp]['pars']['lab_d... | [
"def",
"on_menu_clear_interpretation",
"(",
"self",
",",
"event",
")",
":",
"# delete all previous interpretation",
"for",
"sp",
"in",
"list",
"(",
"self",
".",
"Data",
".",
"keys",
"(",
")",
")",
":",
"del",
"self",
".",
"Data",
"[",
"sp",
"]",
"[",
"'... | 39.444444 | 17.111111 |
def compare(self, statement_a, statement_b):
"""
Compare the two input statements.
:return: The percent of similarity between the closest synset distance.
:rtype: float
"""
document_a = self.nlp(statement_a.text)
document_b = self.nlp(statement_b.text)
r... | [
"def",
"compare",
"(",
"self",
",",
"statement_a",
",",
"statement_b",
")",
":",
"document_a",
"=",
"self",
".",
"nlp",
"(",
"statement_a",
".",
"text",
")",
"document_b",
"=",
"self",
".",
"nlp",
"(",
"statement_b",
".",
"text",
")",
"return",
"document... | 31.727273 | 15 |
def _get_attributes(schema, location):
"""Return the schema's children, filtered by location."""
schema = DottedNameResolver(__name__).maybe_resolve(schema)
def _filter(attr):
if not hasattr(attr, "location"):
valid_location = 'body' in location
else:
... | [
"def",
"_get_attributes",
"(",
"schema",
",",
"location",
")",
":",
"schema",
"=",
"DottedNameResolver",
"(",
"__name__",
")",
".",
"maybe_resolve",
"(",
"schema",
")",
"def",
"_filter",
"(",
"attr",
")",
":",
"if",
"not",
"hasattr",
"(",
"attr",
",",
"\... | 38.666667 | 17.583333 |
def create_transaction(self, outputs, fee=None, leftover=None, combine=True,
message=None, unspents=None, custom_pushdata=False): # pragma: no cover
"""Creates a signed P2PKH transaction.
:param outputs: A sequence of outputs you wish to send in the form
... | [
"def",
"create_transaction",
"(",
"self",
",",
"outputs",
",",
"fee",
"=",
"None",
",",
"leftover",
"=",
"None",
",",
"combine",
"=",
"True",
",",
"message",
"=",
"None",
",",
"unspents",
"=",
"None",
",",
"custom_pushdata",
"=",
"False",
")",
":",
"# ... | 52.586957 | 25.304348 |
def gene_tree(
self,
scale_to=None,
population_size=1,
trim_names=True,
):
""" Using the current tree object as a species tree, generate a gene
tree using the constrained Kingman coalescent process from dendropy. The
species tree should probabl... | [
"def",
"gene_tree",
"(",
"self",
",",
"scale_to",
"=",
"None",
",",
"population_size",
"=",
"1",
",",
"trim_names",
"=",
"True",
",",
")",
":",
"tree",
"=",
"self",
".",
"template",
"or",
"self",
".",
"yule",
"(",
")",
"for",
"leaf",
"in",
"tree",
... | 41.317073 | 25.658537 |
def expand(matrix, power):
"""
Apply cluster expansion to the given matrix by raising
the matrix to the given power.
:param matrix: The matrix to be expanded
:param power: Cluster expansion parameter
:returns: The expanded matrix
"""
if isspmatrix(matrix):
return matrix ** p... | [
"def",
"expand",
"(",
"matrix",
",",
"power",
")",
":",
"if",
"isspmatrix",
"(",
"matrix",
")",
":",
"return",
"matrix",
"**",
"power",
"return",
"np",
".",
"linalg",
".",
"matrix_power",
"(",
"matrix",
",",
"power",
")"
] | 27.846154 | 12.461538 |
def forwards(self, orm):
"Write your forwards methods here."
# Project labels
names = list(orm['samples.Project'].objects.values_list('label', flat=True))
orm['samples.Cohort'].objects.filter(name__in=names).update(published=True)
# World cohort
orm['samples.Cohort'].obj... | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"# Project labels",
"names",
"=",
"list",
"(",
"orm",
"[",
"'samples.Project'",
"]",
".",
"objects",
".",
"values_list",
"(",
"'label'",
",",
"flat",
"=",
"True",
")",
")",
"orm",
"[",
"'samples.Cohor... | 46.625 | 29.125 |
def version_option(f):
"""
Largely a custom clone of click.version_option -- almost identical, but
prints our special output.
"""
def callback(ctx, param, value):
# copied from click.decorators.version_option
# no idea what resilient_parsing means, but...
if not value or ctx... | [
"def",
"version_option",
"(",
"f",
")",
":",
"def",
"callback",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"# copied from click.decorators.version_option",
"# no idea what resilient_parsing means, but...",
"if",
"not",
"value",
"or",
"ctx",
".",
"resilient_pars... | 24.478261 | 18.565217 |
def _on_wid_changed(self, wid):
"""Called when the widget is changed"""
if self._itsme: return
self.update_model(self._get_idx_from_widget(wid))
return | [
"def",
"_on_wid_changed",
"(",
"self",
",",
"wid",
")",
":",
"if",
"self",
".",
"_itsme",
":",
"return",
"self",
".",
"update_model",
"(",
"self",
".",
"_get_idx_from_widget",
"(",
"wid",
")",
")",
"return"
] | 35.8 | 12.4 |
def read_code(self, name):
"""Reads code from a python file called 'name'"""
file_path = self.gen_file_path(name)
with open(file_path) as f:
code = f.read()
return code | [
"def",
"read_code",
"(",
"self",
",",
"name",
")",
":",
"file_path",
"=",
"self",
".",
"gen_file_path",
"(",
"name",
")",
"with",
"open",
"(",
"file_path",
")",
"as",
"f",
":",
"code",
"=",
"f",
".",
"read",
"(",
")",
"return",
"code"
] | 29.571429 | 14 |
def delete_row(self, index):
"""
Deletes a Row by it's index
:param int index: the index of the row. zero indexed
:return bool: Success or Failure
"""
url = self.build_url(self._endpoints.get('delete_row').format(id=index))
return bool(self.session.post(url)) | [
"def",
"delete_row",
"(",
"self",
",",
"index",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'delete_row'",
")",
".",
"format",
"(",
"id",
"=",
"index",
")",
")",
"return",
"bool",
"(",
"self",
"... | 38.5 | 10 |
def getAssociation(self, server_url, handle=None):
"""Retrieve an association. If no handle is specified, return
the association with the latest expiration.
(str, str or NoneType) -> Association or NoneType
"""
if handle is None:
handle = ''
# The filename w... | [
"def",
"getAssociation",
"(",
"self",
",",
"server_url",
",",
"handle",
"=",
"None",
")",
":",
"if",
"handle",
"is",
"None",
":",
"handle",
"=",
"''",
"# The filename with the empty handle is a prefix of all other",
"# associations for the given server URL.",
"filename",
... | 38.512195 | 17.195122 |
def format_name(format, name, target_type, prop_set):
""" Given a target, as given to a custom tag rule, returns a string formatted
according to the passed format. Format is a list of properties that is
represented in the result. For each element of format the corresponding target
informatio... | [
"def",
"format_name",
"(",
"format",
",",
"name",
",",
"target_type",
",",
"prop_set",
")",
":",
"if",
"__debug__",
":",
"from",
".",
".",
"build",
".",
"property_set",
"import",
"PropertySet",
"assert",
"is_iterable_typed",
"(",
"format",
",",
"basestring",
... | 43.67033 | 18.373626 |
def _cost_func(x, kernel_options, tuning_options, runner, results, cache):
""" Cost function used by minimize """
error_time = 1e20
logging.debug('_cost_func called')
logging.debug('x: ' + str(x))
x_key = ",".join([str(i) for i in x])
if x_key in cache:
return cache[x_key]
#snap v... | [
"def",
"_cost_func",
"(",
"x",
",",
"kernel_options",
",",
"tuning_options",
",",
"runner",
",",
"results",
",",
"cache",
")",
":",
"error_time",
"=",
"1e20",
"logging",
".",
"debug",
"(",
"'_cost_func called'",
")",
"logging",
".",
"debug",
"(",
"'x: '",
... | 32.704545 | 21.75 |
def redraw(self, col=0):
"""redraw image, applying the following:
rotation, flips, log scale
max/min values from sliders or explicit intensity ranges
color map
interpolation
"""
conf = self.conf
# note: rotation re-calls display(), to reset the image
... | [
"def",
"redraw",
"(",
"self",
",",
"col",
"=",
"0",
")",
":",
"conf",
"=",
"self",
".",
"conf",
"# note: rotation re-calls display(), to reset the image",
"# other transformations will just do .set_data() on image",
"if",
"conf",
".",
"rot",
":",
"if",
"self",
".",
... | 38.479167 | 14.760417 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.