text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def zip_inject_namespace(
zip_src,
namespace=None,
managed=None,
filename_token=None,
namespace_token=None,
namespaced_org=None,
logger=None,
):
""" Replaces %%%NAMESPACE%%% for all files and ___NAMESPACE___ in all
filenames in the zip with the either '' if no namespace is provid... | [
"def",
"zip_inject_namespace",
"(",
"zip_src",
",",
"namespace",
"=",
"None",
",",
"managed",
"=",
"None",
",",
"filename_token",
"=",
"None",
",",
"namespace_token",
"=",
"None",
",",
"namespaced_org",
"=",
"None",
",",
"logger",
"=",
"None",
",",
")",
":... | 36.086957 | 0.001173 |
def set_keywords(self, keywords):
"""
Pass an array to filter the result by keywords.
:param keywords
"""
self._query_params += str(QueryParam.KEYWORDS) + '+'.join(keywords) | [
"def",
"set_keywords",
"(",
"self",
",",
"keywords",
")",
":",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"KEYWORDS",
")",
"+",
"'+'",
".",
"join",
"(",
"keywords",
")"
] | 34.666667 | 0.00939 |
def timescales(T, tau=1, k=None, ncv=None, reversible=False, mu=None):
r"""Compute implied time scales of given transition matrix
Parameters
----------
T : transition matrix
tau : lag time
k : int (optional)
Compute the first k implied time scales.
ncv : int (optional)
The n... | [
"def",
"timescales",
"(",
"T",
",",
"tau",
"=",
"1",
",",
"k",
"=",
"None",
",",
"ncv",
"=",
"None",
",",
"reversible",
"=",
"False",
",",
"mu",
"=",
"None",
")",
":",
"if",
"k",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Number of time scal... | 36.021739 | 0.00235 |
def wrap(self, methodName, types, skip=2):
"""
Create a message handler that invokes a wrapper method
with the in-order message fields as parameters, skipping over
the first ``skip`` fields, and parsed according to the ``types`` list.
"""
def handler(fields):
... | [
"def",
"wrap",
"(",
"self",
",",
"methodName",
",",
"types",
",",
"skip",
"=",
"2",
")",
":",
"def",
"handler",
"(",
"fields",
")",
":",
"try",
":",
"args",
"=",
"[",
"field",
"if",
"typ",
"is",
"str",
"else",
"int",
"(",
"field",
"or",
"0",
")... | 39.952381 | 0.002328 |
def lindbladR(self,OmegaP,m=2,**kwargs):
"""
NAME:
lindbladR
PURPOSE:
calculate the radius of a Lindblad resonance
INPUT:
OmegaP - pattern speed (can be Quantity)
m= order of the resonance... | [
"def",
"lindbladR",
"(",
"self",
",",
"OmegaP",
",",
"m",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_APY_LOADED",
"and",
"isinstance",
"(",
"OmegaP",
",",
"units",
".",
"Quantity",
")",
":",
"OmegaP",
"=",
"OmegaP",
".",
"to",
"(",
"1",
... | 27.774194 | 0.026936 |
def _process_mgi_note_vocevidence_view(self, limit):
"""
Here we fetch the free text descriptions of the phenotype associations.
Triples:
<annot_id> dc:description "description text"
:param limit:
:return:
"""
line_counter = 0
if self.test_mode:
... | [
"def",
"_process_mgi_note_vocevidence_view",
"(",
"self",
",",
"limit",
")",
":",
"line_counter",
"=",
"0",
"if",
"self",
".",
"test_mode",
":",
"graph",
"=",
"self",
".",
"testgraph",
"else",
":",
"graph",
"=",
"self",
".",
"graph",
"model",
"=",
"Model",... | 35.465116 | 0.001914 |
def read_samples(self, parameters, array_class=None, **kwargs):
"""Reads samples for the given parameter(s).
The ``parameters`` can be the name of any dataset in ``samples_group``,
a virtual field or method of ``FieldArray`` (as long as the file
contains the necessary fields to derive t... | [
"def",
"read_samples",
"(",
"self",
",",
"parameters",
",",
"array_class",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# get the type of array class to use",
"if",
"array_class",
"is",
"None",
":",
"array_class",
"=",
"FieldArray",
"# get the names of fields ne... | 41.5625 | 0.001469 |
def post(self, url, headers=None, params=None, **kwargs):
"""Send a JSON POST request with the given request headers, additional
URL query parameters, and the given JSON in the request body. The
extra query parameters are merged with any which already exist in the
URL. The 'json' and '... | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
">",
"1",
":",
"raise",
"InvalidArgumentsError",
"(",
"\"Too many extra args ({} > 1)\"",... | 45.166667 | 0.001445 |
def find_splice(cigar):
'''Takes a cigar string and finds the first splice position as
an offset from the start. To find the 5' end (read coords) of
the junction for a reverse read, pass in the reversed cigar tuple'''
offset = 0
# a soft clip at the end of the read is taken as splicing
# where ... | [
"def",
"find_splice",
"(",
"cigar",
")",
":",
"offset",
"=",
"0",
"# a soft clip at the end of the read is taken as splicing",
"# where as a soft clip at the start is not.",
"if",
"cigar",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"4",
":",
"offset",
"=",
"cigar",
"[",
... | 31.884615 | 0.001171 |
def setrange(self, key, offset, value):
"""Overwrites part of the string stored at key, starting at the
specified offset, for the entire length of value. If the offset is
larger than the current length of the string at key, the string is
padded with zero-bytes to make offset fit. Non-exi... | [
"def",
"setrange",
"(",
"self",
",",
"key",
",",
"offset",
",",
"value",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'SETRANGE'",
",",
"key",
",",
"ascii",
"(",
"offset",
")",
",",
"value",
"]",
")"
] | 54.02439 | 0.000887 |
def once(func):
"""Runs a thing once and once only."""
lock = threading.Lock()
def new_func(*args, **kwargs):
if new_func.called:
return
with lock:
if new_func.called:
return
rv = func(*args, **kwargs)
new_func.called = True
... | [
"def",
"once",
"(",
"func",
")",
":",
"lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"new_func",
".",
"called",
":",
"return",
"with",
"lock",
":",
"if",
"new_func",
... | 24.588235 | 0.002304 |
def remove(self, *args):
'''
cplan.remove(...) yields a new calculation plan identical to cplan except without any of
the calculation steps listed in the arguments. An exception is raised if any keys are not
found in the calc-plan.
'''
return Plan(reduce(lambda m,k: m.rem... | [
"def",
"remove",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"Plan",
"(",
"reduce",
"(",
"lambda",
"m",
",",
"k",
":",
"m",
".",
"remove",
"(",
"k",
")",
",",
"args",
",",
"self",
".",
"nodes",
")",
")"
] | 48.571429 | 0.014451 |
def get_asset_contents_by_query(self, asset_content_query=None):
"""Gets a list of ``AssetContents`` matching the given asset content query.
arg: asset_content_query (osid.repository.AssetContentQuery): the asset
content query
return: (osid.repository.AssetContentList) - the ... | [
"def",
"get_asset_contents_by_query",
"(",
"self",
",",
"asset_content_query",
"=",
"None",
")",
":",
"return",
"AssetContentList",
"(",
"self",
".",
"_provider_session",
".",
"get_asset_contents_by_query",
"(",
"asset_content_query",
")",
",",
"self",
".",
"_config_m... | 55.8 | 0.008226 |
def _get_types_for_vcard_object(self, object, default_type):
"""
get list of types for phone number, email or post address
:param object: vcard class object
:type object: vobject.vCard
:param default_type: use if the object contains no type
:type default_type: str
... | [
"def",
"_get_types_for_vcard_object",
"(",
"self",
",",
"object",
",",
"default_type",
")",
":",
"type_list",
"=",
"[",
"]",
"# try to find label group for custom value type",
"if",
"object",
".",
"group",
":",
"for",
"label",
"in",
"self",
".",
"vcard",
".",
"g... | 44.914894 | 0.001391 |
def _save_uploaded_data_json(samples, data_json_work, out_dir):
""" Fixes all absolute work-rooted paths to relative final-rooted paths
"""
if not utils.file_exists(data_json_work):
return None
upload_path_mapping = dict()
for sample in samples:
upload_path_mapping.update(get_all_up... | [
"def",
"_save_uploaded_data_json",
"(",
"samples",
",",
"data_json_work",
",",
"out_dir",
")",
":",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"data_json_work",
")",
":",
"return",
"None",
"upload_path_mapping",
"=",
"dict",
"(",
")",
"for",
"sample",
"in"... | 40.904762 | 0.002275 |
def _read_loop(self):
"""
Coroutine which gathers bytes sent by the server
and feeds them to the protocol parser.
In case of error while reading, it will stop running
and its task has to be rescheduled.
"""
while True:
try:
should_bail ... | [
"def",
"_read_loop",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"should_bail",
"=",
"self",
".",
"is_closed",
"or",
"self",
".",
"is_reconnecting",
"if",
"should_bail",
"or",
"self",
".",
"_io_reader",
"is",
"None",
":",
"break",
"if",
"sel... | 39.607143 | 0.001761 |
def _read_para_esp_transform(self, code, cbit, clen, *, desc, length, version):
"""Read HIP ESP_TRANSFORM parameter.
Structure of HIP ESP_TRANSFORM parameter [RFC 7402]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2... | [
"def",
"_read_para_esp_transform",
"(",
"self",
",",
"code",
",",
"cbit",
",",
"clen",
",",
"*",
",",
"desc",
",",
"length",
",",
"version",
")",
":",
"if",
"clen",
"%",
"2",
"!=",
"0",
":",
"raise",
"ProtocolError",
"(",
"f'HIPv{version}: [Parano {code}] ... | 46.565217 | 0.001829 |
def shutdown(self):
"""Shut down the DTLS connection
This method attemps to complete a bidirectional shutdown between
peers. For non-blocking sockets, it should be called repeatedly until
it no longer raises continuation request exceptions.
"""
if hasattr(self, "_listen... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_listening\"",
")",
":",
"# Listening server-side sockets cannot be shut down",
"return",
"try",
":",
"self",
".",
"_wrap_socket_library_call",
"(",
"lambda",
":",
"SSL_shutdown",
"(",
... | 45.823529 | 0.001886 |
def connect_ia(ia_access_key_id=None, ia_secret_access_key=None,
is_secure=False, **kwargs):
"""
Connect to the Internet Archive via their S3-like API.
:type ia_access_key_id: string
:param ia_access_key_id: Your IA Access Key ID. This will also look in your
... | [
"def",
"connect_ia",
"(",
"ia_access_key_id",
"=",
"None",
",",
"ia_secret_access_key",
"=",
"None",
",",
"is_secure",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"boto",
".",
"s3",
".",
"connection",
"import",
"S3Connection",
"from",
"boto",
... | 44.483871 | 0.001419 |
def forget_xy(t):
"""Ignore sizes of dimensions (1, 2) of a 4d tensor in shape inference.
This allows using smaller input sizes, which create an invalid graph at higher
layers (for example because a spatial dimension becomes smaller than a conv
filter) when we only use early parts of it.
"""
shape = (t.sha... | [
"def",
"forget_xy",
"(",
"t",
")",
":",
"shape",
"=",
"(",
"t",
".",
"shape",
"[",
"0",
"]",
",",
"None",
",",
"None",
",",
"t",
".",
"shape",
"[",
"3",
"]",
")",
"return",
"tf",
".",
"placeholder_with_default",
"(",
"t",
",",
"shape",
")"
] | 43.222222 | 0.012594 |
def rebuild_app(app_name, quiet=False, force=True, without_exec=False,
restart=False):
'''
Rebuild cozy apps with deletion of npm directory & new npm build
'''
user = 'cozy-{app_name}'.format(app_name=app_name)
home = '{prefix}/{app_name}'.format(prefix=PREFIX, app_name=app_name)... | [
"def",
"rebuild_app",
"(",
"app_name",
",",
"quiet",
"=",
"False",
",",
"force",
"=",
"True",
",",
"without_exec",
"=",
"False",
",",
"restart",
"=",
"False",
")",
":",
"user",
"=",
"'cozy-{app_name}'",
".",
"format",
"(",
"app_name",
"=",
"app_name",
")... | 38.454545 | 0.002306 |
def CheckSameObj(obj0, obj1, LFields=None):
""" Check if two variables are the same instance of a ToFu class
Checks a list of attributes, provided by LField
Parameters
----------
obj0 : tofu object
A variable refering to a ToFu object of any class
obj1 : tofu object
A... | [
"def",
"CheckSameObj",
"(",
"obj0",
",",
"obj1",
",",
"LFields",
"=",
"None",
")",
":",
"A",
"=",
"True",
"if",
"LField",
"is",
"not",
"None",
"and",
"obj0",
".",
"__class__",
"==",
"obj1",
".",
"__class__",
":",
"assert",
"type",
"(",
"LFields",
")"... | 37.85 | 0.009659 |
def handle_delete_user(self, req):
"""Handles the DELETE v2/<account>/<user> call for deleting a user from an
account.
Can only be called by an account .admin.
:param req: The swob.Request to process.
:returns: swob.Response, 2xx on success.
"""
# Validate path ... | [
"def",
"handle_delete_user",
"(",
"self",
",",
"req",
")",
":",
"# Validate path info",
"account",
"=",
"req",
".",
"path_info_pop",
"(",
")",
"user",
"=",
"req",
".",
"path_info_pop",
"(",
")",
"if",
"req",
".",
"path_info",
"or",
"not",
"account",
"or",
... | 47.327273 | 0.001505 |
def _call(self, mthd, uri, admin, data, headers, std_headers):
"""
Handles all the common functionality required for API calls. Returns
the resulting response object.
"""
if not uri.startswith("http"):
uri = "/".join((self.auth_endpoint.rstrip("/"), uri))
if a... | [
"def",
"_call",
"(",
"self",
",",
"mthd",
",",
"uri",
",",
"admin",
",",
"data",
",",
"headers",
",",
"std_headers",
")",
":",
"if",
"not",
"uri",
".",
"startswith",
"(",
"\"http\"",
")",
":",
"uri",
"=",
"\"/\"",
".",
"join",
"(",
"(",
"self",
"... | 36.652174 | 0.002312 |
def generate_donut():
"""Generate donut like shape with stick inside
:return: dict {'data3d': '', 'segmentation': '', 'voxelsize_mm': ''}
"""
segmentation = np.zeros([20, 30, 40])
# generate test data
segmentation[6:10, 7:24, 10:37] = 1
segmentation[6:10, 7, 10] = 0
segmentation[6:10, 2... | [
"def",
"generate_donut",
"(",
")",
":",
"segmentation",
"=",
"np",
".",
"zeros",
"(",
"[",
"20",
",",
"30",
",",
"40",
"]",
")",
"# generate test data",
"segmentation",
"[",
"6",
":",
"10",
",",
"7",
":",
"24",
",",
"10",
":",
"37",
"]",
"=",
"1"... | 29.208333 | 0.001381 |
def _parse_sum_ouput(exit_code):
"""Parse the SUM output log file.
This method parses through the SUM log file in the
default location to return the SUM update status. Sample return
string:
"Summary: The installation of the component failed. Status of updated
components: Total: 5 Success: 4 F... | [
"def",
"_parse_sum_ouput",
"(",
"exit_code",
")",
":",
"if",
"exit_code",
"==",
"3",
":",
"return",
"\"Summary: %s\"",
"%",
"EXIT_CODE_TO_STRING",
".",
"get",
"(",
"exit_code",
")",
"if",
"exit_code",
"in",
"(",
"0",
",",
"1",
",",
"253",
")",
":",
"if",... | 38.26087 | 0.000554 |
def file_data_to_str(data):
"""
Convert file data to a string for display.
This function takes the file data produced by gather_file_data().
"""
if not data:
return _('<i>File name not recorded</i>')
res = data['name']
try:
mtime_as_str = time.strftime('%Y-%m-%d %H:%M:%S',
... | [
"def",
"file_data_to_str",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"_",
"(",
"'<i>File name not recorded</i>'",
")",
"res",
"=",
"data",
"[",
"'name'",
"]",
"try",
":",
"mtime_as_str",
"=",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S... | 35.444444 | 0.001527 |
def _covert_to_hashable(data):
r"""
Args:
data (?):
Returns:
?:
CommandLine:
python -m utool.util_hash _covert_to_hashable
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_hash import * # NOQA
>>> from utool.util_hash import _covert_to_hashable ... | [
"def",
"_covert_to_hashable",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"binary_type",
")",
":",
"hashable",
"=",
"data",
"prefix",
"=",
"b'TXT'",
"elif",
"util_type",
".",
"HAVE_NUMPY",
"and",
"isinstance",
"(",
"data",
",",... | 33.55 | 0.000483 |
def write(self, data):
"""
write data on the OUT endpoint associated to the HID interface
"""
report_size = self.packet_size
if self.ep_out:
report_size = self.ep_out.wMaxPacketSize
for _ in range(report_size - len(data)):
data.append(0)
... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"report_size",
"=",
"self",
".",
"packet_size",
"if",
"self",
".",
"ep_out",
":",
"report_size",
"=",
"self",
".",
"ep_out",
".",
"wMaxPacketSize",
"for",
"_",
"in",
"range",
"(",
"report_size",
"-",
... | 36.730769 | 0.011224 |
def summarize_tensors(tensor_dict, tag=None):
"""Summarize the tensors.
Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/.
"""
if tag is None:
tag = "tensors/"
for t_name in list(tensor_dict):
t = tensor_dict[t_name]
tf.summary.histogram(tag... | [
"def",
"summarize_tensors",
"(",
"tensor_dict",
",",
"tag",
"=",
"None",
")",
":",
"if",
"tag",
"is",
"None",
":",
"tag",
"=",
"\"tensors/\"",
"for",
"t_name",
"in",
"list",
"(",
"tensor_dict",
")",
":",
"t",
"=",
"tensor_dict",
"[",
"t_name",
"]",
"tf... | 24.692308 | 0.012012 |
def fpath(self, version=None, tags=None, ext=None):
"""Returns the filepath appropriate for an instance of this dataset.
Parameters
----------
version: str, optional
The version of the instance of this dataset.
tags : list of str, optional
The tags associ... | [
"def",
"fpath",
"(",
"self",
",",
"version",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"ext",
"=",
"None",
")",
":",
"if",
"self",
".",
"singleton",
":",
"return",
"dataset_filepath",
"(",
"filename",
"=",
"self",
".",
"fname",
"(",
"version",
"=",... | 32.5 | 0.001992 |
def lambdafan(func):
"""simple decorator that will auto fan out async style in lambda.
outside of lambda, this will invoke synchrously.
"""
if 'AWS_LAMBDA_FUNCTION_NAME' not in os.environ:
return func
@functools.wraps(func)
def scaleout(*args, **kw):
client = boto3.client('lamb... | [
"def",
"lambdafan",
"(",
"func",
")",
":",
"if",
"'AWS_LAMBDA_FUNCTION_NAME'",
"not",
"in",
"os",
".",
"environ",
":",
"return",
"func",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"scaleout",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
... | 32.428571 | 0.001427 |
def import_gtfs(gtfs_sources, output, preserve_connection=False,
print_progress=True, location_name=None, **kwargs):
"""Import a GTFS database
gtfs_sources: str, dict, list
Paths to the gtfs zip file or to the directory containing the GTFS data.
Alternatively, a dict can be prov... | [
"def",
"import_gtfs",
"(",
"gtfs_sources",
",",
"output",
",",
"preserve_connection",
"=",
"False",
",",
"print_progress",
"=",
"True",
",",
"location_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"output",
",",
"sqlite3",
... | 37.370079 | 0.001847 |
def t_QMARK(self, t):
r"\?"
t.endlexpos = t.lexpos + len(t.value)
return t | [
"def",
"t_QMARK",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"endlexpos",
"=",
"t",
".",
"lexpos",
"+",
"len",
"(",
"t",
".",
"value",
")",
"return",
"t"
] | 23.75 | 0.020408 |
def locate_agent(self, recp):
'''locate_agent(recp): Return (host, port, should_redirect) tuple.
'''
if recipient.IRecipient.providedBy(recp):
agent_id = recp.key
else:
agent_id = recp
found = yield self.find_agent(agent_id)
if isinstance(found, ag... | [
"def",
"locate_agent",
"(",
"self",
",",
"recp",
")",
":",
"if",
"recipient",
".",
"IRecipient",
".",
"providedBy",
"(",
"recp",
")",
":",
"agent_id",
"=",
"recp",
".",
"key",
"else",
":",
"agent_id",
"=",
"recp",
"found",
"=",
"yield",
"self",
".",
... | 45.833333 | 0.002137 |
def copy(self):
"""Create a copy of this Vector"""
new_vec = Vector2()
new_vec.X = self.X
new_vec.Y = self.Y
return new_vec | [
"def",
"copy",
"(",
"self",
")",
":",
"new_vec",
"=",
"Vector2",
"(",
")",
"new_vec",
".",
"X",
"=",
"self",
".",
"X",
"new_vec",
".",
"Y",
"=",
"self",
".",
"Y",
"return",
"new_vec"
] | 26.333333 | 0.01227 |
def create(self, **kwargs):
"""Raise error since guid cannot be duplicated
"""
raise exceptions.MethodNotImplemented(method=self.create, url=self.url, details='GUID cannot be duplicated, to create a new GUID use the relationship resource') | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"exceptions",
".",
"MethodNotImplemented",
"(",
"method",
"=",
"self",
".",
"create",
",",
"url",
"=",
"self",
".",
"url",
",",
"details",
"=",
"'GUID cannot be duplicated, to create a... | 65 | 0.011407 |
def find_first_TP(self):
"""
Find first TP of the TPAGB phase and returns the model
number at its LHe maximum.
Parameters
----------
"""
star_mass = self.get('star_mass')
he_lumi = self.get('log_LHe')
h_lumi = self.... | [
"def",
"find_first_TP",
"(",
"self",
")",
":",
"star_mass",
"=",
"self",
".",
"get",
"(",
"'star_mass'",
")",
"he_lumi",
"=",
"self",
".",
"get",
"(",
"'log_LHe'",
")",
"h_lumi",
"=",
"self",
".",
"get",
"(",
"'log_LH'",
")",
"mx2_bot",
"=",
"self",
... | 37.596154 | 0.02343 |
def write_extra_resources(self, compile_context):
"""Override write_extra_resources to produce plugin and annotation processor files."""
target = compile_context.target
if isinstance(target, ScalacPlugin):
self._write_scalac_plugin_info(compile_context.classes_dir.path, target)
elif isinstance(tar... | [
"def",
"write_extra_resources",
"(",
"self",
",",
"compile_context",
")",
":",
"target",
"=",
"compile_context",
".",
"target",
"if",
"isinstance",
"(",
"target",
",",
"ScalacPlugin",
")",
":",
"self",
".",
"_write_scalac_plugin_info",
"(",
"compile_context",
".",... | 64.9 | 0.010638 |
def split_long_sentence(sentence, words_per_line):
"""Takes a sentence and adds a newline every "words_per_line" words.
Parameters
----------
sentence: str
Sentene to split
words_per_line: double
Add a newline every this many words
"""
words = sentence.split(' ')
split_s... | [
"def",
"split_long_sentence",
"(",
"sentence",
",",
"words_per_line",
")",
":",
"words",
"=",
"sentence",
".",
"split",
"(",
"' '",
")",
"split_sentence",
"=",
"''",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"words",
")",
")",
":",
"split_sentence",
"=... | 31.473684 | 0.001623 |
def uninstall(self):
"""Uninstall this importer if possible and un-import any modules imported by it."""
if not self._uninstallable:
_tracer().log('Not uninstalling {}'.format(self), V=9)
return
if self in sys.meta_path:
sys.meta_path.remove(self)
maybe_exposed = frozenset(os.path.j... | [
"def",
"uninstall",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_uninstallable",
":",
"_tracer",
"(",
")",
".",
"log",
"(",
"'Not uninstalling {}'",
".",
"format",
"(",
"self",
")",
",",
"V",
"=",
"9",
")",
"return",
"if",
"self",
"in",
"sys",
... | 43.928571 | 0.015924 |
def plot_summary_distributions(df,ax=None,label_post=False,label_prior=False,
subplots=False,figsize=(11,8.5),pt_color='b'):
""" helper function to plot gaussian distrbutions from prior and posterior
means and standard deviations
Parameters
----------
df : pandas.Data... | [
"def",
"plot_summary_distributions",
"(",
"df",
",",
"ax",
"=",
"None",
",",
"label_post",
"=",
"False",
",",
"label_prior",
"=",
"False",
",",
"subplots",
"=",
"False",
",",
"figsize",
"=",
"(",
"11",
",",
"8.5",
")",
",",
"pt_color",
"=",
"'b'",
")",... | 32.60177 | 0.013172 |
def _apply_units(data_data, data_units, fname):
"""
Apply units to data.
:param data_data: NumPy structured array with data from fname.
:type data_data: :class:`numpy.ndarray`
:param data_units: Units of fields in data_data.
:type data_units: dict
:param fname: Name of file from which data_... | [
"def",
"_apply_units",
"(",
"data_data",
",",
"data_units",
",",
"fname",
")",
":",
"data_names",
"=",
"data_data",
".",
"dtype",
".",
"names",
"# raise error if NumPy data doesn't have names",
"if",
"not",
"data_names",
":",
"raise",
"UnnamedDataError",
"(",
"fname... | 39.677419 | 0.000794 |
def basis_ket_zero_outside_hs(cls, ops, kwargs):
"""For ``BasisKet.create(ind, hs)`` with an integer label `ind`, return a
:class:`ZeroKet` if `ind` is outside of the range of the underlying Hilbert
space
"""
from qnet.algebra.core.state_algebra import ZeroKet
ind, = ops
hs = kwargs['hs']
... | [
"def",
"basis_ket_zero_outside_hs",
"(",
"cls",
",",
"ops",
",",
"kwargs",
")",
":",
"from",
"qnet",
".",
"algebra",
".",
"core",
".",
"state_algebra",
"import",
"ZeroKet",
"ind",
",",
"=",
"ops",
"hs",
"=",
"kwargs",
"[",
"'hs'",
"]",
"if",
"isinstance"... | 38.416667 | 0.002119 |
def step(self, path=None, peer_table=None):
"""
Run one step of this algorithm:
* find the set of missing zonefiles
* try to fetch each of them
* store them
* update our zonefile database
Fetch rarest zonefiles first, but batch
whenever possible.
... | [
"def",
"step",
"(",
"self",
",",
"path",
"=",
"None",
",",
"peer_table",
"=",
"None",
")",
":",
"# if os.environ.get(\"BLOCKSTACK_TEST\", None) == \"1\":",
"# log.debug(\"%s: %s step\" % (self.hostport, self.__class__.__name__))",
"if",
"path",
"is",
"None",
":",
"path",... | 46.619048 | 0.009335 |
def get_results_file_name(boundaries_id, labels_id, config,
annotator_id):
"""Based on the config and the dataset, get the file name to store the
results."""
utils.ensure_dir(msaf.config.results_dir)
file_name = os.path.join(msaf.config.results_dir, "results")
file_name += ... | [
"def",
"get_results_file_name",
"(",
"boundaries_id",
",",
"labels_id",
",",
"config",
",",
"annotator_id",
")",
":",
"utils",
".",
"ensure_dir",
"(",
"msaf",
".",
"config",
".",
"results_dir",
")",
"file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"m... | 45.294118 | 0.001272 |
def create_tax_class(cls, tax_class, **kwargs):
"""Create TaxClass
Create a new TaxClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_tax_class(tax_class, async=True)
>>> res... | [
"def",
"create_tax_class",
"(",
"cls",
",",
"tax_class",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_create_tax_class_with_http_... | 39.904762 | 0.002331 |
def cache(cls, key_attrs, expires=None):
"""Decorates a method to provide cached-memoization using a
combination of the positional arguments, keyword argments, and
whitelisted instance attributes.
"""
def decorator(func):
@functools.wraps(func)
def wrapp... | [
"def",
"cache",
"(",
"cls",
",",
"key_attrs",
",",
"expires",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwa... | 35.708333 | 0.001136 |
def flatten_all_but_last(a):
"""Flatten all dimensions of a except the last."""
ret = tf.reshape(a, [-1, tf.shape(a)[-1]])
if not tf.executing_eagerly():
ret.set_shape([None] + a.get_shape().as_list()[-1:])
return ret | [
"def",
"flatten_all_but_last",
"(",
"a",
")",
":",
"ret",
"=",
"tf",
".",
"reshape",
"(",
"a",
",",
"[",
"-",
"1",
",",
"tf",
".",
"shape",
"(",
"a",
")",
"[",
"-",
"1",
"]",
"]",
")",
"if",
"not",
"tf",
".",
"executing_eagerly",
"(",
")",
":... | 37.333333 | 0.021834 |
def satoshi_to_currency_cached(num, currency):
"""Converts a given number of satoshi to another currency as a formatted
string rounded down to the proper number of decimal places. Results are
cached using a decorator for 60 seconds by default. See :ref:`cache times`.
:param num: The number of satoshi.
... | [
"def",
"satoshi_to_currency_cached",
"(",
"num",
",",
"currency",
")",
":",
"return",
"'{:f}'",
".",
"format",
"(",
"Decimal",
"(",
"num",
"/",
"Decimal",
"(",
"currency_to_satoshi_cached",
"(",
"1",
",",
"currency",
")",
")",
")",
".",
"quantize",
"(",
"D... | 36.578947 | 0.001403 |
def print_periodic_table(filter_function: callable = None):
"""
A pretty ASCII printer for the periodic table, based on some
filter_function.
Args:
filter_function: A filtering function taking an Element as input
and returning a boolean. For example, setting
... | [
"def",
"print_periodic_table",
"(",
"filter_function",
":",
"callable",
"=",
"None",
")",
":",
"for",
"row",
"in",
"range",
"(",
"1",
",",
"10",
")",
":",
"rowstr",
"=",
"[",
"]",
"for",
"group",
"in",
"range",
"(",
"1",
",",
"19",
")",
":",
"try",... | 40.869565 | 0.002079 |
def fetch_items(self, category, **kwargs):
"""Fetch the bugs
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
logger.info("Looking for bugs: '%s' updated from '%... | [
"def",
"fetch_items",
"(",
"self",
",",
"category",
",",
"*",
"*",
"kwargs",
")",
":",
"from_date",
"=",
"kwargs",
"[",
"'from_date'",
"]",
"logger",
".",
"info",
"(",
"\"Looking for bugs: '%s' updated from '%s'\"",
",",
"self",
".",
"url",
",",
"str",
"(",
... | 30.735294 | 0.001855 |
def destroy(name, call=None):
'''
destroy a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
... | [
"def",
"destroy",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called with -d, --destroy, '",
"'-a or --action.'",
")",
"__utils__",
"[",
"'cloud.fire_event'",
... | 26.948052 | 0.000465 |
def library_directories(self):
"""Return a list of directories containing any static libraries built by this IOTile."""
libs = self.find_products('library')
if len(libs) > 0:
return [os.path.join(self.output_folder)]
return [] | [
"def",
"library_directories",
"(",
"self",
")",
":",
"libs",
"=",
"self",
".",
"find_products",
"(",
"'library'",
")",
"if",
"len",
"(",
"libs",
")",
">",
"0",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"output_folder",
")"... | 29.444444 | 0.010989 |
def movie(image, filename=None, writer=None, fps=30):
"""
Create and save a movie - mp4, gif, etc - of the various
2D slices of a 3D ants image
Try this:
conda install -c conda-forge ffmpeg
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
... | [
"def",
"movie",
"(",
"image",
",",
"filename",
"=",
"None",
",",
"writer",
"=",
"None",
",",
"fps",
"=",
"30",
")",
":",
"image",
"=",
"image",
".",
"pad_image",
"(",
")",
"img_arr",
"=",
"image",
".",
"numpy",
"(",
")",
"minidx",
"=",
"max",
"("... | 26.326531 | 0.008969 |
def load(self, filename, set_current=True, add_where='end'):
"""
Load filename, create an editor instance and return it
*Warning* This is loading file, creating editor but not executing
the source code analysis -- the analysis must be done by the editor
plugin (in case multi... | [
"def",
"load",
"(",
"self",
",",
"filename",
",",
"set_current",
"=",
"True",
",",
"add_where",
"=",
"'end'",
")",
":",
"filename",
"=",
"osp",
".",
"abspath",
"(",
"to_text_string",
"(",
"filename",
")",
")",
"self",
".",
"starting_long_process",
".",
"... | 48.066667 | 0.00136 |
def get_object_handle(self, obj):
""" Gets the vrep object handle. """
if obj not in self._object_handles:
self._object_handles[obj] = self._get_object_handle(obj=obj)
return self._object_handles[obj] | [
"def",
"get_object_handle",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
"not",
"in",
"self",
".",
"_object_handles",
":",
"self",
".",
"_object_handles",
"[",
"obj",
"]",
"=",
"self",
".",
"_get_object_handle",
"(",
"obj",
"=",
"obj",
")",
"return",
... | 38.666667 | 0.008439 |
def from_instances(cls,
instances: Iterable['adi.Instance'],
min_count: Dict[str, int] = None,
max_vocab_size: Union[int, Dict[str, int]] = None,
non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES,
... | [
"def",
"from_instances",
"(",
"cls",
",",
"instances",
":",
"Iterable",
"[",
"'adi.Instance'",
"]",
",",
"min_count",
":",
"Dict",
"[",
"str",
",",
"int",
"]",
"=",
"None",
",",
"max_vocab_size",
":",
"Union",
"[",
"int",
",",
"Dict",
"[",
"str",
",",
... | 58.428571 | 0.009621 |
def _handle_response(res, delimiter):
"""Get an iterator over the CSV data from the response."""
if res.status_code == 200:
# Python 2 -- csv.reader will need bytes
if sys.version_info[0] < 3:
csv_io = BytesIO(res.content)
# Python 3 -- csv.reader needs str
else:
... | [
"def",
"_handle_response",
"(",
"res",
",",
"delimiter",
")",
":",
"if",
"res",
".",
"status_code",
"==",
"200",
":",
"# Python 2 -- csv.reader will need bytes",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"csv_io",
"=",
"BytesIO",
"(",
... | 40.214286 | 0.001736 |
def _update_sdss_coverage(
self):
""" update sdss coverage
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- ch... | [
"def",
"_update_sdss_coverage",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_update_sdss_coverage`` method'",
")",
"tableName",
"=",
"self",
".",
"dbTableName",
"# SELECT THE LOCATIONS NEEDING TO BE CHECKED",
"sqlQuery",
"=",
"u\"\"\"\n ... | 34.670732 | 0.002394 |
def versions():
'''
Check the version of active minions
CLI Example:
.. code-block:: bash
salt-run manage.versions
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
minions = client.cmd('*', 'test.version', timeout=__opts__['timeout'])
... | [
"def",
"versions",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"client",
"=",
"salt",
".",
"client",
".",
"get_local_client",
"(",
"__opts__",
"[",
"'conf_file'",
"]",
")",
"try",
":",
"minions",
"=",
"client",
".",
"cmd",
"(",
"'*'",
",",
"'test.version'",
... | 27.6 | 0.001908 |
def presign_v4(method, url, access_key, secret_key, session_token=None,
region=None, headers=None, expires=None, response_headers=None,
request_date=None):
"""
Calculates signature version '4' for regular presigned URLs.
:param method: Method to be presigned examples 'PUT', 'G... | [
"def",
"presign_v4",
"(",
"method",
",",
"url",
",",
"access_key",
",",
"secret_key",
",",
"session_token",
"=",
"None",
",",
"region",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"expires",
"=",
"None",
",",
"response_headers",
"=",
"None",
",",
"req... | 39.197917 | 0.000259 |
def find_counterpart_in(self, tree_b):
""" Finds a TreeNode counterpart for this node in tree_b
:param tree_b: target tree that hosts counterpart to this node
:return: TreeNode from tree_b that has the same timeperiod as self.timeperiod,
or None if no counterpart ware fou... | [
"def",
"find_counterpart_in",
"(",
"self",
",",
"tree_b",
")",
":",
"tree_b_hierarchy_entry",
"=",
"tree_b",
".",
"process_hierarchy",
".",
"get_by_qualifier",
"(",
"self",
".",
"time_qualifier",
")",
"if",
"not",
"tree_b_hierarchy_entry",
":",
"# special case when tr... | 55.9 | 0.008795 |
def calculate_reduce_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, C, H, W] ---> [N, 1, H, W]
2. [N, C, H, W] ---> [N, C, 1, W]
3. [N, C, H, W] ---> [N, C, H, 1]
4. [N, C, H, W] ---> [N, C, 1, 1]
5. [N, C, H, W] ---> [N, 1, 1, 1]
'''
check_... | [
"def",
"calculate_reduce_output_shapes",
"(",
"operator",
")",
":",
"check_input_and_output_numbers",
"(",
"operator",
",",
"input_count_range",
"=",
"1",
",",
"output_count_range",
"=",
"1",
")",
"check_input_and_output_types",
"(",
"operator",
",",
"good_input_types",
... | 36.777778 | 0.001963 |
def workflow_remove_stage(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /workflow-xxxx/removeStage API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fworkflow-xxxx%2FremoveStage
"""
return DXHTTPRequ... | [
"def",
"workflow_remove_stage",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/removeStage'",
"%",
"object_id",
",",
"input_params",
",",
"always_... | 57 | 0.009877 |
def IHDR(self):
"""
IHDR chunk in PNG image
"""
match = lambda chunk: chunk.type_name == PNG_CHUNK_TYPE.IHDR # noqa
IHDR = self._find_first(match)
if IHDR is None:
raise InvalidImageStreamError('no IHDR chunk in PNG image')
return IHDR | [
"def",
"IHDR",
"(",
"self",
")",
":",
"match",
"=",
"lambda",
"chunk",
":",
"chunk",
".",
"type_name",
"==",
"PNG_CHUNK_TYPE",
".",
"IHDR",
"# noqa",
"IHDR",
"=",
"self",
".",
"_find_first",
"(",
"match",
")",
"if",
"IHDR",
"is",
"None",
":",
"raise",
... | 32.888889 | 0.009868 |
def save_model(self, request, obj, form, change):
"""Add an ObjectPosition to the object."""
super(GenericPositionsAdmin, self).save_model(request, obj, form,
change)
c_type = ContentType.objects.get_for_model(obj)
try:
Ob... | [
"def",
"save_model",
"(",
"self",
",",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
":",
"super",
"(",
"GenericPositionsAdmin",
",",
"self",
")",
".",
"save_model",
"(",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
"c_type",
"=",
... | 48.111111 | 0.002265 |
def validation_requests(self):
"""
Access the validation_requests
:returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestList
:rtype: twilio.rest.api.v2010.account.validation_request.ValidationRequestList
"""
if self._validation_requests is None:
... | [
"def",
"validation_requests",
"(",
"self",
")",
":",
"if",
"self",
".",
"_validation_requests",
"is",
"None",
":",
"self",
".",
"_validation_requests",
"=",
"ValidationRequestList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",... | 46.2 | 0.010616 |
def load_json_object(file_name, default=None):
"""
Deserialized <file_name> into a Python object
:param str|unicode file_name: The name of the file to read
:param default: The value to return if the file is not found
"""
if not os.path.isfile(file_name):
return default
# use utf-8-s... | [
"def",
"load_json_object",
"(",
"file_name",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_name",
")",
":",
"return",
"default",
"# use utf-8-sig in case the file has a Byte Order Mark",
"with",
"codecs",
".",
"... | 33.947368 | 0.001508 |
def __sequenceAscendingStrict(l):
"Test a sequences values to be in strictly ascending order."
it = iter(l)
next(it)
if not all(b > a for a, b in zip(l, it)):
raise argparse.ArgumentTypeError('All values must be given in strictly ascending order.')
return l | [
"def",
"__sequenceAscendingStrict",
"(",
"l",
")",
":",
"it",
"=",
"iter",
"(",
"l",
")",
"next",
"(",
"it",
")",
"if",
"not",
"all",
"(",
"b",
">",
"a",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"l",
",",
"it",
")",
")",
":",
"raise",
"argpars... | 39.857143 | 0.010526 |
def dumpb(self, obj, *, max_nested_level=100):
"""Similar to ``dumps()``, but returns ``bytes`` instead of a ``string``"""
self._max_nested_level = max_nested_level
return self._encode(obj).encode('utf-8') | [
"def",
"dumpb",
"(",
"self",
",",
"obj",
",",
"*",
",",
"max_nested_level",
"=",
"100",
")",
":",
"self",
".",
"_max_nested_level",
"=",
"max_nested_level",
"return",
"self",
".",
"_encode",
"(",
"obj",
")",
".",
"encode",
"(",
"'utf-8'",
")"
] | 56.5 | 0.0131 |
def secure(func_or_obj, check_permissions_for_obj=None):
"""
This method secures a method or class depending on invocation.
To decorate a method use one argument:
@secure(<check_permissions_method>)
To secure a class, invoke with two arguments:
secure(<obj instance>, <check_permissions... | [
"def",
"secure",
"(",
"func_or_obj",
",",
"check_permissions_for_obj",
"=",
"None",
")",
":",
"if",
"_allowed_check_permissions_types",
"(",
"func_or_obj",
")",
":",
"return",
"_secure_method",
"(",
"func_or_obj",
")",
"else",
":",
"if",
"not",
"_allowed_check_permi... | 40.555556 | 0.001339 |
def notify_systemd():
'''
Notify systemd that this process has started
'''
try:
import systemd.daemon
except ImportError:
if salt.utils.path.which('systemd-notify') \
and systemd_notify_call('--booted'):
# Notify systemd synchronously
notify_so... | [
"def",
"notify_systemd",
"(",
")",
":",
"try",
":",
"import",
"systemd",
".",
"daemon",
"except",
"ImportError",
":",
"if",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'systemd-notify'",
")",
"and",
"systemd_notify_call",
"(",
"'--booted'",
")",
... | 35.16129 | 0.000893 |
def simple_edge_to_wkt_linestring(edge):
'''
Coverts a simple fault trace to well-known text format
:param trace:
Fault trace as instance of :class: openquake.hazardlib.geo.line.Line
:returns:
Well-known text (WKT) Linstring representation of the trace
'''
trace_str = ""
fo... | [
"def",
"simple_edge_to_wkt_linestring",
"(",
"edge",
")",
":",
"trace_str",
"=",
"\"\"",
"for",
"point",
"in",
"edge",
":",
"trace_str",
"+=",
"' %s %s %s,'",
"%",
"(",
"point",
".",
"longitude",
",",
"point",
".",
"latitude",
",",
"point",
".",
"depth",
"... | 33.4375 | 0.001818 |
def install_monitor(self, mon):
"""Installs monitor on all executors """
assert self.binded
self._monitor = mon
for mod in self._buckets.values():
mod.install_monitor(mon) | [
"def",
"install_monitor",
"(",
"self",
",",
"mon",
")",
":",
"assert",
"self",
".",
"binded",
"self",
".",
"_monitor",
"=",
"mon",
"for",
"mod",
"in",
"self",
".",
"_buckets",
".",
"values",
"(",
")",
":",
"mod",
".",
"install_monitor",
"(",
"mon",
"... | 35 | 0.009302 |
def z2h(text, ignore='', kana=True, ascii=False, digit=False):
"""Convert Full-width (Zenkaku) Katakana to Half-width (Hankaku) Katakana
Parameters
----------
text : str
Full-width Katakana string.
ignore : str
Characters to be ignored in converting.
kana : bool
Either c... | [
"def",
"z2h",
"(",
"text",
",",
"ignore",
"=",
"''",
",",
"kana",
"=",
"True",
",",
"ascii",
"=",
"False",
",",
"digit",
"=",
"False",
")",
":",
"if",
"ascii",
":",
"if",
"digit",
":",
"if",
"kana",
":",
"z2h_map",
"=",
"Z2H_ALL",
"else",
":",
... | 23.25 | 0.000794 |
def _update_raster_info(self, **update_props):
""" Ensures complete removal of raster_info given the two roots: <spdoinfo> and <spref> """
xpath_map = self._data_structures[update_props['prop']]
return [
update_complex(xpath_root=self._data_map.get('_raster_info_root'), xpath_map=x... | [
"def",
"_update_raster_info",
"(",
"self",
",",
"*",
"*",
"update_props",
")",
":",
"xpath_map",
"=",
"self",
".",
"_data_structures",
"[",
"update_props",
"[",
"'prop'",
"]",
"]",
"return",
"[",
"update_complex",
"(",
"xpath_root",
"=",
"self",
".",
"_data_... | 51.555556 | 0.010593 |
def positive_directional_movement(high_data, low_data):
"""
Positive Directional Movement (+DM).
Formula:
+DM: if UPMOVE > DWNMOVE and UPMOVE > 0 then +DM = UPMOVE else +DM = 0
"""
catch_errors.check_for_input_len_diff(high_data, low_data)
up_moves = calculate_up_moves(high_data)
down_m... | [
"def",
"positive_directional_movement",
"(",
"high_data",
",",
"low_data",
")",
":",
"catch_errors",
".",
"check_for_input_len_diff",
"(",
"high_data",
",",
"low_data",
")",
"up_moves",
"=",
"calculate_up_moves",
"(",
"high_data",
")",
"down_moves",
"=",
"calculate_do... | 29.105263 | 0.001751 |
def check_type_and_values_of_alt_name_dict(alt_name_dict, alt_id_col, df):
"""
Ensures that `alt_name_dict` is a dictionary and that its keys are in the
alternative id column of `df`. Raises helpful errors if either condition
is not met.
Parameters
----------
alt_name_dict : dict.
A... | [
"def",
"check_type_and_values_of_alt_name_dict",
"(",
"alt_name_dict",
",",
"alt_id_col",
",",
"df",
")",
":",
"if",
"not",
"isinstance",
"(",
"alt_name_dict",
",",
"dict",
")",
":",
"msg",
"=",
"\"alt_name_dict should be a dictionary. Passed value was a {}\"",
"raise",
... | 35.75 | 0.000851 |
def substitute_globals(config_dict):
"""
Set global variables to values defined in `config_dict`.
Args:
config_dict (dict): dictionary with data, which are used to set \
`globals`.
Note:
`config_dict` have to be dictionary, or it is ignored. Also all
... | [
"def",
"substitute_globals",
"(",
"config_dict",
")",
":",
"constants",
"=",
"get_all_constants",
"(",
")",
"if",
"type",
"(",
"config_dict",
")",
"!=",
"dict",
":",
"return",
"for",
"key",
"in",
"config_dict",
".",
"keys",
"(",
")",
":",
"if",
"key",
"i... | 32.227273 | 0.00137 |
def qteKillApplet(self, appletID: str):
"""
Destroy the applet with ID ``appletID``.
This method removes ``appletID`` from Qtmacs permanently - no
questions asked. It is the responsibility of the (macro)
programmer to use it responsibly.
If the applet was visible then t... | [
"def",
"qteKillApplet",
"(",
"self",
",",
"appletID",
":",
"str",
")",
":",
"# Compile list of all applet IDs.",
"ID_list",
"=",
"[",
"_",
".",
"qteAppletID",
"(",
")",
"for",
"_",
"in",
"self",
".",
"_qteAppletList",
"]",
"if",
"appletID",
"not",
"in",
"I... | 35.177215 | 0.0007 |
def RunOnce(self):
"""Main CronHook method."""
# Start the cron thread if configured to.
if config.CONFIG["Cron.active"]:
self.cron_worker = CronWorker()
self.cron_worker.RunAsync() | [
"def",
"RunOnce",
"(",
"self",
")",
":",
"# Start the cron thread if configured to.",
"if",
"config",
".",
"CONFIG",
"[",
"\"Cron.active\"",
"]",
":",
"self",
".",
"cron_worker",
"=",
"CronWorker",
"(",
")",
"self",
".",
"cron_worker",
".",
"RunAsync",
"(",
")... | 28.571429 | 0.014563 |
def changed(self):
"""Returns dict of fields that changed since save (with old values)"""
return dict(
(field, self.previous(field))
for field in self.fields
if self.has_changed(field)
) | [
"def",
"changed",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"field",
",",
"self",
".",
"previous",
"(",
"field",
")",
")",
"for",
"field",
"in",
"self",
".",
"fields",
"if",
"self",
".",
"has_changed",
"(",
"field",
")",
")"
] | 34.285714 | 0.00813 |
def partition(pred, iterable):
"""Partition an iterable.
Arguments
---------
pred : function
A function that takes an element of the iterable and returns
a boolen indicating to which partition it belongs
iterable : iterable
Returns
-------
A two-tuple ... | [
"def",
"partition",
"(",
"pred",
",",
"iterable",
")",
":",
"pos",
",",
"neg",
"=",
"[",
"]",
",",
"[",
"]",
"pos_append",
",",
"neg_append",
"=",
"pos",
".",
"append",
",",
"neg",
".",
"append",
"for",
"elem",
"in",
"iterable",
":",
"if",
"pred",
... | 29.296296 | 0.001224 |
def timeout(self):
'''Returns either the default plugin timeout value, the value as
provided on the commandline via -k plugin.timeout=value, or the value
of the global --plugin-timeout option.
'''
_timeout = None
try:
opt_timeout = self.get_option('plugin_time... | [
"def",
"timeout",
"(",
"self",
")",
":",
"_timeout",
"=",
"None",
"try",
":",
"opt_timeout",
"=",
"self",
".",
"get_option",
"(",
"'plugin_timeout'",
")",
"own_timeout",
"=",
"int",
"(",
"self",
".",
"get_option",
"(",
"'timeout'",
")",
")",
"if",
"opt_t... | 41.090909 | 0.002162 |
def _calculate_workers():
'''
Determine the number of worker processes based on the CPU
count of the unit containing the application.
Workers will be limited to MAX_DEFAULT_WORKERS in
container environments where no worker-multipler configuration
option been set.
@returns int: number of wo... | [
"def",
"_calculate_workers",
"(",
")",
":",
"multiplier",
"=",
"config",
"(",
"'worker-multiplier'",
")",
"or",
"DEFAULT_MULTIPLIER",
"count",
"=",
"int",
"(",
"_num_cpus",
"(",
")",
"*",
"multiplier",
")",
"if",
"multiplier",
">",
"0",
"and",
"count",
"==",... | 36.16 | 0.001078 |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._counter_alias is not None:
r... | [
"def",
"is_all_field_none",
"(",
"self",
")",
":",
"if",
"self",
".",
"_id_",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_created",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_updated",
"is",
"not",
"None",
... | 20.955556 | 0.002026 |
def create_shared_data(self, **kwargs):
"""Creates shared data on disk with a StorageService on disk.
Needs to be called before shared data can be used later on.
Actual arguments of ``kwargs`` depend on the type of data to be
created. For instance, creating an array one can use the key... | [
"def",
"create_shared_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'flag'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'flag'",
"]",
"=",
"self",
".",
"FLAG",
"if",
"'data'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'obj'",
"]",
"=",
... | 43.714286 | 0.002398 |
def gen_lock(self, lock_type='update', timeout=0, poll_interval=0.5):
'''
Set and automatically clear a lock
'''
if not isinstance(lock_type, six.string_types):
raise GitLockError(
errno.EINVAL,
'Invalid lock_type \'{0}\''.format(lock_type)
... | [
"def",
"gen_lock",
"(",
"self",
",",
"lock_type",
"=",
"'update'",
",",
"timeout",
"=",
"0",
",",
"poll_interval",
"=",
"0.5",
")",
":",
"if",
"not",
"isinstance",
"(",
"lock_type",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"GitLockError",
"(",... | 36.038462 | 0.001039 |
def compute_balance_median_ts(self, ts):
""" Compute the balance at each time 't' of the time series."""
balance = [self.compute_balance_median(ts, t) for t in np.arange(0, len(ts) - 1)]
return balance | [
"def",
"compute_balance_median_ts",
"(",
"self",
",",
"ts",
")",
":",
"balance",
"=",
"[",
"self",
".",
"compute_balance_median",
"(",
"ts",
",",
"t",
")",
"for",
"t",
"in",
"np",
".",
"arange",
"(",
"0",
",",
"len",
"(",
"ts",
")",
"-",
"1",
")",
... | 55.5 | 0.013333 |
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplica... | [
"def",
"_read_repos",
"(",
"conf_file",
",",
"repos",
",",
"filename",
",",
"regex",
")",
":",
"for",
"line",
"in",
"conf_file",
":",
"line",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"line",
")",
"if",
"not",
"regex",
".",... | 30.307692 | 0.002463 |
def wind_series(self):
"""Returns the wind speed time series relative to the
meteostation, in the form of a list of tuples, each one containing the
couple timestamp-value
:returns: a list of tuples
"""
return [(timestamp, \
self._station_history.get_measu... | [
"def",
"wind_series",
"(",
"self",
")",
":",
"return",
"[",
"(",
"timestamp",
",",
"self",
".",
"_station_history",
".",
"get_measurements",
"(",
")",
"[",
"timestamp",
"]",
"[",
"'wind'",
"]",
")",
"for",
"timestamp",
"in",
"self",
".",
"_station_history"... | 41.7 | 0.00939 |
def send_handle_put_request(self, **args):
'''
Send a HTTP PUT request to the handle server to write either an entire
handle or to some specified values to an handle record, using the
requests module.
:param handle: The handle.
:param list_of_entries: A list of h... | [
"def",
"send_handle_put_request",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"# Check if we have write access at all:",
"if",
"not",
"self",
".",
"__has_write_access",
":",
"raise",
"HandleAuthenticationError",
"(",
"msg",
"=",
"self",
".",
"__no_auth_message",
"... | 42.803571 | 0.002447 |
def publish_pushdb_changes_to_remote_scm(self, pushdb_file, coordinate, tag_name, tag_message,
postscript=None):
"""Push pushdb changes to the remote scm repository, and then tag the commit if it succeeds."""
self._add_pushdb(pushdb_file)
self.commit_pushdb(coordi... | [
"def",
"publish_pushdb_changes_to_remote_scm",
"(",
"self",
",",
"pushdb_file",
",",
"coordinate",
",",
"tag_name",
",",
"tag_message",
",",
"postscript",
"=",
"None",
")",
":",
"self",
".",
"_add_pushdb",
"(",
"pushdb_file",
")",
"self",
".",
"commit_pushdb",
"... | 50.1 | 0.009804 |
def rgb_color_picker(obj, min_luminance=None, max_luminance=None):
"""Modified version of colour.RGB_color_picker"""
color_value = int.from_bytes(
hashlib.md5(str(obj).encode('utf-8')).digest(),
'little',
) % 0xffffff
color = Color(f'#{color_value:06x}')
if min_luminance and color.ge... | [
"def",
"rgb_color_picker",
"(",
"obj",
",",
"min_luminance",
"=",
"None",
",",
"max_luminance",
"=",
"None",
")",
":",
"color_value",
"=",
"int",
".",
"from_bytes",
"(",
"hashlib",
".",
"md5",
"(",
"str",
"(",
"obj",
")",
".",
"encode",
"(",
"'utf-8'",
... | 42.333333 | 0.001927 |
def _do_link_patterns(self, text):
"""Caveat emptor: there isn't much guarding against link
patterns being formed inside other standard Markdown links, e.g.
inside a [link def][like this].
Dev Notes: *Could* consider prefixing regexes with a negative
lookbehind assertion to atte... | [
"def",
"_do_link_patterns",
"(",
"self",
",",
"text",
")",
":",
"link_from_hash",
"=",
"{",
"}",
"for",
"regex",
",",
"repl",
"in",
"self",
".",
"link_patterns",
":",
"replacements",
"=",
"[",
"]",
"for",
"match",
"in",
"regex",
".",
"finditer",
"(",
"... | 46.166667 | 0.002122 |
def print_res(data):
""" Print translate result in a better format
Args:
data(str): result
"""
print('===================================')
main_part = data['data']
print(main_part['word_name'])
symbols = main_part['symbols'][0]
print("美式音标:[" + symbols['ph_am'] + "]")
print(... | [
"def",
"print_res",
"(",
"data",
")",
":",
"print",
"(",
"'==================================='",
")",
"main_part",
"=",
"data",
"[",
"'data'",
"]",
"print",
"(",
"main_part",
"[",
"'word_name'",
"]",
")",
"symbols",
"=",
"main_part",
"[",
"'symbols'",
"]",
... | 32.333333 | 0.001669 |
def registerEventHandlers(self):
"""
Registers event handlers used by this widget, e.g. mouse click/motion and window resize.
This will allow the widget to redraw itself upon resizing of the window in case the position needs to be adjusted.
"""
self.peng.registerEventHan... | [
"def",
"registerEventHandlers",
"(",
"self",
")",
":",
"self",
".",
"peng",
".",
"registerEventHandler",
"(",
"\"on_mouse_press\"",
",",
"self",
".",
"on_mouse_press",
")",
"self",
".",
"peng",
".",
"registerEventHandler",
"(",
"\"on_mouse_release\"",
",",
"self",... | 59.454545 | 0.016566 |
def clone_model(instance, cls, commit: bool=True, exclude_fields: tuple=('id',), base_class_suffix: str='_ptr', **kw):
"""
Assigns model fields to new object. Ignores exclude_fields list and
attributes ending with pointer suffix (default '_ptr')
:param instance: Instance to copy
:param cls: Class na... | [
"def",
"clone_model",
"(",
"instance",
",",
"cls",
",",
"commit",
":",
"bool",
"=",
"True",
",",
"exclude_fields",
":",
"tuple",
"=",
"(",
"'id'",
",",
")",
",",
"base_class_suffix",
":",
"str",
"=",
"'_ptr'",
",",
"*",
"*",
"kw",
")",
":",
"keys",
... | 42.904762 | 0.010858 |
def reroot(self, first_node, last_node):
"""
Notes:
● Pick any occurrence of the new root r.
● Split the tour into A and B, where B is the
part of the tour before r.
● Delete the first node of A and append r.
● Concatenate B and A.
... | [
"def",
"reroot",
"(",
"self",
",",
"first_node",
",",
"last_node",
")",
":",
"min_elem",
"=",
"self",
".",
"min_elem",
"(",
")",
"if",
"min_elem",
"==",
"first_node",
".",
"value",
":",
"print",
"(",
"'Already rooted there'",
")",
"return",
"# tour = list(se... | 41.356522 | 0.000616 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.