text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _info_long(self) -> Optional[str]:
"""Extract journey information."""
try:
return str(
html.unescape(self.journey.InfoTextList.InfoText.get("textL")).replace(
"<br />", "\n"
)
)
except AttributeError:
ret... | [
"def",
"_info_long",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"try",
":",
"return",
"str",
"(",
"html",
".",
"unescape",
"(",
"self",
".",
"journey",
".",
"InfoTextList",
".",
"InfoText",
".",
"get",
"(",
"\"textL\"",
")",
")",
".",
... | 31.9 | 17.7 |
def _aha_request(self, cmd, ain=None, param=None, rf=str):
"""Send an AHA request."""
url = 'http://' + self._host + '/webservices/homeautoswitch.lua'
params = {
'switchcmd': cmd,
'sid': self._sid
}
if param:
params['param'] = param
if ... | [
"def",
"_aha_request",
"(",
"self",
",",
"cmd",
",",
"ain",
"=",
"None",
",",
"param",
"=",
"None",
",",
"rf",
"=",
"str",
")",
":",
"url",
"=",
"'http://'",
"+",
"self",
".",
"_host",
"+",
"'/webservices/homeautoswitch.lua'",
"params",
"=",
"{",
"'swi... | 27.736842 | 17.421053 |
def get_interface_switchport_output_switchport_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface... | [
"def",
"get_interface_switchport_output_switchport_interface_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_switchport",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_switchport\"",... | 49.333333 | 18.866667 |
def send_activation_email(user, site):
"""
Send an activation email to the ``user``.
The activation email will make use of two templates:
``registration/activation_email_subject.txt``
This template will be used for the subject line of the
email. Because it is used as the subject line of an emai... | [
"def",
"send_activation_email",
"(",
"user",
",",
"site",
")",
":",
"ctx_dict",
"=",
"{",
"'activation_key'",
":",
"user",
".",
"api_registration_profile",
".",
"activation_key",
",",
"'expiration_days'",
":",
"get_settings",
"(",
"'REGISTRATION_API_ACCOUNT_ACTIVATION_D... | 39.695652 | 19.608696 |
def ess(sim, n):
"""Calculate effective sample size
Parameters
----------
sim : chains
n : int
Parameter index starting from 0
"""
try:
ess = _chains.effective_sample_size(sim, n)
except (ValueError, ZeroDivisionError):
ess = nan
return ess | [
"def",
"ess",
"(",
"sim",
",",
"n",
")",
":",
"try",
":",
"ess",
"=",
"_chains",
".",
"effective_sample_size",
"(",
"sim",
",",
"n",
")",
"except",
"(",
"ValueError",
",",
"ZeroDivisionError",
")",
":",
"ess",
"=",
"nan",
"return",
"ess"
] | 20.571429 | 18.928571 |
def login(self, login, password, set_auth=False):
"""
Attempts a login to the remote server
and on success returns user id and session
or None
Warning: Do not depend on this. This will be deprecated
with SSO.
param set_auth: sets the authentication on the client... | [
"def",
"login",
"(",
"self",
",",
"login",
",",
"password",
",",
"set_auth",
"=",
"False",
")",
":",
"rv",
"=",
"self",
".",
"session",
".",
"post",
"(",
"self",
".",
"host",
",",
"dumps",
"(",
"{",
"\"method\"",
":",
"\"common.db.login\"",
",",
"\"p... | 27.5 | 16.333333 |
def setDisallowed(self, laneID, disallowedClasses):
"""setDisallowed(string, list) -> None
Sets a list of disallowed vehicle classes.
"""
if isinstance(disallowedClasses, str):
disallowedClasses = [disallowedClasses]
self._connection._beginMessage(tc.CMD_SET_LANE_VAR... | [
"def",
"setDisallowed",
"(",
"self",
",",
"laneID",
",",
"disallowedClasses",
")",
":",
"if",
"isinstance",
"(",
"disallowedClasses",
",",
"str",
")",
":",
"disallowedClasses",
"=",
"[",
"disallowedClasses",
"]",
"self",
".",
"_connection",
".",
"_beginMessage",... | 50.181818 | 20.090909 |
def get_data(source, fields='*', env=None, first_row=0, count=-1, schema=None):
""" A utility function to get a subset of data from a Table, Query, Pandas dataframe or List.
Args:
source: the source of the data. Can be a Table, Pandas DataFrame, List of dictionaries or
lists, or a string, in which case... | [
"def",
"get_data",
"(",
"source",
",",
"fields",
"=",
"'*'",
",",
"env",
"=",
"None",
",",
"first_row",
"=",
"0",
",",
"count",
"=",
"-",
"1",
",",
"schema",
"=",
"None",
")",
":",
"ipy",
"=",
"IPython",
".",
"get_ipython",
"(",
")",
"if",
"env",... | 49.982456 | 28.754386 |
def deleteThreads(self, thread_ids):
"""
Deletes threads
:param thread_ids: Thread IDs to delete. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
"""
thread_ids = require_list(thread_ids)
da... | [
"def",
"deleteThreads",
"(",
"self",
",",
"thread_ids",
")",
":",
"thread_ids",
"=",
"require_list",
"(",
"thread_ids",
")",
"data_unpin",
"=",
"dict",
"(",
")",
"data_delete",
"=",
"dict",
"(",
")",
"for",
"i",
",",
"thread_id",
"in",
"enumerate",
"(",
... | 38.944444 | 16.166667 |
def comment_create(self, post_id, comment_body, anonymous=None):
"""Action to lets you create a comment (Requires login).
Parameters:
post_id (int): The post id number to which you are responding.
comment_body (str): The body of the comment.
anonymous (int): Set to 1... | [
"def",
"comment_create",
"(",
"self",
",",
"post_id",
",",
"comment_body",
",",
"anonymous",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'comment[post_id]'",
":",
"post_id",
",",
"'comment[body]'",
":",
"comment_body",
",",
"'comment[anonymous]'",
":",
"anonymou... | 41.333333 | 16.333333 |
def roundup(self, minimum_distance):
"""
If the minimum_distance is nonzero, returns a copy of the
DistancesContext with updated distances, i.e. the ones below
minimum_distance are rounded up to the minimum_distance. Otherwise,
returns the original DistancesContext unchanged.
... | [
"def",
"roundup",
"(",
"self",
",",
"minimum_distance",
")",
":",
"if",
"not",
"minimum_distance",
":",
"return",
"self",
"ctx",
"=",
"DistancesContext",
"(",
")",
"for",
"dist",
",",
"array",
"in",
"vars",
"(",
"self",
")",
".",
"items",
"(",
")",
":"... | 41.823529 | 12.882353 |
def assert_raises_regex(exception, regex, msg_fmt="{msg}"):
"""Fail unless an exception with a message that matches a regular
expression is raised within the context.
The regular expression can be a regular expression string or object.
>>> with assert_raises_regex(ValueError, r"\\d+"):
... ra... | [
"def",
"assert_raises_regex",
"(",
"exception",
",",
"regex",
",",
"msg_fmt",
"=",
"\"{msg}\"",
")",
":",
"def",
"test",
"(",
"exc",
")",
":",
"compiled",
"=",
"re",
".",
"compile",
"(",
"regex",
")",
"if",
"not",
"exc",
".",
"args",
":",
"msg",
"=",... | 33.415094 | 16.698113 |
def _point_scalar(self, name=None):
"""
Returns point scalars of a vtk object
Parameters
----------
name : str
Name of point scalars to retrive.
Returns
-------
scalars : np.ndarray
Numpy array of scalars
"""
if n... | [
"def",
"_point_scalar",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"# use active scalar array",
"field",
",",
"name",
"=",
"self",
".",
"active_scalar_info",
"if",
"field",
"!=",
"POINT_DATA_FIELD",
":",
"raise",
"Runti... | 32.323529 | 17.382353 |
def set_properties(self, path, mode):
"""Set file's properties (name and mode).
This function is also in charge of swapping between textual and
binary streams.
"""
self.name = path
self.mode = mode
if 'b' in self.mode:
if not isinstance(self.read_dat... | [
"def",
"set_properties",
"(",
"self",
",",
"path",
",",
"mode",
")",
":",
"self",
".",
"name",
"=",
"path",
"self",
".",
"mode",
"=",
"mode",
"if",
"'b'",
"in",
"self",
".",
"mode",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"read_data",
","... | 34.933333 | 19.066667 |
def get_base_branch():
# type: () -> str
""" Return the base branch for the current branch.
This function will first try to guess the base branch and if it can't it
will let the user choose the branch from the list of all local branches.
Returns:
str: The name of the branch the current bra... | [
"def",
"get_base_branch",
"(",
")",
":",
"# type: () -> str",
"base_branch",
"=",
"git",
".",
"guess_base_branch",
"(",
")",
"if",
"base_branch",
"is",
"None",
":",
"log",
".",
"info",
"(",
"\"Can't guess the base branch, you have to pick one yourself:\"",
")",
"base_... | 31.823529 | 23.411765 |
def all_finite(self,X):
"""returns true if X is finite, false, otherwise"""
# Adapted from sklearn utils: _assert_all_finite(X)
# First try an O(n) time, O(1) space solution for the common case that
# everything is finite; fall back to O(n) space np.isfinite to prevent
# false po... | [
"def",
"all_finite",
"(",
"self",
",",
"X",
")",
":",
"# Adapted from sklearn utils: _assert_all_finite(X)",
"# First try an O(n) time, O(1) space solution for the common case that",
"# everything is finite; fall back to O(n) space np.isfinite to prevent",
"# false positives from overflow in s... | 56.692308 | 23.538462 |
def package(self):
"""
Find a package name from a build task's parameters.
:returns: name of the package this build task is building.
:raises: ValueError if we could not parse this tasks's request params.
"""
if self.method == 'buildNotification':
return self... | [
"def",
"package",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"==",
"'buildNotification'",
":",
"return",
"self",
".",
"params",
"[",
"1",
"]",
"[",
"'name'",
"]",
"if",
"self",
".",
"method",
"in",
"(",
"'createImage'",
",",
"'image'",
",",
... | 43.305556 | 14.472222 |
def enrich(self, columns):
""" This method appends at the end of the dataframe as many
rows as items are found in the list of elemnents in the
provided columns.
This assumes that the length of the lists for the several
specified columns is the same. As an example, for the row A
... | [
"def",
"enrich",
"(",
"self",
",",
"columns",
")",
":",
"for",
"column",
"in",
"columns",
":",
"if",
"column",
"not",
"in",
"self",
".",
"data",
".",
"columns",
":",
"return",
"self",
".",
"data",
"# Looking for the rows with columns with lists of more",
"# th... | 37.555556 | 17.259259 |
def lint(session):
"""Run flake8.
Returns a failure if flake8 finds linting errors or sufficiently
serious code quality issues.
"""
session.interpreter = 'python3.6'
session.install('flake8')
# Install dev packages.
_install_dev_packages(session)
session.run(
'flake8',
... | [
"def",
"lint",
"(",
"session",
")",
":",
"session",
".",
"interpreter",
"=",
"'python3.6'",
"session",
".",
"install",
"(",
"'flake8'",
")",
"# Install dev packages.",
"_install_dev_packages",
"(",
"session",
")",
"session",
".",
"run",
"(",
"'flake8'",
",",
"... | 31.066667 | 20.066667 |
def new_transient(self, ext=''):
'''Creates empty TransientFile with random name and given extension.
File on FS is not created'''
name = random_name(self.transient_length) + ext
return TransientFile(self.transient_root, name, self) | [
"def",
"new_transient",
"(",
"self",
",",
"ext",
"=",
"''",
")",
":",
"name",
"=",
"random_name",
"(",
"self",
".",
"transient_length",
")",
"+",
"ext",
"return",
"TransientFile",
"(",
"self",
".",
"transient_root",
",",
"name",
",",
"self",
")"
] | 52 | 16.8 |
def copytree(src, dst, symlinks=False, ignore=None):
"""Recursively copy a directory tree using copy2().
The destination directory must not already exist.
If exception(s) occur, an Error is raised with a list of reasons.
If the optional symlinks flag is true, symbolic links in the
source tree resu... | [
"def",
"copytree",
"(",
"src",
",",
"dst",
",",
"symlinks",
"=",
"False",
",",
"ignore",
"=",
"None",
")",
":",
"from",
"shutil",
"import",
"copy2",
",",
"Error",
",",
"copystat",
"names",
"=",
"os",
".",
"listdir",
"(",
"src",
")",
"if",
"ignore",
... | 35.784615 | 18.892308 |
def cmd_quick(action, action_space, ability_id, queued):
"""Do a quick command like 'Stop' or 'Stim'."""
action_cmd = spatial(action, action_space).unit_command
action_cmd.ability_id = ability_id
action_cmd.queue_command = queued | [
"def",
"cmd_quick",
"(",
"action",
",",
"action_space",
",",
"ability_id",
",",
"queued",
")",
":",
"action_cmd",
"=",
"spatial",
"(",
"action",
",",
"action_space",
")",
".",
"unit_command",
"action_cmd",
".",
"ability_id",
"=",
"ability_id",
"action_cmd",
".... | 46.6 | 8.4 |
def _get_variable_name_or_register(var, variables, names, params, prefix):
'''
Args:
var (~nnabla.Variable)
variables (OrderedDict)
names (dict): Force name table, Variable -> str
params (dict): NdArray -> str
prefix(str)
'''
if var not in variables.values():
... | [
"def",
"_get_variable_name_or_register",
"(",
"var",
",",
"variables",
",",
"names",
",",
"params",
",",
"prefix",
")",
":",
"if",
"var",
"not",
"in",
"variables",
".",
"values",
"(",
")",
":",
"vname",
"=",
"prefix",
"if",
"var",
".",
"data",
"in",
"p... | 30.428571 | 19.380952 |
def encode_fetch_request(cls, client_id, correlation_id, payloads=None,
max_wait_time=100, min_bytes=4096):
"""
Encodes some FetchRequest structs
Arguments:
client_id: string
correlation_id: int
payloads: list of FetchRequest
... | [
"def",
"encode_fetch_request",
"(",
"cls",
",",
"client_id",
",",
"correlation_id",
",",
"payloads",
"=",
"None",
",",
"max_wait_time",
"=",
"100",
",",
"min_bytes",
"=",
"4096",
")",
":",
"payloads",
"=",
"[",
"]",
"if",
"payloads",
"is",
"None",
"else",
... | 42.411765 | 23 |
def sensoryCompute(self, activeMinicolumns, learn):
"""
@param activeMinicolumns (numpy array)
List of indices of minicolumns to activate.
@param learn (bool)
If True, the two layers should learn this association.
@return (tuple of dicts)
Data for logging/tracing.
"""
inputParams =... | [
"def",
"sensoryCompute",
"(",
"self",
",",
"activeMinicolumns",
",",
"learn",
")",
":",
"inputParams",
"=",
"{",
"\"activeColumns\"",
":",
"activeMinicolumns",
",",
"\"basalInput\"",
":",
"self",
".",
"getLocationRepresentation",
"(",
")",
",",
"\"basalGrowthCandida... | 28.821429 | 16.892857 |
def trim_tree(tree):
"""
Remove the dead branches of tree, that is, the resulting tree accepts
the same language as the original one (that is, the same words that end
with the < character), but parts of the tree that lead to nothing are
removed.
:param tree: the tree;
... | [
"def",
"trim_tree",
"(",
"tree",
")",
":",
"# Remove empty nodes",
"new_tree",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"tree",
".",
"items",
"(",
")",
"if",
"v",
"}",
"# Remove missing successors",
"new_tree",
"=",
"{",
"k",
":",
"{",
"s... | 43.5 | 17.961538 |
def add_function(self, function_id=None, function=None, inputs=None,
outputs=None, input_domain=None, weight=None,
inp_weight=None, out_weight=None, description=None,
filters=None, await_domain=None, await_result=None,
**kwargs):
... | [
"def",
"add_function",
"(",
"self",
",",
"function_id",
"=",
"None",
",",
"function",
"=",
"None",
",",
"inputs",
"=",
"None",
",",
"outputs",
"=",
"None",
",",
"input_domain",
"=",
"None",
",",
"weight",
"=",
"None",
",",
"inp_weight",
"=",
"None",
",... | 42.582278 | 22.962025 |
def HWProcess(cls, proc: HWProcess, ctx: ResourceContext) -> None:
"""
Gues resource usage by HWProcess
"""
seen = ctx.seen
for stm in proc.statements:
encl = stm._enclosed_for
full_ev_dep = stm._is_completly_event_dependent
now_ev_dep = stm._n... | [
"def",
"HWProcess",
"(",
"cls",
",",
"proc",
":",
"HWProcess",
",",
"ctx",
":",
"ResourceContext",
")",
"->",
"None",
":",
"seen",
"=",
"ctx",
".",
"seen",
"for",
"stm",
"in",
"proc",
".",
"statements",
":",
"encl",
"=",
"stm",
".",
"_enclosed_for",
... | 37.882353 | 15.529412 |
def set_ctype(self, ctype, orig_ctype=None):
"""
Set the selected content type. Will not override the value of
the content type if that has already been determined.
:param ctype: The content type string to set.
:param orig_ctype: The original content type, as found in the
... | [
"def",
"set_ctype",
"(",
"self",
",",
"ctype",
",",
"orig_ctype",
"=",
"None",
")",
":",
"if",
"self",
".",
"ctype",
"is",
"None",
":",
"self",
".",
"ctype",
"=",
"ctype",
"self",
".",
"orig_ctype",
"=",
"orig_ctype"
] | 32.857143 | 17 |
def start(self):
"""Public method for initiating connectivity with the emby server."""
asyncio.ensure_future(self.register(), loop=self._event_loop)
if self._own_loop:
_LOGGER.info("Starting up our own event loop.")
self._event_loop.run_forever()
self._event_... | [
"def",
"start",
"(",
"self",
")",
":",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"register",
"(",
")",
",",
"loop",
"=",
"self",
".",
"_event_loop",
")",
"if",
"self",
".",
"_own_loop",
":",
"_LOGGER",
".",
"info",
"(",
"\"Starting up our own ev... | 41.555556 | 15.666667 |
def appendText(self, text):
'''
appendText - append some inner text
'''
# self.text is just raw string of the text
self.text += text
self.isSelfClosing = False # inner text means it can't self close anymo
# self.blocks is either text or tags, in order of appea... | [
"def",
"appendText",
"(",
"self",
",",
"text",
")",
":",
"# self.text is just raw string of the text",
"self",
".",
"text",
"+=",
"text",
"self",
".",
"isSelfClosing",
"=",
"False",
"# inner text means it can't self close anymo",
"# self.blocks is either text or tags, in orde... | 38.888889 | 19.777778 |
def calculate_hash(options):
"""returns an option_collection_hash given a list of options"""
options = sorted(list(options))
sha_hash = sha1()
# equivalent to loop over the options and call sha_hash.update()
sha_hash.update(''.join(options).encode('utf-8'))
return sha_has... | [
"def",
"calculate_hash",
"(",
"options",
")",
":",
"options",
"=",
"sorted",
"(",
"list",
"(",
"options",
")",
")",
"sha_hash",
"=",
"sha1",
"(",
")",
"# equivalent to loop over the options and call sha_hash.update()",
"sha_hash",
".",
"update",
"(",
"''",
".",
... | 46.714286 | 11.714286 |
def oops(self):
'''Out Of Phase Stereo effect. Mixes stereo to twin-mono where each
mono channel contains the difference between the left and right stereo
channels. This is sometimes known as the 'karaoke' effect as it often
has the effect of removing most or all of the vocals from a rec... | [
"def",
"oops",
"(",
"self",
")",
":",
"effect_args",
"=",
"[",
"'oops'",
"]",
"self",
".",
"effects",
".",
"extend",
"(",
"effect_args",
")",
"self",
".",
"effects_log",
".",
"append",
"(",
"'oops'",
")",
"return",
"self"
] | 38.5 | 26.166667 |
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=... | [
"def",
"add_event",
"(",
"self",
",",
"source",
",",
"reference",
",",
"event_title",
",",
"event_type",
",",
"method",
"=",
"''",
",",
"description",
"=",
"''",
",",
"bucket_list",
"=",
"[",
"]",
",",
"campaign",
"=",
"''",
",",
"confidence",
"=",
"''... | 38.402985 | 14.343284 |
def optimal_variational_posterior(
kernel,
inducing_index_points,
observation_index_points,
observations,
observation_noise_variance,
mean_fn=None,
jitter=1e-6,
name=None):
"""Model selection for optimal variational hyperparameters.
Given the full training set (p... | [
"def",
"optimal_variational_posterior",
"(",
"kernel",
",",
"inducing_index_points",
",",
"observation_index_points",
",",
"observations",
",",
"observation_noise_variance",
",",
"mean_fn",
"=",
"None",
",",
"jitter",
"=",
"1e-6",
",",
"name",
"=",
"None",
")",
":",... | 45.133333 | 23.25 |
def engine(log_file, no_distribute, yes, config_file, make_html_report,
upgrade_db, db_version, what_if_I_upgrade, run,
list_hazard_calculations, list_risk_calculations,
delete_calculation, delete_uncompleted_calculations,
hazard_calculation_id, list_outputs, show_log,
... | [
"def",
"engine",
"(",
"log_file",
",",
"no_distribute",
",",
"yes",
",",
"config_file",
",",
"make_html_report",
",",
"upgrade_db",
",",
"db_version",
",",
"what_if_I_upgrade",
",",
"run",
",",
"list_hazard_calculations",
",",
"list_risk_calculations",
",",
"delete_... | 35.757813 | 18.351563 |
def normalize_pts(pts, ymax, scaler=2):
"""
scales all coordinates and flip y axis due to different
origin coordinates (top left vs. bottom left)
"""
return [(x * scaler, ymax - (y * scaler)) for x, y in pts] | [
"def",
"normalize_pts",
"(",
"pts",
",",
"ymax",
",",
"scaler",
"=",
"2",
")",
":",
"return",
"[",
"(",
"x",
"*",
"scaler",
",",
"ymax",
"-",
"(",
"y",
"*",
"scaler",
")",
")",
"for",
"x",
",",
"y",
"in",
"pts",
"]"
] | 37.166667 | 8.5 |
def _initVirtualOutputs(self):
""" Sets up the structure to hold all the output data arrays for
this image in memory.
"""
self.virtualOutputs = {}
for product in self.outputNames:
self.virtualOutputs[product] = None | [
"def",
"_initVirtualOutputs",
"(",
"self",
")",
":",
"self",
".",
"virtualOutputs",
"=",
"{",
"}",
"for",
"product",
"in",
"self",
".",
"outputNames",
":",
"self",
".",
"virtualOutputs",
"[",
"product",
"]",
"=",
"None"
] | 37.285714 | 5.142857 |
async def get_json(
self, force: bool=False, silent: bool=False, cache: bool=True,
) -> Any:
"""Parses the body data as JSON and returns it.
Arguments:
force: Force JSON parsing even if the mimetype is not JSON.
silent: Do not trigger error handling if parsing fails,... | [
"async",
"def",
"get_json",
"(",
"self",
",",
"force",
":",
"bool",
"=",
"False",
",",
"silent",
":",
"bool",
"=",
"False",
",",
"cache",
":",
"bool",
"=",
"True",
",",
")",
"->",
"Any",
":",
"if",
"cache",
"and",
"self",
".",
"_cached_json",
"is",... | 33.103448 | 18.896552 |
def define_charset(self, code, mode):
"""Define ``G0`` or ``G1`` charset.
:param str code: character set code, should be a character
from ``"B0UK"``, otherwise ignored.
:param str mode: if ``"("`` ``G0`` charset is defined, if
``")"`` -- we oper... | [
"def",
"define_charset",
"(",
"self",
",",
"code",
",",
"mode",
")",
":",
"if",
"code",
"in",
"cs",
".",
"MAPS",
":",
"if",
"mode",
"==",
"\"(\"",
":",
"self",
".",
"g0_charset",
"=",
"cs",
".",
"MAPS",
"[",
"code",
"]",
"elif",
"mode",
"==",
"\"... | 39.133333 | 16.866667 |
def similarity_graph(self, k=5, radius=None, include_self_edges=False,
output_type='SGraph', verbose=True):
"""
Construct the similarity graph on the reference dataset, which is
already stored in the model. This is conceptually very similar to
running `query` wit... | [
"def",
"similarity_graph",
"(",
"self",
",",
"k",
"=",
"5",
",",
"radius",
"=",
"None",
",",
"include_self_edges",
"=",
"False",
",",
"output_type",
"=",
"'SGraph'",
",",
"verbose",
"=",
"True",
")",
":",
"## Validate inputs.",
"if",
"k",
"is",
"not",
"N... | 40.919355 | 25.854839 |
def generate_binding_credentials(self, binding):
"""Generate binding credentials
This function will permit to define the configuration to
connect to the instance.
Those credentials will be stored on a secret and exposed to a a Pod.
We should at least returns the... | [
"def",
"generate_binding_credentials",
"(",
"self",
",",
"binding",
")",
":",
"uri",
"=",
"self",
".",
"clusters",
".",
"get",
"(",
"binding",
".",
"instance",
".",
"get_cluster",
"(",
")",
",",
"None",
")",
"if",
"not",
"uri",
":",
"raise",
"ErrClusterC... | 31.868421 | 21.921053 |
def hasKey(self, key, notNone=False):
'''Return entries where the key is present.
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]},
... {"name... | [
"def",
"hasKey",
"(",
"self",
",",
"key",
",",
"notNone",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"result_tracker",
"=",
"[",
"]",
"for",
"counter",
",",
"row",
"in",
"enumerate",
"(",
"self",
".",
"table",
")",
":",
"(",
"target",
",",
... | 39.090909 | 24.409091 |
def getFrameDimensions(data, page_width, page_height):
"""Calculate dimensions of a frame
Returns left, top, width and height of the frame in points.
"""
box = data.get("-pdf-frame-box", [])
if len(box) == 4:
return [getSize(x) for x in box]
top = getSize(data.get("top", 0))
left = ... | [
"def",
"getFrameDimensions",
"(",
"data",
",",
"page_width",
",",
"page_height",
")",
":",
"box",
"=",
"data",
".",
"get",
"(",
"\"-pdf-frame-box\"",
",",
"[",
"]",
")",
"if",
"len",
"(",
"box",
")",
"==",
"4",
":",
"return",
"[",
"getSize",
"(",
"x"... | 36.694444 | 8.555556 |
def find_protoc(path=os.environ['PATH']):
'''
Traverse a path ($PATH by default) to find the protoc compiler
'''
protoc_filename = 'protoc'
bin_search_paths = path.split(':') or []
for search_path in bin_search_paths:
bin_path = os.path.join(search_path, protoc_filename)
... | [
"def",
"find_protoc",
"(",
"path",
"=",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
")",
":",
"protoc_filename",
"=",
"'protoc'",
"bin_search_paths",
"=",
"path",
".",
"split",
"(",
"':'",
")",
"or",
"[",
"]",
"for",
"search_path",
"in",
"bin_search_paths",
... | 35.307692 | 20.384615 |
def downstream(self, node):
""" Returns a list of all nodes this node has edges towards.
Args:
node (str): The node whose downstream nodes you want to find.
Returns:
list: A list of nodes that are immediately downstream from the
node.
"""
... | [
"def",
"downstream",
"(",
"self",
",",
"node",
")",
":",
"graph",
"=",
"self",
".",
"graph",
"if",
"node",
"not",
"in",
"graph",
":",
"raise",
"KeyError",
"(",
"'node %s is not in graph'",
"%",
"node",
")",
"return",
"list",
"(",
"graph",
"[",
"node",
... | 32.285714 | 20.071429 |
def load(self):
"Loads the state from the state file"
try:
if os.path.getsize(self.state_file) <= 1:
raise IOError("File is empty.")
with open(self.state_file) as fh:
state = json.load(fh)
assert isinstance(state, dict)
... | [
"def",
"load",
"(",
"self",
")",
":",
"try",
":",
"if",
"os",
".",
"path",
".",
"getsize",
"(",
"self",
".",
"state_file",
")",
"<=",
"1",
":",
"raise",
"IOError",
"(",
"\"File is empty.\"",
")",
"with",
"open",
"(",
"self",
".",
"state_file",
")",
... | 38.125 | 9.875 |
def tangent(f):
"""A decorator which removes the `with insert_grad_of` statement.
This allows the function to be called as usual.
Args:
f: A function
Returns:
A function with any `with insert_grad_of` context managers removed.
"""
node = annotate.resolve_calls(f)
RemoveWith().visit(node)
wrap... | [
"def",
"tangent",
"(",
"f",
")",
":",
"node",
"=",
"annotate",
".",
"resolve_calls",
"(",
"f",
")",
"RemoveWith",
"(",
")",
".",
"visit",
"(",
"node",
")",
"wrapped",
"=",
"functools",
".",
"wraps",
"(",
"f",
")",
"(",
"compile_",
".",
"compile_funct... | 25.0625 | 22.3125 |
def copy_ifcfg_file(source_interface, dest_interface):
"""Copies an existing ifcfg network script to another
:param source_interface: String (e.g. 1)
:param dest_interface: String (e.g. 0:0)
:return: None
:raises TypeError, OSError
"""
log = logging.getLogger(mod_logger + '.copy_ifcfg_file'... | [
"def",
"copy_ifcfg_file",
"(",
"source_interface",
",",
"dest_interface",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.copy_ifcfg_file'",
")",
"# Validate args",
"if",
"not",
"isinstance",
"(",
"source_interface",
",",
"basestring",
... | 40.71831 | 21.197183 |
def info(self):
"""Supplemental description of the list, with length and type"""
itext = self.class_info
if self.key_prop.info and self.value_prop.info:
itext += ' (keys: {}; values: {})'.format(
self.key_prop.info, self.value_prop.info
)
elif self... | [
"def",
"info",
"(",
"self",
")",
":",
"itext",
"=",
"self",
".",
"class_info",
"if",
"self",
".",
"key_prop",
".",
"info",
"and",
"self",
".",
"value_prop",
".",
"info",
":",
"itext",
"+=",
"' (keys: {}; values: {})'",
".",
"format",
"(",
"self",
".",
... | 42.333333 | 15.5 |
def get_edit_url(
self,
md_id: str = None,
md_type: str = None,
owner_id: str = None,
tab: str = "identification",
):
"""Constructs the edition URL of a metadata.
:param str md_id: metadata/resource UUID
:param str owner_id: owner UUID
:param ... | [
"def",
"get_edit_url",
"(",
"self",
",",
"md_id",
":",
"str",
"=",
"None",
",",
"md_type",
":",
"str",
"=",
"None",
",",
"owner_id",
":",
"str",
"=",
"None",
",",
"tab",
":",
"str",
"=",
"\"identification\"",
",",
")",
":",
"# checks inputs",
"if",
"... | 30.962963 | 19.962963 |
def get_ast_field_name(ast):
"""Return the normalized field name for the given AST node."""
replacements = {
# We always rewrite the following field names into their proper underlying counterparts.
TYPENAME_META_FIELD_NAME: '@class'
}
base_field_name = ast.name.value
normalized_name ... | [
"def",
"get_ast_field_name",
"(",
"ast",
")",
":",
"replacements",
"=",
"{",
"# We always rewrite the following field names into their proper underlying counterparts.",
"TYPENAME_META_FIELD_NAME",
":",
"'@class'",
"}",
"base_field_name",
"=",
"ast",
".",
"name",
".",
"value",... | 43.444444 | 19.444444 |
def expect_column_values_to_not_match_regex_list(self, column, regex_list,
mostly=None,
result_format=None, include_config=False, catch_exceptions=None, meta=None):
"""Expect the column entries to be string... | [
"def",
"expect_column_values_to_not_match_regex_list",
"(",
"self",
",",
"column",
",",
"regex_list",
",",
"mostly",
"=",
"None",
",",
"result_format",
"=",
"None",
",",
"include_config",
"=",
"False",
",",
"catch_exceptions",
"=",
"None",
",",
"meta",
"=",
"Non... | 50.136364 | 30.659091 |
def _calendar_month_middles(year):
"""List of middle day of each month, used by Linke turbidity lookup"""
# remove mdays[0] since January starts at mdays[1]
# make local copy of mdays since we need to change
# February for leap years
mdays = np.array(calendar.mdays[1:])
ydays = 365
# handle ... | [
"def",
"_calendar_month_middles",
"(",
"year",
")",
":",
"# remove mdays[0] since January starts at mdays[1]",
"# make local copy of mdays since we need to change",
"# February for leap years",
"mdays",
"=",
"np",
".",
"array",
"(",
"calendar",
".",
"mdays",
"[",
"1",
":",
... | 39.125 | 13.625 |
def nodes_for_spec(self, spec):
"""
Determine nodes for an input_algorithms spec
Taking into account nested specs
"""
tokens = []
if isinstance(spec, sb.create_spec):
container = nodes.container(classes=["option_spec_option shortline blue-back"])
... | [
"def",
"nodes_for_spec",
"(",
"self",
",",
"spec",
")",
":",
"tokens",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"spec",
",",
"sb",
".",
"create_spec",
")",
":",
"container",
"=",
"nodes",
".",
"container",
"(",
"classes",
"=",
"[",
"\"option_spec_option s... | 43.804878 | 18.097561 |
def init_metadata(self, origin, backend_name, backend_version,
category, backend_params):
"""Init metadata information.
Metatada is composed by basic information needed to identify
where archived data came from and how it can be retrieved
and built into Perceval it... | [
"def",
"init_metadata",
"(",
"self",
",",
"origin",
",",
"backend_name",
",",
"backend_version",
",",
"category",
",",
"backend_params",
")",
":",
"created_on",
"=",
"datetime_to_utc",
"(",
"datetime_utcnow",
"(",
")",
")",
"created_on_dumped",
"=",
"created_on",
... | 41.152174 | 19.282609 |
def _check_conflict(cls, dirPath, name):
"""
Check whether the module of the given name conflicts with another module on the sys.path.
:param dirPath: the directory from which the module was originally loaded
:param name: the mpdule name
"""
old_sys_path = sys.path
... | [
"def",
"_check_conflict",
"(",
"cls",
",",
"dirPath",
",",
"name",
")",
":",
"old_sys_path",
"=",
"sys",
".",
"path",
"try",
":",
"sys",
".",
"path",
"=",
"[",
"d",
"for",
"d",
"in",
"old_sys_path",
"if",
"os",
".",
"path",
".",
"realpath",
"(",
"d... | 41.2 | 22.7 |
def uint32_to_uint8(cls, img):
"""
Cast uint32 RGB image to 4 uint8 channels.
"""
return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,))) | [
"def",
"uint32_to_uint8",
"(",
"cls",
",",
"img",
")",
":",
"return",
"np",
".",
"flipud",
"(",
"img",
".",
"view",
"(",
"dtype",
"=",
"np",
".",
"uint8",
")",
".",
"reshape",
"(",
"img",
".",
"shape",
"+",
"(",
"4",
",",
")",
")",
")"
] | 35.6 | 11.2 |
def find_definition(name, relative_to=None, importer=__import__):
"""Find definition by name in module-space.
The find algorthm will look for definitions by name relative to a
message definition or by fully qualfied name. If no definition is
found relative to the relative_to parameter it will do the sa... | [
"def",
"find_definition",
"(",
"name",
",",
"relative_to",
"=",
"None",
",",
"importer",
"=",
"__import__",
")",
":",
"# Check parameters.",
"if",
"not",
"(",
"relative_to",
"is",
"None",
"or",
"isinstance",
"(",
"relative_to",
",",
"types",
".",
"ModuleType",... | 39.830189 | 21.264151 |
def absorb_args(self, func):
"""
Calls a function without any arguments. The returned caller function
accepts any arguments (and throws them away).
"""
@wraps(func)
def wrapper(*args, **kwargs):
return func()
return wrapper | [
"def",
"absorb_args",
"(",
"self",
",",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"func",
"(",
")",
"return",
"wrapper"
] | 31.444444 | 13 |
def _fulfills_version_spec(version, version_spec):
'''
Check version number against version specification info and return a
boolean value based on whether or not the version number meets the
specified version.
'''
for oper, spec in version_spec:
if oper is None:
continue
... | [
"def",
"_fulfills_version_spec",
"(",
"version",
",",
"version_spec",
")",
":",
"for",
"oper",
",",
"spec",
"in",
"version_spec",
":",
"if",
"oper",
"is",
"None",
":",
"continue",
"if",
"not",
"salt",
".",
"utils",
".",
"versions",
".",
"compare",
"(",
"... | 37.916667 | 25.583333 |
def _peek_job(self, pos):
"""
Return the job currently at position `pos`, but still keep it in the job queue. An IndexError will be raised
if that position does not currently exist in the job list.
:param int pos: Position of the job to get.
:return: The job
"""
... | [
"def",
"_peek_job",
"(",
"self",
",",
"pos",
")",
":",
"if",
"pos",
"<",
"len",
"(",
"self",
".",
"_job_info_queue",
")",
":",
"return",
"self",
".",
"_job_info_queue",
"[",
"pos",
"]",
".",
"job",
"raise",
"IndexError",
"(",
")"
] | 32.923077 | 21.692308 |
def OnLinkBitmap(self, event):
"""Link bitmap event handler"""
# Get file name
wildcard = "*"
message = _("Select bitmap for current cell")
style = wx.OPEN | wx.CHANGE_DIR
filepath, __ = \
self.grid.interfaces.get_filepath_findex_from_user(wildcard,
... | [
"def",
"OnLinkBitmap",
"(",
"self",
",",
"event",
")",
":",
"# Get file name",
"wildcard",
"=",
"\"*\"",
"message",
"=",
"_",
"(",
"\"Select bitmap for current cell\"",
")",
"style",
"=",
"wx",
".",
"OPEN",
"|",
"wx",
".",
"CHANGE_DIR",
"filepath",
",",
"__"... | 30.869565 | 19.086957 |
def _find_neighbors(self, inst, avg_dist):
""" Identify nearest as well as farthest hits and misses within radius defined by average distance over whole distance array.
This works the same regardless of endpoint type. """
NN_near = []
NN_far = []
min_indices = []
max_indi... | [
"def",
"_find_neighbors",
"(",
"self",
",",
"inst",
",",
"avg_dist",
")",
":",
"NN_near",
"=",
"[",
"]",
"NN_far",
"=",
"[",
"]",
"min_indices",
"=",
"[",
"]",
"max_indices",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_datalen",
"... | 37.68 | 12.84 |
def import_module(filename):
"""
Returns module object
Source: https://www.blog.pythonlibrary.org/2016/05/27/python-201-an-intro-to-importlib/
"""
module_name = "xyz"
module_spec = importlib.util.spec_from_file_location(module_name, filename)
if module_spec is None:
rai... | [
"def",
"import_module",
"(",
"filename",
")",
":",
"module_name",
"=",
"\"xyz\"",
"module_spec",
"=",
"importlib",
".",
"util",
".",
"spec_from_file_location",
"(",
"module_name",
",",
"filename",
")",
"if",
"module_spec",
"is",
"None",
":",
"raise",
"RuntimeErr... | 31 | 22.913043 |
def search_seqs(self, seqrec, in_seq, locus, run=0, partial_ann=None):
"""
search_seqs - method for annotating a BioPython sequence without alignment
:param seqrec: The reference sequence
:type seqrec: SeqRecord
:param locus: The gene locus associated with the sequence.
... | [
"def",
"search_seqs",
"(",
"self",
",",
"seqrec",
",",
"in_seq",
",",
"locus",
",",
"run",
"=",
"0",
",",
"partial_ann",
"=",
"None",
")",
":",
"# Extract out the sequences and feature names",
"# from the reference sequences",
"# The mapped features will be subtracted fro... | 46.273292 | 22.070393 |
def write_study(self, study_id, file_content, branch, author):
"""Given a study_id, temporary filename of content, branch and auth_info
Deprecated but needed until we merge api local-dep to master...
"""
gh_user = branch.split('_study_')[0]
msg = "Update Study #%s via OpenTree ... | [
"def",
"write_study",
"(",
"self",
",",
"study_id",
",",
"file_content",
",",
"branch",
",",
"author",
")",
":",
"gh_user",
"=",
"branch",
".",
"split",
"(",
"'_study_'",
")",
"[",
"0",
"]",
"msg",
"=",
"\"Update Study #%s via OpenTree API\"",
"%",
"study_id... | 42.642857 | 13.285714 |
def asluav_status_encode(self, LED_status, SATCOM_status, Servo_status, Motor_rpm):
'''
Extended state information for ASLUAVs
LED_status : Status of the position-indicator LEDs (uint8_t)
SATCOM_status : Status of the IRIDIUM sa... | [
"def",
"asluav_status_encode",
"(",
"self",
",",
"LED_status",
",",
"SATCOM_status",
",",
"Servo_status",
",",
"Motor_rpm",
")",
":",
"return",
"MAVLink_asluav_status_message",
"(",
"LED_status",
",",
"SATCOM_status",
",",
"Servo_status",
",",
"Motor_rpm",
")"
] | 56.636364 | 38.818182 |
def run_migration(connection, queries, engine):
""" Apply a migration to the SQL server """
# Execute query
with connection.cursor() as cursorMig:
# Parse statements
queries = parse_statements(queries, engine)
for query in queries:
cursorMig.execute(query)
conne... | [
"def",
"run_migration",
"(",
"connection",
",",
"queries",
",",
"engine",
")",
":",
"# Execute query",
"with",
"connection",
".",
"cursor",
"(",
")",
"as",
"cursorMig",
":",
"# Parse statements",
"queries",
"=",
"parse_statements",
"(",
"queries",
",",
"engine",... | 26.076923 | 17.538462 |
def createDenseCNNModel(self):
"""
Create a standard network composed of two CNN / MaxPool layers followed by a
linear layer with using ReLU activation between the layers
"""
# Create denseCNN2 model
model = nn.Sequential(
nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_chan... | [
"def",
"createDenseCNNModel",
"(",
"self",
")",
":",
"# Create denseCNN2 model",
"model",
"=",
"nn",
".",
"Sequential",
"(",
"nn",
".",
"Conv2d",
"(",
"in_channels",
"=",
"self",
".",
"in_channels",
",",
"out_channels",
"=",
"self",
".",
"out_channels",
"[",
... | 30.333333 | 21.121212 |
def remove_allocated_node_name(self, name):
"""
Removes an allocated node name
:param name: allocated node name
"""
if name in self._allocated_node_names:
self._allocated_node_names.remove(name) | [
"def",
"remove_allocated_node_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_allocated_node_names",
":",
"self",
".",
"_allocated_node_names",
".",
"remove",
"(",
"name",
")"
] | 26.666667 | 11.333333 |
def setOrientation( self, orientation ):
"""
Sets the orientation for this toolbar to the inputed value, and \
updates the contents margins and collapse button based on the vaule.
:param orientation | <Qt.Orientation>
"""
super(XToolBar, self).setOrientation... | [
"def",
"setOrientation",
"(",
"self",
",",
"orientation",
")",
":",
"super",
"(",
"XToolBar",
",",
"self",
")",
".",
"setOrientation",
"(",
"orientation",
")",
"self",
".",
"refreshButton",
"(",
")"
] | 39.333333 | 15.555556 |
def _calc_eddy_time(self):
""" estimate the eddy turn-over time in days """
ens = 0.
for j in range(self.nz):
ens = .5*self.Hi[j] * self.spec_var(self.wv2*self.ph[j])
return 2.*pi*np.sqrt( self.H / ens.sum() ) / 86400 | [
"def",
"_calc_eddy_time",
"(",
"self",
")",
":",
"ens",
"=",
"0.",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"nz",
")",
":",
"ens",
"=",
".5",
"*",
"self",
".",
"Hi",
"[",
"j",
"]",
"*",
"self",
".",
"spec_var",
"(",
"self",
".",
"wv2",
"*... | 36.571429 | 18.857143 |
def _get_destcache(self, graph, orig, branch, turn, tick, *, forward):
"""Return a set of destination nodes succeeding ``orig``"""
destcache, destcache_lru, get_keycachelike, successors, adds_dels_sucpred = self._get_destcache_stuff
lru_append(destcache, destcache_lru, ((graph, orig, branch), tu... | [
"def",
"_get_destcache",
"(",
"self",
",",
"graph",
",",
"orig",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"*",
",",
"forward",
")",
":",
"destcache",
",",
"destcache_lru",
",",
"get_keycachelike",
",",
"successors",
",",
"adds_dels_sucpred",
"=",
"sel... | 62.625 | 29 |
def parse_addr(addr, *, proto=None, host=None):
"""Parses an address
Returns:
Address: the parsed address
"""
port = None
if isinstance(addr, Address):
return addr
elif isinstance(addr, str):
if addr.startswith('http://'):
proto, addr = 'http', addr[7:]
... | [
"def",
"parse_addr",
"(",
"addr",
",",
"*",
",",
"proto",
"=",
"None",
",",
"host",
"=",
"None",
")",
":",
"port",
"=",
"None",
"if",
"isinstance",
"(",
"addr",
",",
"Address",
")",
":",
"return",
"addr",
"elif",
"isinstance",
"(",
"addr",
",",
"st... | 26.942857 | 12.457143 |
def _run_command_in_extended_path(syslog_ng_sbin_dir, command, params):
'''
Runs the specified command with the syslog_ng_sbin_dir in the PATH
'''
orig_path = os.environ.get('PATH', '')
env = None
if syslog_ng_sbin_dir:
# Custom environment variables should be str types. This code
... | [
"def",
"_run_command_in_extended_path",
"(",
"syslog_ng_sbin_dir",
",",
"command",
",",
"params",
")",
":",
"orig_path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
",",
"''",
")",
"env",
"=",
"None",
"if",
"syslog_ng_sbin_dir",
":",
"# Custom enviro... | 38.95 | 23.05 |
def scale_points(df_points, scale=INKSCAPE_PPmm.magnitude, inplace=False):
'''
Translate points such that bounding box is anchored at (0, 0) and scale
``x`` and ``y`` columns of input frame by specified :data:`scale`.
Parameters
----------
df_points : pandas.DataFrame
Table of ``x``/``y... | [
"def",
"scale_points",
"(",
"df_points",
",",
"scale",
"=",
"INKSCAPE_PPmm",
".",
"magnitude",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"not",
"inplace",
":",
"df_points",
"=",
"df_points",
".",
"copy",
"(",
")",
"# Offset device, such that all coordinates ... | 29.777778 | 22.311111 |
def do_usufy(self, query, **kwargs):
"""
Verifying a usufy query in this platform.
This might be redefined in any class inheriting from Platform.
Args:
-----
query: The element to be searched.
Return:
-------
A list of elements to be app... | [
"def",
"do_usufy",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"[",
"]",
"test",
"=",
"self",
".",
"check_usufy",
"(",
"query",
",",
"*",
"*",
"kwargs",
")",
"if",
"test",
":",
"r",
"=",
"{",
"\"type\"",
":",
"... | 27.708333 | 16.541667 |
def insurance_limit(self, loss_type, dummy=None):
"""
:returns: the limit fraction of the asset cost for `loss_type`
"""
val = self.calc(loss_type, self.insurance_limits, self.area,
self.number)
if self.calc.limit_abs: # convert to relative value
... | [
"def",
"insurance_limit",
"(",
"self",
",",
"loss_type",
",",
"dummy",
"=",
"None",
")",
":",
"val",
"=",
"self",
".",
"calc",
"(",
"loss_type",
",",
"self",
".",
"insurance_limits",
",",
"self",
".",
"area",
",",
"self",
".",
"number",
")",
"if",
"s... | 41.454545 | 15.636364 |
def serialize_message(self, message: SegmentSequence) -> bytes:
"""Serialize a message (as SegmentSequence, list of FinTS3Segment, or FinTS3Segment) into a byte array"""
if isinstance(message, FinTS3Segment):
message = SegmentSequence([message])
if isinstance(message, (list, tuple, I... | [
"def",
"serialize_message",
"(",
"self",
",",
"message",
":",
"SegmentSequence",
")",
"->",
"bytes",
":",
"if",
"isinstance",
"(",
"message",
",",
"FinTS3Segment",
")",
":",
"message",
"=",
"SegmentSequence",
"(",
"[",
"message",
"]",
")",
"if",
"isinstance"... | 41.461538 | 17.538462 |
def get(self, *keys: str, default: Any = NOT_SET) -> Any:
""" Returns values from the settings in the order of keys, the first value encountered is used.
Example:
>>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2})
>>> settings.get("one")
1
>>> settings.get("one", "... | [
"def",
"get",
"(",
"self",
",",
"*",
"keys",
":",
"str",
",",
"default",
":",
"Any",
"=",
"NOT_SET",
")",
"->",
"Any",
":",
"if",
"not",
"len",
"(",
"keys",
")",
":",
"raise",
"ValueError",
"(",
"\"At least one key must be provided.\"",
")",
"for",
"op... | 33.295455 | 23.022727 |
def Dump(self, key = None):
"""
Using the standard Python pretty printer, return the contents of the
scons build environment as a string.
If the key passed in is anything other than None, then that will
be used as an index into the build environment dictionary and
whatev... | [
"def",
"Dump",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"import",
"pprint",
"pp",
"=",
"pprint",
".",
"PrettyPrinter",
"(",
"indent",
"=",
"2",
")",
"if",
"key",
":",
"dict",
"=",
"self",
".",
"Dictionary",
"(",
"key",
")",
"else",
":",
"d... | 36.529412 | 16.176471 |
def _render_child_fragment(self, child, context, view='student_view'):
"""
Helper method to overcome html block rendering quirks
"""
try:
child_fragment = child.render(view, context)
except NoSuchViewError:
if child.scope_ids.block_type == 'html' and getat... | [
"def",
"_render_child_fragment",
"(",
"self",
",",
"child",
",",
"context",
",",
"view",
"=",
"'student_view'",
")",
":",
"try",
":",
"child_fragment",
"=",
"child",
".",
"render",
"(",
"view",
",",
"context",
")",
"except",
"NoSuchViewError",
":",
"if",
"... | 48.2 | 26.866667 |
def _matches_patterns(path, patterns):
"""Given a list of patterns, returns a if a path matches any pattern."""
for glob in patterns:
try:
if PurePath(path).match(glob):
return True
except TypeError:
pass
return False | [
"def",
"_matches_patterns",
"(",
"path",
",",
"patterns",
")",
":",
"for",
"glob",
"in",
"patterns",
":",
"try",
":",
"if",
"PurePath",
"(",
"path",
")",
".",
"match",
"(",
"glob",
")",
":",
"return",
"True",
"except",
"TypeError",
":",
"pass",
"return... | 34.333333 | 11.444444 |
def close_application(self):
"""Closes the current application and also close webdriver session."""
self._debug('Closing application with session id %s' % self._current_application().session_id)
self._cache.close() | [
"def",
"close_application",
"(",
"self",
")",
":",
"self",
".",
"_debug",
"(",
"'Closing application with session id %s'",
"%",
"self",
".",
"_current_application",
"(",
")",
".",
"session_id",
")",
"self",
".",
"_cache",
".",
"close",
"(",
")"
] | 59.5 | 21.75 |
def plot_reaction_scheme(df, temperature, pressure, potential, pH, e_lim=None):
"""Returns a matplotlib object with the plotted reaction path.
Parameters
----------
df : Pandas DataFrame generated by reaction_network
temperature : numeric
temperature in K
pressure : numeric
press... | [
"def",
"plot_reaction_scheme",
"(",
"df",
",",
"temperature",
",",
"pressure",
",",
"potential",
",",
"pH",
",",
"e_lim",
"=",
"None",
")",
":",
"ncols",
"=",
"int",
"(",
"(",
"df",
".",
"shape",
"[",
"0",
"]",
"/",
"20",
")",
")",
"+",
"1",
"fig... | 39.872093 | 22.627907 |
def authenticate(self):
"""
Handles authentication, and persists the X-APPLE-WEB-KB cookie so that
subsequent logins will not cause additional e-mails from Apple.
"""
logger.info("Authenticating as %s", self.user['apple_id'])
data = dict(self.user)
# We authent... | [
"def",
"authenticate",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Authenticating as %s\"",
",",
"self",
".",
"user",
"[",
"'apple_id'",
"]",
")",
"data",
"=",
"dict",
"(",
"self",
".",
"user",
")",
"# We authenticate every time, so \"remember me\" is ... | 33.138889 | 20.305556 |
def _post_json(self, url, data, **kw):
'''
Makes a POST request, setting Authorization
and Content-Type headers by default
'''
data = json.dumps(data)
headers = kw.pop('headers', {})
headers.setdefault('Content-Type', 'application/json')
headers.setdefault... | [
"def",
"_post_json",
"(",
"self",
",",
"url",
",",
"data",
",",
"*",
"*",
"kw",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
"headers",
"=",
"kw",
".",
"pop",
"(",
"'headers'",
",",
"{",
"}",
")",
"headers",
".",
"setdefault",
... | 33.384615 | 14.615385 |
def get_Cpt_params(A, Cnodes, AggOp, T):
"""Return C and F pts.
Helper function that returns a dictionary of sparse matrices and arrays
which allow us to easily operate on Cpts and Fpts separately.
Parameters
----------
A : {csr_matrix, bsr_matrix}
Operator
Cnodes : {array}
... | [
"def",
"get_Cpt_params",
"(",
"A",
",",
"Cnodes",
",",
"AggOp",
",",
"T",
")",
":",
"if",
"not",
"isspmatrix_bsr",
"(",
"A",
")",
"and",
"not",
"isspmatrix_csr",
"(",
"A",
")",
":",
"raise",
"TypeError",
"(",
"'Expected BSR or CSR matrix A'",
")",
"if",
... | 35.054422 | 18.29932 |
def set_location(self, time, latitude, longitude):
'''
Sets the location for the query.
Parameters
----------
time: datetime or DatetimeIndex
Time range of the query.
'''
if isinstance(time, datetime.datetime):
tzinfo = time.tzinfo
... | [
"def",
"set_location",
"(",
"self",
",",
"time",
",",
"latitude",
",",
"longitude",
")",
":",
"if",
"isinstance",
"(",
"time",
",",
"datetime",
".",
"datetime",
")",
":",
"tzinfo",
"=",
"time",
".",
"tzinfo",
"else",
":",
"tzinfo",
"=",
"time",
".",
... | 28.166667 | 18.722222 |
def pdf_to_text(pdf_filepath='', **kwargs):
"""
Parse pdf to a list of strings using the pdfminer lib.
Args:
no_laparams=False,
all_texts=None,
detect_vertical=None, word_margin=None, char_margin=None,
line_margin=None, boxes_flow=None, codec='utf-8',
strip_control=F... | [
"def",
"pdf_to_text",
"(",
"pdf_filepath",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"[",
"]",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"pdf_filepath",
")",
":",
"raise",
"ValueError",
"(",
"\"No valid pdf file... | 35.216216 | 21.810811 |
def find_by_uuid(self, si, uuid, is_vm=True, path=None, data_center=None):
"""
Finds vm/host by his uuid in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param uuid: the object uuid
:param path: the path to find the object ('dc' or 'dc/f... | [
"def",
"find_by_uuid",
"(",
"self",
",",
"si",
",",
"uuid",
",",
"is_vm",
"=",
"True",
",",
"path",
"=",
"None",
",",
"data_center",
"=",
"None",
")",
":",
"if",
"uuid",
"is",
"None",
":",
"return",
"None",
"if",
"path",
"is",
"not",
"None",
":",
... | 41.333333 | 24.333333 |
def balance(ctx):
"""
Show Zebra balance.
Like the hours balance, vacation left, etc.
"""
backend = plugins_registry.get_backends_by_class(ZebraBackend)[0]
timesheet_collection = get_timesheet_collection_for_context(ctx, None)
hours_to_be_pushed = timesheet_collection.get_hours(pushed=Fals... | [
"def",
"balance",
"(",
"ctx",
")",
":",
"backend",
"=",
"plugins_registry",
".",
"get_backends_by_class",
"(",
"ZebraBackend",
")",
"[",
"0",
"]",
"timesheet_collection",
"=",
"get_timesheet_collection_for_context",
"(",
"ctx",
",",
"None",
")",
"hours_to_be_pushed"... | 42.8 | 28.48 |
def _compute_C_matrix(self):
"""See Fouss et al. (2006) and von Luxburg et al. (2007).
This is the commute-time matrix. It's a squared-euclidian distance
matrix in :math:`\\mathbb{R}^n`.
"""
self.C = np.repeat(np.diag(self.Lp)[:, np.newaxis],
self.Lp.s... | [
"def",
"_compute_C_matrix",
"(",
"self",
")",
":",
"self",
".",
"C",
"=",
"np",
".",
"repeat",
"(",
"np",
".",
"diag",
"(",
"self",
".",
"Lp",
")",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
",",
"self",
".",
"Lp",
".",
"shape",
"[",
"0",
"]",... | 43.15 | 13.45 |
def _is_match(self, response, answer):
"""For MC, can call through to MultiChoice Item Record?"""
# TODO: this varies depending on question type
if self._only_generic_right_feedback():
return str(answer.genus_type) == str(RIGHT_ANSWER_GENUS)
elif self._is_multiple_choice():
... | [
"def",
"_is_match",
"(",
"self",
",",
"response",
",",
"answer",
")",
":",
"# TODO: this varies depending on question type",
"if",
"self",
".",
"_only_generic_right_feedback",
"(",
")",
":",
"return",
"str",
"(",
"answer",
".",
"genus_type",
")",
"==",
"str",
"(... | 56.642857 | 19.5 |
def parsemail(raw_message):
"""Parse message headers, then remove BCC header."""
message = email.parser.Parser().parsestr(raw_message)
# Detect encoding
detected = chardet.detect(bytearray(raw_message, "utf-8"))
encoding = detected["encoding"]
print(">>> encoding {}".format(encoding))
for p... | [
"def",
"parsemail",
"(",
"raw_message",
")",
":",
"message",
"=",
"email",
".",
"parser",
".",
"Parser",
"(",
")",
".",
"parsestr",
"(",
"raw_message",
")",
"# Detect encoding",
"detected",
"=",
"chardet",
".",
"detect",
"(",
"bytearray",
"(",
"raw_message",... | 36.913043 | 16.391304 |
def add_source_root(self, path, langs=tuple(), category=SourceRootCategories.UNKNOWN):
"""Add the specified fixed source root, which must be relative to the buildroot.
Useful in a limited set of circumstances, e.g., when unpacking sources from a jar with
unknown structure. Tests should prefer to use dirs ... | [
"def",
"add_source_root",
"(",
"self",
",",
"path",
",",
"langs",
"=",
"tuple",
"(",
")",
",",
"category",
"=",
"SourceRootCategories",
".",
"UNKNOWN",
")",
":",
"self",
".",
"_trie",
".",
"add_fixed",
"(",
"path",
",",
"langs",
",",
"category",
")"
] | 57.125 | 25.75 |
def gist(cls, gistid):
"""gistid must be in a username/id form"""
url = "https://gist.github.com/{}.js".format(gistid)
script = "<script src=\"{}\"></script>".format(url)
return script | [
"def",
"gist",
"(",
"cls",
",",
"gistid",
")",
":",
"url",
"=",
"\"https://gist.github.com/{}.js\"",
".",
"format",
"(",
"gistid",
")",
"script",
"=",
"\"<script src=\\\"{}\\\"></script>\"",
".",
"format",
"(",
"url",
")",
"return",
"script"
] | 42.4 | 15.2 |
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
"""Helper to create a parse action for converting parsed
datetime string to Python datetime.datetime
Params -
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%dT%H:%M:%S.%f"``)
Example::
dt_exp... | [
"def",
"convertToDatetime",
"(",
"fmt",
"=",
"\"%Y-%m-%dT%H:%M:%S.%f\"",
")",
":",
"def",
"cvt_fn",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"try",
":",
"return",
"datetime",
".",
"strptime",
"(",
"t",
"[",
"0",
"]",
",",
"fmt",
")",
"except",
"ValueE... | 34.130435 | 23.217391 |
def write_new_expr_id(self, search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = None):
"""
Creates a new def_id for the given arguments and returns it.
If an entry already exists with these, will just return that id.
@search_group: string representing the search group (e.g., c... | [
"def",
"write_new_expr_id",
"(",
"self",
",",
"search_group",
",",
"search",
",",
"lars_id",
",",
"instruments",
",",
"gps_start_time",
",",
"gps_end_time",
",",
"comments",
"=",
"None",
")",
":",
"# check if id already exists",
"check_id",
"=",
"self",
".",
"ge... | 37.625 | 22.875 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.