text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def merge(self, other, reference_seq):
'''Tries to merge this VcfRecord with other VcfRecord.
Simple example (working in 0-based coords):
ref = ACGT
var1 = SNP at position 1, C->G
var2 = SNP at position 3, T->A
then this returns new variant, position=1, REF=CGT, ALT=GGA.
... | [
"def",
"merge",
"(",
"self",
",",
"other",
",",
"reference_seq",
")",
":",
"if",
"self",
".",
"CHROM",
"!=",
"other",
".",
"CHROM",
"or",
"self",
".",
"intersects",
"(",
"other",
")",
"or",
"len",
"(",
"self",
".",
"ALT",
")",
"!=",
"1",
"or",
"l... | 37.234043 | 0.00167 |
def rstrip(self, chars=None):
""" Like str.rstrip, except it returns the Colr instance. """
return self.__class__(
self._str_strip('rstrip', chars),
no_closing=chars and (closing_code in chars),
) | [
"def",
"rstrip",
"(",
"self",
",",
"chars",
"=",
"None",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"_str_strip",
"(",
"'rstrip'",
",",
"chars",
")",
",",
"no_closing",
"=",
"chars",
"and",
"(",
"closing_code",
"in",
"chars",
")",
... | 39.833333 | 0.008197 |
def suppress_keyboard_interrupt_message():
"""Register a new excepthook to suppress KeyboardInterrupt
exception messages, and exit with status code 130.
"""
old_excepthook = sys.excepthook
def new_hook(type, value, traceback):
if type != KeyboardInterrupt:
old_excepthook(type, ... | [
"def",
"suppress_keyboard_interrupt_message",
"(",
")",
":",
"old_excepthook",
"=",
"sys",
".",
"excepthook",
"def",
"new_hook",
"(",
"type",
",",
"value",
",",
"traceback",
")",
":",
"if",
"type",
"!=",
"KeyboardInterrupt",
":",
"old_excepthook",
"(",
"type",
... | 28.214286 | 0.002451 |
def _align_method_FRAME(left, right, axis):
""" convert rhs to meet lhs dims if input is list, tuple or np.ndarray """
def to_series(right):
msg = ('Unable to coerce to Series, length must be {req_len}: '
'given {given_len}')
if axis is not None and left._get_axis_name(axis) == '... | [
"def",
"_align_method_FRAME",
"(",
"left",
",",
"right",
",",
"axis",
")",
":",
"def",
"to_series",
"(",
"right",
")",
":",
"msg",
"=",
"(",
"'Unable to coerce to Series, length must be {req_len}: '",
"'given {given_len}'",
")",
"if",
"axis",
"is",
"not",
"None",
... | 41.472727 | 0.000428 |
def clean(self):
"""Routine to return C/NOFS IVM data cleaned to the specified level
Parameters
-----------
inst : (pysat.Instrument)
Instrument class object, whose attribute clean_level is used to return
the desired level of data selectivity.
Returns
--------
Void : (NoneT... | [
"def",
"clean",
"(",
"self",
")",
":",
"# cleans cindi data",
"if",
"self",
".",
"clean_level",
"==",
"'clean'",
":",
"# choose areas below 550km",
"# self.data = self.data[self.data.alt <= 550]",
"idx",
",",
"=",
"np",
".",
"where",
"(",
"self",
".",
"data",
".",... | 32.75 | 0.010653 |
def elapsed(self):
"""
Elapsed time [µs] between start and stop timestamps. If stop is empty then
returned time is difference between start and current timestamp.
"""
if self._stop is None:
return timer() - self._start
return self._stop - self._start | [
"def",
"elapsed",
"(",
"self",
")",
":",
"if",
"self",
".",
"_stop",
"is",
"None",
":",
"return",
"timer",
"(",
")",
"-",
"self",
".",
"_start",
"return",
"self",
".",
"_stop",
"-",
"self",
".",
"_start"
] | 37.875 | 0.009677 |
def convert_to_G(self, word):
"""
Given a size such as '2333M', return the converted value in G
"""
value = 0.0
if word[-1] == 'G' or word[-1] == 'g':
value = float(word[:-1])
elif word[-1] == 'M' or word[-1] == 'm':
value = float(word[:-1]) / 1000.0
elif word[-1] == 'K' or word[... | [
"def",
"convert_to_G",
"(",
"self",
",",
"word",
")",
":",
"value",
"=",
"0.0",
"if",
"word",
"[",
"-",
"1",
"]",
"==",
"'G'",
"or",
"word",
"[",
"-",
"1",
"]",
"==",
"'g'",
":",
"value",
"=",
"float",
"(",
"word",
"[",
":",
"-",
"1",
"]",
... | 33.071429 | 0.010504 |
def argmin(input_, key=None):
"""
Returns index / key of the item with the smallest value.
Args:
input_ (dict or list):
Note:
a[argmin(a, key=key)] == min(a, key=key)
"""
# if isinstance(input_, dict):
# return list(input_.keys())[argmin(list(input_.values()))]
# el... | [
"def",
"argmin",
"(",
"input_",
",",
"key",
"=",
"None",
")",
":",
"# if isinstance(input_, dict):",
"# return list(input_.keys())[argmin(list(input_.values()))]",
"# elif hasattr(input_, 'index'):",
"# return input_.index(min(input_))",
"# else:",
"# return min(enumerate(i... | 29.807692 | 0.00125 |
def isBool(self, type):
"""
is the type a boolean value?
:param type: PKCS#11 type like `CKA_ALWAYS_SENSITIVE`
:rtype: bool
"""
if type in (CKA_ALWAYS_SENSITIVE,
CKA_DECRYPT,
CKA_DERIVE,
CKA_ENCRYPT,
... | [
"def",
"isBool",
"(",
"self",
",",
"type",
")",
":",
"if",
"type",
"in",
"(",
"CKA_ALWAYS_SENSITIVE",
",",
"CKA_DECRYPT",
",",
"CKA_DERIVE",
",",
"CKA_ENCRYPT",
",",
"CKA_EXTRACTABLE",
",",
"CKA_HAS_RESET",
",",
"CKA_LOCAL",
",",
"CKA_MODIFIABLE",
",",
"CKA_NE... | 31.032258 | 0.002016 |
def then(self, success=None, failure=None):
"""
This method takes two optional arguments. The first argument
is used if the "self promise" is fulfilled and the other is
used if the "self promise" is rejected. In either case, this
method returns another promise that effectively ... | [
"def",
"then",
"(",
"self",
",",
"success",
"=",
"None",
",",
"failure",
"=",
"None",
")",
":",
"ret",
"=",
"self",
".",
"create_next",
"(",
")",
"def",
"callAndFulfill",
"(",
"v",
")",
":",
"\"\"\"\n A callback to be invoked if the \"self promise\"\n... | 37.640625 | 0.000809 |
def get_reports():
"""
Returns energy data from 1960 to 2014 across various factors.
"""
if False:
# If there was a Test version of this method, it would go here. But alas.
pass
else:
rows = _Constants._DATABASE.execute("SELECT data FROM energy".format(
hardw... | [
"def",
"get_reports",
"(",
")",
":",
"if",
"False",
":",
"# If there was a Test version of this method, it would go here. But alas.",
"pass",
"else",
":",
"rows",
"=",
"_Constants",
".",
"_DATABASE",
".",
"execute",
"(",
"\"SELECT data FROM energy\"",
".",
"format",
"("... | 32.333333 | 0.008016 |
def get_local_file_dist(self):
"""
Handle importing from a source archive; this also uses setup_requires
but points easy_install directly to the source archive.
"""
if not os.path.isfile(self.path):
return
log.info('Attempting to unpack and import astropy_he... | [
"def",
"get_local_file_dist",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"path",
")",
":",
"return",
"log",
".",
"info",
"(",
"'Attempting to unpack and import astropy_helpers from '",
"'{0!r}'",
".",
"format",
"(",... | 32.677419 | 0.001918 |
def get_definition_location(self):
"""Returns a (module, lineno) tuple"""
if self.lineno is None and self.assignments:
self.lineno = self.assignments[0].get_lineno()
return (self.module, self.lineno) | [
"def",
"get_definition_location",
"(",
"self",
")",
":",
"if",
"self",
".",
"lineno",
"is",
"None",
"and",
"self",
".",
"assignments",
":",
"self",
".",
"lineno",
"=",
"self",
".",
"assignments",
"[",
"0",
"]",
".",
"get_lineno",
"(",
")",
"return",
"(... | 46.2 | 0.008511 |
def _evaluate(self,x,return_indices = False):
'''
Returns the level of the interpolated function at each value in x. Only
called internally by HARKinterpolator1D.__call__ (etc).
'''
return self._evalOrDer(x,True,False)[0] | [
"def",
"_evaluate",
"(",
"self",
",",
"x",
",",
"return_indices",
"=",
"False",
")",
":",
"return",
"self",
".",
"_evalOrDer",
"(",
"x",
",",
"True",
",",
"False",
")",
"[",
"0",
"]"
] | 42.833333 | 0.034351 |
def render_query(dataset, tables, select=None, conditions=None,
groupings=None, having=None, order_by=None, limit=None):
"""Render a query that will run over the given tables using the specified
parameters.
Parameters
----------
dataset : str
The BigQuery dataset to query d... | [
"def",
"render_query",
"(",
"dataset",
",",
"tables",
",",
"select",
"=",
"None",
",",
"conditions",
"=",
"None",
",",
"groupings",
"=",
"None",
",",
"having",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"Non... | 38.339623 | 0.00048 |
def set_up_phase(self, training_info, model, source: Source):
""" Prepare the phase for learning """
self._optimizer_instance = self.optimizer_factory.instantiate(model)
self._source = source | [
"def",
"set_up_phase",
"(",
"self",
",",
"training_info",
",",
"model",
",",
"source",
":",
"Source",
")",
":",
"self",
".",
"_optimizer_instance",
"=",
"self",
".",
"optimizer_factory",
".",
"instantiate",
"(",
"model",
")",
"self",
".",
"_source",
"=",
"... | 53 | 0.009302 |
def del_password(name, root=None):
'''
.. versionadded:: 2014.7.0
Delete the password from name user
name
User to delete
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
cmd = ['passwd']
if roo... | [
"def",
"del_password",
"(",
"name",
",",
"root",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'passwd'",
"]",
"if",
"root",
"is",
"not",
"None",
":",
"cmd",
".",
"extend",
"(",
"(",
"'-R'",
",",
"root",
")",
")",
"cmd",
".",
"extend",
"(",
"(",
"'-... | 20.653846 | 0.001779 |
def tau_from_final_mass_spin(final_mass, final_spin, l=2, m=2, nmodes=1):
"""Returns QNM damping time for the given mass and spin and mode.
Parameters
----------
final_mass : float or array
Mass of the black hole (in solar masses).
final_spin : float or array
Dimensionless spin of t... | [
"def",
"tau_from_final_mass_spin",
"(",
"final_mass",
",",
"final_spin",
",",
"l",
"=",
"2",
",",
"m",
"=",
"2",
",",
"nmodes",
"=",
"1",
")",
":",
"return",
"get_lm_f0tau",
"(",
"final_mass",
",",
"final_spin",
",",
"l",
",",
"m",
",",
"nmodes",
")",
... | 38.653846 | 0.001942 |
def get_requests_for_local_unit(relation_name=None):
"""Extract any certificates data targeted at this unit down relation_name.
:param relation_name: str Name of relation to check for data.
:returns: List of bundles of certificates.
:rtype: List of dicts
"""
local_name = local_unit().replace('/... | [
"def",
"get_requests_for_local_unit",
"(",
"relation_name",
"=",
"None",
")",
":",
"local_name",
"=",
"local_unit",
"(",
")",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")",
"raw_certs_key",
"=",
"'{}.processed_requests'",
".",
"format",
"(",
"local_name",
")",
"... | 40.85 | 0.001196 |
def status(ctx):
"""Print a status of this Lambda function"""
status = ctx.status()
click.echo(click.style('Policy', bold=True))
if status['policy']:
line = ' {} ({})'.format(
status['policy']['PolicyName'],
status['policy']['Arn'])
click.echo(click.style(line,... | [
"def",
"status",
"(",
"ctx",
")",
":",
"status",
"=",
"ctx",
".",
"status",
"(",
")",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"'Policy'",
",",
"bold",
"=",
"True",
")",
")",
"if",
"status",
"[",
"'policy'",
"]",
":",
"line",
"=",
... | 41.69697 | 0.00071 |
def assemble_all(asmcode, pc=0, fork=DEFAULT_FORK):
""" Assemble a sequence of textual representation of EVM instructions
:param asmcode: assembly code for any number of instructions
:type asmcode: str
:param pc: program counter of the first instruction(optional)
:type pc: int
... | [
"def",
"assemble_all",
"(",
"asmcode",
",",
"pc",
"=",
"0",
",",
"fork",
"=",
"DEFAULT_FORK",
")",
":",
"asmcode",
"=",
"asmcode",
".",
"split",
"(",
"'\\n'",
")",
"asmcode",
"=",
"iter",
"(",
"asmcode",
")",
"for",
"line",
"in",
"asmcode",
":",
"if"... | 32.942857 | 0.000842 |
def lookup(self, pathogenName, sampleName):
"""
Look up a pathogen name, sample name combination and get its
FASTA/FASTQ file name and unique read count.
This method should be used instead of C{add} in situations where
you want an exception to be raised if a pathogen/sample comb... | [
"def",
"lookup",
"(",
"self",
",",
"pathogenName",
",",
"sampleName",
")",
":",
"pathogenIndex",
"=",
"self",
".",
"_pathogens",
"[",
"pathogenName",
"]",
"sampleIndex",
"=",
"self",
".",
"_samples",
"[",
"sampleName",
"]",
"return",
"self",
".",
"_readsFile... | 47.222222 | 0.002307 |
def SegmentProd(a, ids):
"""
Segmented prod op.
"""
func = lambda idxs: reduce(np.multiply, a[idxs])
return seg_map(func, a, ids), | [
"def",
"SegmentProd",
"(",
"a",
",",
"ids",
")",
":",
"func",
"=",
"lambda",
"idxs",
":",
"reduce",
"(",
"np",
".",
"multiply",
",",
"a",
"[",
"idxs",
"]",
")",
"return",
"seg_map",
"(",
"func",
",",
"a",
",",
"ids",
")",
","
] | 24.166667 | 0.013333 |
def set_cores_massive(self,filename='core_masses_massive.txt'):
'''
Uesse function cores in nugridse.py
'''
core_info=[]
minis=[]
for i in range(len(self.runs_H5_surf)):
sefiles=se(self.runs_H5_out[i])
mini=sefiles.get('mini')
minis.append(mini)
incycle=in... | [
"def",
"set_cores_massive",
"(",
"self",
",",
"filename",
"=",
"'core_masses_massive.txt'",
")",
":",
"core_info",
"=",
"[",
"]",
"minis",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"runs_H5_surf",
")",
")",
":",
"sefiles",
... | 30 | 0.054566 |
def load_from_args(args):
"""
Given parsed commandline arguments, returns a list of ReadSource objects
"""
if not args.reads:
return None
if args.read_source_name:
read_source_names = util.expand(
args.read_source_name,
'read_source_name',
'read s... | [
"def",
"load_from_args",
"(",
"args",
")",
":",
"if",
"not",
"args",
".",
"reads",
":",
"return",
"None",
"if",
"args",
".",
"read_source_name",
":",
"read_source_names",
"=",
"util",
".",
"expand",
"(",
"args",
".",
"read_source_name",
",",
"'read_source_na... | 26.925926 | 0.001328 |
def _verify_same_spaces(self):
"""Verifies that all the envs have the same observation and action space."""
# Pre-conditions: self._envs is initialized.
if self._envs is None:
raise ValueError("Environments not initialized.")
if not isinstance(self._envs, list):
tf.logging.warning("Not ch... | [
"def",
"_verify_same_spaces",
"(",
"self",
")",
":",
"# Pre-conditions: self._envs is initialized.",
"if",
"self",
".",
"_envs",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Environments not initialized.\"",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_e... | 39.810811 | 0.012591 |
def sources_relative_to_source_root(self):
"""
:API: public
"""
if self.has_sources():
abs_source_root = os.path.join(get_buildroot(), self.target_base)
for source in self.sources_relative_to_buildroot():
abs_source = os.path.join(get_buildroot(), source)
yield os.path.relpat... | [
"def",
"sources_relative_to_source_root",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_sources",
"(",
")",
":",
"abs_source_root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_buildroot",
"(",
")",
",",
"self",
".",
"target_base",
")",
"for",
"source",... | 38 | 0.008571 |
def consumer_initialize_task(processor, consumer_client, shard_id, cursor_position, cursor_start_time, cursor_end_time=None):
"""
return TaskResult if failed, or else, return InitTaskResult
:param processor:
:param consumer_client:
:param shard_id:
:param cursor_position:
:param cursor_start... | [
"def",
"consumer_initialize_task",
"(",
"processor",
",",
"consumer_client",
",",
"shard_id",
",",
"cursor_position",
",",
"cursor_start_time",
",",
"cursor_end_time",
"=",
"None",
")",
":",
"try",
":",
"processor",
".",
"initialize",
"(",
"shard_id",
")",
"is_cur... | 39.90625 | 0.002294 |
def block(self):
'''
pfctl -a switchyard -f- < rules.txt
pfctl -a switchyard -F rules
pfctl -t switchyard -F r
'''
st,output = _runcmd("/sbin/pfctl -aswitchyard -f -", self._rules)
log_debug("Installing rules: {}".format(output)) | [
"def",
"block",
"(",
"self",
")",
":",
"st",
",",
"output",
"=",
"_runcmd",
"(",
"\"/sbin/pfctl -aswitchyard -f -\"",
",",
"self",
".",
"_rules",
")",
"log_debug",
"(",
"\"Installing rules: {}\"",
".",
"format",
"(",
"output",
")",
")"
] | 34.75 | 0.010526 |
def _chart_support(self, name, data, caller, **kwargs):
"template chart support function"
id = 'chart-%s' % next(self.id)
name = self._chart_class_name(name)
options = dict(self.environment.options)
options.update(name=name, id=id)
# jinja2 prepends 'l_' or 'l_{{ n }}'(v... | [
"def",
"_chart_support",
"(",
"self",
",",
"name",
",",
"data",
",",
"caller",
",",
"*",
"*",
"kwargs",
")",
":",
"id",
"=",
"'chart-%s'",
"%",
"next",
"(",
"self",
".",
"id",
")",
"name",
"=",
"self",
".",
"_chart_class_name",
"(",
"name",
")",
"o... | 37.576923 | 0.001996 |
def concat_cols(df1,df2,idx_col,df1_cols,df2_cols,
df1_suffix,df2_suffix,wc_cols=[],suffix_all=False):
"""
Concatenates two pandas tables
:param df1: dataframe 1
:param df2: dataframe 2
:param idx_col: column name which will be used as a common index
"""
df1=df1.set_index... | [
"def",
"concat_cols",
"(",
"df1",
",",
"df2",
",",
"idx_col",
",",
"df1_cols",
",",
"df2_cols",
",",
"df1_suffix",
",",
"df2_suffix",
",",
"wc_cols",
"=",
"[",
"]",
",",
"suffix_all",
"=",
"False",
")",
":",
"df1",
"=",
"df1",
".",
"set_index",
"(",
... | 38.636364 | 0.025249 |
def masked_max(vector: torch.Tensor,
mask: torch.Tensor,
dim: int,
keepdim: bool = False,
min_val: float = -1e7) -> torch.Tensor:
"""
To calculate max along certain dimensions on masked values
Parameters
----------
vector : ``torch.Tensor`... | [
"def",
"masked_max",
"(",
"vector",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
",",
"dim",
":",
"int",
",",
"keepdim",
":",
"bool",
"=",
"False",
",",
"min_val",
":",
"float",
"=",
"-",
"1e7",
")",
"->",
"torch",
".",
... | 31.965517 | 0.001047 |
def merge_recs_headers(recs):
'''
take a list of recs [rec1,rec2,rec3....], each rec is a dictionary.
make sure that all recs have the same headers.
'''
headers = []
for rec in recs:
keys = list(rec.keys())
for key in keys:
if key not in headers:
heade... | [
"def",
"merge_recs_headers",
"(",
"recs",
")",
":",
"headers",
"=",
"[",
"]",
"for",
"rec",
"in",
"recs",
":",
"keys",
"=",
"list",
"(",
"rec",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"not",
"in",
"headers",
":",... | 29.1875 | 0.002075 |
def tuplize(nested):
"""Recursively converts iterables into tuples.
Args:
nested: A nested structure of items and iterables.
Returns:
A nested structure of items and tuples.
"""
if isinstance(nested, str):
return nested
try:
return tuple(map(tuplize, nested))
except TypeError:
return... | [
"def",
"tuplize",
"(",
"nested",
")",
":",
"if",
"isinstance",
"(",
"nested",
",",
"str",
")",
":",
"return",
"nested",
"try",
":",
"return",
"tuple",
"(",
"map",
"(",
"tuplize",
",",
"nested",
")",
")",
"except",
"TypeError",
":",
"return",
"nested"
] | 20.866667 | 0.015291 |
async def get_records_for_zone(self, dns_zone, params=None):
"""Get all resource record sets for a managed zone, using the DNS zone.
Args:
dns_zone (str): Desired DNS zone to query.
params (dict): (optional) Additional query parameters for HTTP
requests to the GD... | [
"async",
"def",
"get_records_for_zone",
"(",
"self",
",",
"dns_zone",
",",
"params",
"=",
"None",
")",
":",
"managed_zone",
"=",
"self",
".",
"get_managed_zone",
"(",
"dns_zone",
")",
"url",
"=",
"f'{self._base_url}/managedZones/{managed_zone}/rrsets'",
"if",
"not",... | 37.029412 | 0.001548 |
def _check_local_option(self, option):
"""Test the status of local negotiated Telnet options."""
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption()
return self.telnet_opt_dict[option].local_option | [
"def",
"_check_local_option",
"(",
"self",
",",
"option",
")",
":",
"if",
"not",
"self",
".",
"telnet_opt_dict",
".",
"has_key",
"(",
"option",
")",
":",
"self",
".",
"telnet_opt_dict",
"[",
"option",
"]",
"=",
"TelnetOption",
"(",
")",
"return",
"self",
... | 53.6 | 0.011029 |
def get_node_by_dsl(self, node_dict: BaseEntity) -> Optional[Node]:
"""Look up a node by its data dictionary by hashing it then using :func:`get_node_by_hash`."""
return self.get_node_by_hash(node_dict.as_sha512()) | [
"def",
"get_node_by_dsl",
"(",
"self",
",",
"node_dict",
":",
"BaseEntity",
")",
"->",
"Optional",
"[",
"Node",
"]",
":",
"return",
"self",
".",
"get_node_by_hash",
"(",
"node_dict",
".",
"as_sha512",
"(",
")",
")"
] | 76 | 0.013043 |
def map_reduce(self, map, reduce, out, full_response=False, session=None,
**kwargs):
"""Perform a map/reduce operation on this collection.
If `full_response` is ``False`` (default) returns a
:class:`~pymongo.collection.Collection` instance containing
the results of th... | [
"def",
"map_reduce",
"(",
"self",
",",
"map",
",",
"reduce",
",",
"out",
",",
"full_response",
"=",
"False",
",",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"out",
",",
"(",
"string_type",
",",
"abc",
... | 43.985714 | 0.001588 |
def squeeze_bits(arr: numpy.ndarray) -> numpy.ndarray:
"""Return a copy of an integer numpy array with the minimum bitness."""
assert arr.dtype.kind in ("i", "u")
if arr.dtype.kind == "i":
assert arr.min() >= 0
mlbl = int(arr.max()).bit_length()
if mlbl <= 8:
dtype = numpy.uint8
... | [
"def",
"squeeze_bits",
"(",
"arr",
":",
"numpy",
".",
"ndarray",
")",
"->",
"numpy",
".",
"ndarray",
":",
"assert",
"arr",
".",
"dtype",
".",
"kind",
"in",
"(",
"\"i\"",
",",
"\"u\"",
")",
"if",
"arr",
".",
"dtype",
".",
"kind",
"==",
"\"i\"",
":",... | 31.266667 | 0.00207 |
def _filter_cluster_data(self):
"""
Filter the cluster data catalog into the filtered_data
catalog, which is what is shown in the H-R diagram.
Filter on the values of the sliders, as well as the lasso
selection in the skyviewer.
"""
min_temp = self.temperature_ra... | [
"def",
"_filter_cluster_data",
"(",
"self",
")",
":",
"min_temp",
"=",
"self",
".",
"temperature_range_slider",
".",
"value",
"[",
"0",
"]",
"max_temp",
"=",
"self",
".",
"temperature_range_slider",
".",
"value",
"[",
"1",
"]",
"temp_mask",
"=",
"np",
".",
... | 38.971429 | 0.001431 |
def get(self, sid):
"""
Constructs a AlphaSenderContext
:param sid: The sid
:returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext
:rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext
"""
return AlphaSenderContext(self._ve... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"AlphaSenderContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | 37.1 | 0.013158 |
def lru_cache(maxsize=100, typed=False):
"""Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) will be treated... | [
"def",
"lru_cache",
"(",
"maxsize",
"=",
"100",
",",
"typed",
"=",
"False",
")",
":",
"# Users should only access the lru_cache through its public API:",
"# cache_info, cache_clear, and f.__wrapped__",
"# The internals of the lru_cache are encapsulated for thread safety and",
"# ... | 43.09375 | 0.002127 |
def p_array_indices(self, p):
'''array_indices : array_index
| array_index COMMA array_indices'''
if len(p) == 2:
p[0] = p[1],
else:
p[0] = (p[1],) + p[3] | [
"def",
"p_array_indices",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
",",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"p",
"[",
"1",
"]",
",",
")",
"+",
"p"... | 31.571429 | 0.008811 |
def maybe_cythonize_extensions(top_path, config):
"""Tweaks for building extensions between release and development mode."""
is_release = os.path.exists(os.path.join(top_path, 'PKG-INFO'))
if is_release:
build_from_c_and_cpp_files(config.ext_modules)
else:
message = ('Please install cyt... | [
"def",
"maybe_cythonize_extensions",
"(",
"top_path",
",",
"config",
")",
":",
"is_release",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"top_path",
",",
"'PKG-INFO'",
")",
")",
"if",
"is_release",
":",
"build_from_c_an... | 39.583333 | 0.000685 |
def syllabify(word):
'''Syllabify the given word, whether simplex or complex.'''
compound = not word.isalpha()
syllabify = _syllabify_complex if compound else _syllabify_simplex
syllabifications = list(syllabify(word))
# if variation, order variants from most preferred to least preferred
if len... | [
"def",
"syllabify",
"(",
"word",
")",
":",
"compound",
"=",
"not",
"word",
".",
"isalpha",
"(",
")",
"syllabify",
"=",
"_syllabify_complex",
"if",
"compound",
"else",
"_syllabify_simplex",
"syllabifications",
"=",
"list",
"(",
"syllabify",
"(",
"word",
")",
... | 38.75 | 0.002101 |
def deriv1(x,y,i,n):
"""
alternative way to smooth the derivative of a noisy signal
using least square fit.
x=array of x axis
y=array of y axis
n=smoothing factor
i= position
in this method the slope in position i is calculated by least square fit of n points
before and after positi... | [
"def",
"deriv1",
"(",
"x",
",",
"y",
",",
"i",
",",
"n",
")",
":",
"m_",
",",
"x_",
",",
"y_",
",",
"xy_",
",",
"x_2",
"=",
"0.",
",",
"0.",
",",
"0.",
",",
"0.",
",",
"0.",
"for",
"ix",
"in",
"range",
"(",
"i",
",",
"i",
"+",
"n",
",... | 27.05 | 0.042857 |
def update_gunicorns():
"""
Updates the dict of gunicorn processes. Run the ps command and parse its
output for processes named after gunicorn, building up a dict of gunicorn
processes. When new gunicorns are discovered, run the netstat command to
determine the ports they're serving on.
"""
... | [
"def",
"update_gunicorns",
"(",
")",
":",
"global",
"tick",
"tick",
"+=",
"1",
"if",
"(",
"tick",
"*",
"screen_delay",
")",
"%",
"ps_delay",
"!=",
"0",
":",
"return",
"tick",
"=",
"0",
"for",
"pid",
"in",
"gunicorns",
":",
"gunicorns",
"[",
"pid",
"]... | 38.891304 | 0.002181 |
def _filter_keys(d: dict, keys: set) -> dict:
"""
Select a subset of keys from a dictionary.
"""
return {key: d[key] for key in keys if key in d} | [
"def",
"_filter_keys",
"(",
"d",
":",
"dict",
",",
"keys",
":",
"set",
")",
"->",
"dict",
":",
"return",
"{",
"key",
":",
"d",
"[",
"key",
"]",
"for",
"key",
"in",
"keys",
"if",
"key",
"in",
"d",
"}"
] | 34.6 | 0.011299 |
def tag_array(events):
"""
Return a numpy array mapping events to tags
- Rows corresponds to events
- Columns correspond to tags
"""
all_tags = sorted(set(tag for event in events for tag in event.tags))
array = np.zeros((len(events), len(all_tags)))
for row, event in enumerate(events):
... | [
"def",
"tag_array",
"(",
"events",
")",
":",
"all_tags",
"=",
"sorted",
"(",
"set",
"(",
"tag",
"for",
"event",
"in",
"events",
"for",
"tag",
"in",
"event",
".",
"tags",
")",
")",
"array",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"events",
... | 31 | 0.00241 |
def scale(requestContext, seriesList, factor):
"""
Takes one metric or a wildcard seriesList followed by a constant, and
multiplies the datapoint by the constant provided at each point.
Example::
&target=scale(Server.instance01.threads.busy,10)
&target=scale(Server.instance*.threads.bu... | [
"def",
"scale",
"(",
"requestContext",
",",
"seriesList",
",",
"factor",
")",
":",
"for",
"series",
"in",
"seriesList",
":",
"series",
".",
"name",
"=",
"\"scale(%s,%g)\"",
"%",
"(",
"series",
".",
"name",
",",
"float",
"(",
"factor",
")",
")",
"series",... | 33.705882 | 0.001698 |
def graphql_impl(
schema,
source,
root_value,
context_value,
variable_values,
operation_name,
field_resolver,
type_resolver,
middleware,
execution_context_class,
) -> AwaitableOrValue[ExecutionResult]:
"""Execute a query, return asynchronously only if necessary."""
# Vali... | [
"def",
"graphql_impl",
"(",
"schema",
",",
"source",
",",
"root_value",
",",
"context_value",
",",
"variable_values",
",",
"operation_name",
",",
"field_resolver",
",",
"type_resolver",
",",
"middleware",
",",
"execution_context_class",
",",
")",
"->",
"AwaitableOrV... | 25.808511 | 0.000794 |
def eye_plot(x,L,S=0):
"""
Eye pattern plot of a baseband digital communications waveform.
The signal must be real, but can be multivalued in terms of the underlying
modulation scheme. Used for BPSK eye plots in the Case Study article.
Parameters
----------
x : ndarray of the real input da... | [
"def",
"eye_plot",
"(",
"x",
",",
"L",
",",
"S",
"=",
"0",
")",
":",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"6",
",",
"4",
")",
")",
"idx",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"L",
"+",
"1",
")",
"plt",
".",
"plot",
"(",
"... | 26.52381 | 0.012121 |
def detectFileEncoding(self, fileName):
'''
Detect content encoding of specific file.
It will return None if it can't determine the encoding.
'''
try:
import chardet
except ImportError:
return
with open(fileName, 'rb') as inputFile:
raw = inputFile.read(2048)
result = chardet.detect(raw)
i... | [
"def",
"detectFileEncoding",
"(",
"self",
",",
"fileName",
")",
":",
"try",
":",
"import",
"chardet",
"except",
"ImportError",
":",
"return",
"with",
"open",
"(",
"fileName",
",",
"'rb'",
")",
"as",
"inputFile",
":",
"raw",
"=",
"inputFile",
".",
"read",
... | 27.363636 | 0.032103 |
def model_eval(sess, x, y, predictions, X_test=None, Y_test=None,
feed=None, args=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:par... | [
"def",
"model_eval",
"(",
"sess",
",",
"x",
",",
"y",
",",
"predictions",
",",
"X_test",
"=",
"None",
",",
"Y_test",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"global",
"_model_eval_cache",
"args",
"=",
"_ArgsWrapper",
... | 35.891892 | 0.010627 |
def interpolate(self, xi, yi, zdata, order=1):
"""
Base class to handle nearest neighbour, linear, and cubic interpolation.
Given a triangulation of a set of nodes and values at the nodes,
this method interpolates the value at the given xi,yi coordinates.
Parameters
----... | [
"def",
"interpolate",
"(",
"self",
",",
"xi",
",",
"yi",
",",
"zdata",
",",
"order",
"=",
"1",
")",
":",
"if",
"order",
"==",
"0",
":",
"zierr",
"=",
"np",
".",
"zeros_like",
"(",
"xi",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"return",
"self"... | 38.842105 | 0.001983 |
def _needSwapWH(self, oldDirection, newDirection ):
"""!
\~english
return screen direction status
@return Boolean
@note No need to rotate if the screen orientation is 0 degrees and 180 degrees
\~chinese
返回屏幕方向状态
@return 布尔值
@note 如果屏幕方向是0度和180度就不需... | [
"def",
"_needSwapWH",
"(",
"self",
",",
"oldDirection",
",",
"newDirection",
")",
":",
"if",
"abs",
"(",
"newDirection",
"-",
"oldDirection",
")",
"==",
"0",
":",
"return",
"False",
"if",
"abs",
"(",
"newDirection",
"-",
"oldDirection",
")",
"%",
"180",
... | 33.75 | 0.016216 |
def chooseBestDuplicates(tped, samples, oldSamples, completion,
concordance_all, prefix):
"""Choose the best duplicates according to the completion rate.
:param tped: the ``tped`` containing the duplicated samples.
:param samples: the updated position of the samples in the tped con... | [
"def",
"chooseBestDuplicates",
"(",
"tped",
",",
"samples",
",",
"oldSamples",
",",
"completion",
",",
"concordance_all",
",",
"prefix",
")",
":",
"# The output files",
"chosenFile",
"=",
"None",
"try",
":",
"chosenFile",
"=",
"open",
"(",
"prefix",
"+",
"\".c... | 39.317829 | 0.000192 |
def anglesep(lon0: float, lat0: float,
lon1: float, lat1: float, deg: bool = True) -> float:
"""
Parameters
----------
lon0 : float
longitude of first point
lat0 : float
latitude of first point
lon1 : float
longitude of second point
lat1 : float
... | [
"def",
"anglesep",
"(",
"lon0",
":",
"float",
",",
"lat0",
":",
"float",
",",
"lon1",
":",
"float",
",",
"lat1",
":",
"float",
",",
"deg",
":",
"bool",
"=",
"True",
")",
"->",
"float",
":",
"if",
"angular_separation",
"is",
"None",
":",
"raise",
"I... | 24.463415 | 0.000959 |
def stop(self):
"""Signals the background thread to stop.
This does not terminate the background thread. It simply queues the
stop signal. If the main process exits before the background thread
processes the stop signal, it will be terminated without finishing
work. The ``grace_... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_alive",
":",
"return",
"True",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_queue",
".",
"put_nowait",
"(",
"_WORKER_TERMINATOR",
")",
"self",
".",
"_thread",
".",
"join",
"(",
... | 35.375 | 0.002294 |
def ngroup(self, ascending=True):
"""
Number each group from 0 to the number of groups - 1.
This is the enumerative complement of cumcount. Note that the
numbers given to the groups match the order in which the groups
would be seen when iterating over the groupby object, not th... | [
"def",
"ngroup",
"(",
"self",
",",
"ascending",
"=",
"True",
")",
":",
"with",
"_group_selection_context",
"(",
"self",
")",
":",
"index",
"=",
"self",
".",
"_selected_obj",
".",
"index",
"result",
"=",
"Series",
"(",
"self",
".",
"grouper",
".",
"group_... | 23.609375 | 0.001271 |
def get_seqs_type(seqs):
"""
automagically determine input type
the following types are detected:
- Fasta object
- FASTA file
- list of regions
- region file
- BED file
"""
region_p = re.compile(r'^(.+):(\d+)-(\d+)$')
if isinstance(seqs, Fasta):
re... | [
"def",
"get_seqs_type",
"(",
"seqs",
")",
":",
"region_p",
"=",
"re",
".",
"compile",
"(",
"r'^(.+):(\\d+)-(\\d+)$'",
")",
"if",
"isinstance",
"(",
"seqs",
",",
"Fasta",
")",
":",
"return",
"\"fasta\"",
"elif",
"isinstance",
"(",
"seqs",
",",
"list",
")",
... | 33.970588 | 0.001684 |
def _update_simulation_start_cards(self):
"""
Update GSSHA cards for simulation start
"""
if self.simulation_start is not None:
self._update_card("START_DATE", self.simulation_start.strftime("%Y %m %d"))
self._update_card("START_TIME", self.simulation_start.strfti... | [
"def",
"_update_simulation_start_cards",
"(",
"self",
")",
":",
"if",
"self",
".",
"simulation_start",
"is",
"not",
"None",
":",
"self",
".",
"_update_card",
"(",
"\"START_DATE\"",
",",
"self",
".",
"simulation_start",
".",
"strftime",
"(",
"\"%Y %m %d\"",
")",
... | 46.571429 | 0.012048 |
def validate(self, table: pd.DataFrame, failed_only=False) -> pd.DataFrame:
"""Return a dataframe of validation results for the appropriate series vs the vector of validators.
Args:
table (pd.DataFrame): A dataframe on which to apply validation logic.
failed_only (bool): If ``Tr... | [
"def",
"validate",
"(",
"self",
",",
"table",
":",
"pd",
".",
"DataFrame",
",",
"failed_only",
"=",
"False",
")",
"->",
"pd",
".",
"DataFrame",
":",
"return",
"pd",
".",
"concat",
"(",
"[",
"self",
".",
"_validate_input",
"(",
"table",
",",
"failed_onl... | 50.909091 | 0.008772 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: TaskQueueStatisticsContext for this TaskQueueStatisticsInstance
:rtype: twilio.rest.taskrouter.v1... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"TaskQueueStatisticsContext",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid'",
... | 45.333333 | 0.008646 |
def create(cls, name, template='High-Security IPS Template'):
"""
Create an IPS Policy
:param str name: Name of policy
:param str template: name of template
:raises CreatePolicyFailed: policy failed to create
:return: IPSPolicy
"""
try:
if cls... | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"template",
"=",
"'High-Security IPS Template'",
")",
":",
"try",
":",
"if",
"cls",
".",
"typeof",
"==",
"'ips_template_policy'",
"and",
"template",
"is",
"None",
":",
"fw_template",
"=",
"None",
"else",
":",
... | 34.916667 | 0.002323 |
def add_pk_if_required(db, table, name):
"""Return a class deriving from our Model class as well as the SQLAlchemy
model.
:param `sqlalchemy.schema.Table` table: table to create primary key for
:param table: table to create primary key for
"""
db.metadata.reflect(bind=db.engine)
cls_dict ... | [
"def",
"add_pk_if_required",
"(",
"db",
",",
"table",
",",
"name",
")",
":",
"db",
".",
"metadata",
".",
"reflect",
"(",
"bind",
"=",
"db",
".",
"engine",
")",
"cls_dict",
"=",
"{",
"'__tablename__'",
":",
"name",
"}",
"if",
"not",
"table",
".",
"pri... | 36.333333 | 0.00149 |
def covar_errors(params, data, errs, B, C=None):
"""
Take a set of parameters that were fit with lmfit, and replace the errors
with the 1\sigma errors calculated using the covariance matrix.
Parameters
----------
params : lmfit.Parameters
Model
data : 2d-array
Image data
... | [
"def",
"covar_errors",
"(",
"params",
",",
"data",
",",
"errs",
",",
"B",
",",
"C",
"=",
"None",
")",
":",
"mask",
"=",
"np",
".",
"where",
"(",
"np",
".",
"isfinite",
"(",
"data",
")",
")",
"# calculate the proper parameter errors and copy them across.",
... | 26.701754 | 0.001267 |
def returnArrayFilters(arr1, arr2, limitsArr1, limitsArr2):
"""#TODO: docstring
:param arr1: #TODO: docstring
:param arr2: #TODO: docstring
:param limitsArr1: #TODO: docstring
:param limitsArr2: #TODO: docstring
:returns: #TODO: docstring
"""
posL = bisect.bisect_left(arr1, limitsArr1[... | [
"def",
"returnArrayFilters",
"(",
"arr1",
",",
"arr2",
",",
"limitsArr1",
",",
"limitsArr2",
")",
":",
"posL",
"=",
"bisect",
".",
"bisect_left",
"(",
"arr1",
",",
"limitsArr1",
"[",
"0",
"]",
")",
"posR",
"=",
"bisect",
".",
"bisect_right",
"(",
"arr1",... | 32.375 | 0.001876 |
def apply_enhancement(data, func, exclude=None, separate=False,
pass_dask=False):
"""Apply `func` to the provided data.
Args:
data (xarray.DataArray): Data to be modified inplace.
func (callable): Function to be applied to an xarray
exclude (iterable): Bands in the... | [
"def",
"apply_enhancement",
"(",
"data",
",",
"func",
",",
"exclude",
"=",
"None",
",",
"separate",
"=",
"False",
",",
"pass_dask",
"=",
"False",
")",
":",
"attrs",
"=",
"data",
".",
"attrs",
"bands",
"=",
"data",
".",
"coords",
"[",
"'bands'",
"]",
... | 35.901639 | 0.000444 |
def delta(t1, t2, words=True, justnow=datetime.timedelta(seconds=10)):
'''
Calculates the estimated delta between two time objects in human-readable
format. Used internally by the :func:`day` and :func:`duration` functions.
:param t1: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
... | [
"def",
"delta",
"(",
"t1",
",",
"t2",
",",
"words",
"=",
"True",
",",
"justnow",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"10",
")",
")",
":",
"t1",
"=",
"_to_datetime",
"(",
"t1",
")",
"t2",
"=",
"_to_datetime",
"(",
"t2",
")",
"d... | 27.575758 | 0.000265 |
def concatenate_textlcs(lclist,
sortby='rjd',
normalize=True):
'''This concatenates a list of light curves.
Does not care about overlaps or duplicates. The light curves must all be
from the same aperture.
The intended use is to concatenate light curves a... | [
"def",
"concatenate_textlcs",
"(",
"lclist",
",",
"sortby",
"=",
"'rjd'",
",",
"normalize",
"=",
"True",
")",
":",
"# read the first light curve",
"lcdict",
"=",
"read_hatpi_textlc",
"(",
"lclist",
"[",
"0",
"]",
")",
"# track which LC goes where",
"# initial LC",
... | 32.734375 | 0.001621 |
def msgBox(self, promptType, _timeout=-1, **options):
''' Send a user prompt request to the GUI
Arguments:
promptType (string):
The prompt type to send to the GUI. Currently
the only type supported is 'confirm'.
_timeout (int):
Th... | [
"def",
"msgBox",
"(",
"self",
",",
"promptType",
",",
"_timeout",
"=",
"-",
"1",
",",
"*",
"*",
"options",
")",
":",
"if",
"promptType",
"==",
"'confirm'",
":",
"return",
"self",
".",
"_sendConfirmPrompt",
"(",
"_timeout",
",",
"options",
")",
"else",
... | 35 | 0.001813 |
def last_modified(self):
"""Retrieves the last modified time stamp of the incident/incidents
from the output response
Returns:
last_modified(namedtuple): List of named tuples of last modified
time stamp of the incident/incidents
"""
resource_list = self.t... | [
"def",
"last_modified",
"(",
"self",
")",
":",
"resource_list",
"=",
"self",
".",
"traffic_incident",
"(",
")",
"last_modified",
"=",
"namedtuple",
"(",
"'last_modified'",
",",
"'last_modified'",
")",
"if",
"len",
"(",
"resource_list",
")",
"==",
"1",
"and",
... | 41.631579 | 0.002472 |
def create_ad_hoc_field(cls, db_type):
'''
Give an SQL column description such as "Enum8('apple' = 1, 'banana' = 2, 'orange' = 3)"
this method returns a matching enum field.
'''
import re
try:
Enum # exists in Python 3.4+
except NameError:
... | [
"def",
"create_ad_hoc_field",
"(",
"cls",
",",
"db_type",
")",
":",
"import",
"re",
"try",
":",
"Enum",
"# exists in Python 3.4+",
"except",
"NameError",
":",
"from",
"enum",
"import",
"Enum",
"# use the enum34 library instead",
"members",
"=",
"{",
"}",
"for",
... | 41.5 | 0.011782 |
def run_container(docker_client, backup_data):
"""Pull the Docker image and creates a container
with a '/backup' volume. This volume will be mounted
on the temporary workdir previously created.
It will then start the container and return the container object.
"""
docker_client.pull(backup_data[... | [
"def",
"run_container",
"(",
"docker_client",
",",
"backup_data",
")",
":",
"docker_client",
".",
"pull",
"(",
"backup_data",
"[",
"'image'",
"]",
")",
"container",
"=",
"docker_client",
".",
"create_container",
"(",
"image",
"=",
"backup_data",
"[",
"'image'",
... | 31 | 0.00149 |
def _path_to_be_kept(self, path):
"""Does the given path pass the filtering criteria?"""
if self.excludes and (path in self.excludes
or helpers.is_inside_any(self.excludes, path)):
return False
if self.includes:
return (path in self.includes
... | [
"def",
"_path_to_be_kept",
"(",
"self",
",",
"path",
")",
":",
"if",
"self",
".",
"excludes",
"and",
"(",
"path",
"in",
"self",
".",
"excludes",
"or",
"helpers",
".",
"is_inside_any",
"(",
"self",
".",
"excludes",
",",
"path",
")",
")",
":",
"return",
... | 42.222222 | 0.010309 |
def get_all_lower(self):
"""Return all parent GO IDs through both reverse 'is_a' and all relationships."""
all_lower = set()
for lower in self.get_goterms_lower():
all_lower.add(lower.item_id)
all_lower |= lower.get_all_lower()
return all_lower | [
"def",
"get_all_lower",
"(",
"self",
")",
":",
"all_lower",
"=",
"set",
"(",
")",
"for",
"lower",
"in",
"self",
".",
"get_goterms_lower",
"(",
")",
":",
"all_lower",
".",
"add",
"(",
"lower",
".",
"item_id",
")",
"all_lower",
"|=",
"lower",
".",
"get_a... | 42 | 0.01 |
def stop(self):
"""Halts the acquisition, this must be called before resetting acquisition"""
try:
self.aitask.stop()
self.aotask.stop()
pass
except:
print u"No task running"
self.aitask = None
self.aotask = None | [
"def",
"stop",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"aitask",
".",
"stop",
"(",
")",
"self",
".",
"aotask",
".",
"stop",
"(",
")",
"pass",
"except",
":",
"print",
"u\"No task running\"",
"self",
".",
"aitask",
"=",
"None",
"self",
".",
"... | 29.6 | 0.016393 |
def operation_recorder(self):
"""
:class:`BaseOperationRecorder`: **Deprecated:** The operation recorder
that was last added to the connection, or `None` if the connection does
not currently have any recorders.
*New in pywbem 0.9 as experimental. Deprecated since pywbem 0.12.*
... | [
"def",
"operation_recorder",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Reading the WBEMConnection.operation_recorder property has been \"",
"\"deprecated. Use the operation_recorders property instead.\"",
",",
"DeprecationWarning",
",",
"2",
")",
"try",
":",
"last... | 42.878788 | 0.001382 |
def dfsummary_made(self):
"""check if the summary table exists"""
try:
empty = self.dfsummary.empty
except AttributeError:
empty = True
return not empty | [
"def",
"dfsummary_made",
"(",
"self",
")",
":",
"try",
":",
"empty",
"=",
"self",
".",
"dfsummary",
".",
"empty",
"except",
"AttributeError",
":",
"empty",
"=",
"True",
"return",
"not",
"empty"
] | 28.857143 | 0.009615 |
def list_requests(status=None):
'''
List certificate requests made to CertCentral. You can filter by
status: ``pending``, ``approved``, ``rejected``
CLI Example:
.. code-block:: bash
salt-run digicert.list_requests pending
'''
if status:
url = '{0}/request?status={1}'.form... | [
"def",
"list_requests",
"(",
"status",
"=",
"None",
")",
":",
"if",
"status",
":",
"url",
"=",
"'{0}/request?status={1}'",
".",
"format",
"(",
"_base_url",
"(",
")",
",",
"status",
")",
"else",
":",
"url",
"=",
"'{0}/request'",
".",
"format",
"(",
"_base... | 26.8 | 0.002401 |
def apply_same_chip_constraints(vertices_resources, nets, constraints):
"""Modify a set of vertices_resources, nets and constraints to account for
all SameChipConstraints.
To allow placement algorithms to handle SameChipConstraints without any
special cases, Vertices identified in a SameChipConstraint ... | [
"def",
"apply_same_chip_constraints",
"(",
"vertices_resources",
",",
"nets",
",",
"constraints",
")",
":",
"# Make a copy of the basic structures to be modified by this function",
"vertices_resources",
"=",
"vertices_resources",
".",
"copy",
"(",
")",
"nets",
"=",
"nets",
... | 43.081301 | 0.000184 |
def p_type_specifier_2(t):
"""type_specifier : INT
| HYPER
| FLOAT
| DOUBLE
| QUADRUPLE
| BOOL
| ID
| UNSIGNED
| enum_type_spec
... | [
"def",
"p_type_specifier_2",
"(",
"t",
")",
":",
"# FRED - Note UNSIGNED is not in spec",
"if",
"isinstance",
"(",
"t",
"[",
"1",
"]",
",",
"type_info",
")",
":",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]",
"else",
":",
"t",
"[",
"0",
"]",
"=",
"t... | 31 | 0.001842 |
def grad(self, X, *params):
"""
Return the gradient of the basis function for each parameter.
Parameters
----------
X : ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
*params : optional
... | [
"def",
"grad",
"(",
"self",
",",
"X",
",",
"*",
"params",
")",
":",
"# Establish a few dimensions",
"N",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"D",
"=",
"self",
".",
"get_dim",
"(",
"X",
")",
"endinds",
"=",
"self",
".",
"__base_locations",
"(",
"... | 36.673469 | 0.001084 |
def wait_for_click(self, button, timeOut=10.0):
"""
Wait for a mouse click
Usage: C{mouse.wait_for_click(self, button, timeOut=10.0)}
@param button: they mouse button click to wait for as a button number, 1-9
@param timeOut: maximum time, in seconds, to wait for the key... | [
"def",
"wait_for_click",
"(",
"self",
",",
"button",
",",
"timeOut",
"=",
"10.0",
")",
":",
"button",
"=",
"int",
"(",
"button",
")",
"w",
"=",
"iomediator",
".",
"Waiter",
"(",
"None",
",",
"None",
",",
"button",
",",
"timeOut",
")",
"w",
".",
"wa... | 36.666667 | 0.011086 |
def _fix_missing_tenant_id(self, context, body, key):
"""Will add the tenant_id to the context from body.
It is assumed that the body must have a tenant_id because neutron
core could never have gotten here otherwise.
"""
if not body:
raise n_exc.BadRequest(resource=k... | [
"def",
"_fix_missing_tenant_id",
"(",
"self",
",",
"context",
",",
"body",
",",
"key",
")",
":",
"if",
"not",
"body",
":",
"raise",
"n_exc",
".",
"BadRequest",
"(",
"resource",
"=",
"key",
",",
"msg",
"=",
"\"Body malformed\"",
")",
"resource",
"=",
"bod... | 43.789474 | 0.002353 |
def search(self, **kwargs):
"""Searches for files/folders
Args:
\*\*kwargs (dict): A dictionary containing necessary parameters
(check https://developers.box.com/docs/#search for
list of parameters)
Returns:
dict. ... | [
"def",
"search",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"query_string",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"query_string",
"[",
"key",
"]",
"=",
"value",
"return",
"self",
".",
"__re... | 33.863636 | 0.009138 |
def read_cands(filename):
"""Read in the contents of a cands comb file"""
import sre
lines=file(filename).readlines()
exps=[]
cands=[]
coo=[]
for line in lines:
if ( line[0:2]=="##" ) :
break
exps.append(line[2:].strip())
for line in lines:
if ( ... | [
"def",
"read_cands",
"(",
"filename",
")",
":",
"import",
"sre",
"lines",
"=",
"file",
"(",
"filename",
")",
".",
"readlines",
"(",
")",
"exps",
"=",
"[",
"]",
"cands",
"=",
"[",
"]",
"coo",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",... | 25.967742 | 0.035928 |
def remove_prefix(self, auth, spec, recursive = False):
""" Remove prefix matching `spec`.
* `auth` [BaseAuth]
AAA options.
* `spec` [prefix_spec]
Specifies prefixe to remove.
* `recursive` [bool]
When set to True, also remove ... | [
"def",
"remove_prefix",
"(",
"self",
",",
"auth",
",",
"spec",
",",
"recursive",
"=",
"False",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"remove_prefix called; spec: %s\"",
"%",
"unicode",
"(",
"spec",
")",
")",
"# sanity check - do we have all attr... | 40.472222 | 0.002345 |
def parse_comment(self, comment, filename, lineno, endlineno,
include_paths=None, stripped=False):
"""
Returns a Comment given a string
"""
if not stripped and not self.__validate_c_comment(comment.strip()):
return None
title_offset = 0
... | [
"def",
"parse_comment",
"(",
"self",
",",
"comment",
",",
"filename",
",",
"lineno",
",",
"endlineno",
",",
"include_paths",
"=",
"None",
",",
"stripped",
"=",
"False",
")",
":",
"if",
"not",
"stripped",
"and",
"not",
"self",
".",
"__validate_c_comment",
"... | 38.95 | 0.002191 |
def main(argv=None):
"""Send X10 commands when module is used from the command line.
This uses syntax similar to sendCommands, for example:
x10.py com2 A1 On, A2 Off, B All Off
"""
if len(argv):
# join all the arguments together by spaces so that quotes
# aren't required on the com... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"len",
"(",
"argv",
")",
":",
"# join all the arguments together by spaces so that quotes",
"# aren't required on the command line.",
"commands",
"=",
"' '",
".",
"join",
"(",
"argv",
")",
"# the comPort is ever... | 28.944444 | 0.001859 |
def lcsstr(self, src, tar):
"""Return the longest common substring of two strings.
Longest common substring (LCSstr).
Based on the code from
https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring
:cite:`Wikibooks:2018`.
This is licensed ... | [
"def",
"lcsstr",
"(",
"self",
",",
"src",
",",
"tar",
")",
":",
"lengths",
"=",
"np_zeros",
"(",
"(",
"len",
"(",
"src",
")",
"+",
"1",
",",
"len",
"(",
"tar",
")",
"+",
"1",
")",
",",
"dtype",
"=",
"np_int",
")",
"longest",
",",
"i_longest",
... | 30.115385 | 0.001855 |
def as_vartype(vartype):
"""Cast various inputs to a valid vartype object.
Args:
vartype (:class:`.Vartype`/str/set):
Variable type. Accepted input values:
* :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
* :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``
Re... | [
"def",
"as_vartype",
"(",
"vartype",
")",
":",
"if",
"isinstance",
"(",
"vartype",
",",
"Vartype",
")",
":",
"return",
"vartype",
"try",
":",
"if",
"isinstance",
"(",
"vartype",
",",
"str",
")",
":",
"vartype",
"=",
"Vartype",
"[",
"vartype",
"]",
"eli... | 28.6 | 0.000966 |
def convert_elementwise_add(
params, w_name, scope_name, inputs, layers, weights, names
):
"""
Convert elementwise addition.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
... | [
"def",
"convert_elementwise_add",
"(",
"params",
",",
"w_name",
",",
"scope_name",
",",
"inputs",
",",
"layers",
",",
"weights",
",",
"names",
")",
":",
"print",
"(",
"'Converting elementwise_add ...'",
")",
"if",
"'broadcast'",
"in",
"params",
":",
"model0",
... | 29.891304 | 0.001408 |
def pretty_repr(instance):
"""
A function assignable to the ``__repr__`` dunder method, so that
the ``prettyprinter`` definition for the type is used to provide
repr output. Usage:
.. code:: python
from prettyprinter import pretty_repr
class MyClass:
__repr__ = pretty_... | [
"def",
"pretty_repr",
"(",
"instance",
")",
":",
"instance_type",
"=",
"type",
"(",
"instance",
")",
"if",
"not",
"is_registered",
"(",
"instance_type",
",",
"check_superclasses",
"=",
"True",
",",
"check_deferred",
"=",
"True",
",",
"register_deferred",
"=",
... | 29.514286 | 0.000937 |
def aseg_on_mri(mri_spec,
aseg_spec,
alpha_mri=1.0,
alpha_seg=1.0,
num_rows=2,
num_cols=6,
rescale_method='global',
aseg_cmap='freesurfer',
sub_cortical=False,
annot=None,
... | [
"def",
"aseg_on_mri",
"(",
"mri_spec",
",",
"aseg_spec",
",",
"alpha_mri",
"=",
"1.0",
",",
"alpha_seg",
"=",
"1.0",
",",
"num_rows",
"=",
"2",
",",
"num_cols",
"=",
"6",
",",
"rescale_method",
"=",
"'global'",
",",
"aseg_cmap",
"=",
"'freesurfer'",
",",
... | 36.55 | 0.001998 |
def get_expiration_seconds_v2(expiration):
"""Convert 'expiration' to a number of seconds in the future.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:raises: :exc:`TypeError` when expiration is not a valid ... | [
"def",
"get_expiration_seconds_v2",
"(",
"expiration",
")",
":",
"# If it's a timedelta, add it to `now` in UTC.",
"if",
"isinstance",
"(",
"expiration",
",",
"datetime",
".",
"timedelta",
")",
":",
"now",
"=",
"NOW",
"(",
")",
".",
"replace",
"(",
"tzinfo",
"=",
... | 37.518519 | 0.000962 |
def buildhtml(self):
"""Build the HTML page
Create the htmlheader with css / js
Create html page
"""
self.buildcontent()
self.buildhtmlheader()
self.content = self._htmlcontent.decode('utf-8') # need to ensure unicode
self._htmlcontent = self.template_page... | [
"def",
"buildhtml",
"(",
"self",
")",
":",
"self",
".",
"buildcontent",
"(",
")",
"self",
".",
"buildhtmlheader",
"(",
")",
"self",
".",
"content",
"=",
"self",
".",
"_htmlcontent",
".",
"decode",
"(",
"'utf-8'",
")",
"# need to ensure unicode",
"self",
".... | 37.4 | 0.010444 |
def eval(w,t,x,msk,s):
"""
Pythia server-side computation of intermediate PRF output.
@w: ensemble key selector (any string, e.g. webserver ID)
@t: tweak (any string, e.g. user ID)
@x: message (any string)
@msk: Pythia server's master secret key
@s: state value from Pythia server's key table... | [
"def",
"eval",
"(",
"w",
",",
"t",
",",
"x",
",",
"msk",
",",
"s",
")",
":",
"# Verify types",
"assertType",
"(",
"w",
",",
"(",
"str",
",",
"int",
",",
"long",
")",
")",
"assertType",
"(",
"t",
",",
"(",
"str",
",",
"int",
",",
"long",
")",
... | 29.24 | 0.011921 |
def create_from_dict(cls, src_dict, roi_skydir=None, rescale=False):
"""Create a source object from a python dictionary.
Parameters
----------
src_dict : dict
Dictionary defining the properties of the source.
"""
src_dict = copy.deepcopy(src_dict)
src... | [
"def",
"create_from_dict",
"(",
"cls",
",",
"src_dict",
",",
"roi_skydir",
"=",
"None",
",",
"rescale",
"=",
"False",
")",
":",
"src_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"src_dict",
")",
"src_dict",
".",
"setdefault",
"(",
"'SpatialModel'",
",",
"'Poi... | 38.984375 | 0.001173 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.