text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def drop_index(self, raw):
""" Executes a drop index command.
{ "op" : "c",
"ns" : "testdb.$cmd",
"o" : { "dropIndexes" : "testcoll",
"index" : "nuie_1" } }
"""
dbname = raw['ns'].split('.', 1)[0]
collname = raw['o']['dropIndexes']... | [
"def",
"drop_index",
"(",
"self",
",",
"raw",
")",
":",
"dbname",
"=",
"raw",
"[",
"'ns'",
"]",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"collname",
"=",
"raw",
"[",
"'o'",
"]",
"[",
"'dropIndexes'",
"]",
"self",
".",
"dest",
"["... | 34.181818 | 0.010363 |
def formatted_completion_sig(completion):
"""Regenerate signature for methods. Return just the name otherwise"""
f_result = completion["name"]
if is_basic_type(completion):
# It's a raw type
return f_result
elif len(completion["typeInfo"]["paramSections"]) == 0:
return f_result
... | [
"def",
"formatted_completion_sig",
"(",
"completion",
")",
":",
"f_result",
"=",
"completion",
"[",
"\"name\"",
"]",
"if",
"is_basic_type",
"(",
"completion",
")",
":",
"# It's a raw type",
"return",
"f_result",
"elif",
"len",
"(",
"completion",
"[",
"\"typeInfo\"... | 39.384615 | 0.001908 |
def R_isrk(self, k):
"""
Function returns the inverse square root of R matrix on step k.
"""
ind = int(self.index[self.R_time_var_index, k])
R = self.R[:, :, ind]
if (R.shape[0] == 1): # 1-D case handle simplier. No storage
# of the result, just compute it e... | [
"def",
"R_isrk",
"(",
"self",
",",
"k",
")",
":",
"ind",
"=",
"int",
"(",
"self",
".",
"index",
"[",
"self",
".",
"R_time_var_index",
",",
"k",
"]",
")",
"R",
"=",
"self",
".",
"R",
"[",
":",
",",
":",
",",
"ind",
"]",
"if",
"(",
"R",
".",
... | 38.21875 | 0.001595 |
def last_seen_utc(self) -> Optional[datetime]:
"""Timestamp when the story has last been watched or None (UTC)."""
if self._node['seen']:
return datetime.utcfromtimestamp(self._node['seen']) | [
"def",
"last_seen_utc",
"(",
"self",
")",
"->",
"Optional",
"[",
"datetime",
"]",
":",
"if",
"self",
".",
"_node",
"[",
"'seen'",
"]",
":",
"return",
"datetime",
".",
"utcfromtimestamp",
"(",
"self",
".",
"_node",
"[",
"'seen'",
"]",
")"
] | 53.75 | 0.009174 |
def compile_format(self, log_format: str) -> Tuple[str, List[KeyMethod]]:
"""Translate log_format into form usable by modulo formatting
All known atoms will be replaced with %s
Also methods for formatting of those atoms will be added to
_methods in appropriate order
For example... | [
"def",
"compile_format",
"(",
"self",
",",
"log_format",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"List",
"[",
"KeyMethod",
"]",
"]",
":",
"# list of (key, method) tuples, we don't use an OrderedDict as users",
"# can repeat the same key more than once",
"methods"... | 40.731707 | 0.00117 |
async def process_frame(self, frame):
"""Update nodes via frame, usually received by house monitor."""
if isinstance(frame, FrameNodeStatePositionChangedNotification):
if frame.node_id not in self.pyvlx.nodes:
return
node = self.pyvlx.nodes[frame.node_id]
... | [
"async",
"def",
"process_frame",
"(",
"self",
",",
"frame",
")",
":",
"if",
"isinstance",
"(",
"frame",
",",
"FrameNodeStatePositionChangedNotification",
")",
":",
"if",
"frame",
".",
"node_id",
"not",
"in",
"self",
".",
"pyvlx",
".",
"nodes",
":",
"return",... | 50.4375 | 0.002433 |
def _create_results_summary(self):
"""
Create the dataframe that displays the estimation results, and store
it on the model instance.
Returns
-------
None.
"""
# Make sure we have all attributes needed to create the results summary
needed_attribut... | [
"def",
"_create_results_summary",
"(",
"self",
")",
":",
"# Make sure we have all attributes needed to create the results summary",
"needed_attributes",
"=",
"[",
"\"params\"",
",",
"\"standard_errors\"",
",",
"\"tvalues\"",
",",
"\"pvalues\"",
",",
"\"robust_std_errs\"",
",",
... | 39.771429 | 0.001403 |
def add_element(self, location, element, delete_elem=False):
"""
Create an entry located at ``location``.
Args:
location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for
instance).
element: Element... | [
"def",
"add_element",
"(",
"self",
",",
"location",
",",
"element",
",",
"delete_elem",
"=",
"False",
")",
":",
"return",
"self",
".",
"_create_entry",
"(",
"location",
",",
"element",
",",
"unique",
"=",
"False",
",",
"delete_element",
"=",
"delete_elem",
... | 43.55 | 0.011236 |
def triangle_normal(a,b,c):
'''
triangle_normal(a, b, c) yields the normal vector of the triangle whose vertices are given by
the points a, b, and c. If the points are 2D points, then 3D normal vectors are still yielded,
that are always (0,0,1) or (0,0,-1). This function auto-threads over matrices, ... | [
"def",
"triangle_normal",
"(",
"a",
",",
"b",
",",
"c",
")",
":",
"(",
"a",
",",
"b",
",",
"c",
")",
"=",
"[",
"np",
".",
"asarray",
"(",
"x",
")",
"for",
"x",
"in",
"(",
"a",
",",
"b",
",",
"c",
")",
"]",
"if",
"len",
"(",
"a",
".",
... | 49.5 | 0.019815 |
def setOptions( self, options ):
"""
Sets the tag option list for this widget. If used, tags need to be
found within the list of options when added.
:param options | [<str>, ..]
"""
self._options = map(str, options)
if ( options ):... | [
"def",
"setOptions",
"(",
"self",
",",
"options",
")",
":",
"self",
".",
"_options",
"=",
"map",
"(",
"str",
",",
"options",
")",
"if",
"(",
"options",
")",
":",
"completer",
"=",
"QCompleter",
"(",
"options",
",",
"self",
")",
"completer",
".",
"set... | 34.6 | 0.015009 |
def flatten(nested_iterable):
"""
Flattens arbitrarily nested lists/tuples.
Code partially taken from https://stackoverflow.com/a/10824420.
Parameters
----------
nested_iterable
A list or tuple of arbitrarily nested values.
Yields
------
any
Non-list and non-tuple ... | [
"def",
"flatten",
"(",
"nested_iterable",
")",
":",
"# don't just check if something is iterable here, because then strings",
"# and arrays will be split into their characters and components",
"if",
"not",
"isinstance",
"(",
"nested_iterable",
",",
"(",
"list",
",",
"tuple",
")",... | 26.928571 | 0.00128 |
def _section_execution_order(self, section, iterargs
, reverse=False
, custom_order=None
, explicit_checks: Iterable = None
, exclude_checks: Iterable = None):
"""
order must:
a) contain... | [
"def",
"_section_execution_order",
"(",
"self",
",",
"section",
",",
"iterargs",
",",
"reverse",
"=",
"False",
",",
"custom_order",
"=",
"None",
",",
"explicit_checks",
":",
"Iterable",
"=",
"None",
",",
"exclude_checks",
":",
"Iterable",
"=",
"None",
")",
"... | 36.612903 | 0.009867 |
def map(self):
"""Perform a function on every item in an iterable."""
with Pool(self.cpu_count) as pool:
pool.map(self._func, self._iterable)
pool.close()
return True | [
"def",
"map",
"(",
"self",
")",
":",
"with",
"Pool",
"(",
"self",
".",
"cpu_count",
")",
"as",
"pool",
":",
"pool",
".",
"map",
"(",
"self",
".",
"_func",
",",
"self",
".",
"_iterable",
")",
"pool",
".",
"close",
"(",
")",
"return",
"True"
] | 34.833333 | 0.009346 |
def write_Track(file, track, bpm=120, repeat=0, verbose=False):
"""Write a mingus.Track to a MIDI file.
Write the name to the file and set the instrument if the instrument has
the attribute instrument_nr, which represents the MIDI instrument
number. The class MidiInstrument in mingus.containers.Instrum... | [
"def",
"write_Track",
"(",
"file",
",",
"track",
",",
"bpm",
"=",
"120",
",",
"repeat",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"m",
"=",
"MidiFile",
"(",
")",
"t",
"=",
"MidiTrack",
"(",
"bpm",
")",
"m",
".",
"tracks",
"=",
"[",
"t",... | 34.866667 | 0.001862 |
def recursive_model_update(model, props):
"""
Recursively updates attributes on a model including other
models. If the type of the new model matches the old model
properties are simply updated, otherwise the model is replaced.
"""
updates = {}
valid_properties = model.properties_with_values(... | [
"def",
"recursive_model_update",
"(",
"model",
",",
"props",
")",
":",
"updates",
"=",
"{",
"}",
"valid_properties",
"=",
"model",
".",
"properties_with_values",
"(",
")",
"for",
"k",
",",
"v",
"in",
"props",
".",
"items",
"(",
")",
":",
"if",
"isinstanc... | 41.052632 | 0.001253 |
def move_identity(db, from_id, to_uuid):
"""Move an identity to a unique identity.
This function shifts the identity identified by 'from_id' to
the unique identity 'to_uuid'.
When 'to_uuid' is the unique identity that is currently related
to 'from_id', the action does not have any effect.
In ... | [
"def",
"move_identity",
"(",
"db",
",",
"from_id",
",",
"to_uuid",
")",
":",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"fid",
"=",
"find_identity",
"(",
"session",
",",
"from_id",
")",
"tuid",
"=",
"find_unique_identity",
"(",
"sessio... | 36.081081 | 0.000729 |
def angle_subtended(ell, **kwargs):
"""
Compute the half angle subtended (or min and max angles)
for an offset elliptical conic
from the origin or an arbitrary viewpoint.
kwargs:
tangent Return tangent instead of angle (default false)
viewpoint Defaults to origin
"""
retu... | [
"def",
"angle_subtended",
"(",
"ell",
",",
"*",
"*",
"kwargs",
")",
":",
"return_tangent",
"=",
"kwargs",
".",
"pop",
"(",
"'tangent'",
",",
"False",
")",
"con",
",",
"transform",
",",
"offset",
"=",
"ell",
".",
"projection",
"(",
"*",
"*",
"kwargs",
... | 32.421053 | 0.009464 |
def make_directory(path):
"""
Make a directory and any intermediate directories that don't already
exist. This function handles the case where two threads try to create
a directory at once.
"""
if not os.path.exists(path):
# concurrent writes that try to create the same dir can fail
... | [
"def",
"make_directory",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"# concurrent writes that try to create the same dir can fail",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as"... | 29.75 | 0.002037 |
def authorize(self):
""" Use the magic of a unicorn and summon the set-top box to listen
to us.
/
,.. /
,' ';
,,.__ _,' /'; .
:',' ~~~~ '. '~
:' ( ) )::,
'. '. .=----=..-~ .;'... | [
"def",
"authorize",
"(",
"self",
")",
":",
"# Read the version of the set-top box and write it back. Why? I've no",
"# idea.",
"version",
"=",
"self",
".",
"con",
".",
"makefile",
"(",
")",
".",
"readline",
"(",
")",
"self",
".",
"con",
".",
"send",
"(",
"versio... | 33.536585 | 0.001413 |
def get(self, key, value=None):
"x.get(k[,d]) -> x[k] if k in x, else d. d defaults to None."
_key = self._prepare_key(key)
prefix, node = self._get_node_by_key(_key)
if prefix==_key and node.value is not None:
return self._unpickle_value(node.value)
else:
... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"value",
"=",
"None",
")",
":",
"_key",
"=",
"self",
".",
"_prepare_key",
"(",
"key",
")",
"prefix",
",",
"node",
"=",
"self",
".",
"_get_node_by_key",
"(",
"_key",
")",
"if",
"prefix",
"==",
"_key",
"and... | 40.75 | 0.009009 |
def set_bytes_at_offset(self, offset, data):
"""Overwrite the bytes at the given file offset with the given string.
Return True if successful, False otherwise. It can fail if the
offset is outside the file's boundaries.
"""
if not isinstance(data, bytes):
raise Type... | [
"def",
"set_bytes_at_offset",
"(",
"self",
",",
"offset",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"'data should be of type: bytes'",
")",
"if",
"0",
"<=",
"offset",
"<",
"len",
"(",
... | 34.125 | 0.008913 |
def histogram(self, stat, value, tags=None):
"""Report a histogram."""
self._log('histogram', stat, value, tags) | [
"def",
"histogram",
"(",
"self",
",",
"stat",
",",
"value",
",",
"tags",
"=",
"None",
")",
":",
"self",
".",
"_log",
"(",
"'histogram'",
",",
"stat",
",",
"value",
",",
"tags",
")"
] | 42 | 0.015625 |
def bin2hexline(data, add_addr=True, width=16):
"""
Format binary data to a Hex-Editor like format...
>>> data = bytearray([i for i in range(256)])
>>> print('\\n'.join(bin2hexline(data, width=16)))
0000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................
0016 10 11 12 13 14 15 16 ... | [
"def",
"bin2hexline",
"(",
"data",
",",
"add_addr",
"=",
"True",
",",
"width",
"=",
"16",
")",
":",
"data",
"=",
"bytearray",
"(",
"data",
")",
"# same as string.printable but without \\t\\n\\r\\v\\f ;)",
"printable",
"=",
"string",
".",
"digits",
"+",
"string",... | 40.065789 | 0.001282 |
def diff_sizes(a, b, progressbar=None):
"""Return list of tuples where sizes differ.
Tuple structure:
(identifier, size in a, size in b)
Assumes list of identifiers in a and b are identical.
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`dtoolcore.DataSet`
:returns: l... | [
"def",
"diff_sizes",
"(",
"a",
",",
"b",
",",
"progressbar",
"=",
"None",
")",
":",
"difference",
"=",
"[",
"]",
"for",
"i",
"in",
"a",
".",
"identifiers",
":",
"a_size",
"=",
"a",
".",
"item_properties",
"(",
"i",
")",
"[",
"\"size_in_bytes\"",
"]",... | 29.304348 | 0.001437 |
def check_data_port_connection(self, check_data_port):
"""Checks the connection validity of a data port
The method is called by a child state to check the validity of a data port in case it is connected with data
flows. The data port does not belong to 'self', but to one of self.states.
... | [
"def",
"check_data_port_connection",
"(",
"self",
",",
"check_data_port",
")",
":",
"for",
"data_flow",
"in",
"self",
".",
"data_flows",
".",
"values",
"(",
")",
":",
"# Check whether the data flow connects the given port",
"from_port",
"=",
"self",
".",
"get_data_por... | 62.333333 | 0.008277 |
def on_value_change(self, picker, old, new):
""" Set the checked property based on the checked state
of all the children
"""
d = self.declaration
with self.widget.setValue.suppressed():
d.value = new | [
"def",
"on_value_change",
"(",
"self",
",",
"picker",
",",
"old",
",",
"new",
")",
":",
"d",
"=",
"self",
".",
"declaration",
"with",
"self",
".",
"widget",
".",
"setValue",
".",
"suppressed",
"(",
")",
":",
"d",
".",
"value",
"=",
"new"
] | 32.125 | 0.011364 |
def expect(self, pattern, timeout=-1):
"""Waits on the given pattern to appear in std_out"""
if self.blocking:
raise RuntimeError("expect can only be used on non-blocking commands.")
try:
self.subprocess.expect(pattern=pattern, timeout=timeout)
except pexpect.EO... | [
"def",
"expect",
"(",
"self",
",",
"pattern",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"blocking",
":",
"raise",
"RuntimeError",
"(",
"\"expect can only be used on non-blocking commands.\"",
")",
"try",
":",
"self",
".",
"subprocess",
".",
... | 33 | 0.00885 |
def _constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value(lb, ub):
"""Helper function used by Constraint and Model"""
if lb is None and ub is None:
raise Exception("Free constraint ...")
elif lb is None:
sense = '<'
rhs = float(ub)
range_value = 0.
elif ub is None:
... | [
"def",
"_constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value",
"(",
"lb",
",",
"ub",
")",
":",
"if",
"lb",
"is",
"None",
"and",
"ub",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Free constraint ...\"",
")",
"elif",
"lb",
"is",
"None",
":",
"sense",
"... | 28.869565 | 0.001458 |
def put(self, item):
"""Adds the passed in item object to the queue and calls :func:`flush` if the size of the queue is larger
than :func:`max_queue_length`. This method does nothing if the passed in item is None.
Args:
item (:class:`contracts.Envelope`) item the telemetry envelope ... | [
"def",
"put",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"item",
":",
"return",
"self",
".",
"_queue",
".",
"put",
"(",
"item",
")",
"if",
"self",
".",
"_queue",
".",
"qsize",
"(",
")",
">=",
"self",
".",
"_max_queue_length",
":",
"self",
"... | 42 | 0.009709 |
def merge_dict_of_lists(adict, indices, pop_later=True, copy=True):
"""Extend the within a dict of lists. The indices will indicate which
list have to be extended by which other list.
Parameters
----------
adict: OrderedDict
An ordered dictionary of lists
indices: list or tuple of 2 it... | [
"def",
"merge_dict_of_lists",
"(",
"adict",
",",
"indices",
",",
"pop_later",
"=",
"True",
",",
"copy",
"=",
"True",
")",
":",
"def",
"check_indices",
"(",
"idxs",
",",
"x",
")",
":",
"for",
"i",
"in",
"chain",
"(",
"*",
"idxs",
")",
":",
"if",
"i"... | 29.686275 | 0.000639 |
def long_poll_notifications(self, **kwargs): # noqa: E501
"""Get notifications using Long Poll # noqa: E501
In this case, notifications are delivered through HTTP long poll requests. The HTTP request is kept open until an event notification or a batch of event notifications are delivered to the clien... | [
"def",
"long_poll_notifications",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
"long_poll_notifi... | 124.05 | 0.0008 |
def print_dependencies(_run):
"""Print the detected source-files and dependencies."""
print('Dependencies:')
for dep in _run.experiment_info['dependencies']:
pack, _, version = dep.partition('==')
print(' {:<20} == {}'.format(pack, version))
print('\nSources:')
for source, digest i... | [
"def",
"print_dependencies",
"(",
"_run",
")",
":",
"print",
"(",
"'Dependencies:'",
")",
"for",
"dep",
"in",
"_run",
".",
"experiment_info",
"[",
"'dependencies'",
"]",
":",
"pack",
",",
"_",
",",
"version",
"=",
"dep",
".",
"partition",
"(",
"'=='",
")... | 38.315789 | 0.00134 |
def relax_AX(self):
"""The parent class method that this method overrides only
implements the relaxation step for the variables of the baseline
consensus algorithm. This method calls the overridden method and
then implements the relaxation step for the additional variables
requir... | [
"def",
"relax_AX",
"(",
"self",
")",
":",
"super",
"(",
"ConvCnstrMODMaskDcpl_Consensus",
",",
"self",
")",
".",
"relax_AX",
"(",
")",
"self",
".",
"AX1nr",
"=",
"sl",
".",
"irfftn",
"(",
"sl",
".",
"inner",
"(",
"self",
".",
"Zf",
",",
"self",
".",
... | 45.777778 | 0.002378 |
def csrf_token():
"""
Get csrf token or create new one
"""
from uliweb import request, settings
from uliweb.utils.common import safe_str
v = {}
token_name = settings.CSRF.cookie_token_name
if not request.session.deleted and request.session.get(token_name):
v = request.sessio... | [
"def",
"csrf_token",
"(",
")",
":",
"from",
"uliweb",
"import",
"request",
",",
"settings",
"from",
"uliweb",
".",
"utils",
".",
"common",
"import",
"safe_str",
"v",
"=",
"{",
"}",
"token_name",
"=",
"settings",
".",
"CSRF",
".",
"cookie_token_name",
"if",... | 31.52 | 0.008621 |
def _position_and_velocity_TEME_km(self, t):
"""Return the raw true equator mean equinox (TEME) vectors from SGP4.
Returns a tuple of NumPy arrays ``([x y z], [xdot ydot zdot])``
expressed in kilometers and kilometers per second. Note that we
assume the TLE epoch to be a UTC date, per ... | [
"def",
"_position_and_velocity_TEME_km",
"(",
"self",
",",
"t",
")",
":",
"sat",
"=",
"self",
".",
"model",
"minutes_past_epoch",
"=",
"(",
"t",
".",
"_utc_float",
"(",
")",
"-",
"sat",
".",
"jdsatepoch",
")",
"*",
"1440.0",
"if",
"getattr",
"(",
"minute... | 41.695652 | 0.002039 |
def get_term(self,term_id):
"""
Returns the term object for the supplied identifier
@type term_id: string
@param term_id: term identifier
"""
if term_id in self.idx:
return Cterm(self.idx[term_id],self.type)
else:
return None | [
"def",
"get_term",
"(",
"self",
",",
"term_id",
")",
":",
"if",
"term_id",
"in",
"self",
".",
"idx",
":",
"return",
"Cterm",
"(",
"self",
".",
"idx",
"[",
"term_id",
"]",
",",
"self",
".",
"type",
")",
"else",
":",
"return",
"None"
] | 29.6 | 0.013115 |
def wait(self, timeout_s: float = None) -> int:
"""
Wait for up to ``timeout_s`` for the child process to finish.
Args:
timeout_s: maximum time to wait or ``None`` to wait forever
Returns:
process return code; or ``0`` if it wasn't running, or ``1`` if
... | [
"def",
"wait",
"(",
"self",
",",
"timeout_s",
":",
"float",
"=",
"None",
")",
"->",
"int",
":",
"if",
"not",
"self",
".",
"running",
":",
"return",
"0",
"retcode",
"=",
"self",
".",
"process",
".",
"wait",
"(",
"timeout",
"=",
"timeout_s",
")",
"# ... | 36.363636 | 0.001623 |
def _decode_filename_to_unicode(f):
'''Get bytestring filename and return unicode.
First, try to decode from default file system encoding
If that fails, use ``chardet`` module to guess encoding.
As a last resort, try to decode as utf-8.
If the argument already is unicode, return as is'''
log.d... | [
"def",
"_decode_filename_to_unicode",
"(",
"f",
")",
":",
"log",
".",
"debug",
"(",
"'_decode_filename_to_unicode(%s)'",
",",
"repr",
"(",
"f",
")",
")",
"if",
"isinstance",
"(",
"f",
",",
"unicode",
")",
":",
"return",
"f",
"try",
":",
"return",
"f",
".... | 38.5 | 0.00149 |
def find_by_id(self, repoid):
"""
Returns the repo with the specified <repoid>
"""
for row in self.jsondata:
if repoid == row["repoid"]:
return self._infofromdict(row) | [
"def",
"find_by_id",
"(",
"self",
",",
"repoid",
")",
":",
"for",
"row",
"in",
"self",
".",
"jsondata",
":",
"if",
"repoid",
"==",
"row",
"[",
"\"repoid\"",
"]",
":",
"return",
"self",
".",
"_infofromdict",
"(",
"row",
")"
] | 31.571429 | 0.008811 |
def collect(path, no_input):
'''Collect static files'''
if exists(path):
msg = '"%s" directory already exists and will be erased'
log.warning(msg, path)
if not no_input:
click.confirm('Are you sure?', abort=True)
log.info('Deleting static directory "%s"', path)
... | [
"def",
"collect",
"(",
"path",
",",
"no_input",
")",
":",
"if",
"exists",
"(",
"path",
")",
":",
"msg",
"=",
"'\"%s\" directory already exists and will be erased'",
"log",
".",
"warning",
"(",
"msg",
",",
"path",
")",
"if",
"not",
"no_input",
":",
"click",
... | 37.666667 | 0.000719 |
def alignment_correcter(self, alignment_file_list, output_file_name,
filter_minimum=None):
'''
Remove lower case insertions in alignment outputs from HMM align. Give
a list of alignments, and an output file name, and each alignment will
be corrected, and writt... | [
"def",
"alignment_correcter",
"(",
"self",
",",
"alignment_file_list",
",",
"output_file_name",
",",
"filter_minimum",
"=",
"None",
")",
":",
"corrected_sequences",
"=",
"{",
"}",
"for",
"alignment_file",
"in",
"alignment_file_list",
":",
"insert_list",
"=",
"[",
... | 53.169492 | 0.008764 |
def sequence_to_dt64ns(data, dtype=None, copy=False,
tz=None,
dayfirst=False, yearfirst=False, ambiguous='raise',
int_as_wall_time=False):
"""
Parameters
----------
data : list-like
dtype : dtype, str, or None, default None
cop... | [
"def",
"sequence_to_dt64ns",
"(",
"data",
",",
"dtype",
"=",
"None",
",",
"copy",
"=",
"False",
",",
"tz",
"=",
"None",
",",
"dayfirst",
"=",
"False",
",",
"yearfirst",
"=",
"False",
",",
"ambiguous",
"=",
"'raise'",
",",
"int_as_wall_time",
"=",
"False"... | 34.348485 | 0.000214 |
def remove_too_short(utterances: List[Utterance],
_winlen=25, winstep=10) -> List[Utterance]:
""" Removes utterances that will probably have issues with CTC because of
the number of frames being less than the number of tokens in the
transcription. Assuming char tokenization to minimize ... | [
"def",
"remove_too_short",
"(",
"utterances",
":",
"List",
"[",
"Utterance",
"]",
",",
"_winlen",
"=",
"25",
",",
"winstep",
"=",
"10",
")",
"->",
"List",
"[",
"Utterance",
"]",
":",
"def",
"is_too_short",
"(",
"utterance",
":",
"Utterance",
")",
"->",
... | 43.5 | 0.001608 |
def port_pair(self):
"""The port and it's transport as a pair"""
if self.transport is NotSpecified:
return (self.port, "tcp")
else:
return (self.port, self.transport) | [
"def",
"port_pair",
"(",
"self",
")",
":",
"if",
"self",
".",
"transport",
"is",
"NotSpecified",
":",
"return",
"(",
"self",
".",
"port",
",",
"\"tcp\"",
")",
"else",
":",
"return",
"(",
"self",
".",
"port",
",",
"self",
".",
"transport",
")"
] | 34.833333 | 0.009346 |
def find_sanitizer_from_module(module_name, function_name):
"""
Attempts to find sanitizer function from given module. If the module
cannot be imported, or function with given name does not exist in it,
nothing will be returned by this method. Otherwise the found sanitizer
functi... | [
"def",
"find_sanitizer_from_module",
"(",
"module_name",
",",
"function_name",
")",
":",
"try",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"except",
"ImportError",
":",
"return",
"None",
"# Look for the function inside the module. At... | 37.372093 | 0.001213 |
def bar(h1: Histogram1D, **kwargs) -> dict:
"""Bar plot of 1D histogram.
Parameters
----------
lw : float
Width of the line between bars
alpha : float
Opacity of the bars
hover_alpha: float
Opacity of the bars when hover on
"""
# TODO: Enable collections
# TO... | [
"def",
"bar",
"(",
"h1",
":",
"Histogram1D",
",",
"*",
"*",
"kwargs",
")",
"->",
"dict",
":",
"# TODO: Enable collections",
"# TODO: Enable legend",
"vega",
"=",
"_create_figure",
"(",
"kwargs",
")",
"_add_title",
"(",
"h1",
",",
"vega",
",",
"kwargs",
")",
... | 28.52381 | 0.001076 |
def print_upper_triangular_matrix_as_complete(matrix):
"""Prints a CVRP data dict upper triangular matrix as a normal matrix
Doesn't print headers.
Arguments
---------
matrix : dict
Description
"""
for i in sorted(matrix.keys()):
for j in sorted(matrix.keys... | [
"def",
"print_upper_triangular_matrix_as_complete",
"(",
"matrix",
")",
":",
"for",
"i",
"in",
"sorted",
"(",
"matrix",
".",
"keys",
"(",
")",
")",
":",
"for",
"j",
"in",
"sorted",
"(",
"matrix",
".",
"keys",
"(",
")",
")",
":",
"a",
",",
"b",
"=",
... | 21.9 | 0.008753 |
def reshape_like_all_dims(a, b):
"""Reshapes a to match the shape of b."""
ret = tf.reshape(a, tf.shape(b))
if not tf.executing_eagerly():
ret.set_shape(b.get_shape())
return ret | [
"def",
"reshape_like_all_dims",
"(",
"a",
",",
"b",
")",
":",
"ret",
"=",
"tf",
".",
"reshape",
"(",
"a",
",",
"tf",
".",
"shape",
"(",
"b",
")",
")",
"if",
"not",
"tf",
".",
"executing_eagerly",
"(",
")",
":",
"ret",
".",
"set_shape",
"(",
"b",
... | 30.833333 | 0.026316 |
def write_tree_newick(self, filename, hide_rooted_prefix=False):
'''Write this ``Tree`` to a Newick file
Args:
``filename`` (``str``): Path to desired output file (plain-text or gzipped)
'''
if not isinstance(filename, str):
raise TypeError("filename must be a st... | [
"def",
"write_tree_newick",
"(",
"self",
",",
"filename",
",",
"hide_rooted_prefix",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"filename must be a str\"",
")",
"treestr",
"=",
"self",... | 45.055556 | 0.0157 |
def values(self, key_type=None):
""" Returns a copy of the dictionary's values.
@param key_type if specified, only values pointed by keys of this type will be returned.
Otherwise list of all values contained in this dictionary will be returned."""
if(key_type is not None... | [
"def",
"values",
"(",
"self",
",",
"key_type",
"=",
"None",
")",
":",
"if",
"(",
"key_type",
"is",
"not",
"None",
")",
":",
"all_items",
"=",
"{",
"}",
"# in order to preserve keys() type (dict_values for python3) \r",
"keys_used",
"=",
"set",
"(",
")",
"direc... | 55.875 | 0.009901 |
def relop_code(self, relop, operands_type):
"""Returns code for relational operator
relop - relational operator
operands_type - int or unsigned
"""
code = self.RELATIONAL_DICT[relop]
offset = 0 if operands_type == SharedData.TYPES.INT else len(SharedData.RELAT... | [
"def",
"relop_code",
"(",
"self",
",",
"relop",
",",
"operands_type",
")",
":",
"code",
"=",
"self",
".",
"RELATIONAL_DICT",
"[",
"relop",
"]",
"offset",
"=",
"0",
"if",
"operands_type",
"==",
"SharedData",
".",
"TYPES",
".",
"INT",
"else",
"len",
"(",
... | 44.875 | 0.008197 |
def copyNodeList(self, node):
"""Do a recursive copy of the node list. """
if node is None: node__o = None
else: node__o = node._o
ret = libxml2mod.xmlDocCopyNodeList(self._o, node__o)
if ret is None:raise treeError('xmlDocCopyNodeList() failed')
__tmp = xmlNode(_obj=ret)... | [
"def",
"copyNodeList",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"is",
"None",
":",
"node__o",
"=",
"None",
"else",
":",
"node__o",
"=",
"node",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlDocCopyNodeList",
"(",
"self",
".",
"_o",
",",
"nod... | 41.75 | 0.017595 |
def make_parser(parser_creator=None, **kwargs):
"""Returns a base argument parser for the ray.tune tool.
Args:
parser_creator: A constructor for the parser class.
kwargs: Non-positional args to be passed into the
parser class constructor.
"""
if parser_creator:
pars... | [
"def",
"make_parser",
"(",
"parser_creator",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"parser_creator",
":",
"parser",
"=",
"parser_creator",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"... | 36.455224 | 0.000199 |
def export_epoch_file(stimfunction,
filename,
tr_duration,
temporal_resolution=100.0
):
""" Output an epoch file, necessary for some inputs into brainiak
This takes in the time course of stimulus events and outputs the epoc... | [
"def",
"export_epoch_file",
"(",
"stimfunction",
",",
"filename",
",",
"tr_duration",
",",
"temporal_resolution",
"=",
"100.0",
")",
":",
"# Cycle through the participants, different entries in the list",
"epoch_file",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"stimfunction"... | 40.482759 | 0.000208 |
def _catalog_check(self, cat_name, append=False):
"""
Check to see if the name of the ingested catalog is valid
Parameters
----------
cat_name: str
The name of the catalog in the Catalog object
append: bool
Append the catalog rather than r... | [
"def",
"_catalog_check",
"(",
"self",
",",
"cat_name",
",",
"append",
"=",
"False",
")",
":",
"good",
"=",
"True",
"# Make sure the attribute name is good",
"if",
"cat_name",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
":",
"print",
"(",
"\"No names beginning wit... | 30.103448 | 0.008879 |
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadde... | [
"def",
"delete_tags",
"(",
"tags",
",",
"name",
"=",
"None",
",",
"group_id",
"=",
"None",
",",
"vpc_name",
"=",
"None",
",",
"vpc_id",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"="... | 25.734375 | 0.001754 |
def _index_sub(self, uri_list, num, batch_num):
"""
Converts a list of uris to elasticsearch json objects
args:
uri_list: list of uris to convert
num: the ending count within the batch
batch_num: the batch number
"""
bname = '%s-%s' % (batch_n... | [
"def",
"_index_sub",
"(",
"self",
",",
"uri_list",
",",
"num",
",",
"batch_num",
")",
":",
"bname",
"=",
"'%s-%s'",
"%",
"(",
"batch_num",
",",
"num",
")",
"log",
".",
"debug",
"(",
"\"batch_num '%s' starting es_json conversion\"",
",",
"bname",
")",
"qry_da... | 39.840909 | 0.00167 |
def create_namespaced_ingress(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_ingress # noqa: E501
create an Ingress # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> ... | [
"def",
"create_namespaced_ingress",
"(",
"self",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return"... | 61 | 0.001291 |
def startDrag(self, dragData):
"""
Starts a new drag with the inputed data.
:param dragData | <dict>
"""
# create the mime data
mimeData = QMimeData()
for key, value in dragData.items():
mimeData.setData('application/x-%s' % key,... | [
"def",
"startDrag",
"(",
"self",
",",
"dragData",
")",
":",
"# create the mime data\r",
"mimeData",
"=",
"QMimeData",
"(",
")",
"for",
"key",
",",
"value",
"in",
"dragData",
".",
"items",
"(",
")",
":",
"mimeData",
".",
"setData",
"(",
"'application/x-%s'",
... | 31.6 | 0.008197 |
def in_attack_range_of(self, unit: Unit, bonus_distance: Union[int, float] = 0) -> "Units":
""" Filters units that are in attack range of the unit in parameter """
return self.filter(lambda x: unit.target_in_range(x, bonus_distance=bonus_distance)) | [
"def",
"in_attack_range_of",
"(",
"self",
",",
"unit",
":",
"Unit",
",",
"bonus_distance",
":",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"0",
")",
"->",
"\"Units\"",
":",
"return",
"self",
".",
"filter",
"(",
"lambda",
"x",
":",
"unit",
".",
"tar... | 87.333333 | 0.015152 |
def get_model_from_path_string(root_model, path):
""" Return a model class for a related model
root_model is the class of the initial model
path is like foo__bar where bar is related to foo
"""
for path_section in path.split('__'):
if path_section:
try:
field, mod... | [
"def",
"get_model_from_path_string",
"(",
"root_model",
",",
"path",
")",
":",
"for",
"path_section",
"in",
"path",
".",
"split",
"(",
"'__'",
")",
":",
"if",
"path_section",
":",
"try",
":",
"field",
",",
"model",
",",
"direct",
",",
"m2m",
"=",
"_get_f... | 40.217391 | 0.002112 |
def rjust_text(text, width=80, indent=0, subsequent=None):
"""Wrap text and adjust it to right border.
Same as L{wrap_text} with the difference that the text is aligned against
the right text border.
Args:
text (str): Text to wrap and align.
width (int): Maximum number of chara... | [
"def",
"rjust_text",
"(",
"text",
",",
"width",
"=",
"80",
",",
"indent",
"=",
"0",
",",
"subsequent",
"=",
"None",
")",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r\"\\s+\"",
",",
"\" \"",
",",
"text",
")",
".",
"strip",
"(",
")",
"if",
"subseque... | 37.5 | 0.001083 |
def get_exporter(obj, name):
"""
Get an exporter for the
:param obj: object to export
:type obj: :class:`Component <cqparts.Component>`
:param name: registered name of exporter
:type name: :class:`str`
:return: an exporter instance of the given type
:rtype: :class:`Exporter`
:raises... | [
"def",
"get_exporter",
"(",
"obj",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"exporter_index",
":",
"raise",
"TypeError",
"(",
"(",
"\"exporter type '%s' is not registered: \"",
"%",
"name",
")",
"+",
"(",
"\"registered types: %r\"",
"%",
"sorted",
"(",
... | 31.68 | 0.001225 |
def validate(node, source):
"""Call this function to validate an AST."""
# TODO: leaving strict checking off to support insert_grad_of
lf = LanguageFence(source, strict=False)
lf.visit(node)
return node | [
"def",
"validate",
"(",
"node",
",",
"source",
")",
":",
"# TODO: leaving strict checking off to support insert_grad_of",
"lf",
"=",
"LanguageFence",
"(",
"source",
",",
"strict",
"=",
"False",
")",
"lf",
".",
"visit",
"(",
"node",
")",
"return",
"node"
] | 34.5 | 0.028302 |
def cleanup_classes(rdf):
"""Remove unnecessary class definitions: definitions of SKOS classes or
unused classes. If a class is also a skos:Concept or skos:Collection,
remove the 'classness' of it but leave the Concept/Collection."""
for t in (OWL.Class, RDFS.Class):
for cl in rdf.subjects... | [
"def",
"cleanup_classes",
"(",
"rdf",
")",
":",
"for",
"t",
"in",
"(",
"OWL",
".",
"Class",
",",
"RDFS",
".",
"Class",
")",
":",
"for",
"cl",
"in",
"rdf",
".",
"subjects",
"(",
"RDF",
".",
"type",
",",
"t",
")",
":",
"# SKOS classes may be safely rem... | 49.90625 | 0.000614 |
def find_type(self, txt):
"""
top level function used to simply return the
ONE ACTUAL string used for data types
"""
searchString = txt.upper()
match = 'Unknown'
for i in self.lst_type:
if searchString in i:
match = i
return ma... | [
"def",
"find_type",
"(",
"self",
",",
"txt",
")",
":",
"searchString",
"=",
"txt",
".",
"upper",
"(",
")",
"match",
"=",
"'Unknown'",
"for",
"i",
"in",
"self",
".",
"lst_type",
":",
"if",
"searchString",
"in",
"i",
":",
"match",
"=",
"i",
"return",
... | 28.454545 | 0.009288 |
def all_subs(bounds):
"""given a list of tuples specifying the bounds of an array, all_subs()
returns a list of all the tuples of subscripts for that array."""
idx_list = []
for i in range(len(bounds)):
this_dim = bounds[i]
lo,hi = this_dim[0],this_dim[1] # bounds for this dimension... | [
"def",
"all_subs",
"(",
"bounds",
")",
":",
"idx_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"bounds",
")",
")",
":",
"this_dim",
"=",
"bounds",
"[",
"i",
"]",
"lo",
",",
"hi",
"=",
"this_dim",
"[",
"0",
"]",
",",
"this_di... | 41 | 0.008677 |
def simEvalCond(simulator, *conds):
"""
Evaluate list of values as condition
"""
_cond = True
_vld = True
for v in conds:
val = bool(v.val)
fullVld = v.vldMask == 1
if fullVld:
if not val:
return False, True
else:
return Fal... | [
"def",
"simEvalCond",
"(",
"simulator",
",",
"*",
"conds",
")",
":",
"_cond",
"=",
"True",
"_vld",
"=",
"True",
"for",
"v",
"in",
"conds",
":",
"val",
"=",
"bool",
"(",
"v",
".",
"val",
")",
"fullVld",
"=",
"v",
".",
"vldMask",
"==",
"1",
"if",
... | 20.947368 | 0.002404 |
def filter(self, datasource_type, datasource_id, column):
"""
Endpoint to retrieve values for specified column.
:param datasource_type: Type of datasource e.g. table
:param datasource_id: Datasource id
:param column: Column name to retrieve values for
:return:
""... | [
"def",
"filter",
"(",
"self",
",",
"datasource_type",
",",
"datasource_id",
",",
"column",
")",
":",
"# TODO: Cache endpoint by user, datasource and column",
"datasource",
"=",
"ConnectorRegistry",
".",
"get_datasource",
"(",
"datasource_type",
",",
"datasource_id",
",",
... | 40.181818 | 0.00221 |
def generate_and_run(simulation,
simulator,
network=None,
return_results=False,
base_dir=None,
target_dir=None,
num_processors=1):
"""
Generates the network in the specified simulato... | [
"def",
"generate_and_run",
"(",
"simulation",
",",
"simulator",
",",
"network",
"=",
"None",
",",
"return_results",
"=",
"False",
",",
"base_dir",
"=",
"None",
",",
"target_dir",
"=",
"None",
",",
"num_processors",
"=",
"1",
")",
":",
"if",
"network",
"=="... | 45.574879 | 0.013329 |
def types_strict(instance):
"""Ensure that no custom object types are used, but only the official ones
from the specification.
"""
if instance['type'] not in enums.TYPES:
yield JSONError("Object type '%s' is not one of those defined in the"
" specification." % instance['t... | [
"def",
"types_strict",
"(",
"instance",
")",
":",
"if",
"instance",
"[",
"'type'",
"]",
"not",
"in",
"enums",
".",
"TYPES",
":",
"yield",
"JSONError",
"(",
"\"Object type '%s' is not one of those defined in the\"",
"\" specification.\"",
"%",
"instance",
"[",
"'type... | 51.066667 | 0.001282 |
def render_to_message(self, extra_context=None, **kwargs):
"""
Renders and returns an unsent message with the provided context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional contex... | [
"def",
"render_to_message",
"(",
"self",
",",
"extra_context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"extra_context",
"is",
"None",
":",
"extra_context",
"=",
"{",
"}",
"# Ensure our custom headers are added to the underlying message class.",
"kwargs",... | 37.625 | 0.00216 |
def logpdf_link(self, link_f, y, Y_metadata=None):
"""
:param link_f: latent variables (link(f))
:type link_f: Nx1 array
:param y: data
:type y: Nx1 array
:param Y_metadata: includes censoring information in dictionary key 'censored'
:returns: likelihood evaluated... | [
"def",
"logpdf_link",
"(",
"self",
",",
"link_f",
",",
"y",
",",
"Y_metadata",
"=",
"None",
")",
":",
"assert",
"np",
".",
"atleast_1d",
"(",
"link_f",
")",
".",
"shape",
"==",
"np",
".",
"atleast_1d",
"(",
"y",
")",
".",
"shape",
"c",
"=",
"np",
... | 44.052632 | 0.011696 |
def mysql(host, user, passwd, db, charset):
"""Set MySQL/MariaDB connection"""
connection_string = database.set_mysql_connection(host=host, user=user, passwd=passwd, db=db, charset=charset)
test_connection(connection_string) | [
"def",
"mysql",
"(",
"host",
",",
"user",
",",
"passwd",
",",
"db",
",",
"charset",
")",
":",
"connection_string",
"=",
"database",
".",
"set_mysql_connection",
"(",
"host",
"=",
"host",
",",
"user",
"=",
"user",
",",
"passwd",
"=",
"passwd",
",",
"db"... | 58.25 | 0.008475 |
def update_id(self, sequence_id=None):
"""Alter the sequence id, and all of the names and ids derived from it. This
often needs to be done after an IntegrityError in a multiprocessing run"""
if sequence_id:
self.sequence_id = sequence_id
self._set_ids(force=True)
i... | [
"def",
"update_id",
"(",
"self",
",",
"sequence_id",
"=",
"None",
")",
":",
"if",
"sequence_id",
":",
"self",
".",
"sequence_id",
"=",
"sequence_id",
"self",
".",
"_set_ids",
"(",
"force",
"=",
"True",
")",
"if",
"self",
".",
"dataset",
":",
"self",
".... | 32.545455 | 0.01087 |
def import_class(class_path):
"""imports and returns given class string.
:param class_path: Class path as string
:type class_path: str
:returns: Class that has given path
:rtype: class
:Example:
>>> import_class('collections.OrderedDict').__name__
'OrderedDict'
"""
try:
... | [
"def",
"import_class",
"(",
"class_path",
")",
":",
"try",
":",
"from",
"django",
".",
"utils",
".",
"importlib",
"import",
"import_module",
"module_name",
"=",
"'.'",
".",
"join",
"(",
"class_path",
".",
"split",
"(",
"\".\"",
")",
"[",
":",
"-",
"1",
... | 27.142857 | 0.001695 |
def get_pipeline_names():
"""Returns the class paths of all Pipelines defined in alphabetical order."""
class_path_set = set()
for cls in _PipelineMeta._all_classes:
if cls.class_path is not None:
class_path_set.add(cls.class_path)
return sorted(class_path_set) | [
"def",
"get_pipeline_names",
"(",
")",
":",
"class_path_set",
"=",
"set",
"(",
")",
"for",
"cls",
"in",
"_PipelineMeta",
".",
"_all_classes",
":",
"if",
"cls",
".",
"class_path",
"is",
"not",
"None",
":",
"class_path_set",
".",
"add",
"(",
"cls",
".",
"c... | 39.571429 | 0.021201 |
def _send_signal(self, unique_id, signalno, configs):
""" Issues a signal for the specified process
:Parameter unique_id: the name of the process
"""
pids = self.get_pid(unique_id, configs)
if pids != constants.PROCESS_NOT_RUNNING_PID:
pid_str = ' '.join(str(pid) for pid in pids)
hostna... | [
"def",
"_send_signal",
"(",
"self",
",",
"unique_id",
",",
"signalno",
",",
"configs",
")",
":",
"pids",
"=",
"self",
".",
"get_pid",
"(",
"unique_id",
",",
"configs",
")",
"if",
"pids",
"!=",
"constants",
".",
"PROCESS_NOT_RUNNING_PID",
":",
"pid_str",
"=... | 54.666667 | 0.016492 |
def copy_db(source_env, destination_env):
"""
Copies Db betweem servers, ie develop to qa.
Should be called by function from function defined in project fabfile.
Example usage:
def copy_db_between_servers(source_server, destination_server):
source_env = {}
d... | [
"def",
"copy_db",
"(",
"source_env",
",",
"destination_env",
")",
":",
"env",
".",
"update",
"(",
"source_env",
")",
"local_file_path",
"=",
"_get_db",
"(",
")",
"# put the file on external file system",
"# clean external db",
"# load database into external file system",
... | 43.80597 | 0.002333 |
def extract_version(exepath, version_arg, word_index=-1, version_rank=3):
"""Run an executable and get the program version.
Args:
exepath: Filepath to executable.
version_arg: Arg to pass to program, eg "-V". Can also be a list.
word_index: Expect the Nth word of output to be the versio... | [
"def",
"extract_version",
"(",
"exepath",
",",
"version_arg",
",",
"word_index",
"=",
"-",
"1",
",",
"version_rank",
"=",
"3",
")",
":",
"if",
"isinstance",
"(",
"version_arg",
",",
"basestring",
")",
":",
"version_arg",
"=",
"[",
"version_arg",
"]",
"args... | 35.457143 | 0.000784 |
def insert_route(**kw):
"""
`path` - '/', '/some/other/path/', '/test/<int:index>/'
`node_id`
`weight` - How this path is selected before other similar paths
`method` - 'GET' is default.
"""
binding = {
'path': None,
'node_id': None,
'weight': None,
... | [
"def",
"insert_route",
"(",
"*",
"*",
"kw",
")",
":",
"binding",
"=",
"{",
"'path'",
":",
"None",
",",
"'node_id'",
":",
"None",
",",
"'weight'",
":",
"None",
",",
"'method'",
":",
"\"GET\"",
"}",
"binding",
".",
"update",
"(",
"kw",
")",
"with",
"... | 29.6875 | 0.002041 |
def digest(args):
"""
%prog digest fastafile NspI,BfuCI
Digest fasta sequences to map restriction site positions.
"""
p = OptionParser(digest.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, enzymes = args
... | [
"def",
"digest",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"digest",
".",
"__doc__",
")",
"p",
".",
"set_outfile",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",... | 30.285714 | 0.001143 |
def is_running(conn, args):
"""
Run a command to check the status of a mon, return a boolean.
We heavily depend on the format of the output, if that ever changes
we need to modify this.
Check daemon status for 3 times
output of the status should be similar to::
mon.mira094: running {"v... | [
"def",
"is_running",
"(",
"conn",
",",
"args",
")",
":",
"stdout",
",",
"stderr",
",",
"_",
"=",
"remoto",
".",
"process",
".",
"check",
"(",
"conn",
",",
"args",
")",
"result_string",
"=",
"b' '",
".",
"join",
"(",
"stdout",
")",
"for",
"run_check",... | 28 | 0.001381 |
def map_add(self, key, mapkey, value, create=False, **kwargs):
"""
Set a value for a key in a map.
.. warning::
The functionality of the various `map_*`, `list_*`, `queue_*`
and `set_*` functions are considered experimental and are included
in the library to... | [
"def",
"map_add",
"(",
"self",
",",
"key",
",",
"mapkey",
",",
"value",
",",
"create",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"op",
"=",
"SD",
".",
"upsert",
"(",
"mapkey",
",",
"value",
")",
"sdres",
"=",
"self",
".",
"mutate_in",
"(",... | 41 | 0.001402 |
def _process_filters(cls, filters):
"""Takes a list of filters and returns JSON
:Parameters:
- `filters`: List of Filters, (key, val) tuples, or dicts
Returns: List of JSON API filters
"""
data = []
# Filters should always be a list
for f in filters:
... | [
"def",
"_process_filters",
"(",
"cls",
",",
"filters",
")",
":",
"data",
"=",
"[",
"]",
"# Filters should always be a list",
"for",
"f",
"in",
"filters",
":",
"if",
"isinstance",
"(",
"f",
",",
"Filter",
")",
":",
"if",
"f",
".",
"filters",
":",
"data",
... | 33.21875 | 0.001828 |
def poll(self, timeout=0.0):
"""Modified version of poll() from asyncore module"""
if self.sock_map is None:
Log.warning("Socket map is not registered to Gateway Looper")
readable_lst = []
writable_lst = []
error_lst = []
if self.sock_map is not None:
for fd, obj in self.sock_map.it... | [
"def",
"poll",
"(",
"self",
",",
"timeout",
"=",
"0.0",
")",
":",
"if",
"self",
".",
"sock_map",
"is",
"None",
":",
"Log",
".",
"warning",
"(",
"\"Socket map is not registered to Gateway Looper\"",
")",
"readable_lst",
"=",
"[",
"]",
"writable_lst",
"=",
"["... | 28.779661 | 0.01139 |
def get_detection_results(url, timeout, metadata=False, save_har=False):
""" Return results from detector.
This function prepares the environment loading the plugins,
getting the response and passing it to the detector.
In case of errors, it raises exceptions to be handled externally.
"""
plu... | [
"def",
"get_detection_results",
"(",
"url",
",",
"timeout",
",",
"metadata",
"=",
"False",
",",
"save_har",
"=",
"False",
")",
":",
"plugins",
"=",
"load_plugins",
"(",
")",
"if",
"not",
"plugins",
":",
"raise",
"NoPluginsError",
"(",
"'No plugins found'",
"... | 26.794118 | 0.002119 |
def Nu_cylinder_Whitaker(Re, Pr, mu=None, muw=None):
r'''Calculates Nusselt number for crossflow across a single tube as shown
in [1]_ at a specified `Re` and `Pr`, both evaluated at the free stream
temperature. Recommends a viscosity exponent correction of 0.25, which is
applied only if provided. Also ... | [
"def",
"Nu_cylinder_Whitaker",
"(",
"Re",
",",
"Pr",
",",
"mu",
"=",
"None",
",",
"muw",
"=",
"None",
")",
":",
"Nu",
"=",
"(",
"0.4",
"*",
"Re",
"**",
"0.5",
"+",
"0.06",
"*",
"Re",
"**",
"(",
"2",
"/",
"3.",
")",
")",
"*",
"Pr",
"**",
"0.... | 36.211538 | 0.000517 |
def handle(self, cycle_delay=0.1):
"""
Call this method to spend about ``cycle_delay`` seconds processing
requests in the pcaspy server. Under load, for example when running ``caget`` at a
high frequency, the actual time spent in the method may be much shorter. This effect
is not... | [
"def",
"handle",
"(",
"self",
",",
"cycle_delay",
"=",
"0.1",
")",
":",
"if",
"self",
".",
"_server",
"is",
"not",
"None",
":",
"self",
".",
"_server",
".",
"process",
"(",
"cycle_delay",
")",
"self",
".",
"_driver",
".",
"process_pv_updates",
"(",
")"... | 46.75 | 0.008741 |
def to_pypsa(network, mode, timesteps):
"""
Translate graph based grid representation to PyPSA Network
For details from a user perspective see API documentation of
:meth:`~.grid.network.EDisGo.analyze` of the API class
:class:`~.grid.network.EDisGo`.
Translating eDisGo's grid topology to PyPSA... | [
"def",
"to_pypsa",
"(",
"network",
",",
"mode",
",",
"timesteps",
")",
":",
"# check if timesteps is array-like, otherwise convert to list (necessary",
"# to obtain a dataframe when using .loc in time series functions)",
"if",
"not",
"hasattr",
"(",
"timesteps",
",",
"\"__len__\"... | 43.710983 | 0.000388 |
def ratioTerminatorToStar(H_p, R_p, R_s): # TODO add into planet class
r"""Calculates the ratio of the terminator to the star assuming 5 scale
heights large. If you dont know all of the input try
:py:func:`calcRatioTerminatorToStar`
.. math::
\Delta F = \frac{10 H R_p + 25 H^2}{R_\star^2}
... | [
"def",
"ratioTerminatorToStar",
"(",
"H_p",
",",
"R_p",
",",
"R_s",
")",
":",
"# TODO add into planet class",
"deltaF",
"=",
"(",
"(",
"10",
"*",
"H_p",
"*",
"R_p",
")",
"+",
"(",
"25",
"*",
"H_p",
"**",
"2",
")",
")",
"/",
"(",
"R_s",
"**",
"2",
... | 33.55 | 0.001449 |
def _analyzeDontMeasure(self, chunkSize, willMeasureLater, *sinks):
""" Figure out the best diffs to use to reach all our required volumes. """
nodes = [None]
height = 1
def sortKey(node):
if node is None:
return None
return (node.intermediate, s... | [
"def",
"_analyzeDontMeasure",
"(",
"self",
",",
"chunkSize",
",",
"willMeasureLater",
",",
"*",
"sinks",
")",
":",
"nodes",
"=",
"[",
"None",
"]",
"height",
"=",
"1",
"def",
"sortKey",
"(",
"node",
")",
":",
"if",
"node",
"is",
"None",
":",
"return",
... | 39.008621 | 0.002155 |
def get_hash(self):
"""
Get the HMAC-SHA1 that has been calculated this far.
"""
if not self.executed:
raise pyhsm.exception.YHSM_Error("HMAC-SHA1 hash not available, before execute().")
return self.result.hash_result | [
"def",
"get_hash",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"executed",
":",
"raise",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
"(",
"\"HMAC-SHA1 hash not available, before execute().\"",
")",
"return",
"self",
".",
"result",
".",
"hash_result"
] | 37.571429 | 0.011152 |
def coerce(value):
"""
Takes a number (float, int) or a two-valued integer and returns the
[low, high] in the standard interval form
"""
is_number = lambda x: isinstance(x, (int, float, complex)) #is x an instance of those things
if isinstance(value, IntervalCell) or issu... | [
"def",
"coerce",
"(",
"value",
")",
":",
"is_number",
"=",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"(",
"int",
",",
"float",
",",
"complex",
")",
")",
"#is x an instance of those things",
"if",
"isinstance",
"(",
"value",
",",
"IntervalCell",
")",... | 44.592593 | 0.009756 |
def main():
"""
Primary Tarbell command dispatch.
"""
command = Command.lookup(args.get(0))
if len(args) == 0 or args.contains(('-h', '--help', 'help')):
display_info(args)
sys.exit(1)
elif args.contains(('-v', '--version')):
display_version()
sys.exit(1)
e... | [
"def",
"main",
"(",
")",
":",
"command",
"=",
"Command",
".",
"lookup",
"(",
"args",
".",
"get",
"(",
"0",
")",
")",
"if",
"len",
"(",
"args",
")",
"==",
"0",
"or",
"args",
".",
"contains",
"(",
"(",
"'-h'",
",",
"'--help'",
",",
"'help'",
")",... | 23.88 | 0.00161 |
def savepysyn(self,wave,flux,fname,units=None):
""" Cannot ever use the .writefits() method, because the array is
frequently just sampled at the synphot waveset; plus, writefits
is smart and does things like tapering."""
if units is None:
ytype='throughput'
units=... | [
"def",
"savepysyn",
"(",
"self",
",",
"wave",
",",
"flux",
",",
"fname",
",",
"units",
"=",
"None",
")",
":",
"if",
"units",
"is",
"None",
":",
"ytype",
"=",
"'throughput'",
"units",
"=",
"' '",
"else",
":",
"ytype",
"=",
"'flux'",
"col1",
"=",
"py... | 47 | 0.027816 |
def mkdtemp(suffix="", prefix=template, dir=None):
"""User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
The directory is readable, writable, an... | [
"def",
"mkdtemp",
"(",
"suffix",
"=",
"\"\"",
",",
"prefix",
"=",
"template",
",",
"dir",
"=",
"None",
")",
":",
"if",
"dir",
"is",
"None",
":",
"dir",
"=",
"gettempdir",
"(",
")",
"names",
"=",
"_get_candidate_names",
"(",
")",
"for",
"seq",
"in",
... | 29.965517 | 0.001115 |
def interpolate(self, factor, minGlyph, maxGlyph,
round=True, suppressError=True):
"""
Interpolate the contents of this glyph at location ``factor``
in a linear interpolation between ``minGlyph`` and ``maxGlyph``.
>>> glyph.interpolate(0.5, otherGlyph1, otherGlyp... | [
"def",
"interpolate",
"(",
"self",
",",
"factor",
",",
"minGlyph",
",",
"maxGlyph",
",",
"round",
"=",
"True",
",",
"suppressError",
"=",
"True",
")",
":",
"factor",
"=",
"normalizers",
".",
"normalizeInterpolationFactor",
"(",
"factor",
")",
"if",
"not",
... | 52.214286 | 0.001343 |
def dfa_word_acceptance(dfa: dict, word: list) -> bool:
""" Checks if a given **word** is accepted by a DFA,
returning True/false.
The word w is accepted by a DFA if DFA has an accepting run
on w. Since A is deterministic,
:math:`w ∈ L(A)` if and only if :math:`ρ(s_0 , w) ∈ F` .
:param dict df... | [
"def",
"dfa_word_acceptance",
"(",
"dfa",
":",
"dict",
",",
"word",
":",
"list",
")",
"->",
"bool",
":",
"current_state",
"=",
"dfa",
"[",
"'initial_state'",
"]",
"for",
"action",
"in",
"word",
":",
"if",
"(",
"current_state",
",",
"action",
")",
"in",
... | 33.291667 | 0.001217 |
def inverse_lin_decay(max_step, min_value=0.01, step=None):
"""Inverse-decay linearly from 0.01 to 1.0 reached at max_step."""
if step is None:
step = tf.train.get_global_step()
if step is None:
return 1.0
step = to_float(step)
progress = tf.minimum(step / float(max_step), 1.0)
return progress * (1.... | [
"def",
"inverse_lin_decay",
"(",
"max_step",
",",
"min_value",
"=",
"0.01",
",",
"step",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"tf",
".",
"train",
".",
"get_global_step",
"(",
")",
"if",
"step",
"is",
"None",
":",
"retu... | 37.555556 | 0.020231 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.