text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _CheckStatusAnalysisProcess(self, pid):
"""Checks the status of an analysis process.
Args:
pid (int): process ID (PID) of a registered analysis process.
Raises:
KeyError: if the process is not registered with the engine.
"""
# TODO: Refactor this method, simplify and separate conce... | [
"def",
"_CheckStatusAnalysisProcess",
"(",
"self",
",",
"pid",
")",
":",
"# TODO: Refactor this method, simplify and separate concerns (monitoring",
"# vs management).",
"self",
".",
"_RaiseIfNotRegistered",
"(",
"pid",
")",
"if",
"pid",
"in",
"self",
".",
"_completed_analy... | 34.61039 | 0.008391 |
def ch_stop_time(self, *channels: List[Channel]) -> int:
"""Return maximum start time for supplied channels.
Args:
*channels: Supplied channels
"""
return self.timeslots.ch_stop_time(*channels) | [
"def",
"ch_stop_time",
"(",
"self",
",",
"*",
"channels",
":",
"List",
"[",
"Channel",
"]",
")",
"->",
"int",
":",
"return",
"self",
".",
"timeslots",
".",
"ch_stop_time",
"(",
"*",
"channels",
")"
] | 33.142857 | 0.008403 |
def check_arrays_survival(X, y, **kwargs):
"""Check that all arrays have consistent first dimensions.
Parameters
----------
X : array-like
Data matrix containing feature vectors.
y : structured array with two fields
A structured array containing the binary event indicator
a... | [
"def",
"check_arrays_survival",
"(",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"event",
",",
"time",
"=",
"check_y_survival",
"(",
"y",
")",
"kwargs",
".",
"setdefault",
"(",
"\"dtype\"",
",",
"numpy",
".",
"float64",
")",
"X",
"=",
"check_arra... | 29.4375 | 0.001028 |
def taskfile_user_data(file_, role):
"""Return the data for user
:param file_: the file that holds the data
:type file_: :class:`jukeboxcore.djadapter.models.File`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the user
:rtype: depending on role
:raise... | [
"def",
"taskfile_user_data",
"(",
"file_",
",",
"role",
")",
":",
"if",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"DisplayRole",
"or",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"EditRole",
":",
"return",
"file_",
".",
"user",
".",
"username"
] | 32.769231 | 0.002283 |
def parse(self, argument):
"""See base class."""
if isinstance(argument, list):
return argument
elif not argument:
return []
else:
return [s.strip() for s in argument.split(self._token)] | [
"def",
"parse",
"(",
"self",
",",
"argument",
")",
":",
"if",
"isinstance",
"(",
"argument",
",",
"list",
")",
":",
"return",
"argument",
"elif",
"not",
"argument",
":",
"return",
"[",
"]",
"else",
":",
"return",
"[",
"s",
".",
"strip",
"(",
")",
"... | 26.625 | 0.018182 |
def setup(self, steps=None, drop_na=False, **kwargs):
''' Set up the sequence of steps for analysis.
Args:
steps (list): Optional list of steps to set up. Each element
must be either an int giving the index of the step in the
JSON config block list, or a str ... | [
"def",
"setup",
"(",
"self",
",",
"steps",
"=",
"None",
",",
"drop_na",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# In the beginning, there was nothing",
"input_nodes",
"=",
"None",
"# Use inputs from model, and update with kwargs",
"selectors",
"=",
"self",... | 41.448276 | 0.001626 |
def centroid(X):
"""
Calculate the centroid from a matrix X
"""
C = np.sum(X, axis=0) / len(X)
return C | [
"def",
"centroid",
"(",
"X",
")",
":",
"C",
"=",
"np",
".",
"sum",
"(",
"X",
",",
"axis",
"=",
"0",
")",
"/",
"len",
"(",
"X",
")",
"return",
"C"
] | 19.666667 | 0.00813 |
def push_zipkin_attrs(zipkin_attr):
"""Stores the zipkin attributes to thread local.
.. deprecated::
Use the Tracer interface which offers better multi-threading support.
push_zipkin_attrs will be removed in version 1.0.
:param zipkin_attr: tuple containing zipkin related attrs
:type zip... | [
"def",
"push_zipkin_attrs",
"(",
"zipkin_attr",
")",
":",
"from",
"py_zipkin",
".",
"storage",
"import",
"ThreadLocalStack",
"log",
".",
"warning",
"(",
"'push_zipkin_attrs is deprecated. See DEPRECATIONS.rst for'",
"'details on how to migrate to using Tracer.'",
")",
"return",... | 42.071429 | 0.001661 |
def compute_cumsum(
df,
id_cols: List[str],
reference_cols: List[str],
value_cols: List[str],
new_value_cols: List[str] = None,
cols_to_keep: List[str] = None
):
"""
Compute cumsum for a group of columns.
---
### Parameters
*mandatory :*
- `id_cols` (*list*): the colum... | [
"def",
"compute_cumsum",
"(",
"df",
",",
"id_cols",
":",
"List",
"[",
"str",
"]",
",",
"reference_cols",
":",
"List",
"[",
"str",
"]",
",",
"value_cols",
":",
"List",
"[",
"str",
"]",
",",
"new_value_cols",
":",
"List",
"[",
"str",
"]",
"=",
"None",
... | 26.194444 | 0.001533 |
def apply_gates_to_fd(stilde_dict, gates):
"""Applies the given dictionary of gates to the given dictionary of
strain in the frequency domain.
Gates are applied by IFFT-ing the strain data to the time domain, applying
the gate, then FFT-ing back to the frequency domain.
Parameters
----------
... | [
"def",
"apply_gates_to_fd",
"(",
"stilde_dict",
",",
"gates",
")",
":",
"# copy data to new dictionary",
"outdict",
"=",
"dict",
"(",
"stilde_dict",
".",
"items",
"(",
")",
")",
"# create a time-domin strain dictionary to apply the gates to",
"strain_dict",
"=",
"dict",
... | 37.931034 | 0.001773 |
def best_tile_layout(pool_size):
""" Determine and return the best layout of "tiles" for fastest
overall parallel processing of a rectangular image broken up into N
smaller equally-sized rectangular tiles, given as input the number
of processes/chunks which can be run/worked at the same time (pool_size)... | [
"def",
"best_tile_layout",
"(",
"pool_size",
")",
":",
"# Easy answer sanity-checks",
"if",
"pool_size",
"<",
"2",
":",
"return",
"(",
"1",
",",
"1",
")",
"# Next, use a small mapping of hard-coded results. While we agree",
"# that many of these are unlikely pool_size values, ... | 43.111111 | 0.01974 |
def ref_build_and_muscle_chunk(data, sample):
"""
1. Run bedtools to get all overlapping regions
2. Parse out reads from regions using pysam and dump into chunk files.
We measure it out to create 10 chunk files per sample.
3. If we really wanted to speed this up, though it is pretty fast alrea... | [
"def",
"ref_build_and_muscle_chunk",
"(",
"data",
",",
"sample",
")",
":",
"## get regions using bedtools",
"regions",
"=",
"bedtools_merge",
"(",
"data",
",",
"sample",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"nregions",
"=",
"len",
... | 41.7 | 0.00937 |
def shift(self,
periods: int,
axis: libinternals.BlockPlacement = 0,
fill_value: Any = None) -> List['ExtensionBlock']:
"""
Shift the block by `periods`.
Dispatches to underlying ExtensionArray and re-boxes in an
ExtensionBlock.
"""
... | [
"def",
"shift",
"(",
"self",
",",
"periods",
":",
"int",
",",
"axis",
":",
"libinternals",
".",
"BlockPlacement",
"=",
"0",
",",
"fill_value",
":",
"Any",
"=",
"None",
")",
"->",
"List",
"[",
"'ExtensionBlock'",
"]",
":",
"return",
"[",
"self",
".",
... | 33.333333 | 0.009728 |
def validate_empty_values(self, data):
"""
Validate empty values, and either:
* Raise `ValidationError`, indicating invalid data.
* Raise `SkipField`, indicating that the field should be ignored.
* Return (True, data), indicating an empty value that should be
returned ... | [
"def",
"validate_empty_values",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"read_only",
":",
"return",
"(",
"True",
",",
"self",
".",
"get_default",
"(",
")",
")",
"if",
"data",
"is",
"empty",
":",
"if",
"getattr",
"(",
"self",
".",
"root... | 34.407407 | 0.002094 |
def SensorsDelete(self, sensor_id):
"""
Delete a sensor from CommonSense.
@param sensor_id (int) - Sensor id of sensor to delete from CommonSense.
@return (bool) - Boolean indicating whether SensorsDelete was successful.
"""
i... | [
"def",
"SensorsDelete",
"(",
"self",
",",
"sensor_id",
")",
":",
"if",
"self",
".",
"__SenseApiCall__",
"(",
"'/sensors/{0}.json'",
".",
"format",
"(",
"sensor_id",
")",
",",
"'DELETE'",
")",
":",
"return",
"True",
"else",
":",
"self",
".",
"__error__",
"=... | 38.538462 | 0.013645 |
def extract_tree(self, labels, without, suppress_unifurcations=True):
'''Helper function for ``extract_tree_*`` functions'''
if not isinstance(suppress_unifurcations, bool):
raise TypeError("suppress_unifurcations must be a bool")
if labels is not None and not isinstance(labels, set)... | [
"def",
"extract_tree",
"(",
"self",
",",
"labels",
",",
"without",
",",
"suppress_unifurcations",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"suppress_unifurcations",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"suppress_unifurcations must be a... | 50.206897 | 0.009434 |
def __draw_cluster_item_multi_dimension(self, ax, pair, item, cluster_descr):
"""!
@brief Draw cluster chunk defined by pair coordinates in data space with dimension greater than 1.
@param[in] ax (axis): Matplotlib axis that is used to display chunk of cluster point.
@param[in] pai... | [
"def",
"__draw_cluster_item_multi_dimension",
"(",
"self",
",",
"ax",
",",
"pair",
",",
"item",
",",
"cluster_descr",
")",
":",
"index_dimension1",
"=",
"pair",
"[",
"0",
"]",
"index_dimension2",
"=",
"pair",
"[",
"1",
"]",
"if",
"cluster_descr",
".",
"data"... | 54.25 | 0.008152 |
def generate_instance_identity_document(instance):
"""
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html
A JSON file that describes an instance. Usually retrieved by URL:
http://169.254.169.254/latest/dynamic/instance-identity/document
Here we just fill a dictionar... | [
"def",
"generate_instance_identity_document",
"(",
"instance",
")",
":",
"document",
"=",
"{",
"'devPayProductCodes'",
":",
"None",
",",
"'availabilityZone'",
":",
"instance",
".",
"placement",
"[",
"'AvailabilityZone'",
"]",
",",
"'privateIp'",
":",
"instance",
"."... | 36.566667 | 0.000888 |
def simple_pattern_exists_in_gcs(file_pattern, credentials=None):
"""True iff an object exists matching the input GCS pattern.
The GCS pattern must be a full object reference or a "simple pattern" that
conforms to the dsub input and output parameter restrictions:
* No support for **, ? wildcards or [] chara... | [
"def",
"simple_pattern_exists_in_gcs",
"(",
"file_pattern",
",",
"credentials",
"=",
"None",
")",
":",
"if",
"'*'",
"not",
"in",
"file_pattern",
":",
"return",
"_file_exists_in_gcs",
"(",
"file_pattern",
",",
"credentials",
")",
"if",
"not",
"file_pattern",
".",
... | 39.368421 | 0.010437 |
def line(
xo: int, yo: int, xd: int, yd: int, py_callback: Callable[[int, int], bool]
) -> bool:
""" Iterate over a line using a callback function.
Your callback function will take x and y parameters and return True to
continue iteration or False to stop iteration and return.
This function include... | [
"def",
"line",
"(",
"xo",
":",
"int",
",",
"yo",
":",
"int",
",",
"xd",
":",
"int",
",",
"yd",
":",
"int",
",",
"py_callback",
":",
"Callable",
"[",
"[",
"int",
",",
"int",
"]",
",",
"bool",
"]",
")",
"->",
"bool",
":",
"for",
"x",
",",
"y"... | 30.580645 | 0.001022 |
def imp_print(self, text, end):
"""Directly send utf8 bytes to stdout"""
sys.stdout.write((text + end).encode("utf-8")) | [
"def",
"imp_print",
"(",
"self",
",",
"text",
",",
"end",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"(",
"text",
"+",
"end",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")"
] | 40.333333 | 0.03252 |
def check_ns_run(run, dup_assert=False, dup_warn=False):
"""Checks a nestcheck format nested sampling run dictionary has the
expected properties (see the data_processing module docstring for more
details).
Parameters
----------
run: dict
nested sampling run to check.
dup_assert: boo... | [
"def",
"check_ns_run",
"(",
"run",
",",
"dup_assert",
"=",
"False",
",",
"dup_warn",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"run",
",",
"dict",
")",
"check_ns_run_members",
"(",
"run",
")",
"check_ns_run_logls",
"(",
"run",
",",
"dup_assert",
... | 28.541667 | 0.001412 |
def configGet(self, vartype, category, name, optional=False, specialReturnMessage=None):
"""
Wraps a try / except and a check for self.filename around ConfigParser
as it talks to the configuration file.
Also, checks for existence of configuration file so this won't execute (and fail)
when no config... | [
"def",
"configGet",
"(",
"self",
",",
"vartype",
",",
"category",
",",
"name",
",",
"optional",
"=",
"False",
",",
"specialReturnMessage",
"=",
"None",
")",
":",
"try",
":",
"if",
"vartype",
"==",
"'float'",
":",
"var",
"=",
"self",
".",
"config",
".",... | 46.2 | 0.013487 |
def user_log_list(self, userid, cur_p=''):
'''
View the list of the Log.
'''
if cur_p == '':
current_page_number = 1
else:
current_page_number = int(cur_p)
current_page_number = 1 if current_page_number < 1 else current_page_number
pager... | [
"def",
"user_log_list",
"(",
"self",
",",
"userid",
",",
"cur_p",
"=",
"''",
")",
":",
"if",
"cur_p",
"==",
"''",
":",
"current_page_number",
"=",
"1",
"else",
":",
"current_page_number",
"=",
"int",
"(",
"cur_p",
")",
"current_page_number",
"=",
"1",
"i... | 33.815789 | 0.002269 |
def grok_keys(config):
"""Will retrieve a GPG key from either Keybase or GPG directly"""
key_ids = []
for key in config['pgp_keys']:
if key.startswith('keybase:'):
key_id = from_keybase(key[8:])
LOG.debug("Encrypting for keybase user %s", key[8:])
else:
if... | [
"def",
"grok_keys",
"(",
"config",
")",
":",
"key_ids",
"=",
"[",
"]",
"for",
"key",
"in",
"config",
"[",
"'pgp_keys'",
"]",
":",
"if",
"key",
".",
"startswith",
"(",
"'keybase:'",
")",
":",
"key_id",
"=",
"from_keybase",
"(",
"key",
"[",
"8",
":",
... | 32.111111 | 0.001681 |
def filesystems(config='/etc/filesystems'):
'''
.. versionadded:: 2018.3.3
List the contents of the filesystems
CLI Example:
.. code-block:: bash
salt '*' mount.filesystems
'''
ret = {}
if 'AIX' not in __grains__['kernel']:
return ret
ret_dict = _filesystems(conf... | [
"def",
"filesystems",
"(",
"config",
"=",
"'/etc/filesystems'",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"'AIX'",
"not",
"in",
"__grains__",
"[",
"'kernel'",
"]",
":",
"return",
"ret",
"ret_dict",
"=",
"_filesystems",
"(",
"config",
")",
"if",
"ret_dict",
"... | 19.545455 | 0.002217 |
def setup_parametrization(result, parametrize):
"""Modifies result's data according to the parametrization settings."""
if parametrize:
# remove parameters from title
title = result.get("title")
if title:
result["title"] = TEST_PARAM_RE.sub("", title)
else:
# don'... | [
"def",
"setup_parametrization",
"(",
"result",
",",
"parametrize",
")",
":",
"if",
"parametrize",
":",
"# remove parameters from title",
"title",
"=",
"result",
".",
"get",
"(",
"\"title\"",
")",
"if",
"title",
":",
"result",
"[",
"\"title\"",
"]",
"=",
"TEST_... | 38 | 0.002336 |
def use_in(ContentHandler):
"""
Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table,
Column, and Stream classes defined in this module when parsing XML
documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class LIGOLWContentHandler(ligolw.LIGO... | [
"def",
"use_in",
"(",
"ContentHandler",
")",
":",
"def",
"startColumn",
"(",
"self",
",",
"parent",
",",
"attrs",
")",
":",
"return",
"Column",
"(",
"attrs",
")",
"def",
"startStream",
"(",
"self",
",",
"parent",
",",
"attrs",
",",
"__orig_startStream",
... | 28.575758 | 0.030769 |
def _simplify_feature_value(self, name, value):
"""Return simplified and more pythonic feature values."""
if name == 'prefix':
channel_modes, channel_chars = value.split(')')
channel_modes = channel_modes[1:]
# [::-1] to reverse order and go from lowest to highest pr... | [
"def",
"_simplify_feature_value",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"name",
"==",
"'prefix'",
":",
"channel_modes",
",",
"channel_chars",
"=",
"value",
".",
"split",
"(",
"')'",
")",
"channel_modes",
"=",
"channel_modes",
"[",
"1",
":... | 31.615385 | 0.001574 |
def get_entries(latest, filters, exclude, limit=None):
"""
Lists all available instances.
:param latest: If true, ignores the cache and grabs the latest list.
:type latest: ``bool``
:param filters: Filters to apply to results. A result will only be shown
if it includes all text ... | [
"def",
"get_entries",
"(",
"latest",
",",
"filters",
",",
"exclude",
",",
"limit",
"=",
"None",
")",
":",
"entry_list",
"=",
"_list_all_latest",
"(",
")",
"if",
"latest",
"is",
"True",
"or",
"not",
"_is_valid_cache",
"(",
")",
"else",
"_list_all_cached",
"... | 39.08 | 0.001998 |
def exp(self):
""" Returns the exponent of the quaternion.
(not tested)
"""
# Init
vecNorm = self.x**2 + self.y**2 + self.z**2
wPart = np.exp(self.w)
q = Quaternion()
# Calculate
q.w = wPart * np.cos(vecNorm)
q.x ... | [
"def",
"exp",
"(",
"self",
")",
":",
"# Init",
"vecNorm",
"=",
"self",
".",
"x",
"**",
"2",
"+",
"self",
".",
"y",
"**",
"2",
"+",
"self",
".",
"z",
"**",
"2",
"wPart",
"=",
"np",
".",
"exp",
"(",
"self",
".",
"w",
")",
"q",
"=",
"Quaternio... | 28.705882 | 0.013889 |
def _repeat(self, index, stage, stop):
""" Repeat a stage.
:param index: Stage index.
:param stage: Stage object to repeat.
:param iterations: Number of iterations (default infinite).
:param stages: Stages back to repeat (default 1).
"""
times = None
if '... | [
"def",
"_repeat",
"(",
"self",
",",
"index",
",",
"stage",
",",
"stop",
")",
":",
"times",
"=",
"None",
"if",
"'iterations'",
"in",
"stage",
".",
"kwargs",
":",
"times",
"=",
"stage",
".",
"kwargs",
"[",
"'iterations'",
"]",
"-",
"1",
"stages_back",
... | 35.166667 | 0.002307 |
def _batch_insert(self, inserts, intervals, **kwargs):
'''
Specialized batch insert
'''
if 'pipeline' in kwargs:
pipe = kwargs.get('pipeline')
own_pipe = False
else:
pipe = self._client.pipeline(transaction=False)
kwargs['pipeline'] = pipe
own_pipe = True
ttl_batch... | [
"def",
"_batch_insert",
"(",
"self",
",",
"inserts",
",",
"intervals",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'pipeline'",
"in",
"kwargs",
":",
"pipe",
"=",
"kwargs",
".",
"get",
"(",
"'pipeline'",
")",
"own_pipe",
"=",
"False",
"else",
":",
"pipe",... | 29.333333 | 0.022008 |
def all_props(self):
"""Return a dictionary with the values of all children, and place holders for all of the section
argumemts. It combines props and arg_props"""
d = self.arg_props
d.update(self.props)
return d | [
"def",
"all_props",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"arg_props",
"d",
".",
"update",
"(",
"self",
".",
"props",
")",
"return",
"d"
] | 30.875 | 0.011811 |
def header(self):
"""
Return the BAM/SAM header
Returns
-------
generator
Each line of the header
"""
cmd = [self.__samtools, 'view', '-H', self.__bam]
stdout = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout
fo... | [
"def",
"header",
"(",
"self",
")",
":",
"cmd",
"=",
"[",
"self",
".",
"__samtools",
",",
"'view'",
",",
"'-H'",
",",
"self",
".",
"__bam",
"]",
"stdout",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")... | 21.388889 | 0.012438 |
def _setup_source_and_destination(self):
"""instantiate the classes that implement the source and destination
crash storage systems."""
try:
self.source = self.config.source.crashstorage_class(
self.config.source,
quit_check_callback=self.quit_check
... | [
"def",
"_setup_source_and_destination",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"source",
"=",
"self",
".",
"config",
".",
"source",
".",
"crashstorage_class",
"(",
"self",
".",
"config",
".",
"source",
",",
"quit_check_callback",
"=",
"self",
".",
... | 34.6 | 0.00225 |
def get_template(self, context, **kwargs):
"""
Returns the template to be used for the current context and arguments.
"""
if 'template' in kwargs['params']:
self.template = kwargs['params']['template']
return super(GoscaleTemplateInclusionTag, self).get_template(conte... | [
"def",
"get_template",
"(",
"self",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'template'",
"in",
"kwargs",
"[",
"'params'",
"]",
":",
"self",
".",
"template",
"=",
"kwargs",
"[",
"'params'",
"]",
"[",
"'template'",
"]",
"return",
"super... | 46.714286 | 0.009009 |
def list_zones(permanent=True):
'''
List everything added for or enabled in all zones
CLI Example:
.. code-block:: bash
salt '*' firewalld.list_zones
'''
zones = {}
cmd = '--list-all-zones'
if permanent:
cmd += ' --permanent'
for i in __firewall_cmd(cmd).splitli... | [
"def",
"list_zones",
"(",
"permanent",
"=",
"True",
")",
":",
"zones",
"=",
"{",
"}",
"cmd",
"=",
"'--list-all-zones'",
"if",
"permanent",
":",
"cmd",
"+=",
"' --permanent'",
"for",
"i",
"in",
"__firewall_cmd",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")... | 22.433333 | 0.001425 |
def close(self):
"""
Flush the write buffers of the stream if applicable and
close the object.
"""
if self._writable and not self._is_raw_of_buffered and not self._closed:
self._closed = True
if self._write_buffer:
self.flush() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writable",
"and",
"not",
"self",
".",
"_is_raw_of_buffered",
"and",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"_closed",
"=",
"True",
"if",
"self",
".",
"_write_buffer",
":",
"self",
".... | 33.222222 | 0.009772 |
def authenticate(self, request, email=None, password=None, username=None):
"""
Attempt to authenticate a set of credentials.
Args:
request:
The request associated with the authentication attempt.
email:
The user's email address.
... | [
"def",
"authenticate",
"(",
"self",
",",
"request",
",",
"email",
"=",
"None",
",",
"password",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"email",
"=",
"email",
"or",
"username",
"try",
":",
"email_instance",
"=",
"models",
".",
"EmailAddress"... | 29.6 | 0.001869 |
def pascalcase(text, acronyms=None):
"""Return text in PascalCase style (aka MixedCase).
Args:
text: input string to convert case
detect_acronyms: should attempt to detect acronyms
acronyms: a list of acronyms to detect
>>> pascalcase("hello world")
'HelloWorld'
>>> pascalc... | [
"def",
"pascalcase",
"(",
"text",
",",
"acronyms",
"=",
"None",
")",
":",
"words",
",",
"_case",
",",
"_sep",
"=",
"case_parse",
".",
"parse_case",
"(",
"text",
",",
"acronyms",
")",
"return",
"''",
".",
"join",
"(",
"words",
")"
] | 30.866667 | 0.002096 |
def download(self, url, path):
"""Download url and save data to path."""
# original_url = url
# print(url)
qurl = QUrl(url)
url = to_text_string(qurl.toEncoded(), encoding='utf-8')
logger.debug(str((url, path)))
if url in self._workers:
while not self.... | [
"def",
"download",
"(",
"self",
",",
"url",
",",
"path",
")",
":",
"# original_url = url",
"# print(url)",
"qurl",
"=",
"QUrl",
"(",
"url",
")",
"url",
"=",
"to_text_string",
"(",
"qurl",
".",
"toEncoded",
"(",
")",
",",
"encoding",
"=",
"'utf-8'",
... | 29.925926 | 0.002398 |
def get_task_var(self, key, default=None):
"""
Fetch the value of a task variable related to connection configuration,
or, if delegate_to is active, fetch the same variable via HostVars for
the delegated-to machine.
When running with delegate_to, Ansible tasks have variables ass... | [
"def",
"get_task_var",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"self",
".",
"_task_vars",
":",
"if",
"self",
".",
"delegate_to_hostname",
"is",
"None",
":",
"if",
"key",
"in",
"self",
".",
"_task_vars",
":",
"return",
"sel... | 44.608696 | 0.001908 |
def infer_shape(self, *args, **kwargs):
"""Infers the shapes of all arguments and all outputs given the known shapes of
some arguments.
This function takes the known shapes of some arguments in either positional way
or keyword argument way as input. It returns a tuple of `None` values
... | [
"def",
"infer_shape",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"_infer_shape_impl",
"(",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"res",
"[",
"1",
"]",
"is",
"N... | 40.258824 | 0.001997 |
def latexify_spacegroup(spacegroup_symbol):
"""
Generates a latex formatted spacegroup. E.g., P2_1/c is converted to
P2$_{1}$/c and P-1 is converted to P$\\overline{1}$.
Args:
spacegroup_symbol (str): A spacegroup symbol
Returns:
A latex formatted spacegroup with proper subscripts ... | [
"def",
"latexify_spacegroup",
"(",
"spacegroup_symbol",
")",
":",
"sym",
"=",
"re",
".",
"sub",
"(",
"r\"_(\\d+)\"",
",",
"r\"$_{\\1}$\"",
",",
"spacegroup_symbol",
")",
"return",
"re",
".",
"sub",
"(",
"r\"-(\\d)\"",
",",
"r\"$\\\\overline{\\1}$\"",
",",
"sym",... | 34.076923 | 0.002198 |
def with_cache(function):
"""Return a decorator that interacts with a handler's cache.
This decorator must be applied to a DefaultHandler class method or
instance method as it assumes `cache`, `ca_lock` and `timeouts` are
available.
"""
@wraps(function)
def wrap... | [
"def",
"with_cache",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"wrapped",
"(",
"cls",
",",
"_cache_key",
",",
"_cache_ignore",
",",
"_cache_timeout",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"clear_timeouts",
"(",
")",
":",
... | 44.853659 | 0.001064 |
def is_training_name(name):
"""
**Guess** if this variable is only used in training.
Only used internally to avoid too many logging. Do not use it.
"""
# TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES?
# TODO or use get_slot_names()
name = get_op_tensor_name(name)[0... | [
"def",
"is_training_name",
"(",
"name",
")",
":",
"# TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES?",
"# TODO or use get_slot_names()",
"name",
"=",
"get_op_tensor_name",
"(",
"name",
")",
"[",
"0",
"]",
"if",
"name",
".",
"endswith",
"(",
"'/Ad... | 37.28 | 0.002092 |
def get_content(self):
"""Open content as a stream for reading.
See DAVResource.get_content()
"""
assert not self.is_collection
d = self.fctx.data()
return compat.StringIO(d) | [
"def",
"get_content",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"is_collection",
"d",
"=",
"self",
".",
"fctx",
".",
"data",
"(",
")",
"return",
"compat",
".",
"StringIO",
"(",
"d",
")"
] | 27 | 0.008969 |
def send(self, task, result, expire=60):
"""
Sends the result back to the producer. This should be called if only you
want to return the result in async manner.
:arg task: ::class:`~retask.task.Task` object
:arg result: Result data to be send back. Should be in JSON serializable... | [
"def",
"send",
"(",
"self",
",",
"task",
",",
"result",
",",
"expire",
"=",
"60",
")",
":",
"self",
".",
"rdb",
".",
"lpush",
"(",
"task",
".",
"urn",
",",
"json",
".",
"dumps",
"(",
"result",
")",
")",
"self",
".",
"rdb",
".",
"expire",
"(",
... | 45.545455 | 0.009785 |
def start(name, called = None):
"""Start a task."""
if name not in tasks:
logger.log(logger.red("Task '%s' not in your pylpfile" % name))
else:
task = tasks[name]
runner = TaskRunner(name, task[0], task[1], called)
running.append(runner)
return runner | [
"def",
"start",
"(",
"name",
",",
"called",
"=",
"None",
")",
":",
"if",
"name",
"not",
"in",
"tasks",
":",
"logger",
".",
"log",
"(",
"logger",
".",
"red",
"(",
"\"Task '%s' not in your pylpfile\"",
"%",
"name",
")",
")",
"else",
":",
"task",
"=",
"... | 28.444444 | 0.041667 |
def split_unbalanced(chunks):
"""Return (unbalanced_start, balanced, unbalanced_end), where each is
a list of text and tag chunks.
unbalanced_start is a list of all the tags that are opened, but
not closed in this span. Similarly, unbalanced_end is a list of
tags that are closed but were not opene... | [
"def",
"split_unbalanced",
"(",
"chunks",
")",
":",
"start",
"=",
"[",
"]",
"end",
"=",
"[",
"]",
"tag_stack",
"=",
"[",
"]",
"balanced",
"=",
"[",
"]",
"for",
"chunk",
"in",
"chunks",
":",
"if",
"not",
"chunk",
".",
"startswith",
"(",
"'<'",
")",
... | 35.512821 | 0.000703 |
def replace_entities(self, html):
"""
Replace htmlentities with unicode characters
@Params
html - html source to replace entities in
@Returns
String html with entities replaced
"""
def fixup(text):
"""replace the htmlentities in some text"""
... | [
"def",
"replace_entities",
"(",
"self",
",",
"html",
")",
":",
"def",
"fixup",
"(",
"text",
")",
":",
"\"\"\"replace the htmlentities in some text\"\"\"",
"text",
"=",
"text",
".",
"group",
"(",
"0",
")",
"if",
"text",
"[",
":",
"2",
"]",
"==",
"\"&#\"",
... | 33.535714 | 0.00207 |
def _detect_notebook():
"""
This isn't 100% correct but seems good enough
Returns
-------
bool
True if it detects this is a notebook, otherwise False.
"""
try:
from IPython import get_ipython
from ipykernel import zmqshell
except ImportError:
return False... | [
"def",
"_detect_notebook",
"(",
")",
":",
"try",
":",
"from",
"IPython",
"import",
"get_ipython",
"from",
"ipykernel",
"import",
"zmqshell",
"except",
"ImportError",
":",
"return",
"False",
"kernel",
"=",
"get_ipython",
"(",
")",
"return",
"isinstance",
"(",
"... | 24.5 | 0.002457 |
def remove_transcript(self,tx_id):
"""Remove a transcript from the locus by its id
:param tx_id:
:type tx_id: string
"""
txs = self.get_transcripts()
if tx_id not in [x.id for x in txs]:
return
tx = [x for x in txs if x.id==tx_id][0]
for n in [x for x in self.g.get_nodes()]:
... | [
"def",
"remove_transcript",
"(",
"self",
",",
"tx_id",
")",
":",
"txs",
"=",
"self",
".",
"get_transcripts",
"(",
")",
"if",
"tx_id",
"not",
"in",
"[",
"x",
".",
"id",
"for",
"x",
"in",
"txs",
"]",
":",
"return",
"tx",
"=",
"[",
"x",
"for",
"x",
... | 28.125 | 0.017204 |
def value(self):
''' Data decoded with the specified charset '''
pos = self.file.tell()
self.file.seek(0)
val = self.file.read()
self.file.seek(pos)
return val.decode(self.charset) | [
"def",
"value",
"(",
"self",
")",
":",
"pos",
"=",
"self",
".",
"file",
".",
"tell",
"(",
")",
"self",
".",
"file",
".",
"seek",
"(",
"0",
")",
"val",
"=",
"self",
".",
"file",
".",
"read",
"(",
")",
"self",
".",
"file",
".",
"seek",
"(",
"... | 31.714286 | 0.008772 |
def strip_leading_comments(text):
"""Strips the leading whitespaces and % from the given text.
Adapted from textwrap.dedent
"""
# Look for the longest leading string of spaces and tabs common to
# all lines.
margin = None
text = _whitespace_only_re.sub('', text)
indents = _leading_white... | [
"def",
"strip_leading_comments",
"(",
"text",
")",
":",
"# Look for the longest leading string of spaces and tabs common to",
"# all lines.",
"margin",
"=",
"None",
"text",
"=",
"_whitespace_only_re",
".",
"sub",
"(",
"''",
",",
"text",
")",
"indents",
"=",
"_leading_wh... | 30.769231 | 0.000808 |
def commit_check():
'''
Perform a commit check on the configuration
CLI Example:
.. code-block:: bash
salt 'device_name' junos.commit_check
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cu.commit_check()
ret['message'] = 'Commit ... | [
"def",
"commit_check",
"(",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"try",
":",
"conn",
".",
"cu",
".",
"commit_check",
"(",
")",
"ret",
"[",
"'message'",
... | 22.333333 | 0.002045 |
def check_api_version(resource_root, min_version):
"""
Checks if the resource_root's API version it at least the given minimum
version.
"""
if resource_root.version < min_version:
raise Exception("API version %s is required but %s is in use."
% (min_version, resource_root.version)) | [
"def",
"check_api_version",
"(",
"resource_root",
",",
"min_version",
")",
":",
"if",
"resource_root",
".",
"version",
"<",
"min_version",
":",
"raise",
"Exception",
"(",
"\"API version %s is required but %s is in use.\"",
"%",
"(",
"min_version",
",",
"resource_root",
... | 37.125 | 0.013158 |
def _get_hydrated_path(field):
"""Return HydratedPath object for file-type field."""
# Get only file path if whole file object is given.
if isinstance(field, str) and hasattr(field, 'file_name'):
# field is already actually a HydratedPath object
return field
if isinstance(field, dict) a... | [
"def",
"_get_hydrated_path",
"(",
"field",
")",
":",
"# Get only file path if whole file object is given.",
"if",
"isinstance",
"(",
"field",
",",
"str",
")",
"and",
"hasattr",
"(",
"field",
",",
"'file_name'",
")",
":",
"# field is already actually a HydratedPath object"... | 36.785714 | 0.001894 |
def avglosses_data_transfer(token, dstore):
"""
Determine the amount of average losses transferred from the workers to the
controller node in a risk calculation.
"""
oq = dstore['oqparam']
N = len(dstore['assetcol'])
R = dstore['csm_info'].get_num_rlzs()
L = len(dstore.get_attr('risk_mod... | [
"def",
"avglosses_data_transfer",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"N",
"=",
"len",
"(",
"dstore",
"[",
"'assetcol'",
"]",
")",
"R",
"=",
"dstore",
"[",
"'csm_info'",
"]",
".",
"get_num_rlzs",
"(",
")",... | 40.357143 | 0.00173 |
def rm_dup_args_safe(self, tag: str = None) -> None:
"""Remove duplicate arguments in a safe manner.
Remove the duplicate arguments only in the following situations:
1. Both arguments have the same name AND value. (Remove one of
them.)
2. Arguments have the same ... | [
"def",
"rm_dup_args_safe",
"(",
"self",
",",
"tag",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"name_to_lastarg_vals",
"=",
"{",
"}",
"# type: Dict[str, Tuple[Argument, List[str]]]",
"# Removing positional args affects their name. By reversing the list",
"# we avoid enc... | 47.929825 | 0.000717 |
def next_checkpoint(model_dir, timeout_mins=240):
"""Yields successive checkpoints from model_dir.
Args:
model_dir: The directory in which checkpoints are saved.
timeout_mins: The maximum amount of time in minutes to wait
between checkpoints. Set this to -1 to wait indefinitely.
Yields:... | [
"def",
"next_checkpoint",
"(",
"model_dir",
",",
"timeout_mins",
"=",
"240",
")",
":",
"last_ckpt",
"=",
"None",
"timeout_secs",
"=",
"None",
"if",
"timeout_mins",
"!=",
"-",
"1",
":",
"timeout_secs",
"=",
"timeout_mins",
"*",
"60",
"while",
"True",
":",
"... | 32.625 | 0.009926 |
def simple_returns(prices):
"""
Compute simple returns from a timeseries of prices.
Parameters
----------
prices : pd.Series, pd.DataFrame or np.ndarray
Prices of assets in wide-format, with assets as columns,
and indexed by datetimes.
Returns
-------
returns : array-li... | [
"def",
"simple_returns",
"(",
"prices",
")",
":",
"if",
"isinstance",
"(",
"prices",
",",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
")",
")",
":",
"out",
"=",
"prices",
".",
"pct_change",
"(",
")",
".",
"iloc",
"[",
"1",
":",
"]",
"e... | 27.041667 | 0.001488 |
def combining_goal(state):
"""
Check if two Cubies are combined on the U face.
"""
((corner, edge), (L, U, F, D, R, B)) = state
if "U" not in corner or "U" not in edge: return False
if set(edge).issubset(set(corner)): return True
elif set(edge.facings.keys()).issu... | [
"def",
"combining_goal",
"(",
"state",
")",
":",
"(",
"(",
"corner",
",",
"edge",
")",
",",
"(",
"L",
",",
"U",
",",
"F",
",",
"D",
",",
"R",
",",
"B",
")",
")",
"=",
"state",
"if",
"\"U\"",
"not",
"in",
"corner",
"or",
"\"U\"",
"not",
"in",
... | 41.333333 | 0.014455 |
def jinja_extensions_feature(app):
""" Enables custom templating extensions """
# register jinja filters
app.jinja_env.globals['momentjs'] = MomentJsFilters
app.jinja_env.filters.update(MomentJsFilters().get_filters())
app.jinja_env.filters.update(DateFilters().get_filters())
app.jinja_env.filt... | [
"def",
"jinja_extensions_feature",
"(",
"app",
")",
":",
"# register jinja filters",
"app",
".",
"jinja_env",
".",
"globals",
"[",
"'momentjs'",
"]",
"=",
"MomentJsFilters",
"app",
".",
"jinja_env",
".",
"filters",
".",
"update",
"(",
"MomentJsFilters",
"(",
")"... | 36 | 0.001934 |
def arm(self, level, code):
"""(Helper) Arm system at specified level (away, vacation, etc)"""
self._elk.send(al_encode(level, self._index, code)) | [
"def",
"arm",
"(",
"self",
",",
"level",
",",
"code",
")",
":",
"self",
".",
"_elk",
".",
"send",
"(",
"al_encode",
"(",
"level",
",",
"self",
".",
"_index",
",",
"code",
")",
")"
] | 53.333333 | 0.012346 |
def keras_model_to_graph_def(keras_layer):
"""Returns a GraphDef representation of the Keras model in a dict form.
Note that it only supports models that implemented to_json().
Args:
keras_layer: A dict from Keras model.to_json().
Returns:
A GraphDef representation of the layers in the model.
"""
... | [
"def",
"keras_model_to_graph_def",
"(",
"keras_layer",
")",
":",
"input_to_layer",
"=",
"{",
"}",
"model_name_to_output",
"=",
"{",
"}",
"g",
"=",
"GraphDef",
"(",
")",
"# Sequential model layers do not have a field \"inbound_nodes\" but",
"# instead are defined implicitly vi... | 37.3 | 0.013496 |
def error_handler(response, **kwargs):
"""Error Handler to surface 4XX and 5XX errors.
Attached as a callback hook on the Request object.
Parameters
response (requests.Response)
The HTTP response from an API request.
**kwargs
Arbitrary keyword arguments.
Raises... | [
"def",
"error_handler",
"(",
"response",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"body",
"=",
"response",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"body",
"=",
"{",
"}",
"status_code",
"=",
"response",
".",
"status_code",
"message",
"... | 29.055556 | 0.000925 |
def outputs_are_present(outputs):
"""True if each output contains at least one file or no output specified."""
# outputs are OutputFileParam (see param_util.py)
# If outputs contain a pattern, then there is no way for `dsub` to verify
# that *all* output is present. The best that `dsub` can do is to verify
#... | [
"def",
"outputs_are_present",
"(",
"outputs",
")",
":",
"# outputs are OutputFileParam (see param_util.py)",
"# If outputs contain a pattern, then there is no way for `dsub` to verify",
"# that *all* output is present. The best that `dsub` can do is to verify",
"# that *some* output was created fo... | 34.705882 | 0.018152 |
def _reflow_lines(parsed_tokens, indentation, max_line_length,
start_on_prefix_line):
"""Reflow the lines so that it looks nice."""
if unicode(parsed_tokens[0]) == 'def':
# A function definition gets indented a bit more.
continued_indent = indentation + ' ' * 2 * DEFAULT_INDEN... | [
"def",
"_reflow_lines",
"(",
"parsed_tokens",
",",
"indentation",
",",
"max_line_length",
",",
"start_on_prefix_line",
")",
":",
"if",
"unicode",
"(",
"parsed_tokens",
"[",
"0",
"]",
")",
"==",
"'def'",
":",
"# A function definition gets indented a bit more.",
"contin... | 36.45 | 0.000668 |
def Images(self, run, tag):
"""Retrieve the image events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available... | [
"def",
"Images",
"(",
"self",
",",
"run",
",",
"tag",
")",
":",
"accumulator",
"=",
"self",
".",
"GetAccumulator",
"(",
"run",
")",
"return",
"accumulator",
".",
"Images",
"(",
"tag",
")"
] | 30.1875 | 0.002008 |
def separate(polylines, f_mx_dist=2, mn_group_len=4):
"""
split polylines wherever crinkles are found
"""
s = []
for n in range(len(polylines) - 1, -1, -1):
c = polylines[n]
separated = False
start = 0
for m in range(mn_group_len, len(c) - 1):
if m - sta... | [
"def",
"separate",
"(",
"polylines",
",",
"f_mx_dist",
"=",
"2",
",",
"mn_group_len",
"=",
"4",
")",
":",
"s",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"polylines",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"c",... | 27.075 | 0.001783 |
def _decode(rawstr):
"""Convert a raw string to a Message.
"""
# Check for the magick word.
try:
rawstr = rawstr.decode('utf-8')
except (AttributeError, UnicodeEncodeError):
pass
except (UnicodeDecodeError):
try:
rawstr = rawstr.decode('iso-8859-1')
ex... | [
"def",
"_decode",
"(",
"rawstr",
")",
":",
"# Check for the magick word.",
"try",
":",
"rawstr",
"=",
"rawstr",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"(",
"AttributeError",
",",
"UnicodeEncodeError",
")",
":",
"pass",
"except",
"(",
"UnicodeDecodeError",... | 32.166667 | 0.000503 |
def exitCircuitGate(self, ctx: QuilParser.CircuitGateContext):
"""
PyQuil has no constructs yet for representing gate instructions within a DEFCIRCUIT (ie. gates where the qubits
are inputs to the call to the circuit). Therefore we parse them as a raw instructions.
"""
gate_name ... | [
"def",
"exitCircuitGate",
"(",
"self",
",",
"ctx",
":",
"QuilParser",
".",
"CircuitGateContext",
")",
":",
"gate_name",
"=",
"ctx",
".",
"name",
"(",
")",
".",
"getText",
"(",
")",
"params",
"=",
"[",
"param",
".",
"getText",
"(",
")",
"for",
"param",
... | 57.166667 | 0.008608 |
def get_reference_section_beginning(fulltext):
"""Get start of reference section."""
sect_start = {
'start_line': None,
'end_line': None,
'title_string': None,
'marker_pattern': None,
'marker': None,
'how_found_start': None,
}
# Find start of refs section... | [
"def",
"get_reference_section_beginning",
"(",
"fulltext",
")",
":",
"sect_start",
"=",
"{",
"'start_line'",
":",
"None",
",",
"'end_line'",
":",
"None",
",",
"'title_string'",
":",
"None",
",",
"'marker_pattern'",
":",
"None",
",",
"'marker'",
":",
"None",
",... | 40.116279 | 0.000566 |
def read_raw_parser_conf(data: str) -> dict:
"""We expect to have a section like this
```
[commitizen]
name = cz_jira
files = [
"commitizen/__version__.py",
"pyproject.toml"
] # this tab at the end is important
```
"""
config = configparser.ConfigParser(allow_no... | [
"def",
"read_raw_parser_conf",
"(",
"data",
":",
"str",
")",
"->",
"dict",
":",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
"config",
".",
"read_string",
"(",
"data",
")",
"try",
":",
"_data",
":",
"dict",
... | 23.84 | 0.001613 |
def extract_program_summary(data):
'''
Extract the summary data from a program's detail page
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'html.parser')
try:
return soup.find(
'div', {'class': 'episode-synopsis'}
).find_all('div')[-1].text.strip()
... | [
"def",
"extract_program_summary",
"(",
"data",
")",
":",
"from",
"bs4",
"import",
"BeautifulSoup",
"soup",
"=",
"BeautifulSoup",
"(",
"data",
",",
"'html.parser'",
")",
"try",
":",
"return",
"soup",
".",
"find",
"(",
"'div'",
",",
"{",
"'class'",
":",
"'ep... | 33.571429 | 0.00207 |
def set_bios_settings(self, data=None, only_allowed_settings=True):
"""Sets current BIOS settings to the provided data.
:param: only_allowed_settings: True when only allowed BIOS settings
are to be set. If False, all the BIOS settings supported by
iLO and present in the ... | [
"def",
"set_bios_settings",
"(",
"self",
",",
"data",
"=",
"None",
",",
"only_allowed_settings",
"=",
"True",
")",
":",
"if",
"not",
"data",
":",
"raise",
"exception",
".",
"IloError",
"(",
"\"Could not apply settings with\"",
"\" empty data\"",
")",
"sushy_system... | 51.131579 | 0.00101 |
def _is_propertyable(
names, # type: List[str]
attrs, # type: Dict[str, Any]
annotations, # type: Dict[str, type]
attr, # Dict[str, Any]
):
# type: (...) -> bool
"""Determine if an attribute can be replaced with a property.
Args:
names: The complete list of all attribute names f... | [
"def",
"_is_propertyable",
"(",
"names",
",",
"# type: List[str]",
"attrs",
",",
"# type: Dict[str, Any]",
"annotations",
",",
"# type: Dict[str, type]",
"attr",
",",
"# Dict[str, Any]",
")",
":",
"# type: (...) -> bool",
"return",
"(",
"attr",
"in",
"annotations",
"and... | 32.32 | 0.001202 |
def log(prefix = ''):
'''Add start and stop logging messages to the function.
Parameters
----------
:``prefix``: a prefix for the function name (optional)
'''
function = None
if inspect.isfunction(prefix):
prefix, function = '', prefix
def _(function):
@functools.wr... | [
"def",
"log",
"(",
"prefix",
"=",
"''",
")",
":",
"function",
"=",
"None",
"if",
"inspect",
".",
"isfunction",
"(",
"prefix",
")",
":",
"prefix",
",",
"function",
"=",
"''",
",",
"prefix",
"def",
"_",
"(",
"function",
")",
":",
"@",
"functools",
".... | 30.56 | 0.010146 |
def InjectionStatistics(campaign=0, clobber=False, model='nPLD', plot=True,
show=True, **kwargs):
'''
Computes and plots the statistics for injection/recovery tests.
:param int campaign: The campaign number. Default 0
:param str model: The :py:obj:`everest` model name
:param... | [
"def",
"InjectionStatistics",
"(",
"campaign",
"=",
"0",
",",
"clobber",
"=",
"False",
",",
"model",
"=",
"'nPLD'",
",",
"plot",
"=",
"True",
",",
"show",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Compute the statistics",
"stars",
"=",
"GetK2Cam... | 44.347594 | 0.00059 |
def convert_ids_to_tokens(self, ids):
"""Converts a sequence of ids in wordpiece tokens using the vocab."""
tokens = []
for i in ids:
tokens.append(self.ids_to_tokens[i])
return tokens | [
"def",
"convert_ids_to_tokens",
"(",
"self",
",",
"ids",
")",
":",
"tokens",
"=",
"[",
"]",
"for",
"i",
"in",
"ids",
":",
"tokens",
".",
"append",
"(",
"self",
".",
"ids_to_tokens",
"[",
"i",
"]",
")",
"return",
"tokens"
] | 37.166667 | 0.008772 |
def get_gl_configuration():
"""Read the current gl configuration
This function uses constants that are not in the OpenGL ES 2.1
namespace, so only use this on desktop systems.
Returns
-------
config : dict
The currently active OpenGL configuration.
"""
# XXX eventually maybe we... | [
"def",
"get_gl_configuration",
"(",
")",
":",
"# XXX eventually maybe we can ask `gl` whether or not we can access these",
"gl",
".",
"check_error",
"(",
"'pre-config check'",
")",
"config",
"=",
"dict",
"(",
")",
"gl",
".",
"glBindFramebuffer",
"(",
"gl",
".",
"GL_FRAM... | 39.232558 | 0.000578 |
def remove(self, docid):
"""
Remove a document from the database.
"""
docid = int(docid)
self.store.executeSQL(self.removeSQL, (docid,)) | [
"def",
"remove",
"(",
"self",
",",
"docid",
")",
":",
"docid",
"=",
"int",
"(",
"docid",
")",
"self",
".",
"store",
".",
"executeSQL",
"(",
"self",
".",
"removeSQL",
",",
"(",
"docid",
",",
")",
")"
] | 28.5 | 0.011364 |
def on_mouse_release(x, y, button, modifiers):
""" 松开鼠标时 """
if button == MouseKeyCode.LEFT:
mouse.release()
elif button == MouseKeyCode.RIGHT:
mouse.right_release() | [
"def",
"on_mouse_release",
"(",
"x",
",",
"y",
",",
"button",
",",
"modifiers",
")",
":",
"if",
"button",
"==",
"MouseKeyCode",
".",
"LEFT",
":",
"mouse",
".",
"release",
"(",
")",
"elif",
"button",
"==",
"MouseKeyCode",
".",
"RIGHT",
":",
"mouse",
"."... | 31.5 | 0.010309 |
def solve_kkt(U_Q, d, G, A, U_S, rx, rs, rz, ry, dbg=False):
""" Solve KKT equations for the affine step"""
nineq, nz, neq, _ = get_sizes(G, A)
invQ_rx = torch.potrs(rx.view(-1, 1), U_Q).view(-1)
if neq > 0:
h = torch.cat([torch.mv(A, invQ_rx) - ry,
torch.mv(G, invQ_rx) +... | [
"def",
"solve_kkt",
"(",
"U_Q",
",",
"d",
",",
"G",
",",
"A",
",",
"U_S",
",",
"rx",
",",
"rs",
",",
"rz",
",",
"ry",
",",
"dbg",
"=",
"False",
")",
":",
"nineq",
",",
"nz",
",",
"neq",
",",
"_",
"=",
"get_sizes",
"(",
"G",
",",
"A",
")",... | 29 | 0.001043 |
def singlehtml_sidebars(app):
"""When using a ``singlehtml`` builder, replace the
``html_sidebars`` config with ``singlehtml_sidebars``. This can be
used to change what sidebars are rendered for the single page called
``"index"`` by the builder.
"""
if app.config.singlehtml_sidebars is not None ... | [
"def",
"singlehtml_sidebars",
"(",
"app",
")",
":",
"if",
"app",
".",
"config",
".",
"singlehtml_sidebars",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"app",
".",
"builder",
",",
"SingleFileHTMLBuilder",
")",
":",
"app",
".",
"config",
".",
"html_sidebar... | 44.2 | 0.002217 |
def pretty_xml(string_input, add_ns=False):
""" pretty indent string_input """
if add_ns:
elem = "<foo "
for key, value in DOC_CONTENT_ATTRIB.items():
elem += ' %s="%s"' % (key, value)
string_input = elem + ">" + string_input + "</foo>"
doc = minidom.parseString(string_in... | [
"def",
"pretty_xml",
"(",
"string_input",
",",
"add_ns",
"=",
"False",
")",
":",
"if",
"add_ns",
":",
"elem",
"=",
"\"<foo \"",
"for",
"key",
",",
"value",
"in",
"DOC_CONTENT_ATTRIB",
".",
"items",
"(",
")",
":",
"elem",
"+=",
"' %s=\"%s\"'",
"%",
"(",
... | 34.538462 | 0.002169 |
def mtf_image_transformer_base_imagenet_mp64():
"""Model parallel ImageNet parameters."""
hparams = mtf_image_transformer_base_imagenet()
hparams.mesh_shape = "model:8;batch:4"
hparams.layout = "batch:batch;d_ff:model;heads:model"
hparams.batch_size = 8
hparams.img_len = 64
hparams.num_decoder_layers = 8
... | [
"def",
"mtf_image_transformer_base_imagenet_mp64",
"(",
")",
":",
"hparams",
"=",
"mtf_image_transformer_base_imagenet",
"(",
")",
"hparams",
".",
"mesh_shape",
"=",
"\"model:8;batch:4\"",
"hparams",
".",
"layout",
"=",
"\"batch:batch;d_ff:model;heads:model\"",
"hparams",
"... | 36.444444 | 0.026786 |
def _build_vocab(filename, vocab_dir, vocab_name):
"""Reads a file to build a vocabulary.
Args:
filename: file to read list of words from.
vocab_dir: directory where to save the vocabulary.
vocab_name: vocab file name.
Returns:
text encoder.
"""
vocab_path = os.path.join(vocab_dir, vocab_nam... | [
"def",
"_build_vocab",
"(",
"filename",
",",
"vocab_dir",
",",
"vocab_name",
")",
":",
"vocab_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"vocab_dir",
",",
"vocab_name",
")",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"vocab_path",
")",
... | 32.608696 | 0.009067 |
def jsonobjkeys(self, name, path=Path.rootPath()):
"""
Returns the key names in the dictionary JSON value under ``path`` at key
``name``
"""
return self.execute_command('JSON.OBJKEYS', name, str_path(path)) | [
"def",
"jsonobjkeys",
"(",
"self",
",",
"name",
",",
"path",
"=",
"Path",
".",
"rootPath",
"(",
")",
")",
":",
"return",
"self",
".",
"execute_command",
"(",
"'JSON.OBJKEYS'",
",",
"name",
",",
"str_path",
"(",
"path",
")",
")"
] | 40.166667 | 0.012195 |
def publish(self, topic, payload, qos=0, retain=False):
"""
Publishes an MQTT message
"""
# TODO: check (full transmission) success
return self._client.publish(topic, payload, qos, retain) | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"payload",
",",
"qos",
"=",
"0",
",",
"retain",
"=",
"False",
")",
":",
"# TODO: check (full transmission) success",
"return",
"self",
".",
"_client",
".",
"publish",
"(",
"topic",
",",
"payload",
",",
"qos... | 37.166667 | 0.008772 |
def get_range_content(ds, start, end):
'''Generator for range-requested datastream content. Iterates over
datastream content in chunks, and yields the chunks (or partial chunks)
that are part of the requested range.'''
if not end or end > ds.info.size:
end = ds.info.size - 1
chunksize = 409... | [
"def",
"get_range_content",
"(",
"ds",
",",
"start",
",",
"end",
")",
":",
"if",
"not",
"end",
"or",
"end",
">",
"ds",
".",
"info",
".",
"size",
":",
"end",
"=",
"ds",
".",
"info",
".",
"size",
"-",
"1",
"chunksize",
"=",
"4096",
"content_chunks",
... | 36.380952 | 0.001274 |
def _archive_self(self, logfile, key=JobDetails.topkey, status=JobStatus.unknown):
"""Write info about a job run by this `Link` to the job archive"""
self._register_self(logfile, key, status)
if self._job_archive is None:
return
self._job_archive.register_jobs(self.get_jobs()... | [
"def",
"_archive_self",
"(",
"self",
",",
"logfile",
",",
"key",
"=",
"JobDetails",
".",
"topkey",
",",
"status",
"=",
"JobStatus",
".",
"unknown",
")",
":",
"self",
".",
"_register_self",
"(",
"logfile",
",",
"key",
",",
"status",
")",
"if",
"self",
"... | 52.666667 | 0.009346 |
def _at_dump_mixins(self, calculator, rule, scope, block):
"""
Implements @dump_mixins
"""
sys.stderr.write("%s\n" % repr(rule.namespace._mixins)) | [
"def",
"_at_dump_mixins",
"(",
"self",
",",
"calculator",
",",
"rule",
",",
"scope",
",",
"block",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"repr",
"(",
"rule",
".",
"namespace",
".",
"_mixins",
")",
")"
] | 34.8 | 0.011236 |
def usearch_sort_by_abundance(
fasta_filepath,
output_filepath=None,
sizein=True,
sizeout=True,
minsize=0,
log_name="abundance_sort.log",
usersort=False,
HALT_EXEC=False,
save_intermediate_files=False,
remove_usearch_logs=False,
wor... | [
"def",
"usearch_sort_by_abundance",
"(",
"fasta_filepath",
",",
"output_filepath",
"=",
"None",
",",
"sizein",
"=",
"True",
",",
"sizeout",
"=",
"True",
",",
"minsize",
"=",
"0",
",",
"log_name",
"=",
"\"abundance_sort.log\"",
",",
"usersort",
"=",
"False",
",... | 30.446154 | 0.000489 |
def t_asmcomment_NEWLINE(self, t):
r'\r?\n'
# New line => remove whatever state in top of the stack and replace it with INITIAL
t.lexer.lineno += 1
t.lexer.pop_state()
return t | [
"def",
"t_asmcomment_NEWLINE",
"(",
"self",
",",
"t",
")",
":",
"# New line => remove whatever state in top of the stack and replace it with INITIAL",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"1",
"t",
".",
"lexer",
".",
"pop_state",
"(",
")",
"return",
"t"
] | 35.166667 | 0.013889 |
def load(self, service_name, api_version=None, cached=True):
"""
Loads the desired JSON for a service. (uncached)
This will fall back through all the ``data_dirs`` provided to the
constructor, returning the **first** one it finds.
:param service_name: The name of the desired se... | [
"def",
"load",
"(",
"self",
",",
"service_name",
",",
"api_version",
"=",
"None",
",",
"cached",
"=",
"True",
")",
":",
"# Fetch from the cache first if it's there.",
"if",
"cached",
":",
"if",
"service_name",
"in",
"self",
".",
"_loaded_data",
":",
"if",
"api... | 34.659091 | 0.001276 |
def _most_frequent(array, extra_value, n_repeat):
"""Compute the most frequent value in a 1d array extended with
[extra_value] * n_repeat, where extra_value is assumed to be not part
of the array."""
# Compute the most frequent value in array only
if array.size > 0:
with warnings.catch... | [
"def",
"_most_frequent",
"(",
"array",
",",
"extra_value",
",",
"n_repeat",
")",
":",
"# Compute the most frequent value in array only",
"if",
"array",
".",
"size",
">",
"0",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"# stats.mode raises a warni... | 39.4375 | 0.000773 |
def _gen_vol_xml(vmname,
diskname,
disktype,
size,
pool):
'''
Generate the XML string to define a libvirt storage volume
'''
size = int(size) * 1024 # MB
context = {
'name': vmname,
'filename': '{0}.{1}'.format(disk... | [
"def",
"_gen_vol_xml",
"(",
"vmname",
",",
"diskname",
",",
"disktype",
",",
"size",
",",
"pool",
")",
":",
"size",
"=",
"int",
"(",
"size",
")",
"*",
"1024",
"# MB",
"context",
"=",
"{",
"'name'",
":",
"vmname",
",",
"'filename'",
":",
"'{0}.{1}'",
... | 28.25 | 0.001427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.