text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def frompsl(args):
"""
%prog frompsl old.new.psl old.fasta new.fasta
Generate chain file from psl file. The pipeline is describe in:
<http://genomewiki.ucsc.edu/index.php/Minimal_Steps_For_LiftOver>
"""
from jcvi.formats.sizes import Sizes
p = OptionParser(frompsl.__doc__)
opts, args =... | [
"def",
"frompsl",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"sizes",
"import",
"Sizes",
"p",
"=",
"OptionParser",
"(",
"frompsl",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
... | 32.557692 | 0.000573 |
def getInstitutions(self, tags = None, seperator = ";", _getTag = False):
"""Returns a list of the names of institutions. This is done by looking (in order) for any of fields in _tags_ and splitting the strings on _seperator_ (in case of multiple institutions). If no strings are found an empty list will be retu... | [
"def",
"getInstitutions",
"(",
"self",
",",
"tags",
"=",
"None",
",",
"seperator",
"=",
"\";\"",
",",
"_getTag",
"=",
"False",
")",
":",
"return",
"self",
".",
"getInvestigators",
"(",
"tags",
"=",
"tags",
",",
"seperator",
"=",
"seperator",
",",
"_getTa... | 39.954545 | 0.018889 |
def create_birthday(min_age=18, max_age=80):
"""
Create a random birthday fomr someone between the ages of min_age and max_age
"""
age = random.randint(min_age, max_age)
start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365))
return start - datetime.timedelta(days=age * 3... | [
"def",
"create_birthday",
"(",
"min_age",
"=",
"18",
",",
"max_age",
"=",
"80",
")",
":",
"age",
"=",
"random",
".",
"randint",
"(",
"min_age",
",",
"max_age",
")",
"start",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"-",
"datetime",
".",
... | 45.285714 | 0.009288 |
def register(self, object_tool_class, model_class=None):
"""
Registers the given model(s) with the given object tool class.
The model(s) should be Model classes, not instances.
If a model class isn't given the object tool class will be registered
for all models.
If a m... | [
"def",
"register",
"(",
"self",
",",
"object_tool_class",
",",
"model_class",
"=",
"None",
")",
":",
"if",
"not",
"object_tool_class",
":",
"return",
"None",
"# Don't validate unless required.",
"if",
"object_tool_class",
"and",
"settings",
".",
"DEBUG",
":",
"fro... | 35.947368 | 0.001426 |
def from_string(url, default_protocol='telnet'):
"""
Parses the given URL and returns an URL object. There are some
differences to Python's built-in URL parser:
- It is less strict, many more inputs are accepted. This is
necessary to allow for passing a simple hostname as a UR... | [
"def",
"from_string",
"(",
"url",
",",
"default_protocol",
"=",
"'telnet'",
")",
":",
"if",
"url",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'Expected string but got'",
"+",
"type",
"(",
"url",
")",
")",
"# Extract the protocol name from the URL.",
"result",
... | 34.441176 | 0.00083 |
def line(surf, start, end, color=BLACK, width=1, style=FLAT):
"""Draws an antialiased line on the surface."""
width = round(width, 1)
if width == 1:
# return pygame.draw.aaline(surf, color, start, end)
return gfxdraw.line(surf, *start, *end, color)
start = V2(*start)
end = V2(*end)... | [
"def",
"line",
"(",
"surf",
",",
"start",
",",
"end",
",",
"color",
"=",
"BLACK",
",",
"width",
"=",
"1",
",",
"style",
"=",
"FLAT",
")",
":",
"width",
"=",
"round",
"(",
"width",
",",
"1",
")",
"if",
"width",
"==",
"1",
":",
"# return pygame.dra... | 25.638889 | 0.001044 |
def dumps_tabledata(value, format_name="rst_grid_table", **kwargs):
"""
:param tabledata.TableData value: Tabular data to dump.
:param str format_name:
Dumped format name of tabular data.
Available formats are described in
:py:meth:`~pytablewriter.TableWriterFactory.create_from_forma... | [
"def",
"dumps_tabledata",
"(",
"value",
",",
"format_name",
"=",
"\"rst_grid_table\"",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"_factory",
"import",
"TableWriterFactory",
"if",
"not",
"value",
":",
"raise",
"TypeError",
"(",
"\"value must be a tabledata.Ta... | 28.944444 | 0.000929 |
def save_schedule(self):
'''
Save the current schedule
'''
self.persist()
# Fire the complete event back along with the list of schedule
evt = salt.utils.event.get_event('minion', opts=self.opts, listen=False)
evt.fire_event({'complete': True},
... | [
"def",
"save_schedule",
"(",
"self",
")",
":",
"self",
".",
"persist",
"(",
")",
"# Fire the complete event back along with the list of schedule",
"evt",
"=",
"salt",
".",
"utils",
".",
"event",
".",
"get_event",
"(",
"'minion'",
",",
"opts",
"=",
"self",
".",
... | 35.7 | 0.008197 |
def start():
'''
Start simple_server()
'''
from wsgiref.simple_server import make_server
# When started outside of salt-api __opts__ will not be injected
if '__opts__' not in globals():
globals()['__opts__'] = get_opts()
if __virtual__() is False:
raise SystemExit(1... | [
"def",
"start",
"(",
")",
":",
"from",
"wsgiref",
".",
"simple_server",
"import",
"make_server",
"# When started outside of salt-api __opts__ will not be injected",
"if",
"'__opts__'",
"not",
"in",
"globals",
"(",
")",
":",
"globals",
"(",
")",
"[",
"'__opts__'",
"]... | 24.772727 | 0.001767 |
def Disc(
pos=(0, 0, 0),
normal=(0, 0, 1),
r1=0.5,
r2=1,
c="coral",
bc="darkgreen",
lw=1,
alpha=1,
res=12,
resphi=None,
):
"""
Build a 2D disc of internal radius `r1` and outer radius `r2`,
oriented perpendicular to `normal`.
|Disk|
"""
ps = vtk.vtkDi... | [
"def",
"Disc",
"(",
"pos",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"normal",
"=",
"(",
"0",
",",
"0",
",",
"1",
")",
",",
"r1",
"=",
"0.5",
",",
"r2",
"=",
"1",
",",
"c",
"=",
"\"coral\"",
",",
"bc",
"=",
"\"darkgreen\"",
",",
"lw",
... | 25.666667 | 0.001317 |
def lock(self): # type: () -> Installer
"""
Prepare the installer for locking only.
"""
self.update()
self.execute_operations(False)
self._lock = True
return self | [
"def",
"lock",
"(",
"self",
")",
":",
"# type: () -> Installer",
"self",
".",
"update",
"(",
")",
"self",
".",
"execute_operations",
"(",
"False",
")",
"self",
".",
"_lock",
"=",
"True",
"return",
"self"
] | 23.555556 | 0.009091 |
def is_connected(self):
"""Return connection status"""
self._connected = self._connected and self._conn.is_connected()
return self._connected | [
"def",
"is_connected",
"(",
"self",
")",
":",
"self",
".",
"_connected",
"=",
"self",
".",
"_connected",
"and",
"self",
".",
"_conn",
".",
"is_connected",
"(",
")",
"return",
"self",
".",
"_connected"
] | 40.5 | 0.012121 |
def __isValidZIP(self, suffix):
"""Determine if the suffix is `.zip` format"""
if suffix and isinstance(suffix, string_types):
if suffix.endswith(".zip"):
return True
return False | [
"def",
"__isValidZIP",
"(",
"self",
",",
"suffix",
")",
":",
"if",
"suffix",
"and",
"isinstance",
"(",
"suffix",
",",
"string_types",
")",
":",
"if",
"suffix",
".",
"endswith",
"(",
"\".zip\"",
")",
":",
"return",
"True",
"return",
"False"
] | 38.5 | 0.008475 |
def read_json(directory, data_files='data/js/tweets/*.js'):
'''
Scrape a twitter archive file.
Inspiration from https://github.com/mshea/Parse-Twitter-Archive
'''
files = path.join(directory, data_files)
for fname in iglob(files):
with open(fname, 'r') as f:
# Twitter's JSON... | [
"def",
"read_json",
"(",
"directory",
",",
"data_files",
"=",
"'data/js/tweets/*.js'",
")",
":",
"files",
"=",
"path",
".",
"join",
"(",
"directory",
",",
"data_files",
")",
"for",
"fname",
"in",
"iglob",
"(",
"files",
")",
":",
"with",
"open",
"(",
"fna... | 30.8125 | 0.001969 |
def get_entry_point(key, value):
"""Check if registered entry point is available for a given name and
load it. Otherwise, return None.
key (unicode): Entry point name.
value (unicode): Name of entry point to load.
RETURNS: The loaded entry point or None.
"""
for entry_point in pkg_resources... | [
"def",
"get_entry_point",
"(",
"key",
",",
"value",
")",
":",
"for",
"entry_point",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"key",
")",
":",
"if",
"entry_point",
".",
"name",
"==",
"value",
":",
"return",
"entry_point",
".",
"load",
"(",
")"
... | 37.272727 | 0.002381 |
def write_pp_file(filename,pp_df):
"""write a pilot points dataframe to a pilot points file
Parameters
----------
filename : str
pilot points file to write
pp_df : pandas.DataFrame
a dataframe that has columns "x","y","zone", and "value"
"""
with open(filename,'w') as f:
... | [
"def",
"write_pp_file",
"(",
"filename",
",",
"pp_df",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"pp_df",
".",
"to_string",
"(",
"col_space",
"=",
"0",
",",
"columns",
"=",
"PP_NAMES",
",",
... | 32.944444 | 0.014754 |
def cdx_sort_closest(closest, cdx_iter, limit=10):
"""
sort CDXCaptureResult by closest to timestamp.
"""
closest_cdx = []
closest_keys = []
closest_sec = timestamp_to_sec(closest)
for cdx in cdx_iter:
sec = timestamp_to_sec(cdx[TIMESTAMP])
key = abs(closest_sec - sec)
... | [
"def",
"cdx_sort_closest",
"(",
"closest",
",",
"cdx_iter",
",",
"limit",
"=",
"10",
")",
":",
"closest_cdx",
"=",
"[",
"]",
"closest_keys",
"=",
"[",
"]",
"closest_sec",
"=",
"timestamp_to_sec",
"(",
"closest",
")",
"for",
"cdx",
"in",
"cdx_iter",
":",
... | 27.241379 | 0.002445 |
def _parse_file(cls, path, pickle=False):
"""parse a .chain file into a list of the type [(L{Chain}, arr, arr, arr) ...]
:param fname: name of the file"""
fname = path
if fname.endswith(".gz"):
fname = path[:-3]
if fname.endswith('.pkl'):
#you asked for... | [
"def",
"_parse_file",
"(",
"cls",
",",
"path",
",",
"pickle",
"=",
"False",
")",
":",
"fname",
"=",
"path",
"if",
"fname",
".",
"endswith",
"(",
"\".gz\"",
")",
":",
"fname",
"=",
"path",
"[",
":",
"-",
"3",
"]",
"if",
"fname",
".",
"endswith",
"... | 43.038462 | 0.008741 |
def import_field(field_classpath):
"""
Imports a field by its dotted class path, prepending "django.db.models"
to raw class names and raising an exception if the import fails.
"""
if '.' in field_classpath:
fully_qualified = field_classpath
else:
fully_qualified = "django.db.mode... | [
"def",
"import_field",
"(",
"field_classpath",
")",
":",
"if",
"'.'",
"in",
"field_classpath",
":",
"fully_qualified",
"=",
"field_classpath",
"else",
":",
"fully_qualified",
"=",
"\"django.db.models.%s\"",
"%",
"field_classpath",
"try",
":",
"return",
"import_dotted_... | 42 | 0.001553 |
def merge(self, evaluation_context: 'EvaluationContext') -> None:
"""
Merges the provided evaluation context to the current evaluation context.
:param evaluation_context: Evaluation context to merge.
"""
self.global_context.merge(evaluation_context.global_context)
self.lo... | [
"def",
"merge",
"(",
"self",
",",
"evaluation_context",
":",
"'EvaluationContext'",
")",
"->",
"None",
":",
"self",
".",
"global_context",
".",
"merge",
"(",
"evaluation_context",
".",
"global_context",
")",
"self",
".",
"local_context",
".",
"merge",
"(",
"ev... | 52.142857 | 0.008086 |
def plot(self, ax, scatter=True, grid=True, progress_colors=True, progress_max=1., depth=10, plot_dims=[0,1]):
"""
Plot a projection on 2D of the Tree.
Parameters
----------
ax : plt axis
scatter : bool
If the points are ploted
grid : bool
... | [
"def",
"plot",
"(",
"self",
",",
"ax",
",",
"scatter",
"=",
"True",
",",
"grid",
"=",
"True",
",",
"progress_colors",
"=",
"True",
",",
"progress_max",
"=",
"1.",
",",
"depth",
"=",
"10",
",",
"plot_dims",
"=",
"[",
"0",
",",
"1",
"]",
")",
":",
... | 33.62963 | 0.009636 |
def wrap(text, width=70, **kwargs):
"""Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), ... | [
"def",
"wrap",
"(",
"text",
",",
"width",
"=",
"70",
",",
"*",
"*",
"kwargs",
")",
":",
"w",
"=",
"TextWrapper",
"(",
"width",
"=",
"width",
",",
"*",
"*",
"kwargs",
")",
"return",
"w",
".",
"wrap",
"(",
"text",
")"
] | 46.5 | 0.001757 |
def contains(self, url: str):
'''Return whether the URL is in the table.'''
try:
self.get_one(url)
except NotFound:
return False
else:
return True | [
"def",
"contains",
"(",
"self",
",",
"url",
":",
"str",
")",
":",
"try",
":",
"self",
".",
"get_one",
"(",
"url",
")",
"except",
"NotFound",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | 23 | 0.009302 |
def __setkey(key):
"""
Set up the key schedule from the encryption key.
"""
global C, D, KS, E
shifts = (1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1)
# First, generate C and D by permuting the key. The lower order bit of each
# 8-bit char is not used, so C and D are only 28 bits apiece.... | [
"def",
"__setkey",
"(",
"key",
")",
":",
"global",
"C",
",",
"D",
",",
"KS",
",",
"E",
"shifts",
"=",
"(",
"1",
",",
"1",
",",
"2",
",",
"2",
",",
"2",
",",
"2",
",",
"2",
",",
"2",
",",
"1",
",",
"2",
",",
"2",
",",
"2",
",",
"2",
... | 25.351351 | 0.001027 |
def _expand_if_needed(self, dims, write_dims, start, offset):
"""
expand the on-disk image if the indended write will extend
beyond the existing dimensions
"""
from operator import mul
if numpy.isscalar(start):
start_is_scalar = True
else:
... | [
"def",
"_expand_if_needed",
"(",
"self",
",",
"dims",
",",
"write_dims",
",",
"start",
",",
"offset",
")",
":",
"from",
"operator",
"import",
"mul",
"if",
"numpy",
".",
"isscalar",
"(",
"start",
")",
":",
"start_is_scalar",
"=",
"True",
"else",
":",
"sta... | 34.759259 | 0.001036 |
def mean(arrays, masks=None, dtype=None, out=None,
zeros=None, scales=None,
weights=None):
"""Combine arrays using the mean, with masks and offsets.
Arrays and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
... | [
"def",
"mean",
"(",
"arrays",
",",
"masks",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
",",
"zeros",
"=",
"None",
",",
"scales",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"return",
"generic_combine",
"(",
"intl_combine... | 36.131579 | 0.000709 |
def timelag_filter(function, pad=True, index=0):
'''Filtering in the time-lag domain.
This is primarily useful for adapting image filters to operate on
`recurrence_to_lag` output.
Using `timelag_filter` is equivalent to the following sequence of
operations:
>>> data_tl = librosa.segment.recur... | [
"def",
"timelag_filter",
"(",
"function",
",",
"pad",
"=",
"True",
",",
"index",
"=",
"0",
")",
":",
"def",
"__my_filter",
"(",
"wrapped_f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"'''Decorator to wrap the filter'''",
"# Map the input data into t... | 32.542169 | 0.000359 |
def select_ignore_interrupts(iwtd, owtd, ewtd, timeout=None):
'''This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). '''
# if select... | [
"def",
"select_ignore_interrupts",
"(",
"iwtd",
",",
"owtd",
",",
"ewtd",
",",
"timeout",
"=",
"None",
")",
":",
"# if select() is interrupted by a signal (errno==EINTR) then",
"# we loop back and enter the select() again.",
"if",
"timeout",
"is",
"not",
"None",
":",
"end... | 40.518519 | 0.000893 |
def trunk_mode(self, **kwargs):
"""Set trunk mode (trunk, trunk-no-default-vlan).
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
mode (str): Trunk port mode (trun... | [
"def",
"trunk_mode",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"int_type",
"=",
"kwargs",
".",
"pop",
"(",
"'int_type'",
")",
".",
"lower",
"(",
")",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
")",
"mode",
"=",
"kwargs",
".",
"pop",
... | 42.885246 | 0.000747 |
def addConcept(self, conceptUri, weight, label = None, conceptType = None):
"""
add a relevant concept to the topic page
@param conceptUri: uri of the concept to be added
@param weight: importance of the provided concept (typically in range 1 - 50)
"""
assert isinstance(w... | [
"def",
"addConcept",
"(",
"self",
",",
"conceptUri",
",",
"weight",
",",
"label",
"=",
"None",
",",
"conceptType",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a posit... | 54.909091 | 0.019544 |
def baseline_or_audit(self, allow_deletion=False, audit_only=False):
"""Baseline synchonization or audit.
Both functions implemented in this routine because audit is a prerequisite
for a baseline sync. In the case of baseline sync the last timestamp seen
is recorded as client state.
... | [
"def",
"baseline_or_audit",
"(",
"self",
",",
"allow_deletion",
"=",
"False",
",",
"audit_only",
"=",
"False",
")",
":",
"action",
"=",
"(",
"'audit'",
"if",
"(",
"audit_only",
")",
"else",
"'baseline sync'",
")",
"self",
".",
"logger",
".",
"debug",
"(",
... | 50.313953 | 0.00204 |
def recall(self):
"""Calculates recall
:return: Recall
"""
true_pos = self.matrix[0][0]
false_neg = self.matrix[0][1]
return divide(1.0 * true_pos, true_pos + false_neg) | [
"def",
"recall",
"(",
"self",
")",
":",
"true_pos",
"=",
"self",
".",
"matrix",
"[",
"0",
"]",
"[",
"0",
"]",
"false_neg",
"=",
"self",
".",
"matrix",
"[",
"0",
"]",
"[",
"1",
"]",
"return",
"divide",
"(",
"1.0",
"*",
"true_pos",
",",
"true_pos",... | 26.375 | 0.009174 |
def run(addr, *commands, **kwargs):
"""
Non-threaded batch command runner returning output results
"""
results = []
handler = VarnishHandler(addr, **kwargs)
for cmd in commands:
if isinstance(cmd, tuple) and len(cmd)>1:
results.extend([getattr(handler, c[0].replace('.','_'))(... | [
"def",
"run",
"(",
"addr",
",",
"*",
"commands",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"[",
"]",
"handler",
"=",
"VarnishHandler",
"(",
"addr",
",",
"*",
"*",
"kwargs",
")",
"for",
"cmd",
"in",
"commands",
":",
"if",
"isinstance",
"(",... | 34.428571 | 0.012121 |
def rio_save(self, filename, fformat=None, fill_value=None,
dtype=np.uint8, compute=True, tags=None,
keep_palette=False, cmap=None,
**format_kwargs):
"""Save the image using rasterio.
Overviews can be added to the file using the `overviews` kwarg, eg::... | [
"def",
"rio_save",
"(",
"self",
",",
"filename",
",",
"fformat",
"=",
"None",
",",
"fill_value",
"=",
"None",
",",
"dtype",
"=",
"np",
".",
"uint8",
",",
"compute",
"=",
"True",
",",
"tags",
"=",
"None",
",",
"keep_palette",
"=",
"False",
",",
"cmap"... | 39.656863 | 0.001206 |
def cube2map(data_cube, layout):
r"""Cube to Map
This method transforms the input data from a 3D cube to a 2D map with a
specified layout
Parameters
----------
data_cube : np.ndarray
Input data cube, 3D array of 2D images
Layout : tuple
2D layout of 2D images
Returns
... | [
"def",
"cube2map",
"(",
"data_cube",
",",
"layout",
")",
":",
"if",
"data_cube",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'The input data must have 3 dimensions.'",
")",
"if",
"data_cube",
".",
"shape",
"[",
"0",
"]",
"!=",
"np",
".",
"pro... | 24.444444 | 0.000874 |
def regularization(variables, regtype, regcoef, name="regularization"):
"""Compute the regularization tensor.
Parameters
----------
variables : list of tf.Variable
List of model variables.
regtype : str
Type of regularization. Can be ["none", "l1", "l2"... | [
"def",
"regularization",
"(",
"variables",
",",
"regtype",
",",
"regcoef",
",",
"name",
"=",
"\"regularization\"",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
")",
":",
"if",
"regtype",
"!=",
"'none'",
":",
"regs",
"=",
"tf",
".",
"constant",... | 28.571429 | 0.001934 |
def dumps(data, **kwargs):
"""Convert a PPMP entity to JSON. Additional arguments are the same as
accepted by `json.dumps`."""
def _encoder(value):
if isinstance(value, datetime.datetime):
return value.isoformat()
if hasattr(value, "_data"):
return value._data
... | [
"def",
"dumps",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_encoder",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"value",
".",
"isoformat",
"(",
")",
"if",
"hasattr",
... | 29.571429 | 0.002342 |
def run_from_cli():
"""
Perform an update instigated from a CLI.
"""
arg_parser = argparse.ArgumentParser(
description='Read and write properties in a wp-config.php file. '
'Include a --value argument to set the value, omit it to '
'read the value of the ... | [
"def",
"run_from_cli",
"(",
")",
":",
"arg_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Read and write properties in a wp-config.php file. '",
"'Include a --value argument to set the value, omit it to '",
"'read the value of the specified key.'",
",",
... | 30.261538 | 0.000492 |
def as_yaml(self):
"""
as_yaml
"""
self.set_reprdict_from_attributes()
return "---\n" + yaml.dump(self.m_reprdict, default_flow_style=False) | [
"def",
"as_yaml",
"(",
"self",
")",
":",
"self",
".",
"set_reprdict_from_attributes",
"(",
")",
"return",
"\"---\\n\"",
"+",
"yaml",
".",
"dump",
"(",
"self",
".",
"m_reprdict",
",",
"default_flow_style",
"=",
"False",
")"
] | 29.166667 | 0.011111 |
def fromxml(node):
"""Static method return an OutputTemplate instance from the given XML description. Node can be a string or an etree._Element."""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = parsexmlstring(node)
assert node.tag.lower() == '... | [
"def",
"fromxml",
"(",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_Element",
")",
":",
"#pylint: disable=protected-access",
"node",
"=",
"parsexmlstring",
"(",
"node",
")",
"assert",
"node",
".",
"tag",
".",
"lower",
... | 47.162791 | 0.010145 |
def get_validation_col_names(df):
"""
Input: validated pandas DataFrame (using validate_df)
Output: names of all value validation columns,
names of all presence validation columns,
names of all type validation columns,
names of all missing group columns,
names... | [
"def",
"get_validation_col_names",
"(",
"df",
")",
":",
"value_cols",
"=",
"df",
".",
"columns",
".",
"str",
".",
"match",
"(",
"\"^value_pass_\"",
")",
"present_cols",
"=",
"df",
".",
"columns",
".",
"str",
".",
"match",
"(",
"\"^presence_pass\"",
")",
"t... | 46.208333 | 0.001767 |
def spawn_watcher(self, label, target=None, eternal=False):
"""Spawns a config watcher in a separate daemon thread.
If a particular config value changes, and the item has a
``watch_target`` defined, then that method will be called.
If a ``target`` is passed in, then it will call the ``... | [
"def",
"spawn_watcher",
"(",
"self",
",",
"label",
",",
"target",
"=",
"None",
",",
"eternal",
"=",
"False",
")",
":",
"if",
"label",
"not",
"in",
"self",
".",
"_sources",
":",
"raise",
"YapconfSourceError",
"(",
"'Cannot watch %s no source named %s'",
"%",
... | 37.37931 | 0.001799 |
def rows(self, *args) -> List[List[Well]]:
"""
Accessor function used to navigate through a labware by row.
With indexing one can treat it as a typical python nested list.
To access row A for example, simply write: labware.rows()[0]. This
will output ['A1', 'A2', 'A3', 'A4'...]
... | [
"def",
"rows",
"(",
"self",
",",
"*",
"args",
")",
"->",
"List",
"[",
"List",
"[",
"Well",
"]",
"]",
":",
"row_dict",
"=",
"self",
".",
"_create_indexed_dictionary",
"(",
"group",
"=",
"1",
")",
"keys",
"=",
"sorted",
"(",
"row_dict",
")",
"if",
"n... | 38.714286 | 0.0018 |
def cluster_and_update(records, group_dist=50, eps=100):
"""
Update records, by clustering their positions using the DBSCAN algorithm.
Returns a dictionnary associating new antenna identifiers to (lat, lon)
location tuples.
.. note:: Use this function to cluster fine-grained GPS records.
Param... | [
"def",
"cluster_and_update",
"(",
"records",
",",
"group_dist",
"=",
"50",
",",
"eps",
"=",
"100",
")",
":",
"# Run the DBSCAN algorithm with all stop locations and 1 minimal point.",
"stops",
"=",
"get_stops",
"(",
"records",
",",
"group_dist",
")",
"labels",
"=",
... | 36.027778 | 0.000751 |
def _get_callable(self, func, *targets):
"""
If func is already a callable, it is returned directly. If it's a string, it is assumed
to be a method on one of the objects supplied in targets and that is returned. If no
method with the specified name is found, an AttributeError is raised.
... | [
"def",
"_get_callable",
"(",
"self",
",",
"func",
",",
"*",
"targets",
")",
":",
"if",
"not",
"callable",
"(",
"func",
")",
":",
"func_name",
"=",
"func",
"func",
"=",
"next",
"(",
"(",
"getattr",
"(",
"obj",
",",
"func",
",",
"None",
")",
"for",
... | 45.190476 | 0.008256 |
def _datetime_view(
request,
template,
dt,
timeslot_factory=None,
items=None,
params=None
):
'''
Build a time slot grid representation for the given datetime ``dt``. See
utils.create_timeslot_table documentation for items and params.
Context parameters:
``day``
the ... | [
"def",
"_datetime_view",
"(",
"request",
",",
"template",
",",
"dt",
",",
"timeslot_factory",
"=",
"None",
",",
"items",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"timeslot_factory",
"=",
"timeslot_factory",
"or",
"utils",
".",
"create_timeslot_table"... | 21.75 | 0.001222 |
def create(source,
requirement_files=None,
force=False,
keep_wheels=False,
archive_destination_dir='.',
python_versions=None,
validate_archive=False,
wheel_args='',
archive_format='zip',
build_tag=''):
"""Create a Wag... | [
"def",
"create",
"(",
"source",
",",
"requirement_files",
"=",
"None",
",",
"force",
"=",
"False",
",",
"keep_wheels",
"=",
"False",
",",
"archive_destination_dir",
"=",
"'.'",
",",
"python_versions",
"=",
"None",
",",
"validate_archive",
"=",
"False",
",",
... | 33.554217 | 0.000349 |
def create_package_file(root, master_package, subroot, py_files, opts, subs):
"""Build the text of the file and write the file."""
text = format_heading(1, '%s' % makename(master_package, subroot))
if opts.modulefirst:
text += format_directive(subroot, master_package)
text += '\n'
# bu... | [
"def",
"create_package_file",
"(",
"root",
",",
"master_package",
",",
"subroot",
",",
"py_files",
",",
"opts",
",",
"subs",
")",
":",
"text",
"=",
"format_heading",
"(",
"1",
",",
"'%s'",
"%",
"makename",
"(",
"master_package",
",",
"subroot",
")",
")",
... | 42.134615 | 0.000892 |
def compute_pointwise_distances(self, other, default=None):
"""
Compute the minimal distance between each point on self and other.
Parameters
----------
other : tuple of number \
or imgaug.augmentables.kps.Keypoint \
or imgaug.augmentables.LineStr... | [
"def",
"compute_pointwise_distances",
"(",
"self",
",",
"other",
",",
"default",
"=",
"None",
")",
":",
"import",
"shapely",
".",
"geometry",
"from",
".",
"kps",
"import",
"Keypoint",
"if",
"isinstance",
"(",
"other",
",",
"Keypoint",
")",
":",
"other",
"=... | 34.214286 | 0.00203 |
def get_uuid_like_indexes_on_table(model):
"""
Gets a list of database index names for the given model for the
uuid-containing fields that have had a like-index created on them.
:param model: Django model
:return: list of database rows; the first field of each row is an index
name
"""
... | [
"def",
"get_uuid_like_indexes_on_table",
"(",
"model",
")",
":",
"with",
"default_connection",
".",
"cursor",
"(",
")",
"as",
"c",
":",
"indexes",
"=",
"select_uuid_like_indexes_on_table",
"(",
"model",
",",
"c",
")",
"return",
"indexes"
] | 35.916667 | 0.002262 |
def get_main_filename_attr(self):
'''Returns the main filename attribute of the entry.
As an entry can have multiple FILENAME attributes, this function allows
to return the main one, i.e., the one with the lowest attribute id and
the "biggest" namespace.
'''
fn_attrs = s... | [
"def",
"get_main_filename_attr",
"(",
"self",
")",
":",
"fn_attrs",
"=",
"self",
".",
"get_attributes",
"(",
"AttrTypes",
".",
"FILE_NAME",
")",
"high_attr_id",
"=",
"0xFFFFFFFF",
"main_fn",
"=",
"None",
"if",
"fn_attrs",
"is",
"not",
"None",
":",
"#search for... | 45.814815 | 0.008709 |
def _refresh_state(self):
""" Get the state of a job. If the job is complete this does nothing;
otherwise it gets a refreshed copy of the job resource.
"""
# TODO(gram): should we put a choke on refreshes? E.g. if the last call was less than
# a second ago should we return the cached value?
... | [
"def",
"_refresh_state",
"(",
"self",
")",
":",
"# TODO(gram): should we put a choke on refreshes? E.g. if the last call was less than",
"# a second ago should we return the cached value?",
"if",
"self",
".",
"_is_complete",
":",
"return",
"try",
":",
"response",
"=",
"self",
"... | 38.857143 | 0.011659 |
def t_LABELDECL(self, token):
ur'-\s<label>\s*\[(?P<label>.+?)\]\s*(?P<text>.+?)\n'
label = token.lexer.lexmatch.group("label").decode("utf8")
text = token.lexer.lexmatch.group("text").decode("utf8")
token.value = (label, text)
token.lexer.lineno += 1
return token | [
"def",
"t_LABELDECL",
"(",
"self",
",",
"token",
")",
":",
"label",
"=",
"token",
".",
"lexer",
".",
"lexmatch",
".",
"group",
"(",
"\"label\"",
")",
".",
"decode",
"(",
"\"utf8\"",
")",
"text",
"=",
"token",
".",
"lexer",
".",
"lexmatch",
".",
"grou... | 43.714286 | 0.022436 |
def cmap_from_color(color, dark=False):
'''
Generates a matplotlib colormap from a single color.
Colormap will be built, by default, from white to ``color``.
Args:
color: Can be one of several things:
1. Hex code
2. HTML color name
3. RGB tuple
da... | [
"def",
"cmap_from_color",
"(",
"color",
",",
"dark",
"=",
"False",
")",
":",
"if",
"dark",
":",
"return",
"sns",
".",
"dark_palette",
"(",
"color",
",",
"as_cmap",
"=",
"True",
")",
"else",
":",
"return",
"sns",
".",
"light_palette",
"(",
"color",
",",... | 24.222222 | 0.001471 |
def __Logout(si):
"""
Disconnect (logout) service instance
@param si: Service instance (returned from Connect)
"""
try:
if si:
content = si.RetrieveContent()
content.sessionManager.Logout()
except Exception as e:
pass | [
"def",
"__Logout",
"(",
"si",
")",
":",
"try",
":",
"if",
"si",
":",
"content",
"=",
"si",
".",
"RetrieveContent",
"(",
")",
"content",
".",
"sessionManager",
".",
"Logout",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"pass"
] | 23.181818 | 0.030189 |
def get_angles(self, angle_id):
"""Get sun-satellite viewing angles"""
tic = datetime.now()
sunz40km = self._data["ang"][:, :, 0] * 1e-2
satz40km = self._data["ang"][:, :, 1] * 1e-2
azidiff40km = self._data["ang"][:, :, 2] * 1e-2
try:
from geotiepoints.inte... | [
"def",
"get_angles",
"(",
"self",
",",
"angle_id",
")",
":",
"tic",
"=",
"datetime",
".",
"now",
"(",
")",
"sunz40km",
"=",
"self",
".",
"_data",
"[",
"\"ang\"",
"]",
"[",
":",
",",
":",
",",
"0",
"]",
"*",
"1e-2",
"satz40km",
"=",
"self",
".",
... | 37.323529 | 0.002304 |
def profile():
"""View for editing a profile."""
# Create forms
verification_form = VerificationForm(formdata=None, prefix="verification")
profile_form = profile_form_factory()
# Process forms
form = request.form.get('submit', None)
if form == 'profile':
handle_profile_form(profile_... | [
"def",
"profile",
"(",
")",
":",
"# Create forms",
"verification_form",
"=",
"VerificationForm",
"(",
"formdata",
"=",
"None",
",",
"prefix",
"=",
"\"verification\"",
")",
"profile_form",
"=",
"profile_form_factory",
"(",
")",
"# Process forms",
"form",
"=",
"requ... | 33.235294 | 0.001721 |
def _load_output_data_port_models(self):
"""Reloads the output data port models directly from the the state
"""
self.output_data_ports = []
for output_data_port in self.state.output_data_ports.values():
self._add_model(self.output_data_ports, output_data_port, DataPortModel) | [
"def",
"_load_output_data_port_models",
"(",
"self",
")",
":",
"self",
".",
"output_data_ports",
"=",
"[",
"]",
"for",
"output_data_port",
"in",
"self",
".",
"state",
".",
"output_data_ports",
".",
"values",
"(",
")",
":",
"self",
".",
"_add_model",
"(",
"se... | 52.333333 | 0.009404 |
def _cacheSequenceInfoType(self):
"""Figure out whether reset, sequenceId,
both or neither are present in the data.
Compute once instead of every time.
Taken from filesource.py"""
hasReset = self.resetFieldName is not None
hasSequenceId = self.sequenceIdFieldName is not None
if hasReset a... | [
"def",
"_cacheSequenceInfoType",
"(",
"self",
")",
":",
"hasReset",
"=",
"self",
".",
"resetFieldName",
"is",
"not",
"None",
"hasSequenceId",
"=",
"self",
".",
"sequenceIdFieldName",
"is",
"not",
"None",
"if",
"hasReset",
"and",
"not",
"hasSequenceId",
":",
"s... | 35.4 | 0.009629 |
def run_jar(jar_name, more_args=None, properties=None, hadoop_conf_dir=None,
keep_streams=True):
"""
Run a jar on Hadoop (``hadoop jar`` command).
All arguments are passed to :func:`run_cmd` (``args = [jar_name] +
more_args``) .
"""
if hu.is_readable(jar_name):
args = [jar_n... | [
"def",
"run_jar",
"(",
"jar_name",
",",
"more_args",
"=",
"None",
",",
"properties",
"=",
"None",
",",
"hadoop_conf_dir",
"=",
"None",
",",
"keep_streams",
"=",
"True",
")",
":",
"if",
"hu",
".",
"is_readable",
"(",
"jar_name",
")",
":",
"args",
"=",
"... | 32.777778 | 0.001647 |
def unsign_url_safe(token, secret_key, salt=None, **kw):
"""
To sign url safe data.
If expires_in is provided it will Time the signature
:param token:
:param secret_key:
:param salt: (string) a namespace key
:param kw:
:return:
"""
if len(token.split(".")) == 3:
s = URLSa... | [
"def",
"unsign_url_safe",
"(",
"token",
",",
"secret_key",
",",
"salt",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"len",
"(",
"token",
".",
"split",
"(",
"\".\"",
")",
")",
"==",
"3",
":",
"s",
"=",
"URLSafeTimedSerializer2",
"(",
"secret_key... | 35.208333 | 0.002304 |
def encrypt(self, data, *recipients, **kwargs):
"""Encrypt the message contained in ``data`` to ``recipients``.
:param str data: The file or bytestream to encrypt.
:param str recipients: The recipients to encrypt to. Recipients must
be specified keyID/fingerprint. Care should be ta... | [
"def",
"encrypt",
"(",
"self",
",",
"data",
",",
"*",
"recipients",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_is_stream",
"(",
"data",
")",
":",
"stream",
"=",
"data",
"else",
":",
"stream",
"=",
"_make_binary_stream",
"(",
"data",
",",
"self",
".",... | 46.771739 | 0.000455 |
def stack_encoders(self, *layers):
"""
Stack encoding layers, this must be done before stacking decoding layers.
"""
self.stack(*layers)
self.encoding_layes.extend(layers) | [
"def",
"stack_encoders",
"(",
"self",
",",
"*",
"layers",
")",
":",
"self",
".",
"stack",
"(",
"*",
"layers",
")",
"self",
".",
"encoding_layes",
".",
"extend",
"(",
"layers",
")"
] | 34.333333 | 0.014218 |
def pull_requests(self):
'''
Looks for any of the following pull request formats in the description field:
pr12345, pr 2345, PR2345, PR 2345
'''
pr_numbers = re.findall(r"[pP][rR]\s?[0-9]+", self.description)
pr_numbers += re.findall(re.compile("pull\s?request\s?[0-9... | [
"def",
"pull_requests",
"(",
"self",
")",
":",
"pr_numbers",
"=",
"re",
".",
"findall",
"(",
"r\"[pP][rR]\\s?[0-9]+\"",
",",
"self",
".",
"description",
")",
"pr_numbers",
"+=",
"re",
".",
"findall",
"(",
"re",
".",
"compile",
"(",
"\"pull\\s?request\\s?[0-9]+... | 39 | 0.014614 |
def next_formatted_pair(self):
"""\
Returns a :class:`FormattedPair <shorten.store.FormattedPair>` containing
attributes `key`, `token`, `formatted_key` and `formatted_token`.
Calling this method will always consume a key and token.
"""
key = self.key_gen.next()
token = self... | [
"def",
"next_formatted_pair",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"key_gen",
".",
"next",
"(",
")",
"token",
"=",
"self",
".",
"token_gen",
".",
"create_token",
"(",
"key",
")",
"fkey",
"=",
"self",
".",
"formatter",
".",
"format_key",
"(",... | 37.230769 | 0.020161 |
def render(self, at):
# draw bg
surf = self.surf
surf.fill(BASE3)
bg = pygame.Surface((self.size[0], self.bar_height))
bg.fill(BASE2)
surf.blit(bg, (0, 0))
# draw bar
ratio = self.gauge.get(at) / float(self.gauge.max(at))
if ratio > 1:
... | [
"def",
"render",
"(",
"self",
",",
"at",
")",
":",
"# draw bg",
"surf",
"=",
"self",
".",
"surf",
"surf",
".",
"fill",
"(",
"BASE3",
")",
"bg",
"=",
"pygame",
".",
"Surface",
"(",
"(",
"self",
".",
"size",
"[",
"0",
"]",
",",
"self",
".",
"bar_... | 36.346939 | 0.00164 |
def _get_newsfeeds(self, uri, detail_level = None):
'''General purpose function to get newsfeeds
Args:
uri uri for the feed base
detail_level arguments for req str ['ALL', 'CONDENSED']
return list of feed dicts parse at your convenience
'''
if detail_level:
if detail_level not in ['ALL', 'CON... | [
"def",
"_get_newsfeeds",
"(",
"self",
",",
"uri",
",",
"detail_level",
"=",
"None",
")",
":",
"if",
"detail_level",
":",
"if",
"detail_level",
"not",
"in",
"[",
"'ALL'",
",",
"'CONDENSED'",
"]",
":",
"return",
"requests",
".",
"codes",
".",
"bad_request",
... | 43.846154 | 0.036082 |
def write_raster_window(
in_tile=None, in_data=None, out_profile=None, out_tile=None, out_path=None,
tags=None, bucket_resource=None
):
"""
Write a window from a numpy array to an output file.
Parameters
----------
in_tile : ``BufferedTile``
``BufferedTile`` with a data attribute ho... | [
"def",
"write_raster_window",
"(",
"in_tile",
"=",
"None",
",",
"in_data",
"=",
"None",
",",
"out_profile",
"=",
"None",
",",
"out_tile",
"=",
"None",
",",
"out_path",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"bucket_resource",
"=",
"None",
")",
":",
... | 36.885714 | 0.000754 |
def build_articles_from_article_xmls(article_xmls, detail="full",
build_parts=None, remove_tags=None):
"""
Given a list of article XML filenames, convert to article objects
"""
poa_articles = []
for article_xml in article_xmls:
print("working on ", arti... | [
"def",
"build_articles_from_article_xmls",
"(",
"article_xmls",
",",
"detail",
"=",
"\"full\"",
",",
"build_parts",
"=",
"None",
",",
"remove_tags",
"=",
"None",
")",
":",
"poa_articles",
"=",
"[",
"]",
"for",
"article_xml",
"in",
"article_xmls",
":",
"print",
... | 35.1875 | 0.00173 |
def _write2(self, data, multithread=True, **kwargs):
'''
:param data: Data to be written
:type data: str or mmap object
:param multithread: If True, sends multiple write requests asynchronously
:type multithread: boolean
Writes the data *data* to the file.
.. no... | [
"def",
"_write2",
"(",
"self",
",",
"data",
",",
"multithread",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"USING_PYTHON2",
":",
"assert",
"(",
"isinstance",
"(",
"data",
",",
"bytes",
")",
")",
"self",
".",
"_ensure_write_bufsize",
"... | 38.192982 | 0.001791 |
def voronoi(script, target_layer=0, source_layer=1, backward=True):
""" Given a Mesh 'M' and a Pointset 'P', the filter projects each vertex of
P over M and color M according to the geodesic distance from these
projected points. Projection and coloring are done on a per vertex
basis.
Ar... | [
"def",
"voronoi",
"(",
"script",
",",
"target_layer",
"=",
"0",
",",
"source_layer",
"=",
"1",
",",
"backward",
"=",
"True",
")",
":",
"filter_xml",
"=",
"''",
".",
"join",
"(",
"[",
"' <filter name=\"Voronoi Vertex Coloring\">\\n'",
",",
"' <Param name=\"Co... | 37.26087 | 0.000569 |
def _set_load_action(self, mem_addr, rec_count, retries,
read_complete=False):
"""Calculate the next record to read.
If the last record was successful and one record was being read then
look for the next record until we get to the high water mark.
If the last r... | [
"def",
"_set_load_action",
"(",
"self",
",",
"mem_addr",
",",
"rec_count",
",",
"retries",
",",
"read_complete",
"=",
"False",
")",
":",
"if",
"self",
".",
"_have_all_records",
"(",
")",
":",
"mem_addr",
"=",
"None",
"rec_count",
"=",
"0",
"retries",
"=",
... | 39.06383 | 0.001594 |
def findNextItem(self, item):
"""
Returns the next item in the tree.
:param item | <QtGui.QTreeWidgetItem>
:return <QtGui.QTreeWidgetItem>
"""
if not item:
return None
if item.childCount():
re... | [
"def",
"findNextItem",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"item",
":",
"return",
"None",
"if",
"item",
".",
"childCount",
"(",
")",
":",
"return",
"item",
".",
"child",
"(",
"0",
")",
"while",
"item",
".",
"parent",
"(",
")",
":",
"... | 27.541667 | 0.011696 |
def t_offset(self, s):
r'[+]\d+'
pos = self.pos
self.add_token('OFFSET', s)
self.pos = pos + len(s) | [
"def",
"t_offset",
"(",
"self",
",",
"s",
")",
":",
"pos",
"=",
"self",
".",
"pos",
"self",
".",
"add_token",
"(",
"'OFFSET'",
",",
"s",
")",
"self",
".",
"pos",
"=",
"pos",
"+",
"len",
"(",
"s",
")"
] | 25.4 | 0.015267 |
def _parse_prefix_as_idd(idd_pattern, number):
"""Strips the IDD from the start of the number if present.
Helper function used by _maybe_strip_i18n_prefix_and_normalize().
Returns a 2-tuple:
- Boolean indicating if IDD was stripped
- Number with IDD stripped
"""
match = idd_pattern.mat... | [
"def",
"_parse_prefix_as_idd",
"(",
"idd_pattern",
",",
"number",
")",
":",
"match",
"=",
"idd_pattern",
".",
"match",
"(",
"number",
")",
"if",
"match",
":",
"match_end",
"=",
"match",
".",
"end",
"(",
")",
"# Only strip this if the first digit after the match is... | 38.666667 | 0.001202 |
def process_non_raw_string_token(self, prefix, string_body, start_row):
"""check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line ... | [
"def",
"process_non_raw_string_token",
"(",
"self",
",",
"prefix",
",",
"string_body",
",",
"start_row",
")",
":",
"# Walk through the string; if we see a backslash then escape the next",
"# character, and skip over it. If we see a non-escaped character,",
"# alert, and continue.",
"#... | 45.571429 | 0.001754 |
def is_b_connected(H, source_node, target_node):
"""Checks if a target node is B-connected to a source node.
A node t is B-connected to a node s iff:
- t is s, or
- there exists an edge in the backward star of t such that all nodes in
the tail of that edge are B-connected to s
... | [
"def",
"is_b_connected",
"(",
"H",
",",
"source_node",
",",
"target_node",
")",
":",
"b_visited_nodes",
",",
"Pv",
",",
"Pe",
",",
"v",
"=",
"b_visit",
"(",
"H",
",",
"source_node",
")",
"return",
"target_node",
"in",
"b_visited_nodes"
] | 43.05 | 0.001136 |
def getargs(obj):
"""Get the names and default values of a function's arguments"""
if inspect.isfunction(obj) or inspect.isbuiltin(obj):
func_obj = obj
elif inspect.ismethod(obj):
func_obj = get_meth_func(obj)
elif inspect.isclass(obj) and hasattr(obj, '__init__'):
func_obj = get... | [
"def",
"getargs",
"(",
"obj",
")",
":",
"if",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
"or",
"inspect",
".",
"isbuiltin",
"(",
"obj",
")",
":",
"func_obj",
"=",
"obj",
"elif",
"inspect",
".",
"ismethod",
"(",
"obj",
")",
":",
"func_obj",
"=",
... | 34.27027 | 0.002301 |
def strace_set_buffer_size(self, size):
"""Sets the STRACE buffer size.
Args:
self (JLink): the ``JLink`` instance.
Returns:
``None``
Raises:
JLinkException: on error.
"""
size = ctypes.c_uint32(size)
res = self._dll.JLINK_STRACE_C... | [
"def",
"strace_set_buffer_size",
"(",
"self",
",",
"size",
")",
":",
"size",
"=",
"ctypes",
".",
"c_uint32",
"(",
"size",
")",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINK_STRACE_Control",
"(",
"enums",
".",
"JLinkStraceCommand",
".",
"SET_BUFFER_SIZE",
",",... | 26.611111 | 0.008065 |
def setup_components_and_tf_funcs(self, custom_getter=None):
"""
Constructs the extra Replay memory.
"""
custom_getter = super(QDemoModel, self).setup_components_and_tf_funcs(custom_getter)
self.demo_memory = Replay(
states=self.states_spec,
internals=sel... | [
"def",
"setup_components_and_tf_funcs",
"(",
"self",
",",
"custom_getter",
"=",
"None",
")",
":",
"custom_getter",
"=",
"super",
"(",
"QDemoModel",
",",
"self",
")",
".",
"setup_components_and_tf_funcs",
"(",
"custom_getter",
")",
"self",
".",
"demo_memory",
"=",
... | 31.444444 | 0.002056 |
def train(epoch):
""" train model on each epoch in trainset
"""
global trainloader
global testloader
global net
global criterion
global optimizer
logger.debug("Epoch: %d", epoch)
net.train()
train_loss = 0
correct = 0
total = 0
for batch_idx, (inputs, targets) in e... | [
"def",
"train",
"(",
"epoch",
")",
":",
"global",
"trainloader",
"global",
"testloader",
"global",
"net",
"global",
"criterion",
"global",
"optimizer",
"logger",
".",
"debug",
"(",
"\"Epoch: %d\"",
",",
"epoch",
")",
"net",
".",
"train",
"(",
")",
"train_los... | 23.35 | 0.001028 |
def _gen_dimension_table(self):
"""
2D array describing each registered dimension
together with headers - for use in __str__
"""
headers = ['Dimension Name', 'Description',
'Global Size', 'Extents']
table = []
for dimval in sorted(self.dimensions(copy... | [
"def",
"_gen_dimension_table",
"(",
"self",
")",
":",
"headers",
"=",
"[",
"'Dimension Name'",
",",
"'Description'",
",",
"'Global Size'",
",",
"'Extents'",
"]",
"table",
"=",
"[",
"]",
"for",
"dimval",
"in",
"sorted",
"(",
"self",
".",
"dimensions",
"(",
... | 33 | 0.00982 |
def shouldSkipUrl(self, url, data):
"""Skip pages without images."""
return url in (
self.stripUrl % '130217', # video
self.stripUrl % '130218', # video
self.stripUrl % '130226', # video
self.stripUrl % '130424', # video
) | [
"def",
"shouldSkipUrl",
"(",
"self",
",",
"url",
",",
"data",
")",
":",
"return",
"url",
"in",
"(",
"self",
".",
"stripUrl",
"%",
"'130217'",
",",
"# video",
"self",
".",
"stripUrl",
"%",
"'130218'",
",",
"# video",
"self",
".",
"stripUrl",
"%",
"'1302... | 35.875 | 0.020408 |
def fromfits(infilename, hdu = 0, verbose = True):
"""
Reads a FITS file and returns a 2D numpy array of the data.
Use hdu to specify which HDU you want (default = primary = 0)
"""
pixelarray, hdr = pyfits.getdata(infilename, hdu, header=True)
pixelarray = np.asarray(pixelarray).transpose()... | [
"def",
"fromfits",
"(",
"infilename",
",",
"hdu",
"=",
"0",
",",
"verbose",
"=",
"True",
")",
":",
"pixelarray",
",",
"hdr",
"=",
"pyfits",
".",
"getdata",
"(",
"infilename",
",",
"hdu",
",",
"header",
"=",
"True",
")",
"pixelarray",
"=",
"np",
".",
... | 37.6875 | 0.016181 |
def _extract_multi_indexer_columns(self, header, index_names, col_names,
passed_names=False):
""" extract and return the names, index_names, col_names
header is a list-of-lists returned from the parsers """
if len(header) < 2:
return header[... | [
"def",
"_extract_multi_indexer_columns",
"(",
"self",
",",
"header",
",",
"index_names",
",",
"col_names",
",",
"passed_names",
"=",
"False",
")",
":",
"if",
"len",
"(",
"header",
")",
"<",
"2",
":",
"return",
"header",
"[",
"0",
"]",
",",
"index_names",
... | 38.203704 | 0.001418 |
def update_environment_variables(self, filename):
"""Updating OS environment variables and current script path and filename."""
self.env.update(os.environ.copy())
self.env.update({'PIPELINE_BASH_FILE': filename}) | [
"def",
"update_environment_variables",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"env",
".",
"update",
"(",
"os",
".",
"environ",
".",
"copy",
"(",
")",
")",
"self",
".",
"env",
".",
"update",
"(",
"{",
"'PIPELINE_BASH_FILE'",
":",
"filename",... | 58.25 | 0.012712 |
def cdk_module_matches_env(env_name, env_config, env_vars):
"""Return bool on whether cdk command should continue in current env."""
if env_config.get(env_name):
current_env_config = env_config[env_name]
if isinstance(current_env_config, type(True)) and current_env_config:
return Tru... | [
"def",
"cdk_module_matches_env",
"(",
"env_name",
",",
"env_config",
",",
"env_vars",
")",
":",
"if",
"env_config",
".",
"get",
"(",
"env_name",
")",
":",
"current_env_config",
"=",
"env_config",
"[",
"env_name",
"]",
"if",
"isinstance",
"(",
"current_env_config... | 46.7 | 0.001049 |
def make_sparse(arr, kind='block', fill_value=None, dtype=None, copy=False):
"""
Convert ndarray to sparse format
Parameters
----------
arr : ndarray
kind : {'block', 'integer'}
fill_value : NaN or another value
dtype : np.dtype, optional
copy : bool, default False
Returns
... | [
"def",
"make_sparse",
"(",
"arr",
",",
"kind",
"=",
"'block'",
",",
"fill_value",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"arr",
"=",
"_sanitize_values",
"(",
"arr",
")",
"if",
"arr",
".",
"ndim",
">",
"1",
":",... | 28.924528 | 0.000631 |
def handle_friday(next_date: Datum, period: str, mult: int, start_date: Datum):
""" Extracted the calculation for when the next_day is Friday """
assert isinstance(next_date, Datum)
assert isinstance(start_date, Datum)
# Starting from line 220.
tmp_sat = next_date.clone()
tmp_sat.add_days(1)
... | [
"def",
"handle_friday",
"(",
"next_date",
":",
"Datum",
",",
"period",
":",
"str",
",",
"mult",
":",
"int",
",",
"start_date",
":",
"Datum",
")",
":",
"assert",
"isinstance",
"(",
"next_date",
",",
"Datum",
")",
"assert",
"isinstance",
"(",
"start_date",
... | 36.15 | 0.000673 |
def http_exception_error_handler(
exception):
"""
Handle HTTP exception
:param werkzeug.exceptions.HTTPException exception: Raised exception
A response is returned, as formatted by the :py:func:`response` function.
"""
assert issubclass(type(exception), HTTPException), type(exception)... | [
"def",
"http_exception_error_handler",
"(",
"exception",
")",
":",
"assert",
"issubclass",
"(",
"type",
"(",
"exception",
")",
",",
"HTTPException",
")",
",",
"type",
"(",
"exception",
")",
"assert",
"hasattr",
"(",
"exception",
",",
"\"code\"",
")",
"assert",... | 29.933333 | 0.00216 |
def optimize_png_file(f, o=None):
"""
Use pngquant for optimize PNG-image.
f - path to input image file or file-object.
o - path to output image file or file-object for save result.
NOTICE: f and o can not be of different type
"""
if isinstance(f, basestring):
if o is None:
... | [
"def",
"optimize_png_file",
"(",
"f",
",",
"o",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"basestring",
")",
":",
"if",
"o",
"is",
"None",
":",
"o",
"=",
"f",
"else",
":",
"assert",
"isinstance",
"(",
"o",
",",
"basestring",
")",
... | 28.171429 | 0.001961 |
def baseline(self, rf='', v0='0..', v1='', v2='', off=None):
"""Defines a baselin measure. It has to specify a reference code, uvw
quantity values (see introduction for the action on a scalar quantity
with either a vector or scalar value, and when a vector of quantities
is given), and op... | [
"def",
"baseline",
"(",
"self",
",",
"rf",
"=",
"''",
",",
"v0",
"=",
"'0..'",
",",
"v1",
"=",
"''",
",",
"v2",
"=",
"''",
",",
"off",
"=",
"None",
")",
":",
"loc",
"=",
"{",
"'type'",
":",
"\"baseline\"",
",",
"'refer'",
":",
"rf",
"}",
"loc... | 44.142857 | 0.001584 |
def merge_files(context):
"""
Given a context containing path to template, env, and service:
merge config into template and output the result to stdout
Args:
context: a populated context object
"""
resolver = EFTemplateResolver(
profile=context.profile,
region=context.region,
env=conte... | [
"def",
"merge_files",
"(",
"context",
")",
":",
"resolver",
"=",
"EFTemplateResolver",
"(",
"profile",
"=",
"context",
".",
"profile",
",",
"region",
"=",
"context",
".",
"region",
",",
"env",
"=",
"context",
".",
"env",
",",
"service",
"=",
"context",
"... | 37.309524 | 0.013988 |
def load_mplstyle():
"""Try to load conf.plot.mplstyle matplotlib style."""
plt = importlib.import_module('matplotlib.pyplot')
if conf.plot.mplstyle:
for style in conf.plot.mplstyle.split():
stfile = config.CONFIG_DIR / (style + '.mplstyle')
if stfile.is_file():
... | [
"def",
"load_mplstyle",
"(",
")",
":",
"plt",
"=",
"importlib",
".",
"import_module",
"(",
"'matplotlib.pyplot'",
")",
"if",
"conf",
".",
"plot",
".",
"mplstyle",
":",
"for",
"style",
"in",
"conf",
".",
"plot",
".",
"mplstyle",
".",
"split",
"(",
")",
... | 37.0625 | 0.001645 |
def count_cycles(series, ndigits=None, left=False, right=False):
"""Count cycles in the series.
Parameters
----------
series : iterable sequence of numbers
ndigits : int, optional
Round cycle magnitudes to the given number of digits before counting.
left: bool, optional
If True,... | [
"def",
"count_cycles",
"(",
"series",
",",
"ndigits",
"=",
"None",
",",
"left",
"=",
"False",
",",
"right",
"=",
"False",
")",
":",
"counts",
"=",
"defaultdict",
"(",
"float",
")",
"round_",
"=",
"_get_round_function",
"(",
"ndigits",
")",
"for",
"low",
... | 34 | 0.0011 |
def genes_by_alias(hgnc_genes):
"""Return a dictionary with hgnc symbols as keys
Value of the dictionaries are information about the hgnc ids for a symbol.
If the symbol is primary for a gene then 'true_id' will exist.
A list of hgnc ids that the symbol points to is in ids.
Args:
hgnc_gene... | [
"def",
"genes_by_alias",
"(",
"hgnc_genes",
")",
":",
"alias_genes",
"=",
"{",
"}",
"for",
"hgnc_id",
"in",
"hgnc_genes",
":",
"gene",
"=",
"hgnc_genes",
"[",
"hgnc_id",
"]",
"# This is the primary symbol:",
"hgnc_symbol",
"=",
"gene",
"[",
"'hgnc_symbol'",
"]",... | 31.1 | 0.001559 |
def _map_or_starmap_async(function, iterable, args, kwargs, map_or_starmap):
"""
Shared function between parmap.map_async and parmap.starmap_async.
Refer to those functions for details.
"""
arg_newarg = (("parallel", "pm_parallel"), ("chunksize", "pm_chunksize"),
("pool", "pm_pool"... | [
"def",
"_map_or_starmap_async",
"(",
"function",
",",
"iterable",
",",
"args",
",",
"kwargs",
",",
"map_or_starmap",
")",
":",
"arg_newarg",
"=",
"(",
"(",
"\"parallel\"",
",",
"\"pm_parallel\"",
")",
",",
"(",
"\"chunksize\"",
",",
"\"pm_chunksize\"",
")",
",... | 46.72093 | 0.000488 |
def PushEvent(self, timestamp, event_data):
"""Pushes a serialized event onto the heap.
Args:
timestamp (int): event timestamp, which contains the number of
micro seconds since January 1, 1970, 00:00:00 UTC.
event_data (bytes): serialized event.
"""
heap_values = (timestamp, event... | [
"def",
"PushEvent",
"(",
"self",
",",
"timestamp",
",",
"event_data",
")",
":",
"heap_values",
"=",
"(",
"timestamp",
",",
"event_data",
")",
"heapq",
".",
"heappush",
"(",
"self",
".",
"_heap",
",",
"heap_values",
")",
"self",
".",
"data_size",
"+=",
"l... | 36.181818 | 0.002451 |
def key_slice(self, start_key, end_key, reverse=False):
"""T.key_slice(start_key, end_key) -> key iterator:
start_key <= key < end_key.
Yields keys in ascending order if reverse is False else in descending order.
"""
return (k for k, v in self.iter_items(start_key, end_key, reve... | [
"def",
"key_slice",
"(",
"self",
",",
"start_key",
",",
"end_key",
",",
"reverse",
"=",
"False",
")",
":",
"return",
"(",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"iter_items",
"(",
"start_key",
",",
"end_key",
",",
"reverse",
"=",
"reverse",
")... | 46.714286 | 0.012012 |
def custom_add_user_view(request):
''' The page to add a new user. '''
page_name = "Admin - Add User"
add_user_form = AddUserForm(request.POST or None, initial={
'status': UserProfile.RESIDENT,
})
if add_user_form.is_valid():
add_user_form.save()
message = MESSAGES['USER_... | [
"def",
"custom_add_user_view",
"(",
"request",
")",
":",
"page_name",
"=",
"\"Admin - Add User\"",
"add_user_form",
"=",
"AddUserForm",
"(",
"request",
".",
"POST",
"or",
"None",
",",
"initial",
"=",
"{",
"'status'",
":",
"UserProfile",
".",
"RESIDENT",
",",
"... | 45.058824 | 0.001279 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.