text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _line_by_type(self, line, header, hgroups, htypes, out, want_type,
collapse_quals_fn = None):
"""Parse out key value pairs for line information based on a group of values.
"""
for index, htype in ((i, t) for i, t in enumerate(htypes) if t == want_type):
col ... | [
"def",
"_line_by_type",
"(",
"self",
",",
"line",
",",
"header",
",",
"hgroups",
",",
"htypes",
",",
"out",
",",
"want_type",
",",
"collapse_quals_fn",
"=",
"None",
")",
":",
"for",
"index",
",",
"htype",
"in",
"(",
"(",
"i",
",",
"t",
")",
"for",
... | 45.538462 | 0.014901 |
def is_sqlatype_text_of_length_at_least(
coltype: Union[TypeEngine, VisitableType],
min_length: int = 1000) -> bool:
"""
Is the SQLAlchemy column type a string type that's at least the specified
length?
"""
coltype = _coltype_to_typeengine(coltype)
if not isinstance(coltype, sqlt... | [
"def",
"is_sqlatype_text_of_length_at_least",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
",",
"min_length",
":",
"int",
"=",
"1000",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"if",
"... | 38.153846 | 0.001969 |
async def handler(self, request):
"""
Receives HTTP request and negotiates up to a Websocket session
"""
def task_done(future):
self.tasks.remove(future)
exception = future.exception()
if exception:
log.warning(
'Wh... | [
"async",
"def",
"handler",
"(",
"self",
",",
"request",
")",
":",
"def",
"task_done",
"(",
"future",
")",
":",
"self",
".",
"tasks",
".",
"remove",
"(",
"future",
")",
"exception",
"=",
"future",
".",
"exception",
"(",
")",
"if",
"exception",
":",
"l... | 35.823529 | 0.001066 |
def from_hdf(cls, filename):
"""Load camera model params from a HDF5 file
The HDF5 file should contain the following datasets:
wc : (2,) float with distortion center
lgamma : float distortion parameter
readout : float readout value
size : (2,) int image s... | [
"def",
"from_hdf",
"(",
"cls",
",",
"filename",
")",
":",
"import",
"h5py",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"wc",
"=",
"f",
"[",
"\"wc\"",
"]",
".",
"value",
"lgamma",
"=",
"f",
"[",
"\"lgamma\"",
"]... | 31.451613 | 0.00199 |
def get_collection(self, namespace):
"""Get a pymongo collection from a namespace."""
database, coll = namespace.split(".", 1)
return self.primary_client[database][coll] | [
"def",
"get_collection",
"(",
"self",
",",
"namespace",
")",
":",
"database",
",",
"coll",
"=",
"namespace",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"return",
"self",
".",
"primary_client",
"[",
"database",
"]",
"[",
"coll",
"]"
] | 47.5 | 0.010363 |
def long_input(prompt='Multi-line input\n' + \
'Enter EOF on a blank line to end ' + \
'(ctrl-D in *nix, ctrl-Z in windows)',
maxlines = None, maxlength = None):
"""Get a multi-line string as input"""
lines = []
print(prompt)
lnum = 1
try:
while True:
... | [
"def",
"long_input",
"(",
"prompt",
"=",
"'Multi-line input\\n'",
"+",
"'Enter EOF on a blank line to end '",
"+",
"'(ctrl-D in *nix, ctrl-Z in windows)'",
",",
"maxlines",
"=",
"None",
",",
"maxlength",
"=",
"None",
")",
":",
"lines",
"=",
"[",
"]",
"print",
"(",
... | 26.171429 | 0.015789 |
def _surfdens(self,R,z,phi=0.,t=0.):
"""
NAME:
_surfdens
PURPOSE:
evaluate the surface density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | [
"def",
"_surfdens",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"r",
"=",
"numpy",
".",
"sqrt",
"(",
"R",
"**",
"2.",
"+",
"z",
"**",
"2.",
")",
"Rma",
"=",
"numpy",
".",
"sqrt",
"(",
"R",
"**",
... | 38.064516 | 0.019008 |
def get_anlz_factor(freq):
"""Find the number of periods per year given a frequency.
Parameters
----------
freq : str
Any frequency str or anchored offset str recognized by Pandas.
Returns
-------
float
Example
-------
>>> get_anlz_factor('D')
252.0
... | [
"def",
"get_anlz_factor",
"(",
"freq",
")",
":",
"# 'Q-NOV' would give us (2001, 1); we just want (2000, 1).\r",
"try",
":",
"base",
",",
"mult",
"=",
"get_freq_code",
"(",
"freq",
")",
"except",
"ValueError",
":",
"# The above will fail for a bunch of irregular frequencies, ... | 26.75 | 0.00082 |
def computeOutput(self):
"""Computes output for both learning and inference. In both cases, the
output is the boolean OR of activeState and predictedState at t.
Stores currentOutput for checkPrediction."""
# todo: This operation can be sped up by:
# 1.) Pre-allocating space for the currentOutput... | [
"def",
"computeOutput",
"(",
"self",
")",
":",
"# todo: This operation can be sped up by:",
"# 1.) Pre-allocating space for the currentOutput",
"# 2.) Making predictedState and activeState of type 'float32' up front",
"# 3.) Using logical_or(self.predictedState['t'], self.activeState['t'],",... | 41.0625 | 0.001488 |
def install(self, paths, maker, **kwargs):
"""
Install a wheel to the specified paths. If kwarg ``warner`` is
specified, it should be a callable, which will be called with two
tuples indicating the wheel version of this software and the wheel
version in the file, if there is a di... | [
"def",
"install",
"(",
"self",
",",
"paths",
",",
"maker",
",",
"*",
"*",
"kwargs",
")",
":",
"dry_run",
"=",
"maker",
".",
"dry_run",
"warner",
"=",
"kwargs",
".",
"get",
"(",
"'warner'",
")",
"lib_only",
"=",
"kwargs",
".",
"get",
"(",
"'lib_only'"... | 48.627706 | 0.000523 |
def fit_angular_distribution(angles, rates, rate_errors, shape='pexp'):
"""Fits angular distribution of rates.
Parameters
----------
rates: numpy array
with rates for all PMT combinations
angles: numpy array
with angles for all PMT combinations
shape:
which function to fit; ex... | [
"def",
"fit_angular_distribution",
"(",
"angles",
",",
"rates",
",",
"rate_errors",
",",
"shape",
"=",
"'pexp'",
")",
":",
"if",
"shape",
"==",
"'exp'",
":",
"fit_function",
"=",
"exponential",
"# p0 = [-0.91871169, 2.72224241, -1.19065965, 1.48054122]",
"if",
"shap... | 30.551724 | 0.001094 |
def similar_items(self, itemid, N=10):
""" Returns a list of the most similar other items """
if itemid >= self.similarity.shape[0]:
return []
return sorted(list(nonzeros(self.similarity, itemid)), key=lambda x: -x[1])[:N] | [
"def",
"similar_items",
"(",
"self",
",",
"itemid",
",",
"N",
"=",
"10",
")",
":",
"if",
"itemid",
">=",
"self",
".",
"similarity",
".",
"shape",
"[",
"0",
"]",
":",
"return",
"[",
"]",
"return",
"sorted",
"(",
"list",
"(",
"nonzeros",
"(",
"self",... | 42.333333 | 0.011583 |
def istft(stft_matrix, hop_length=None, win_length=None, window='hann',
center=True, dtype=np.float32, length=None):
"""
Inverse short-time Fourier transform (ISTFT).
Converts a complex-valued spectrogram `stft_matrix` to time-series `y`
by minimizing the mean squared error between `stft_matr... | [
"def",
"istft",
"(",
"stft_matrix",
",",
"hop_length",
"=",
"None",
",",
"win_length",
"=",
"None",
",",
"window",
"=",
"'hann'",
",",
"center",
"=",
"True",
",",
"dtype",
"=",
"np",
".",
"float32",
",",
"length",
"=",
"None",
")",
":",
"n_fft",
"=",... | 34.291391 | 0.000375 |
def handle_entityref(self, name):
"""Process a general entity reference of the form "&name;".
Transform to text whenever possible."""
char_code = html_entities.name2codepoint.get(name, None)
if char_code is not None:
try:
self.result += unichr(char_code).encod... | [
"def",
"handle_entityref",
"(",
"self",
",",
"name",
")",
":",
"char_code",
"=",
"html_entities",
".",
"name2codepoint",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"char_code",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"result",
"+=",
"u... | 40.555556 | 0.008043 |
def write_json_to_file(json_data, filename="metadata"):
"""
Write all JSON in python dictionary to a new json file.
:param dict json_data: JSON data
:param str filename: Target filename (defaults to 'metadata.jsonld')
:return None:
"""
logger_jsons.info("enter write_json_to_file")
json_d... | [
"def",
"write_json_to_file",
"(",
"json_data",
",",
"filename",
"=",
"\"metadata\"",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter write_json_to_file\"",
")",
"json_data",
"=",
"rm_empty_fields",
"(",
"json_data",
")",
"# Use demjson to maintain unicode characters ... | 43.6 | 0.002245 |
def set_fun_prop(f, k, v):
"""Set the value of property `k` to be `v` in function `f`.
We define properties as annotations added to a function throughout
the process of defining a function for verification, e.g. the
argument types. This sets function `f`'s property named `k` to be
value `v`.
... | [
"def",
"set_fun_prop",
"(",
"f",
",",
"k",
",",
"v",
")",
":",
"if",
"not",
"hasattr",
"(",
"f",
",",
"_FUN_PROPS",
")",
":",
"setattr",
"(",
"f",
",",
"_FUN_PROPS",
",",
"{",
"}",
")",
"if",
"not",
"isinstance",
"(",
"getattr",
"(",
"f",
",",
... | 39.8 | 0.001637 |
def W(self,value):
""" set fixed effect design """
if value is None: value = sp.zeros((self._N, 0))
assert value.shape[0]==self._N, 'Dimension mismatch'
self._K = value.shape[1]
self._W = value
self._notify()
self.clear_cache('predict_in_sample','Yres') | [
"def",
"W",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"sp",
".",
"zeros",
"(",
"(",
"self",
".",
"_N",
",",
"0",
")",
")",
"assert",
"value",
".",
"shape",
"[",
"0",
"]",
"==",
"self",
".",
"_N",
"... | 38 | 0.019293 |
def voc_eval(detpath, annopath, imageset_file, classname, cache_dir, ovthresh=0.5, use_07_metric=False):
"""
pascal voc evaluation
:param detpath: detection results detpath.format(classname)
:param annopath: annotations annopath.format(classname)
:param imageset_file: text file containing list of im... | [
"def",
"voc_eval",
"(",
"detpath",
",",
"annopath",
",",
"imageset_file",
",",
"classname",
",",
"cache_dir",
",",
"ovthresh",
"=",
"0.5",
",",
"use_07_metric",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"cache_dir",
")",
... | 36.441441 | 0.001444 |
def _do_api_call(self, method, data):
"""
Convenience method to carry out a standard API call against the
Petfinder API.
:param basestring method: The API method name to call.
:param dict data: Key/value parameters to send to the API method.
This varies based on the ... | [
"def",
"_do_api_call",
"(",
"self",
",",
"method",
",",
"data",
")",
":",
"# Developer API keys, auth tokens, and other standard, required args.",
"data",
".",
"update",
"(",
"{",
"\"key\"",
":",
"self",
".",
"api_key",
",",
"# No API methods currently use this, but we're... | 40.261905 | 0.001732 |
def blueprint(self):
"""
:return: blueprint
:rtype: dict
"""
blueprint = dict()
for key in self.keys():
blueprint[key] = self.is_attribute_visible(key)
return blueprint | [
"def",
"blueprint",
"(",
"self",
")",
":",
"blueprint",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"self",
".",
"keys",
"(",
")",
":",
"blueprint",
"[",
"key",
"]",
"=",
"self",
".",
"is_attribute_visible",
"(",
"key",
")",
"return",
"blueprint"
] | 22.8 | 0.008439 |
def invoke(
src, event_file='event.json',
config_file='config.yaml', profile_name=None,
verbose=False,
):
"""Simulates a call to your function.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:... | [
"def",
"invoke",
"(",
"src",
",",
"event_file",
"=",
"'event.json'",
",",
"config_file",
"=",
"'config.yaml'",
",",
"profile_name",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
")",
":",
"# Load and parse the config file.",
"path_to_config_file",
"=",
"os",
"... | 32.677966 | 0.001007 |
def make_api_method(func):
"""
Provides a single entry point for modifying all API methods.
For now this is limited to allowing the client object to be modified
with an `extra_params` keyword arg to each method, that is then used
as the params for each web service request.
Please note that this... | [
"def",
"make_api_method",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"[",
"0",
"]",
".",
"_extra_params",
"=",
"kwargs",
".",
"pop",
"(",
... | 36.85 | 0.001323 |
def images():
"""Upload images via REST interface
Check if file upload was successful and sanatize user input.
TODO: return file URL instead of filename
"""
if request.method == 'POST':
file_upload = request.files['file']
if file_upload:
image = dict()
imag... | [
"def",
"images",
"(",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"file_upload",
"=",
"request",
".",
"files",
"[",
"'file'",
"]",
"if",
"file_upload",
":",
"image",
"=",
"dict",
"(",
")",
"image",
"[",
"'filename'",
"]",
"=",
"sec... | 39.5 | 0.000951 |
def namify(root_uri):
'''Turns a root uri into a less noisy representation that will probably
make sense in most circumstances. Used by Navigator's __repr__, but can be
overridden if the Navigator is created with a 'name' parameter.'''
root_uri = unidecode.unidecode(decode(unquote(root_uri), 'utf-8'))
... | [
"def",
"namify",
"(",
"root_uri",
")",
":",
"root_uri",
"=",
"unidecode",
".",
"unidecode",
"(",
"decode",
"(",
"unquote",
"(",
"root_uri",
")",
",",
"'utf-8'",
")",
")",
"generic_domains",
"=",
"set",
"(",
"[",
"'localhost'",
",",
"'herokuapp'",
",",
"'... | 34.71831 | 0.001183 |
def export_fem(self, arms=None, format='json', df_kwargs=None):
"""
Export the project's form to event mapping
Parameters
----------
arms : list
Limit exported form event mappings to these arm numbers
format : (``'json'``), ``'csv'``, ``'xml'``
Re... | [
"def",
"export_fem",
"(",
"self",
",",
"arms",
"=",
"None",
",",
"format",
"=",
"'json'",
",",
"df_kwargs",
"=",
"None",
")",
":",
"ret_format",
"=",
"format",
"if",
"format",
"==",
"'df'",
":",
"from",
"pandas",
"import",
"read_csv",
"ret_format",
"=",
... | 34.973684 | 0.001464 |
def copyfile(src, dst):
"""Copy data from src to dst"""
if _samefile(src, dst):
raise Error("`%s` and `%s` are the same file" % (src, dst))
for fn in [src, dst]:
try:
st = os.stat(fn)
except OSError:
# File most likely does not exist
pass
... | [
"def",
"copyfile",
"(",
"src",
",",
"dst",
")",
":",
"if",
"_samefile",
"(",
"src",
",",
"dst",
")",
":",
"raise",
"Error",
"(",
"\"`%s` and `%s` are the same file\"",
"%",
"(",
"src",
",",
"dst",
")",
")",
"for",
"fn",
"in",
"[",
"src",
",",
"dst",
... | 31.473684 | 0.001623 |
def combine_filters(filters, operator=AND):
# type: (Iterable[Any], int) -> Optional[Union[LDAPFilter, LDAPCriteria]]
"""
Combines two LDAP filters, which can be strings or LDAPFilter objects
:param filters: Filters to combine
:param operator: The operator for combination
:return: The combined ... | [
"def",
"combine_filters",
"(",
"filters",
",",
"operator",
"=",
"AND",
")",
":",
"# type: (Iterable[Any], int) -> Optional[Union[LDAPFilter, LDAPCriteria]]",
"if",
"not",
"filters",
":",
"return",
"None",
"if",
"not",
"hasattr",
"(",
"filters",
",",
"\"__iter__\"",
")... | 30.404762 | 0.000759 |
def tilequeue_rawr_enqueue(cfg, args):
"""command to take tile expiry path and enqueue for rawr tile generation"""
from tilequeue.stats import RawrTileEnqueueStatsHandler
from tilequeue.rawr import make_rawr_enqueuer_from_cfg
msg_marshall_yaml = cfg.yml.get('message-marshall')
assert msg_marshall_y... | [
"def",
"tilequeue_rawr_enqueue",
"(",
"cfg",
",",
"args",
")",
":",
"from",
"tilequeue",
".",
"stats",
"import",
"RawrTileEnqueueStatsHandler",
"from",
"tilequeue",
".",
"rawr",
"import",
"make_rawr_enqueuer_from_cfg",
"msg_marshall_yaml",
"=",
"cfg",
".",
"yml",
".... | 43.555556 | 0.001248 |
def query_all(**kwargs):
'''
Qeury recent wiki.
'''
kind = kwargs.get('kind', '1')
limit = kwargs.get('limit', 50)
return TabWiki.select().where(TabWiki.kind == kind).limit(limit) | [
"def",
"query_all",
"(",
"*",
"*",
"kwargs",
")",
":",
"kind",
"=",
"kwargs",
".",
"get",
"(",
"'kind'",
",",
"'1'",
")",
"limit",
"=",
"kwargs",
".",
"get",
"(",
"'limit'",
",",
"50",
")",
"return",
"TabWiki",
".",
"select",
"(",
")",
".",
"wher... | 27.625 | 0.008772 |
def record(self, chunk_size = None,
dfmt = "f",
channels = 1,
rate = DEFAULT_SAMPLE_RATE,
**kwargs
):
"""
Records audio from device into a Stream.
Parameters
----------
chunk_size :
Number of samples per c... | [
"def",
"record",
"(",
"self",
",",
"chunk_size",
"=",
"None",
",",
"dfmt",
"=",
"\"f\"",
",",
"channels",
"=",
"1",
",",
"rate",
"=",
"DEFAULT_SAMPLE_RATE",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"chunk_size",
"is",
"None",
":",
"chunk_size",
"=",
... | 32.136364 | 0.012354 |
def genargs(prog: Optional[str] = None) -> ArgumentParser:
"""
Create a command line parser
:return: parser
"""
parser = ArgumentParser(prog)
parser.add_argument("rdf", help="Input RDF file or SPARQL endpoint if slurper or sparql options")
parser.add_argument("shex", help="ShEx specification... | [
"def",
"genargs",
"(",
"prog",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"ArgumentParser",
":",
"parser",
"=",
"ArgumentParser",
"(",
"prog",
")",
"parser",
".",
"add_argument",
"(",
"\"rdf\"",
",",
"help",
"=",
"\"Input RDF file or SPARQL en... | 74.423077 | 0.008163 |
def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None):
"""Unroll an RNN cell across time steps.
Parameters
----------
length : int
Number of steps to unroll.
inputs : Symbol, list of Symbol, or None
If `inputs` is a single S... | [
"def",
"unroll",
"(",
"self",
",",
"length",
",",
"inputs",
",",
"begin_state",
"=",
"None",
",",
"layout",
"=",
"'NTC'",
",",
"merge_outputs",
"=",
"None",
")",
":",
"self",
".",
"reset",
"(",
")",
"inputs",
",",
"_",
"=",
"_normalize_sequence",
"(",
... | 38.894737 | 0.00176 |
def remove_handler(self, name):
"""
Remove handler from the logging system if present already.
Available handlers are currently: ['console-bw', 'console-color', 'rotating-log']
"""
if name in self.handlers:
self.log.removeHandler(self.handlers[name]) | [
"def",
"remove_handler",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"handlers",
":",
"self",
".",
"log",
".",
"removeHandler",
"(",
"self",
".",
"handlers",
"[",
"name",
"]",
")"
] | 42.285714 | 0.009934 |
def clean_old_jobs():
'''
Clean out minions's return data for old jobs.
Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually
get cleaned by redis.But for jobs with some very late minion return, the
corresponding hset's TTL will be refreshed to a too late timestamp, we'll
do manu... | [
"def",
"clean_old_jobs",
"(",
")",
":",
"serv",
"=",
"_get_serv",
"(",
"ret",
"=",
"None",
")",
"ret_jids",
"=",
"serv",
".",
"keys",
"(",
"'ret:*'",
")",
"living_jids",
"=",
"set",
"(",
"serv",
".",
"keys",
"(",
"'load:*'",
")",
")",
"to_remove",
"=... | 35.9 | 0.001357 |
def losses_by_tag(dstore, tag):
"""
Statistical average losses by tag. For instance call
$ oq extract losses_by_tag/occupancy
"""
dt = [(tag, vstr)] + dstore['oqparam'].loss_dt_list()
aids = dstore['assetcol/array'][tag]
dset, stats = _get(dstore, 'avg_losses')
arr = dset.value
tagv... | [
"def",
"losses_by_tag",
"(",
"dstore",
",",
"tag",
")",
":",
"dt",
"=",
"[",
"(",
"tag",
",",
"vstr",
")",
"]",
"+",
"dstore",
"[",
"'oqparam'",
"]",
".",
"loss_dt_list",
"(",
")",
"aids",
"=",
"dstore",
"[",
"'assetcol/array'",
"]",
"[",
"tag",
"]... | 37.05 | 0.001316 |
def _build_mac_signature_key_information(self, value):
"""
Build an MACSignatureKeyInformation struct from a dictionary.
Args:
value (dict): A dictionary containing the key/value pairs for a
MACSignatureKeyInformation struct.
Returns:
MACSignatur... | [
"def",
"_build_mac_signature_key_information",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"MAC/signature key information mu... | 36.322581 | 0.00173 |
def make_V_and_J_mask_mapping(self, genV, genJ):
"""Constructs the V and J mask mapping dictionaries.
Parameters
----------
genV : list
List of genomic V information.
genJ : list
List of genomic J information.
"""
... | [
"def",
"make_V_and_J_mask_mapping",
"(",
"self",
",",
"genV",
",",
"genJ",
")",
":",
"#construct mapping between allele/gene names and index for custom V_usage_masks",
"V_allele_names",
"=",
"[",
"V",
"[",
"0",
"]",
"for",
"V",
"in",
"genV",
"]",
"V_mask_mapping",
"="... | 43.564103 | 0.009211 |
def rstyle(self, name):
"""
Remove one style
"""
try:
del self.chart_style[name]
except KeyError:
self.warning("Style " + name + " is not set")
except:
self.err("Can not remove style " + name) | [
"def",
"rstyle",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"del",
"self",
".",
"chart_style",
"[",
"name",
"]",
"except",
"KeyError",
":",
"self",
".",
"warning",
"(",
"\"Style \"",
"+",
"name",
"+",
"\" is not set\"",
")",
"except",
":",
"self",... | 20.4 | 0.056338 |
def squeeze(self, trits, offset=0, length=HASH_LENGTH):
# type: (MutableSequence[int], Optional[int], Optional[int]) -> None
"""
Squeeze trits from the sponge.
:param trits:
Sequence that the squeezed trits will be copied to.
Note: this object will be modified!
... | [
"def",
"squeeze",
"(",
"self",
",",
"trits",
",",
"offset",
"=",
"0",
",",
"length",
"=",
"HASH_LENGTH",
")",
":",
"# type: (MutableSequence[int], Optional[int], Optional[int]) -> None",
"# Squeeze is kind of like the opposite of absorb; it copies",
"# trits from internal state t... | 33.810345 | 0.001487 |
def magfit(logfile):
'''find best magnetometer offset fit to a log file'''
print("Processing log %s" % filename)
mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps)
data = []
last_t = 0
offsets = Vector3(0,0,0)
# now gather all the data
while True:
m =... | [
"def",
"magfit",
"(",
"logfile",
")",
":",
"print",
"(",
"\"Processing log %s\"",
"%",
"filename",
")",
"mlog",
"=",
"mavutil",
".",
"mavlink_connection",
"(",
"filename",
",",
"notimestamps",
"=",
"args",
".",
"notimestamps",
")",
"data",
"=",
"[",
"]",
"... | 31.530303 | 0.008854 |
def transform(geom, to_sref):
"""Returns a transformed Geometry.
Arguments:
geom -- any coercible Geometry value or Envelope
to_sref -- SpatialReference or EPSG ID as int
"""
# If we have an envelope, assume it's in the target sref.
try:
geom = getattr(geom, 'polygon', Envelope(geom... | [
"def",
"transform",
"(",
"geom",
",",
"to_sref",
")",
":",
"# If we have an envelope, assume it's in the target sref.",
"try",
":",
"geom",
"=",
"getattr",
"(",
"geom",
",",
"'polygon'",
",",
"Envelope",
"(",
"geom",
")",
".",
"polygon",
")",
"except",
"(",
"T... | 31.76 | 0.001222 |
def _get_spec(self, index):
user_data = self.itemData(index)
""" :type: QVariant"""
spec = user_data.toPyObject()
return {str(key): value for key, value in spec.items()} | [
"def",
"_get_spec",
"(",
"self",
",",
"index",
")",
":",
"user_data",
"=",
"self",
".",
"itemData",
"(",
"index",
")",
"spec",
"=",
"user_data",
".",
"toPyObject",
"(",
")",
"return",
"{",
"str",
"(",
"key",
")",
":",
"value",
"for",
"key",
",",
"v... | 39.4 | 0.00995 |
def output_eol_literal_marker(self, m):
"""Pass through rest link."""
marker = ':' if m.group(1) is None else ''
return self.renderer.eol_literal_marker(marker) | [
"def",
"output_eol_literal_marker",
"(",
"self",
",",
"m",
")",
":",
"marker",
"=",
"':'",
"if",
"m",
".",
"group",
"(",
"1",
")",
"is",
"None",
"else",
"''",
"return",
"self",
".",
"renderer",
".",
"eol_literal_marker",
"(",
"marker",
")"
] | 45.25 | 0.01087 |
def algorithm_u(ns, m):
"""
taken from `Stack Overflow <https://codereview.stackexchange.com/questions/1526/finding-all-k-subset-partitions>`_
"""
def visit(nv, av):
ps = [[] for _ in range(m)]
for jv in range(nv):
ps[av[jv + 1]].append(ns[jv])
return ps
def f(m... | [
"def",
"algorithm_u",
"(",
"ns",
",",
"m",
")",
":",
"def",
"visit",
"(",
"nv",
",",
"av",
")",
":",
"ps",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"m",
")",
"]",
"for",
"jv",
"in",
"range",
"(",
"nv",
")",
":",
"ps",
"[",
"av"... | 30.35 | 0.000798 |
def SetAttributes(self,
urn,
attributes,
to_delete,
add_child_index=True,
mutation_pool=None):
"""Sets the attributes in the data store."""
attributes[AFF4Object.SchemaCls.LAST] = [
rdfvalue.RDFDatetime.... | [
"def",
"SetAttributes",
"(",
"self",
",",
"urn",
",",
"attributes",
",",
"to_delete",
",",
"add_child_index",
"=",
"True",
",",
"mutation_pool",
"=",
"None",
")",
":",
"attributes",
"[",
"AFF4Object",
".",
"SchemaCls",
".",
"LAST",
"]",
"=",
"[",
"rdfvalue... | 29 | 0.014514 |
def _replace(self, **kwds):
'Return a new NamedTuple object replacing specified fields with new values'
result = self._make(map(kwds.pop, self._fields, self))
if kwds:
raise ValueError('Got unexpected field names: %r' % kwds.keys())
return result | [
"def",
"_replace",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
":",
"result",
"=",
"self",
".",
"_make",
"(",
"map",
"(",
"kwds",
".",
"pop",
",",
"self",
".",
"_fields",
",",
"self",
")",
")",
"if",
"kwds",
":",
"raise",
"ValueError",
"(",
"'Got un... | 37.625 | 0.016234 |
def execute(self, method, args, kwargs):
"""
Execute the given method and stores its result.
The result is considered "done" even if the method raises an exception
:param method: The method to execute
:param args: Method positional arguments
:param kwargs: Method keyword... | [
"def",
"execute",
"(",
"self",
",",
"method",
",",
"args",
",",
"kwargs",
")",
":",
"# Normalize arguments",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"[",
"]",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"try",
":",
"# Call the m... | 31.866667 | 0.00203 |
def kappa_analysis_cicchetti(kappa):
"""
Analysis kappa number with Cicchetti benchmark.
:param kappa: kappa number
:type kappa : float
:return: strength of agreement as str
"""
try:
if kappa < 0.4:
return "Poor"
if kappa >= 0.4 and kappa < 0.59:
retu... | [
"def",
"kappa_analysis_cicchetti",
"(",
"kappa",
")",
":",
"try",
":",
"if",
"kappa",
"<",
"0.4",
":",
"return",
"\"Poor\"",
"if",
"kappa",
">=",
"0.4",
"and",
"kappa",
"<",
"0.59",
":",
"return",
"\"Fair\"",
"if",
"kappa",
">=",
"0.59",
"and",
"kappa",
... | 26.85 | 0.001799 |
def update_translations(self, entries, translated_strings):
"""Update translations in entries.
The order and number of translations should match to get_strings_to_translate() result.
:param entries: list of entries to translate
:type entries: collections.Iterable[polib.POEntry] | polib... | [
"def",
"update_translations",
"(",
"self",
",",
"entries",
",",
"translated_strings",
")",
":",
"translations",
"=",
"iter",
"(",
"translated_strings",
")",
"for",
"entry",
"in",
"entries",
":",
"if",
"not",
"self",
".",
"need_translate",
"(",
"entry",
")",
... | 44.971429 | 0.002488 |
def create_one(self, commit=True):
'''
Create and return one model instance. If *commit* is ``False`` the
instance will not be saved and many to many relations will not be
processed.
Subclasses that override ``create_one`` can specify arbitrary keyword
arguments. They wi... | [
"def",
"create_one",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"tries",
"=",
"self",
".",
"tries",
"instance",
"=",
"self",
".",
"model",
"(",
")",
"process",
"=",
"instance",
".",
"_meta",
".",
"fields",
"while",
"process",
"and",
"tries",
... | 40.610169 | 0.002445 |
def query_edges_by_pubmed_identifiers(self, pubmed_identifiers: List[str]) -> List[Edge]:
"""Get all edges annotated to the documents identified by the given PubMed identifiers."""
fi = and_(Citation.type == CITATION_TYPE_PUBMED, Citation.reference.in_(pubmed_identifiers))
return self.session.qu... | [
"def",
"query_edges_by_pubmed_identifiers",
"(",
"self",
",",
"pubmed_identifiers",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Edge",
"]",
":",
"fi",
"=",
"and_",
"(",
"Citation",
".",
"type",
"==",
"CITATION_TYPE_PUBMED",
",",
"Citation",
".",
... | 93.25 | 0.015957 |
def node_display(root, expandattrs=False, expandvals=False, output=sys.stdout):
"""
Write an indented representation of the Node object on the output;
this is intended for testing/debugging purposes.
:param root: a Node object
:param bool expandattrs: if True, the values of the attributes are
... | [
"def",
"node_display",
"(",
"root",
",",
"expandattrs",
"=",
"False",
",",
"expandvals",
"=",
"False",
",",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"_display",
"(",
"root",
",",
"''",
",",
"expandattrs",
",",
"expandvals",
",",
"output",
")"
] | 48.692308 | 0.00155 |
def min_interp(interp_object):
"""
Find the global minimum of a function represented as an interpolation object.
"""
try:
return interp_object.x[interp_object(interp_object.x).argmin()]
except Exception as e:
s = "Cannot find minimum of the interpolation object" + str(interp_object.x... | [
"def",
"min_interp",
"(",
"interp_object",
")",
":",
"try",
":",
"return",
"interp_object",
".",
"x",
"[",
"interp_object",
"(",
"interp_object",
".",
"x",
")",
".",
"argmin",
"(",
")",
"]",
"except",
"Exception",
"as",
"e",
":",
"s",
"=",
"\"Cannot find... | 42.8 | 0.011442 |
def diff(name, **kwargs):
'''
Gets the difference between the candidate and the current configuration.
.. code-block:: yaml
get the diff:
junos:
- diff
- id: 10
Parameters:
Optional
* id:
The rollback id value [0-49]. (... | [
"def",
"diff",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"__salt__",... | 24.315789 | 0.002083 |
def sersic_constant(self):
""" A parameter derived from Sersic index which ensures that effective radius contains 50% of the profile's
total integrated light.
"""
return (2 * self.sersic_index) - (1. / 3.) + (4. / (405. * self.sersic_index)) + (
46. / (25515. * self.sersi... | [
"def",
"sersic_constant",
"(",
"self",
")",
":",
"return",
"(",
"2",
"*",
"self",
".",
"sersic_index",
")",
"-",
"(",
"1.",
"/",
"3.",
")",
"+",
"(",
"4.",
"/",
"(",
"405.",
"*",
"self",
".",
"sersic_index",
")",
")",
"+",
"(",
"46.",
"/",
"(",... | 64.857143 | 0.01087 |
def mkdir(self, foldername):
'Create a new subfolder and return the new JFSFolder'
#url = '%s?mkDir=true' % posixpath.join(self.path, foldername)
url = posixpath.join(self.path, foldername)
params = {'mkDir':'true'}
r = self.jfs.post(url, params)
self.sync()
retur... | [
"def",
"mkdir",
"(",
"self",
",",
"foldername",
")",
":",
"#url = '%s?mkDir=true' % posixpath.join(self.path, foldername)",
"url",
"=",
"posixpath",
".",
"join",
"(",
"self",
".",
"path",
",",
"foldername",
")",
"params",
"=",
"{",
"'mkDir'",
":",
"'true'",
"}",... | 39.5 | 0.012384 |
async def open_session(self, request: BaseRequestWebsocket) -> Session:
"""Open and return a Session using the request."""
return await ensure_coroutine(self.session_interface.open_session)(self, request) | [
"async",
"def",
"open_session",
"(",
"self",
",",
"request",
":",
"BaseRequestWebsocket",
")",
"->",
"Session",
":",
"return",
"await",
"ensure_coroutine",
"(",
"self",
".",
"session_interface",
".",
"open_session",
")",
"(",
"self",
",",
"request",
")"
] | 72.666667 | 0.013636 |
def _read_record(self, f, blk, chans):
"""Read raw data from a single EDF channel.
Parameters
----------
i_chan : int
index of the channel to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Re... | [
"def",
"_read_record",
"(",
"self",
",",
"f",
",",
"blk",
",",
"chans",
")",
":",
"dat_in_rec",
"=",
"empty",
"(",
"(",
"len",
"(",
"chans",
")",
",",
"self",
".",
"max_smp",
")",
")",
"i_ch_in_dat",
"=",
"0",
"for",
"i_ch",
"in",
"chans",
":",
"... | 27.548387 | 0.002262 |
def CmykToCmy(c, m, y, k):
'''Convert the color from CMYK coordinates to CMY.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:k:
The Black component value [0...1]
Return... | [
"def",
"CmykToCmy",
"(",
"c",
",",
"m",
",",
"y",
",",
"k",
")",
":",
"mk",
"=",
"1",
"-",
"k",
"return",
"(",
"(",
"c",
"*",
"mk",
"+",
"k",
")",
",",
"(",
"m",
"*",
"mk",
"+",
"k",
")",
",",
"(",
"y",
"*",
"mk",
"+",
"k",
")",
")"... | 21.88 | 0.001751 |
def get_Zstar(x_segment, y_segment, x_int, y_int, slope, n):
"""
input: x_segment, y_segment, x_int, y_int, slope, n
output: Z* (Arai plot zigzag parameter (alternate))
"""
total = 0
first_time = True
for num, x in enumerate(x_segment):
b_wiggle = get_b_wiggle(x, y_segment[num], y_in... | [
"def",
"get_Zstar",
"(",
"x_segment",
",",
"y_segment",
",",
"x_int",
",",
"y_int",
",",
"slope",
",",
"n",
")",
":",
"total",
"=",
"0",
"first_time",
"=",
"True",
"for",
"num",
",",
"x",
"in",
"enumerate",
"(",
"x_segment",
")",
":",
"b_wiggle",
"="... | 35.928571 | 0.00969 |
def linspace(self,dim,*args,**kwargs):
"""
Creates a range of values for a specific dimension that go from its minimum to its
maximum either in certain steps (resolution != None) or a fixed number of bins
(bins != None). The output can be converted into a different unit (eg... | [
"def",
"linspace",
"(",
"self",
",",
"dim",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"spike_times",
".",
"get_label",
"(",
"dim",
")",
".",
"linspace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 51.272727 | 0.013925 |
def readsleb128(buff):
"""
Read a signed LEB128 at the current position of the buffer.
:param buff: a file like object
:return: decoded sLEB128
"""
result = 0
shift = 0
for x in range(0, 5):
cur = get_byte(buff)
result |= (cur & 0x7f) << shift
shift += 7
... | [
"def",
"readsleb128",
"(",
"buff",
")",
":",
"result",
"=",
"0",
"shift",
"=",
"0",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"5",
")",
":",
"cur",
"=",
"get_byte",
"(",
"buff",
")",
"result",
"|=",
"(",
"cur",
"&",
"0x7f",
")",
"<<",
"shift",
... | 23.833333 | 0.001681 |
def _read_layers(self, layers, image_id):
""" Reads the JSON metadata for specified layer / image id """
for layer in self.docker.history(image_id):
layers.append(layer['Id']) | [
"def",
"_read_layers",
"(",
"self",
",",
"layers",
",",
"image_id",
")",
":",
"for",
"layer",
"in",
"self",
".",
"docker",
".",
"history",
"(",
"image_id",
")",
":",
"layers",
".",
"append",
"(",
"layer",
"[",
"'Id'",
"]",
")"
] | 40 | 0.009804 |
def Lewis(D=None, alpha=None, Cp=None, k=None, rho=None):
r'''Calculates Lewis number or `Le` for a fluid with the given parameters.
.. math::
Le = \frac{k}{\rho C_p D} = \frac{\alpha}{D}
Inputs can be either of the following sets:
* Diffusivity and Thermal diffusivity
* Diffusivity, heat... | [
"def",
"Lewis",
"(",
"D",
"=",
"None",
",",
"alpha",
"=",
"None",
",",
"Cp",
"=",
"None",
",",
"k",
"=",
"None",
",",
"rho",
"=",
"None",
")",
":",
"if",
"k",
"and",
"Cp",
"and",
"rho",
":",
"alpha",
"=",
"k",
"/",
"(",
"rho",
"*",
"Cp",
... | 27.9 | 0.000577 |
def optimal_partitions(sizes, counts, num_part):
"""Compute the optimal partitions given a distribution of set sizes.
Args:
sizes (numpy.array): The complete domain of set sizes in ascending
order.
counts (numpy.array): The frequencies of all set sizes in the same
order ... | [
"def",
"optimal_partitions",
"(",
"sizes",
",",
"counts",
",",
"num_part",
")",
":",
"if",
"num_part",
"<",
"2",
":",
"return",
"[",
"(",
"sizes",
"[",
"0",
"]",
",",
"sizes",
"[",
"-",
"1",
"]",
")",
"]",
"if",
"num_part",
">=",
"len",
"(",
"siz... | 38.391304 | 0.001105 |
def register_checker(self, checker):
"""register a new checker
checker is an object implementing IRawChecker or / and IAstroidChecker
"""
assert checker.priority <= 0, "checker priority can't be >= 0"
self._checkers[checker.name].append(checker)
for r_id, r_title, r_cb i... | [
"def",
"register_checker",
"(",
"self",
",",
"checker",
")",
":",
"assert",
"checker",
".",
"priority",
"<=",
"0",
",",
"\"checker priority can't be >= 0\"",
"self",
".",
"_checkers",
"[",
"checker",
".",
"name",
"]",
".",
"append",
"(",
"checker",
")",
"for... | 43.611111 | 0.002494 |
def ravd(result, reference):
"""
Relative absolute volume difference.
Compute the relative absolute volume difference between the (joined) binary objects
in the two images.
Parameters
----------
result : array_like
Input data containing objects. Can be any type but will be ... | [
"def",
"ravd",
"(",
"result",
",",
"reference",
")",
":",
"result",
"=",
"numpy",
".",
"atleast_1d",
"(",
"result",
".",
"astype",
"(",
"numpy",
".",
"bool",
")",
")",
"reference",
"=",
"numpy",
".",
"atleast_1d",
"(",
"reference",
".",
"astype",
"(",
... | 28.465116 | 0.010265 |
def _get_price(self, data, market, field):
"""
Given the data (in json format), returns the
field for a given market.
"""
for m in data:
if m["symbol"] == market:
return m[field] | [
"def",
"_get_price",
"(",
"self",
",",
"data",
",",
"market",
",",
"field",
")",
":",
"for",
"m",
"in",
"data",
":",
"if",
"m",
"[",
"\"symbol\"",
"]",
"==",
"market",
":",
"return",
"m",
"[",
"field",
"]"
] | 29.875 | 0.00813 |
def length(self):
"""Length in Feet (f)"""
length = self.parse['attributes'].get('Shape_Length')
if length:
return round(float(length)) | [
"def",
"length",
"(",
"self",
")",
":",
"length",
"=",
"self",
".",
"parse",
"[",
"'attributes'",
"]",
".",
"get",
"(",
"'Shape_Length'",
")",
"if",
"length",
":",
"return",
"round",
"(",
"float",
"(",
"length",
")",
")"
] | 33.4 | 0.011696 |
def download_mail_attachments(self,
name,
local_output_directory,
mail_folder='INBOX',
check_regex=False,
latest_only=False,
... | [
"def",
"download_mail_attachments",
"(",
"self",
",",
"name",
",",
"local_output_directory",
",",
"mail_folder",
"=",
"'INBOX'",
",",
"check_regex",
"=",
"False",
",",
"latest_only",
"=",
"False",
",",
"not_found_mode",
"=",
"'raise'",
")",
":",
"mail_attachments"... | 52.815789 | 0.008317 |
def list(self, limit=None, page_size=None):
"""
Lists KeyInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param int limit: Upper limit for the number of records to return. list() guaran... | [
"def",
"list",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"return",
"list",
"(",
"self",
".",
"stream",
"(",
"limit",
"=",
"limit",
",",
"page_size",
"=",
"page_size",
",",
")",
")"
] | 56.705882 | 0.008163 |
def run_as_admin(command, cwd=None, environ=None):
"""
Runs a command as an admin in the specified *cwd* and *environ*.
On Windows, this creates a temporary directory where this information
is stored temporarily so that the new process can launch the proper
subprocess.
"""
if isinstance(command, str):
... | [
"def",
"run_as_admin",
"(",
"command",
",",
"cwd",
"=",
"None",
",",
"environ",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"command",
",",
"str",
")",
":",
"command",
"=",
"shlex",
".",
"split",
"(",
"command",
")",
"if",
"os",
".",
"name",
"=... | 29.8 | 0.009756 |
def user_verify_password(user_id=None, name=None, password=None,
profile=None, **connection_args):
'''
Verify a user's password
CLI Examples:
.. code-block:: bash
salt '*' keystone.user_verify_password name=test password=foobar
salt '*' keystone.user_verify_pa... | [
"def",
"user_verify_password",
"(",
"user_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"password",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"kstone",
"=",
"auth",
"(",
"profile",
",",
"*",
"*",
"connecti... | 35.021739 | 0.001208 |
def selection(self):
"""Returns items in selection as a QItemSelection object"""
sel = QtGui.QItemSelection()
for index in self.selectedIndexes():
sel.select(index, index)
return sel | [
"def",
"selection",
"(",
"self",
")",
":",
"sel",
"=",
"QtGui",
".",
"QItemSelection",
"(",
")",
"for",
"index",
"in",
"self",
".",
"selectedIndexes",
"(",
")",
":",
"sel",
".",
"select",
"(",
"index",
",",
"index",
")",
"return",
"sel"
] | 36.833333 | 0.00885 |
def clipTo(self, bsp):
"""
Remove all polygons in this BSP tree that are inside the other BSP tree
`bsp`.
"""
self.polygons = bsp.clipPolygons(self.polygons)
if self.front:
self.front.clipTo(bsp)
if self.back:
self.back.clipTo(bsp) | [
"def",
"clipTo",
"(",
"self",
",",
"bsp",
")",
":",
"self",
".",
"polygons",
"=",
"bsp",
".",
"clipPolygons",
"(",
"self",
".",
"polygons",
")",
"if",
"self",
".",
"front",
":",
"self",
".",
"front",
".",
"clipTo",
"(",
"bsp",
")",
"if",
"self",
... | 30.5 | 0.015924 |
def notify(cls, user_or_email_, object_id=None, **filters):
"""Start notifying the given user or email address when this event
occurs and meets the criteria given in ``filters``.
Return the created (or the existing matching) Watch so you can call
:meth:`~tidings.models.Watch.activate()`... | [
"def",
"notify",
"(",
"cls",
",",
"user_or_email_",
",",
"object_id",
"=",
"None",
",",
"*",
"*",
"filters",
")",
":",
"# A test-for-existence-then-create race condition exists here, but it",
"# doesn't matter: de-duplication on fire() and deletion of all matches",
"# on stop_not... | 46.140625 | 0.000663 |
def selected(self):
"""Action to be executed when a valid item has been selected"""
EditableComboBox.selected(self)
self.open_dir.emit(self.currentText()) | [
"def",
"selected",
"(",
"self",
")",
":",
"EditableComboBox",
".",
"selected",
"(",
"self",
")",
"self",
".",
"open_dir",
".",
"emit",
"(",
"self",
".",
"currentText",
"(",
")",
")"
] | 44.5 | 0.01105 |
def namedb_get_all_namespace_ids( cur ):
"""
Get a list of all READY namespace IDs.
"""
query = "SELECT namespace_id FROM namespaces WHERE op = ?;"
args = (NAMESPACE_READY,)
namespace_rows = namedb_query_execute( cur, query, args )
ret = []
for namespace_row in namespace_rows:
... | [
"def",
"namedb_get_all_namespace_ids",
"(",
"cur",
")",
":",
"query",
"=",
"\"SELECT namespace_id FROM namespaces WHERE op = ?;\"",
"args",
"=",
"(",
"NAMESPACE_READY",
",",
")",
"namespace_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"query",
",",
"args",
")"... | 26.142857 | 0.01847 |
def newick_replace_otuids(tree, biomf):
"""
Replace the OTU ids in the Newick phylogenetic tree format with truncated
OTU names
"""
for val, id_, md in biomf.iter(axis="observation"):
otu_loc = find_otu(id_, tree)
if otu_loc is not None:
tree = tree[:otu_loc] + \
... | [
"def",
"newick_replace_otuids",
"(",
"tree",
",",
"biomf",
")",
":",
"for",
"val",
",",
"id_",
",",
"md",
"in",
"biomf",
".",
"iter",
"(",
"axis",
"=",
"\"observation\"",
")",
":",
"otu_loc",
"=",
"find_otu",
"(",
"id_",
",",
"tree",
")",
"if",
"otu_... | 34.333333 | 0.002364 |
def _datetime_to_rfc3339(value, ignore_zone=True):
"""Convert a timestamp to a string.
:type value: :class:`datetime.datetime`
:param value: The datetime object to be converted to a string.
:type ignore_zone: bool
:param ignore_zone: If True, then the timezone (if any) of the datetime
... | [
"def",
"_datetime_to_rfc3339",
"(",
"value",
",",
"ignore_zone",
"=",
"True",
")",
":",
"if",
"not",
"ignore_zone",
"and",
"value",
".",
"tzinfo",
"is",
"not",
"None",
":",
"# Convert to UTC and remove the time zone info.",
"value",
"=",
"value",
".",
"replace",
... | 35.111111 | 0.001541 |
def list_to_dict(lst, key=None, remove_key=True):
""" convert a list of dicts to a dict with root keys
Parameters
----------
lst : list[dict]
key : str or None
a key contained by all of the dicts
if None use index number string
remove_key : bool
remove key from dicts in ... | [
"def",
"list_to_dict",
"(",
"lst",
",",
"key",
"=",
"None",
",",
"remove_key",
"=",
"True",
")",
":",
"assert",
"all",
"(",
"[",
"is_dict_like",
"(",
"d",
")",
"for",
"d",
"in",
"lst",
"]",
")",
"if",
"key",
"is",
"not",
"None",
":",
"assert",
"a... | 25.1 | 0.000959 |
def snip(tag="",start=-2,write_date=True):
"""
This function records a previously execute notebook cell into a file (default: ipython_history.py)
a tag can be added to sort the cell
`start` defines which cell in the history to record. Default is -2, ie. the one executed previously to the ... | [
"def",
"snip",
"(",
"tag",
"=",
"\"\"",
",",
"start",
"=",
"-",
"2",
",",
"write_date",
"=",
"True",
")",
":",
"import",
"IPython",
"i",
"=",
"IPython",
".",
"get_ipython",
"(",
")",
"last_history",
"=",
"i",
".",
"history_manager",
".",
"get_range",
... | 46.678571 | 0.011244 |
def values(self):
"""
Iterate values.
"""
for key, value in self.__data__.items():
if key not in (META, KEY):
yield DictTree(__data__=value) | [
"def",
"values",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__data__",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"(",
"META",
",",
"KEY",
")",
":",
"yield",
"DictTree",
"(",
"__data__",
"=",
"value",
")"
] | 27.714286 | 0.01 |
def get_if_list():
"""Returns a list containing all network interfaces."""
# Get ifconfig output
try:
fd = os.popen("%s -a" % conf.prog.ifconfig)
except OSError as msg:
raise Scapy_Exception("Failed to execute ifconfig: (%s)" % msg)
# Get interfaces
interfaces = [line[:line.fin... | [
"def",
"get_if_list",
"(",
")",
":",
"# Get ifconfig output",
"try",
":",
"fd",
"=",
"os",
".",
"popen",
"(",
"\"%s -a\"",
"%",
"conf",
".",
"prog",
".",
"ifconfig",
")",
"except",
"OSError",
"as",
"msg",
":",
"raise",
"Scapy_Exception",
"(",
"\"Failed to ... | 31.692308 | 0.002358 |
def get_param_descriptor(mcs,param_name):
"""
Goes up the class hierarchy (starting from the current class)
looking for a Parameter class attribute param_name. As soon as
one is found as a class attribute, that Parameter is returned
along with the class in which it is declared.
... | [
"def",
"get_param_descriptor",
"(",
"mcs",
",",
"param_name",
")",
":",
"classes",
"=",
"classlist",
"(",
"mcs",
")",
"for",
"c",
"in",
"classes",
"[",
":",
":",
"-",
"1",
"]",
":",
"attribute",
"=",
"c",
".",
"__dict__",
".",
"get",
"(",
"param_name... | 41.692308 | 0.01083 |
def get_pipeline_path(pipeline_name, working_directory):
"""Look for the pipeline in the various places it could be.
First checks the cwd. Then checks pypyr/pipelines dir.
Args:
pipeline_name: string. Name of pipeline to find
working_directory: string. Path in which to look for pipeline_na... | [
"def",
"get_pipeline_path",
"(",
"pipeline_name",
",",
"working_directory",
")",
":",
"logger",
".",
"debug",
"(",
"\"starting\"",
")",
"# look for name.yaml in the pipelines/ sub-directory",
"logger",
".",
"debug",
"(",
"f\"current directory is {working_directory}\"",
")",
... | 36.235294 | 0.000527 |
def latex(self):
"""Gives a latex representation of the assessment."""
output = self.latex_preamble
output += self._repr_latex_()
output += self.latex_post
return output | [
"def",
"latex",
"(",
"self",
")",
":",
"output",
"=",
"self",
".",
"latex_preamble",
"output",
"+=",
"self",
".",
"_repr_latex_",
"(",
")",
"output",
"+=",
"self",
".",
"latex_post",
"return",
"output"
] | 34 | 0.009569 |
def from_csv(filename_or_buffer, copy_index=True, **kwargs):
"""Shortcut to read a csv file using pandas and convert to a DataFrame directly.
:rtype: DataFrame
"""
import pandas as pd
return from_pandas(pd.read_csv(filename_or_buffer, **kwargs), copy_index=copy_index) | [
"def",
"from_csv",
"(",
"filename_or_buffer",
",",
"copy_index",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"pandas",
"as",
"pd",
"return",
"from_pandas",
"(",
"pd",
".",
"read_csv",
"(",
"filename_or_buffer",
",",
"*",
"*",
"kwargs",
")",
... | 40.428571 | 0.010381 |
def welch(timeseries, segmentlength, noverlap=None, scheme=None, **kwargs):
"""Calculate a PSD using Welch's method with a mean average
Parameters
----------
timeseries : `~gwpy.timeseries.TimeSeries`
input `TimeSeries` data.
segmentlength : `int`
number of samples in single averag... | [
"def",
"welch",
"(",
"timeseries",
",",
"segmentlength",
",",
"noverlap",
"=",
"None",
",",
"scheme",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"pycbc",
".",
"psd",
"import",
"welch",
"as",
"pycbc_welch",
"# default to 'standard' welch",
"kwarg... | 29.117647 | 0.000651 |
def step_rhythmic(self, tau=1.0, error_coupling=1.0):
"""Generate a single step of x for rhythmic
closed loop movements. Decaying from 1 to 0
according to dx = -ax*x.
tau float: gain on execution time
increase tau to make the system execute faster
er... | [
"def",
"step_rhythmic",
"(",
"self",
",",
"tau",
"=",
"1.0",
",",
"error_coupling",
"=",
"1.0",
")",
":",
"self",
".",
"x",
"+=",
"(",
"1",
"*",
"error_coupling",
"*",
"tau",
")",
"*",
"self",
".",
"dt",
"return",
"self",
".",
"x"
] | 40.727273 | 0.010917 |
def build_uda_config_overrides(targets):
""" Returns a list of UDAs defined by given targets
For all targets in `targets`, build a dictionary of configuration overrides
representing the UDAs defined by the passed-in services (`targets`).
Given a hypothetical situation in which you have two services, t... | [
"def",
"build_uda_config_overrides",
"(",
"targets",
")",
":",
"from",
"bugwarrior",
".",
"services",
"import",
"get_service",
"targets_udas",
"=",
"{",
"}",
"for",
"target",
"in",
"targets",
":",
"targets_udas",
".",
"update",
"(",
"get_service",
"(",
"target",... | 32.307692 | 0.00077 |
def poll(
self,
transaction_hash: bytes,
):
""" Wait until the `transaction_hash` is applied or rejected.
Args:
transaction_hash: Transaction hash that we are waiting for.
"""
if len(transaction_hash) != 32:
raise ValueError(
... | [
"def",
"poll",
"(",
"self",
",",
"transaction_hash",
":",
"bytes",
",",
")",
":",
"if",
"len",
"(",
"transaction_hash",
")",
"!=",
"32",
":",
"raise",
"ValueError",
"(",
"'transaction_hash must be a 32 byte hash'",
",",
")",
"transaction_hash",
"=",
"encode_hex"... | 35.895833 | 0.00226 |
def _strategy(codes, context):
"""
Convert SRE regex parse tree to strategy that generates strings matching that
regex represented by that parse tree.
`codes` is either a list of SRE regex elements representations or a particular
element representation. Each element is a tuple of element code (as s... | [
"def",
"_strategy",
"(",
"codes",
",",
"context",
")",
":",
"if",
"not",
"isinstance",
"(",
"codes",
",",
"tuple",
")",
":",
"# List of codes",
"strategies",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"codes",
")",
":",
"if",
"cod... | 36.225 | 0.001847 |
def readList(self):
"""
Read a C{list} from the data stream.
"""
obj = []
self.context.addObject(obj)
l = self.stream.read_ulong()
for i in xrange(l):
obj.append(self.readElement())
return obj | [
"def",
"readList",
"(",
"self",
")",
":",
"obj",
"=",
"[",
"]",
"self",
".",
"context",
".",
"addObject",
"(",
"obj",
")",
"l",
"=",
"self",
".",
"stream",
".",
"read_ulong",
"(",
")",
"for",
"i",
"in",
"xrange",
"(",
"l",
")",
":",
"obj",
".",... | 21.583333 | 0.011111 |
def load_umls():
"""UMLs Dataset.
The data consists of information about a 135 Graph and the relations between
their nodes given as a DataFrame with three columns, source, target and type,
indicating which nodes are related and with which type of link. The target is
a 1d numpy binary integer array ... | [
"def",
"load_umls",
"(",
")",
":",
"dataset_path",
"=",
"_load",
"(",
"'umls'",
")",
"X",
"=",
"_load_csv",
"(",
"dataset_path",
",",
"'data'",
")",
"y",
"=",
"X",
".",
"pop",
"(",
"'label'",
")",
".",
"values",
"graph",
"=",
"nx",
".",
"Graph",
"(... | 37.470588 | 0.009188 |
def make_flatten(decl_or_decls):
"""
Converts tree representation of declarations to flatten one.
:param decl_or_decls: reference to list of declaration's or single
declaration
:type decl_or_decls: :class:`declaration_t` or [ :class:`declaration_t` ]
:rtype: [ all internal declarations ]
... | [
"def",
"make_flatten",
"(",
"decl_or_decls",
")",
":",
"def",
"proceed_single",
"(",
"decl",
")",
":",
"answer",
"=",
"[",
"decl",
"]",
"if",
"not",
"isinstance",
"(",
"decl",
",",
"scopedef_t",
")",
":",
"return",
"answer",
"for",
"elem",
"in",
"decl",
... | 28.16129 | 0.001107 |
def excess_drawdown_idx(self, benchmark, method="caer"):
"""Excess drawdown index; TSeries of excess drawdowns.
There are several ways of computing this metric. For highly
volatile returns, the `method` specified will have a
non-negligible effect on the result.
Parameters
... | [
"def",
"excess_drawdown_idx",
"(",
"self",
",",
"benchmark",
",",
"method",
"=",
"\"caer\"",
")",
":",
"# TODO: plot these (compared) in docs.",
"if",
"isinstance",
"(",
"method",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"method",
"=",
"[",
"\"caer\"",
... | 35.758621 | 0.000939 |
def _migrate_subresources(parent, migrations):
"""
Migrate a resource's subresources
:param parent: the parent perch.Document instance
:param migrations: the migrations for a resource
"""
for subresource, resource_migrations in migrations.items():
parent = _migrate_subresource(
... | [
"def",
"_migrate_subresources",
"(",
"parent",
",",
"migrations",
")",
":",
"for",
"subresource",
",",
"resource_migrations",
"in",
"migrations",
".",
"items",
"(",
")",
":",
"parent",
"=",
"_migrate_subresource",
"(",
"subresource",
",",
"parent",
",",
"resourc... | 26.866667 | 0.002398 |
def backward_word_extend_selection(self, e): #
u"""Move back to the start of the current or previous word. Words are
composed of letters and digits."""
self.l_buffer.backward_word_extend_selection(self.argument_reset)
self.finalize() | [
"def",
"backward_word_extend_selection",
"(",
"self",
",",
"e",
")",
":",
"# \r",
"self",
".",
"l_buffer",
".",
"backward_word_extend_selection",
"(",
"self",
".",
"argument_reset",
")",
"self",
".",
"finalize",
"(",
")"
] | 53.2 | 0.014815 |
def get_bucket_name(self):
'''get or return the s3 bucket name. If not yet defined via an environment
variable or setting, we create a name with the pattern.
sregistry-<robotnamer>-<1234>
You can use the following environment variables to determine
interacti... | [
"def",
"get_bucket_name",
"(",
"self",
")",
":",
"# Get bucket name",
"bucket_name",
"=",
"'sregistry-%s'",
"%",
"RobotNamer",
"(",
")",
".",
"generate",
"(",
")",
"self",
".",
"bucket_name",
"=",
"self",
".",
"_get_and_update_setting",
"(",
"'SREGISTRY_S3_BUCKET'... | 45.2 | 0.008671 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.