text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def elastic_transform(im, alpha=0.5, sigma=0.2, affine_sigma=1.):
"""
Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5
elastic deformation of images as described in [Simard2003]
"""
# fixme : not implemented for multi channel !
import cv2
islist = isinstance(im, (tuple, lis... | [
"def",
"elastic_transform",
"(",
"im",
",",
"alpha",
"=",
"0.5",
",",
"sigma",
"=",
"0.2",
",",
"affine_sigma",
"=",
"1.",
")",
":",
"# fixme : not implemented for multi channel !",
"import",
"cv2",
"islist",
"=",
"isinstance",
"(",
"im",
",",
"(",
"tuple",
... | 38.307692 | 25.730769 |
def import_sbml(document):
"""
Import a model from a SBMLDocument.
Parameters
----------
document : SBMLDocument
Returns
-------
model : NetworkModel
y0 : dict
Initial condition.
volume : Real or Real3, optional
A size of the simulation volume.
"""
from... | [
"def",
"import_sbml",
"(",
"document",
")",
":",
"from",
"ecell4",
".",
"util",
".",
"decorator",
"import",
"generate_ratelaw",
"m",
"=",
"document",
".",
"getModel",
"(",
")",
"if",
"m",
".",
"getNumCompartments",
"(",
")",
"==",
"0",
":",
"raise",
"Run... | 30.540323 | 18.524194 |
def plot(self, *args, **kwargs):
"""Plot data onto these axes
Parameters
----------
args
a single instance of
- `~gwpy.segments.DataQualityFlag`
- `~gwpy.segments.Segment`
- `~gwpy.segments.SegmentList`
- `~gwp... | [
"def",
"plot",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"[",
"]",
"args",
"=",
"list",
"(",
"args",
")",
"while",
"args",
":",
"try",
":",
"plotter",
"=",
"self",
".",
"_plot_method",
"(",
"args",
"[",
"0",
... | 28.463415 | 21.219512 |
def serialize_database(metamodel):
'''
Serialize all instances, class definitions, association definitions, and
unique identifiers in a *metamodel*.
'''
schema = serialize_schema(metamodel)
instances = serialize_instances(metamodel)
identifiers = serialize_unique_identifiers(metamodel)
... | [
"def",
"serialize_database",
"(",
"metamodel",
")",
":",
"schema",
"=",
"serialize_schema",
"(",
"metamodel",
")",
"instances",
"=",
"serialize_instances",
"(",
"metamodel",
")",
"identifiers",
"=",
"serialize_unique_identifiers",
"(",
"metamodel",
")",
"return",
"'... | 36.4 | 18 |
def breadcrumb_safe(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not escaped.
"""
append_breadcrumb(context, _(label), viewname, args, kwargs)
return '' | [
"def",
"breadcrumb_safe",
"(",
"context",
",",
"label",
",",
"viewname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"append_breadcrumb",
"(",
"context",
",",
"_",
"(",
"label",
")",
",",
"viewname",
",",
"args",
",",
"kwargs",
")",
"return",
... | 33.666667 | 13.666667 |
def before_render(self):
"""Before template render hook
"""
super(PricelistsView, self).before_render()
# Render the Add button if the user has the AddPricelist permission
if check_permission(AddPricelist, self.context):
self.context_actions[_("Add")] = {
... | [
"def",
"before_render",
"(",
"self",
")",
":",
"super",
"(",
"PricelistsView",
",",
"self",
")",
".",
"before_render",
"(",
")",
"# Render the Add button if the user has the AddPricelist permission",
"if",
"check_permission",
"(",
"AddPricelist",
",",
"self",
".",
"co... | 45.166667 | 14.916667 |
def _do_pnp(self, pnp, anchor=None):
""" Attaches prepositional noun phrases.
Identifies PNP's from either the PNP tag or the P-attachment tag.
This does not determine the PP-anchor, it only groups words in a PNP chunk.
"""
if anchor or pnp and pnp.endswith("PNP"):
... | [
"def",
"_do_pnp",
"(",
"self",
",",
"pnp",
",",
"anchor",
"=",
"None",
")",
":",
"if",
"anchor",
"or",
"pnp",
"and",
"pnp",
".",
"endswith",
"(",
"\"PNP\"",
")",
":",
"if",
"anchor",
"is",
"not",
"None",
":",
"m",
"=",
"find",
"(",
"lambda",
"x",... | 42.909091 | 14.772727 |
def cd(path):
"""Context manager to temporarily change working directories
:param str path: The directory to move into
>>> print(os.path.abspath(os.curdir))
'/home/user/code/myrepo'
>>> with cd("/home/user/code/otherdir/subdir"):
... print("Changed directory: %s" % os.path.abspath(os.curdi... | [
"def",
"cd",
"(",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"prev_cwd",
"=",
"Path",
".",
"cwd",
"(",
")",
".",
"as_posix",
"(",
")",
"if",
"isinstance",
"(",
"path",
",",
"Path",
")",
":",
"path",
"=",
"path",
".",
"as_posix",
"(",
... | 28.391304 | 16.869565 |
def rank(words: List[str], exclude_stopwords: bool = False) -> Counter:
"""
Sort words by frequency
:param list words: a list of words
:param bool exclude_stopwords: exclude stopwords
:return: Counter
"""
if not words:
return None
if exclude_stopwords:
words = [word for... | [
"def",
"rank",
"(",
"words",
":",
"List",
"[",
"str",
"]",
",",
"exclude_stopwords",
":",
"bool",
"=",
"False",
")",
"->",
"Counter",
":",
"if",
"not",
"words",
":",
"return",
"None",
"if",
"exclude_stopwords",
":",
"words",
"=",
"[",
"word",
"for",
... | 24.933333 | 19.866667 |
def insort_no_dup(lst, item):
"""
If item is not in lst, add item to list at its sorted position
"""
import bisect
ix = bisect.bisect_left(lst, item)
if lst[ix] != item:
lst[ix:ix] = [item] | [
"def",
"insort_no_dup",
"(",
"lst",
",",
"item",
")",
":",
"import",
"bisect",
"ix",
"=",
"bisect",
".",
"bisect_left",
"(",
"lst",
",",
"item",
")",
"if",
"lst",
"[",
"ix",
"]",
"!=",
"item",
":",
"lst",
"[",
"ix",
":",
"ix",
"]",
"=",
"[",
"i... | 26.875 | 11.375 |
def execute(self, fetchall=False, fetchone=False, use_labels=True):
"""
:param fetchall: get all rows
:param fetchone: get only one row
:param use_labels: prefix row columns names by the table name
:return:
"""
query = self.get_query(use_labels=use_labels)
... | [
"def",
"execute",
"(",
"self",
",",
"fetchall",
"=",
"False",
",",
"fetchone",
"=",
"False",
",",
"use_labels",
"=",
"True",
")",
":",
"query",
"=",
"self",
".",
"get_query",
"(",
"use_labels",
"=",
"use_labels",
")",
"if",
"fetchall",
":",
"return",
"... | 39 | 14.666667 |
def mpl_outside_legend(ax, **kwargs):
""" Places a legend box outside a matplotlib Axes instance. """
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])
# Put a legend to the right of the current axis
ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs) | [
"def",
"mpl_outside_legend",
"(",
"ax",
",",
"*",
"*",
"kwargs",
")",
":",
"box",
"=",
"ax",
".",
"get_position",
"(",
")",
"ax",
".",
"set_position",
"(",
"[",
"box",
".",
"x0",
",",
"box",
".",
"y0",
",",
"box",
".",
"width",
"*",
"0.75",
",",
... | 52.166667 | 13 |
def real(self):
""" Real time data """
try:
unch = sum([covstr(self.stock[3]),covstr(self.stock[4])])/2
re = {'name': unicode(self.stock[36].replace(' ',''), 'cp950'),
'no': self.stock[0],
'range': self.stock[1],
'time': self.stock[2],
'max': self.stoc... | [
"def",
"real",
"(",
"self",
")",
":",
"try",
":",
"unch",
"=",
"sum",
"(",
"[",
"covstr",
"(",
"self",
".",
"stock",
"[",
"3",
"]",
")",
",",
"covstr",
"(",
"self",
".",
"stock",
"[",
"4",
"]",
")",
"]",
")",
"/",
"2",
"re",
"=",
"{",
"'n... | 36.23913 | 18.586957 |
def call(self, command, *args):
"""
Passes an arbitrary command to the coin daemon.
Args:
command (str): command to be sent to the coin daemon
"""
return self.rpc.call(str(command), *args) | [
"def",
"call",
"(",
"self",
",",
"command",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"rpc",
".",
"call",
"(",
"str",
"(",
"command",
")",
",",
"*",
"args",
")"
] | 25.777778 | 18 |
def _write(self, lines, fname):
"""
Writes a intermediate temporary sorted file
:param lines: The lines to write.
:param fname: The name of the temporary file.
:return:
"""
with open(fname, 'wb') as out_fhndl:
for line in sorted(lines, key=self.key):
... | [
"def",
"_write",
"(",
"self",
",",
"lines",
",",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
"out_fhndl",
":",
"for",
"line",
"in",
"sorted",
"(",
"lines",
",",
"key",
"=",
"self",
".",
"key",
")",
":",
"pickle",
".",... | 32.181818 | 10.727273 |
def remove_padding(sequence):
"""Selects the used frames of a sequence, up to its length.
This function does not expect a batch of sequences, but a single sequence.
The sequence must be a dict with `length` key, which will removed from the
result.
Args:
sequence: Nested dict of tensors with time dimensi... | [
"def",
"remove_padding",
"(",
"sequence",
")",
":",
"length",
"=",
"sequence",
".",
"pop",
"(",
"'length'",
")",
"sequence",
"=",
"tools",
".",
"nested",
".",
"map",
"(",
"lambda",
"tensor",
":",
"tensor",
"[",
":",
"length",
"]",
",",
"sequence",
")",... | 32.8125 | 25.5625 |
def compute_venn3_regions(centers, radii):
'''
Given the 3x2 matrix with circle center coordinates, and a 3-element list (or array) with circle radii [as returned from solve_venn3_circles],
returns the 7 regions, comprising the venn diagram, as VennRegion objects.
Regions are returned in order (Abc, aB... | [
"def",
"compute_venn3_regions",
"(",
"centers",
",",
"radii",
")",
":",
"A",
"=",
"VennCircleRegion",
"(",
"centers",
"[",
"0",
"]",
",",
"radii",
"[",
"0",
"]",
")",
"B",
"=",
"VennCircleRegion",
"(",
"centers",
"[",
"1",
"]",
",",
"radii",
"[",
"1"... | 52.904762 | 26.809524 |
def OnLineWidth(self, event):
"""Line width choice event handler"""
linewidth_combobox = event.GetEventObject()
idx = event.GetInt()
width = int(linewidth_combobox.GetString(idx))
borders = self.bordermap[self.borderstate]
post_command_event(self, self.BorderWidthMsg, w... | [
"def",
"OnLineWidth",
"(",
"self",
",",
"event",
")",
":",
"linewidth_combobox",
"=",
"event",
".",
"GetEventObject",
"(",
")",
"idx",
"=",
"event",
".",
"GetInt",
"(",
")",
"width",
"=",
"int",
"(",
"linewidth_combobox",
".",
"GetString",
"(",
"idx",
")... | 36.6 | 16.7 |
def release_value_set(self):
"""
Release a reserved value set so that other executions can use it also.
"""
if self._remotelib:
self._remotelib.run_keyword('release_value_set', [self._my_id], {})
else:
_PabotLib.release_value_set(self, self._my_id) | [
"def",
"release_value_set",
"(",
"self",
")",
":",
"if",
"self",
".",
"_remotelib",
":",
"self",
".",
"_remotelib",
".",
"run_keyword",
"(",
"'release_value_set'",
",",
"[",
"self",
".",
"_my_id",
"]",
",",
"{",
"}",
")",
"else",
":",
"_PabotLib",
".",
... | 38.125 | 18.375 |
def export(export_path, vocabulary, embeddings, num_oov_buckets,
preprocess_text):
"""Exports a TF-Hub module that performs embedding lookups.
Args:
export_path: Location to export the module.
vocabulary: List of the N tokens in the vocabulary.
embeddings: Numpy array of shape [N+K,M] the fi... | [
"def",
"export",
"(",
"export_path",
",",
"vocabulary",
",",
"embeddings",
",",
"num_oov_buckets",
",",
"preprocess_text",
")",
":",
"# Write temporary vocab file for module construction.",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"vocabulary_file",
"=",
"... | 42.625 | 19.425 |
def properties(self):
"""Return the base station info."""
resource = "basestation"
basestn_event = self.publish_and_get_event(resource)
if basestn_event:
return basestn_event.get('properties')
return None | [
"def",
"properties",
"(",
"self",
")",
":",
"resource",
"=",
"\"basestation\"",
"basestn_event",
"=",
"self",
".",
"publish_and_get_event",
"(",
"resource",
")",
"if",
"basestn_event",
":",
"return",
"basestn_event",
".",
"get",
"(",
"'properties'",
")",
"return... | 31.25 | 16.625 |
def establish_ssh_tunnel(self):
"""
Establish an ssh tunnel for each local host and port
that can be used to communicate with the state host.
"""
localportlist = []
for (host, port) in self.hostportlist:
localport = self.pick_unused_port()
self.tunnel.append(subprocess.Popen(
... | [
"def",
"establish_ssh_tunnel",
"(",
"self",
")",
":",
"localportlist",
"=",
"[",
"]",
"for",
"(",
"host",
",",
"port",
")",
"in",
"self",
".",
"hostportlist",
":",
"localport",
"=",
"self",
".",
"pick_unused_port",
"(",
")",
"self",
".",
"tunnel",
".",
... | 38.916667 | 11.583333 |
def is_reparse_point(path):
"""
Determine if the given path is a reparse point.
Return False if the file does not exist or the file attributes cannot
be determined.
"""
res = api.GetFileAttributes(path)
return (
res != api.INVALID_FILE_ATTRIBUTES
and bool(res & api.FILE_ATTRIBUTE_REPARSE_POINT)
) | [
"def",
"is_reparse_point",
"(",
"path",
")",
":",
"res",
"=",
"api",
".",
"GetFileAttributes",
"(",
"path",
")",
"return",
"(",
"res",
"!=",
"api",
".",
"INVALID_FILE_ATTRIBUTES",
"and",
"bool",
"(",
"res",
"&",
"api",
".",
"FILE_ATTRIBUTE_REPARSE_POINT",
")... | 27.181818 | 15 |
def from_totient(public_key, totient):
"""given the totient, one can factorize the modulus
The totient is defined as totient = (p - 1) * (q - 1),
and the modulus is defined as modulus = p * q
Args:
public_key (PaillierPublicKey): The corresponding public
key
... | [
"def",
"from_totient",
"(",
"public_key",
",",
"totient",
")",
":",
"p_plus_q",
"=",
"public_key",
".",
"n",
"-",
"totient",
"+",
"1",
"p_minus_q",
"=",
"isqrt",
"(",
"p_plus_q",
"*",
"p_plus_q",
"-",
"public_key",
".",
"n",
"*",
"4",
")",
"q",
"=",
... | 36.6 | 20.2 |
def clear(self):
"""Removes all child widgets."""
layout = self.layout()
for index in reversed(range(layout.count())):
item = layout.takeAt(index)
try:
item.widget().deleteLater()
except AttributeError:
item = None | [
"def",
"clear",
"(",
"self",
")",
":",
"layout",
"=",
"self",
".",
"layout",
"(",
")",
"for",
"index",
"in",
"reversed",
"(",
"range",
"(",
"layout",
".",
"count",
"(",
")",
")",
")",
":",
"item",
"=",
"layout",
".",
"takeAt",
"(",
"index",
")",
... | 33.111111 | 10.444444 |
def Bvirial(self):
r'''Second virial coefficient of the gas phase of the chemical at its
current temperature and pressure, in units of [mol/m^3].
This property uses the object-oriented interface
:obj:`thermo.volume.VolumeGas`, converting its result with
:obj:`thermo.utils.B_from... | [
"def",
"Bvirial",
"(",
"self",
")",
":",
"if",
"self",
".",
"Vmg",
":",
"return",
"B_from_Z",
"(",
"self",
".",
"Zg",
",",
"self",
".",
"T",
",",
"self",
".",
"P",
")",
"return",
"None"
] | 32.4375 | 21.9375 |
def set_next(self, frame, step_ignore=0, step_events=None):
"Sets to stop on the next event that happens in frame 'frame'."
self.step_events = None # Consider all events
self.stop_level = Mstack.count_frames(frame)
self.last_level = self.stop_level
self.last_fra... | [
"def",
"set_next",
"(",
"self",
",",
"frame",
",",
"step_ignore",
"=",
"0",
",",
"step_events",
"=",
"None",
")",
":",
"self",
".",
"step_events",
"=",
"None",
"# Consider all events",
"self",
".",
"stop_level",
"=",
"Mstack",
".",
"count_frames",
"(",
"fr... | 47.222222 | 14.333333 |
def setAttribute(values, value):
"""
Takes the values of an attribute value list and attempts to append
attributes of the proper type, inferred from their Python type.
"""
if isinstance(value, int):
values.add().int32_value = value
elif isinstance(value, float):
values.add().doub... | [
"def",
"setAttribute",
"(",
"values",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"values",
".",
"add",
"(",
")",
".",
"int32_value",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"value... | 36.083333 | 10.25 |
def nvmlDeviceGetPciInfo(handle):
r"""
/**
* Retrieves the PCI attributes of this device.
*
* For all products.
*
* See \ref nvmlPciInfo_t for details on the available PCI info.
*
* @param device The identifier of the target device
* @param p... | [
"def",
"nvmlDeviceGetPciInfo",
"(",
"handle",
")",
":",
"c_info",
"=",
"nvmlPciInfo_t",
"(",
")",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlDeviceGetPciInfo_v2\"",
")",
"ret",
"=",
"fn",
"(",
"handle",
",",
"byref",
"(",
"c_info",
")",
")",
"_nvmlCheck... | 42.769231 | 27.730769 |
def get_passenger_queue_stats(self):
"""
Execute passenger-stats, parse its output, returnand requests in queue
"""
queue_stats = {
"top_level_queue_size": 0.0,
"passenger_queue_size": 0.0,
}
command = [self.config["passenger_status_bin"]]
... | [
"def",
"get_passenger_queue_stats",
"(",
"self",
")",
":",
"queue_stats",
"=",
"{",
"\"top_level_queue_size\"",
":",
"0.0",
",",
"\"passenger_queue_size\"",
":",
"0.0",
",",
"}",
"command",
"=",
"[",
"self",
".",
"config",
"[",
"\"passenger_status_bin\"",
"]",
"... | 37.14 | 17.82 |
def import_obj(cls, i_datasource, import_time=None):
"""Imports the datasource from the object to the database.
Metrics and columns and datasource will be overrided if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metadata is... | [
"def",
"import_obj",
"(",
"cls",
",",
"i_datasource",
",",
"import_time",
"=",
"None",
")",
":",
"def",
"lookup_sqlatable",
"(",
"table",
")",
":",
"return",
"db",
".",
"session",
".",
"query",
"(",
"SqlaTable",
")",
".",
"join",
"(",
"Database",
")",
... | 46.6 | 19.15 |
def plasma(self, species=_pt.hydrogen):
"""
The matched :class:`Plasma`.
"""
return _Plasma(self.n_p, species=species) | [
"def",
"plasma",
"(",
"self",
",",
"species",
"=",
"_pt",
".",
"hydrogen",
")",
":",
"return",
"_Plasma",
"(",
"self",
".",
"n_p",
",",
"species",
"=",
"species",
")"
] | 29.2 | 2.8 |
def _convert_option(self):
'''
Determines which symbol to use for numpy conversions
> : a little endian system to big endian ordering
< : a big endian system to little endian ordering
= : No conversion
'''
data_endian = 'little'
if (self._encoding == 1 or ... | [
"def",
"_convert_option",
"(",
"self",
")",
":",
"data_endian",
"=",
"'little'",
"if",
"(",
"self",
".",
"_encoding",
"==",
"1",
"or",
"self",
".",
"_encoding",
"==",
"2",
"or",
"self",
".",
"_encoding",
"==",
"5",
"or",
"self",
".",
"_encoding",
"==",... | 36.347826 | 21.304348 |
def get_datacenter(service_instance, datacenter_name):
'''
Returns a vim.Datacenter managed object.
service_instance
The Service Instance Object from which to obtain datacenter.
datacenter_name
The datacenter name
'''
items = get_datacenters(service_instance,
... | [
"def",
"get_datacenter",
"(",
"service_instance",
",",
"datacenter_name",
")",
":",
"items",
"=",
"get_datacenters",
"(",
"service_instance",
",",
"datacenter_names",
"=",
"[",
"datacenter_name",
"]",
")",
"if",
"not",
"items",
":",
"raise",
"salt",
".",
"except... | 32.375 | 22.875 |
def pre_save(self, instance):
super(UserViewMixin, self).pre_save(instance)
"""
Use SaveHookMixin pre_save to set the user.
"""
if self.request.user.is_authenticated():
for field in self.user_field:
setattr(instance, field, self.request.user) | [
"def",
"pre_save",
"(",
"self",
",",
"instance",
")",
":",
"super",
"(",
"UserViewMixin",
",",
"self",
")",
".",
"pre_save",
"(",
"instance",
")",
"if",
"self",
".",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"for",
"field",
"in",
... | 33.777778 | 11.555556 |
def active(self, registered_only=True):
"Returns all active users, e.g. not logged and non-expired session."
visitors = self.filter(
expiry_time__gt=timezone.now(),
end_time=None
)
if registered_only:
visitors = visitors.filter(user__isnull=False)
... | [
"def",
"active",
"(",
"self",
",",
"registered_only",
"=",
"True",
")",
":",
"visitors",
"=",
"self",
".",
"filter",
"(",
"expiry_time__gt",
"=",
"timezone",
".",
"now",
"(",
")",
",",
"end_time",
"=",
"None",
")",
"if",
"registered_only",
":",
"visitors... | 36.777778 | 15.888889 |
def cmd(self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
kwarg=None,
**kwargs):
'''
Execute a single command via the salt-ssh subsystem and return all
routines at once
.. versionadded:: 2015.5.0
... | [
"def",
"cmd",
"(",
"self",
",",
"tgt",
",",
"fun",
",",
"arg",
"=",
"(",
")",
",",
"timeout",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
",",
"kwarg",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ssh",
"=",
"self",
".",
"_prep_ssh",
"(",
... | 24.192308 | 20.038462 |
def register_view(self, view):
"""Called when the view was registered"""
super(StateMachineTreeController, self).register_view(view)
self.view.connect('button_press_event', self.mouse_click)
self.view_is_registered = True
self.update(with_expand=True) | [
"def",
"register_view",
"(",
"self",
",",
"view",
")",
":",
"super",
"(",
"StateMachineTreeController",
",",
"self",
")",
".",
"register_view",
"(",
"view",
")",
"self",
".",
"view",
".",
"connect",
"(",
"'button_press_event'",
",",
"self",
".",
"mouse_click... | 47.666667 | 11.166667 |
def getChrPartTypeByNotation(notation, graph=None):
"""
This method will figure out the kind of feature that a given band
is based on pattern matching to standard karyotype notation.
(e.g. 13q22.2 ==> chromosome sub-band)
This has been validated against human, mouse, fish, and rat nomenclature.
... | [
"def",
"getChrPartTypeByNotation",
"(",
"notation",
",",
"graph",
"=",
"None",
")",
":",
"# Note that for mouse,",
"# they don't usually include the \"q\" in their notation,",
"# though UCSC does. We may need to adjust for that here",
"if",
"re",
".",
"match",
"(",
"r'p$'",
","... | 35.433333 | 18.366667 |
def retry(*r_args, **r_kwargs):
"""
Decorator wrapper for retry_call. Accepts arguments to retry_call
except func and then returns a decorator for the decorated function.
Ex:
>>> @retry(retries=3)
... def my_func(a, b):
... "this is my funk"
... print(a, b)
>>> my_func.__doc__
'this is my funk'
"""... | [
"def",
"retry",
"(",
"*",
"r_args",
",",
"*",
"*",
"r_kwargs",
")",
":",
"def",
"decorate",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"f_args",
",",
"*",
"*",
"f_kwargs",
")",
":",
"bound... | 24.809524 | 19.190476 |
def cli(self, prt=sys.stdout):
"""Command-line interface to print specified GO Terms from the DAG source ."""
kws = self.objdoc.get_docargs(prt=None)
print("KWS", kws)
goids = GetGOs().get_goids(kws.get('GO'), kws.get('GO_FILE'), sys.stdout)
if not goids and 'name' in kws:
... | [
"def",
"cli",
"(",
"self",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"kws",
"=",
"self",
".",
"objdoc",
".",
"get_docargs",
"(",
"prt",
"=",
"None",
")",
"print",
"(",
"\"KWS\"",
",",
"kws",
")",
"goids",
"=",
"GetGOs",
"(",
")",
".",
"g... | 57.666667 | 18.333333 |
def validate_string_dict(dct):
"""Validate that the input is a dict with string keys and values.
Raises ValueError if not."""
for k,v in dct.iteritems():
if not isinstance(k, basestring):
raise ValueError('key %r in dict must be a string' % k)
if not isinstance(v, basestring):
... | [
"def",
"validate_string_dict",
"(",
"dct",
")",
":",
"for",
"k",
",",
"v",
"in",
"dct",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"k",
",",
"basestring",
")",
":",
"raise",
"ValueError",
"(",
"'key %r in dict must be a string'",
"%",... | 42.222222 | 13 |
def download_playlist_by_search(self, playlist_name):
"""Download a playlist's songs by its name.
:params playlist_name: playlist name.
"""
try:
playlist = self.crawler.search_playlist(
playlist_name, self.quiet)
except RequestException as exception:... | [
"def",
"download_playlist_by_search",
"(",
"self",
",",
"playlist_name",
")",
":",
"try",
":",
"playlist",
"=",
"self",
".",
"crawler",
".",
"search_playlist",
"(",
"playlist_name",
",",
"self",
".",
"quiet",
")",
"except",
"RequestException",
"as",
"exception",... | 32.785714 | 14.357143 |
def _add_wire(self, wire):
"""Add a qubit or bit to the circuit.
Args:
wire (tuple): (Register,int) containing a register instance and index
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire
... | [
"def",
"_add_wire",
"(",
"self",
",",
"wire",
")",
":",
"if",
"wire",
"not",
"in",
"self",
".",
"wires",
":",
"self",
".",
"wires",
".",
"append",
"(",
"wire",
")",
"self",
".",
"_max_node_id",
"+=",
"1",
"input_map_wire",
"=",
"self",
".",
"input_ma... | 37.928571 | 22.02381 |
def sendEmail(self, emails, mass_type='SingleEmailMessage'):
"""
Send one or more emails from Salesforce.
Parameters:
emails - a dictionary or list of dictionaries, each representing
a single email as described by https://www.salesforce.com
... | [
"def",
"sendEmail",
"(",
"self",
",",
"emails",
",",
"mass_type",
"=",
"'SingleEmailMessage'",
")",
":",
"preparedEmails",
"=",
"_prepareSObjects",
"(",
"emails",
")",
"if",
"isinstance",
"(",
"preparedEmails",
",",
"dict",
")",
":",
"# If root element is a dict, ... | 41.512195 | 19.512195 |
def collect(self):
"""
Overrides the Collector.collect method
"""
performance_indicators = {
'ns': 'network_send',
'nr': 'network_receive',
'dw': 'disk_write',
'dr': 'disk_read',
'al': 'activity_log',
'bm': 'bit_map'... | [
"def",
"collect",
"(",
"self",
")",
":",
"performance_indicators",
"=",
"{",
"'ns'",
":",
"'network_send'",
",",
"'nr'",
":",
"'network_receive'",
",",
"'dw'",
":",
"'disk_write'",
",",
"'dr'",
":",
"'disk_read'",
",",
"'al'",
":",
"'activity_log'",
",",
"'b... | 36.814815 | 15.037037 |
def _qt_set_leaf_data(self, qvar):
""" Sets backend data using QVariants """
if VERBOSE_PREF:
print('')
print('+--- [pref.qt_set_leaf_data]')
print('[pref.qt_set_leaf_data] qvar = %r' % qvar)
print('[pref.qt_set_leaf_data] _intern.name=%r' % self._intern.name)
print('[pre... | [
"def",
"_qt_set_leaf_data",
"(",
"self",
",",
"qvar",
")",
":",
"if",
"VERBOSE_PREF",
":",
"print",
"(",
"''",
")",
"print",
"(",
"'+--- [pref.qt_set_leaf_data]'",
")",
"print",
"(",
"'[pref.qt_set_leaf_data] qvar = %r'",
"%",
"qvar",
")",
"print",
"(",
"'[pref.... | 45.975309 | 13.617284 |
def latmio_dir(R, itr, D=None, seed=None):
'''
This function "latticizes" a directed network, while preserving the in-
and out-degree distributions. In weighted networks, the function
preserves the out-strength but not the in-strength distributions.
Parameters
----------
R : NxN np.ndarray
... | [
"def",
"latmio_dir",
"(",
"R",
",",
"itr",
",",
"D",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"rng",
"=",
"get_rng",
"(",
"seed",
")",
"n",
"=",
"len",
"(",
"R",
")",
"ind_rp",
"=",
"rng",
".",
"permutation",
"(",
"n",
")",
"# randomly ... | 31.666667 | 20.956989 |
def pseudo_organization(organization, classification, default=None):
""" helper for setting an appropriate ID for organizations """
if organization and classification:
raise ScrapeValueError('cannot specify both classification and organization')
elif classification:
return _make_pseudo_id(cl... | [
"def",
"pseudo_organization",
"(",
"organization",
",",
"classification",
",",
"default",
"=",
"None",
")",
":",
"if",
"organization",
"and",
"classification",
":",
"raise",
"ScrapeValueError",
"(",
"'cannot specify both classification and organization'",
")",
"elif",
"... | 41.058824 | 15.882353 |
def sighash_all(self, index=0, script=None,
prevout_value=None, anyone_can_pay=False):
'''
SproutTx, int, byte-like, byte-like, bool -> bytearray
Sighashes suck
Generates the hash to be signed with SIGHASH_ALL
https://en.bitcoin.it/wiki/OP_CHECKSIG#Hashtype_SI... | [
"def",
"sighash_all",
"(",
"self",
",",
"index",
"=",
"0",
",",
"script",
"=",
"None",
",",
"prevout_value",
"=",
"None",
",",
"anyone_can_pay",
"=",
"False",
")",
":",
"if",
"riemann",
".",
"network",
".",
"FORKID",
"is",
"not",
"None",
":",
"return",... | 45.318182 | 24.409091 |
def initialize_options(self):
"""Set command option defaults."""
setuptools.command.build_py.build_py.initialize_options(self)
self.meteor = 'meteor'
self.meteor_debug = False
self.build_lib = None
self.package_dir = None
self.meteor_builds = []
self.no_pr... | [
"def",
"initialize_options",
"(",
"self",
")",
":",
"setuptools",
".",
"command",
".",
"build_py",
".",
"build_py",
".",
"initialize_options",
"(",
"self",
")",
"self",
".",
"meteor",
"=",
"'meteor'",
"self",
".",
"meteor_debug",
"=",
"False",
"self",
".",
... | 35.3 | 10.7 |
def substitute_state(target_state_m, state_m_to_insert, as_template=False):
""" Substitutes the target state
Both, the state to be replaced (the target state) and the state to be inserted (the new state) are passed via
parameters.
The new state adapts the size and position of the target state.
Stat... | [
"def",
"substitute_state",
"(",
"target_state_m",
",",
"state_m_to_insert",
",",
"as_template",
"=",
"False",
")",
":",
"# print(\"substitute_state\")",
"state_to_insert",
"=",
"state_m_to_insert",
".",
"state",
"action_parent_m",
"=",
"target_state_m",
".",
"parent",
"... | 58.425532 | 32.43617 |
def restore(self, name, value, pttl=0):
"""
Restore serialized dump of a key back into redis
:param name: the name of the key
:param value: the binary representation of the key.
:param pttl: milliseconds till key expires
:return:
"""
with self.pipe as pip... | [
"def",
"restore",
"(",
"self",
",",
"name",
",",
"value",
",",
"pttl",
"=",
"0",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"res",
"=",
"pipe",
".",
"restore",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"ttl",
"=",
"pt... | 30.055556 | 17.5 |
def find_file(name, directory):
"""Searches up from a directory looking for a file"""
path_bits = directory.split(os.sep)
for i in range(0, len(path_bits) - 1):
check_path = path_bits[0:len(path_bits) - i]
check_file = "%s%s%s" % (os.sep.join(check_path), os.sep, name)
if os.path.exi... | [
"def",
"find_file",
"(",
"name",
",",
"directory",
")",
":",
"path_bits",
"=",
"directory",
".",
"split",
"(",
"os",
".",
"sep",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"path_bits",
")",
"-",
"1",
")",
":",
"check_path",
"=",
"... | 38.3 | 12.4 |
def get_versus(self):
"""Return the versus board, player, opponent and extra actions.
Return None for any parts that can't be found.
"""
# game
game_image = self._game_image_from_screen('versus')
if game_image is None:
return None, None, None, None # nothing ... | [
"def",
"get_versus",
"(",
"self",
")",
":",
"# game",
"game_image",
"=",
"self",
".",
"_game_image_from_screen",
"(",
"'versus'",
")",
"if",
"game_image",
"is",
"None",
":",
"return",
"None",
",",
"None",
",",
"None",
",",
"None",
"# nothing else will work",
... | 43.190476 | 18.047619 |
def set_select(self, select_or_deselect = 'select', value=None, text=None, index=None):
"""
Private method used by select methods
@type select_or_deselect: str
@param select_or_deselect: Should I select or deselect the element
@type value: str
@type val... | [
"def",
"set_select",
"(",
"self",
",",
"select_or_deselect",
"=",
"'select'",
",",
"value",
"=",
"None",
",",
"text",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"# TODO: raise exception if element is not select element",
"if",
"select_or_deselect",
"is",
"'... | 38.342105 | 16.710526 |
def get_agents(self):
"""Gets the agent list resulting from the search.
return: (osid.authentication.AgentList) - the agent list
raise: IllegalState - list already retrieved
*compliance: mandatory -- This method must be implemented.*
"""
if self.retrieved:
... | [
"def",
"get_agents",
"(",
"self",
")",
":",
"if",
"self",
".",
"retrieved",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'List has already been retrieved.'",
")",
"self",
".",
"retrieved",
"=",
"True",
"return",
"objects",
".",
"AgentList",
"(",
"self",
... | 39.25 | 20.916667 |
def set_pscale(self):
""" Compute the pixel scale based on active WCS values. """
if self.new:
self.pscale = 1.0
else:
self.pscale = self.compute_pscale(self.cd11,self.cd21) | [
"def",
"set_pscale",
"(",
"self",
")",
":",
"if",
"self",
".",
"new",
":",
"self",
".",
"pscale",
"=",
"1.0",
"else",
":",
"self",
".",
"pscale",
"=",
"self",
".",
"compute_pscale",
"(",
"self",
".",
"cd11",
",",
"self",
".",
"cd21",
")"
] | 36 | 17.166667 |
def get_last_components_by_type(component_types, topic_id, db_conn=None):
"""For each component type of a topic, get the last one."""
db_conn = db_conn or flask.g.db_conn
schedule_components_ids = []
for ct in component_types:
where_clause = sql.and_(models.COMPONENTS.c.type == ct,
... | [
"def",
"get_last_components_by_type",
"(",
"component_types",
",",
"topic_id",
",",
"db_conn",
"=",
"None",
")",
":",
"db_conn",
"=",
"db_conn",
"or",
"flask",
".",
"g",
".",
"db_conn",
"schedule_components_ids",
"=",
"[",
"]",
"for",
"ct",
"in",
"component_ty... | 49.04 | 18.68 |
def devopsy(self, *args):
"""Return a gif based on search of several *reactions
Ported to Legobot from:
"https://github.com/ricardokirkner/err-devops-reactions"
... and extended.
Return a random gif if no query is specified or query not found
Example:
... | [
"def",
"devopsy",
"(",
"self",
",",
"*",
"args",
")",
":",
"args",
"=",
"' '",
".",
"join",
"(",
"self",
".",
"message",
"[",
"'text'",
"]",
".",
"split",
"(",
")",
"[",
"1",
":",
"]",
")",
"if",
"args",
":",
"base_main",
"=",
"{",
"'dev'",
"... | 32.12963 | 18.018519 |
def get_text_or_url(args):
"""Determine if we need text or url output"""
redirect_mode = args.bang or args.search or args.lucky
if redirect_mode or args.url:
return 'url'
else:
return 'text' | [
"def",
"get_text_or_url",
"(",
"args",
")",
":",
"redirect_mode",
"=",
"args",
".",
"bang",
"or",
"args",
".",
"search",
"or",
"args",
".",
"lucky",
"if",
"redirect_mode",
"or",
"args",
".",
"url",
":",
"return",
"'url'",
"else",
":",
"return",
"'text'"
... | 30.857143 | 15.571429 |
def wait_for_service_endpoint(service_name, timeout_sec=120):
"""Checks the service url if available it returns true, on expiration
it returns false"""
master_count = len(get_all_masters())
return time_wait(lambda: service_available_predicate(service_name),
timeout_seconds=timeout_... | [
"def",
"wait_for_service_endpoint",
"(",
"service_name",
",",
"timeout_sec",
"=",
"120",
")",
":",
"master_count",
"=",
"len",
"(",
"get_all_masters",
"(",
")",
")",
"return",
"time_wait",
"(",
"lambda",
":",
"service_available_predicate",
"(",
"service_name",
")"... | 48.375 | 16.375 |
def bytes_to_long(s):
"""Convert a byte string to a long integer (big endian).
In Python 3.2+, use the native method instead::
>>> int.from_bytes(s, 'big')
For instance::
>>> int.from_bytes(b'\x00P', 'big')
80
This is (essentially) the inverse of :func:`long_to_bytes`.
"... | [
"def",
"bytes_to_long",
"(",
"s",
")",
":",
"acc",
"=",
"0",
"unpack",
"=",
"struct",
".",
"unpack",
"length",
"=",
"len",
"(",
"s",
")",
"if",
"length",
"%",
"4",
":",
"extra",
"=",
"(",
"4",
"-",
"length",
"%",
"4",
")",
"s",
"=",
"b'\\000'",... | 24.125 | 19.666667 |
def t_power(logu, t, self_normalized=False, name=None):
"""The T-Power Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True` the T-Power Csiszar-function is:
```none
f(u) = s [ u**t - 1 - t(u - 1) ]
s = { -1 0 <... | [
"def",
"t_power",
"(",
"logu",
",",
"t",
",",
"self_normalized",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"t_power\"",
",",
"[",
"logu",
",",
"t",
"]",
")",
"... | 32.095238 | 23.714286 |
def paths(self):
"""
Assuming the skeleton is structured as a single tree, return a
list of all traversal paths across all components. For each component,
start from the first vertex, find the most distant vertex by
hops and set that as the root. Then use depth first traversal
to produce pat... | [
"def",
"paths",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"tree",
"in",
"self",
".",
"components",
"(",
")",
":",
"paths",
"+=",
"self",
".",
"_single_tree_paths",
"(",
"tree",
")",
"return",
"paths"
] | 35.214286 | 19.785714 |
def cache_call(self, method, *options):
"""
Call a remote method and store the result locally. Subsequent
calls to the same method with the same arguments will return the
cached result without invoking the remote procedure. Cached results are
kept indefinitely and must be manually refreshed with a call to
:... | [
"def",
"cache_call",
"(",
"self",
",",
"method",
",",
"*",
"options",
")",
":",
"options_hash",
"=",
"self",
".",
"encode",
"(",
"options",
")",
"if",
"len",
"(",
"options_hash",
")",
">",
"20",
":",
"options_hash",
"=",
"hashlib",
".",
"new",
"(",
"... | 42.733333 | 19.4 |
def _argparse_minmax_type(self, string):
"""Custom type for argparse to enforce value limits"""
value = float(string)
if value < 0 or value > 8:
raise argparse.ArgumentTypeError(
'%s must be between 0.0 and 8.0' % string,
)
return value | [
"def",
"_argparse_minmax_type",
"(",
"self",
",",
"string",
")",
":",
"value",
"=",
"float",
"(",
"string",
")",
"if",
"value",
"<",
"0",
"or",
"value",
">",
"8",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"'%s must be between 0.0 and 8.0'",
"%... | 33.444444 | 14.111111 |
def add_group(group_name, system_group=False, gid=None):
"""Add a group to the system
Will log but otherwise succeed if the group already exists.
:param str group_name: group to create
:param bool system_group: Create system group
:param int gid: GID for user being created
:returns: The passw... | [
"def",
"add_group",
"(",
"group_name",
",",
"system_group",
"=",
"False",
",",
"gid",
"=",
"None",
")",
":",
"try",
":",
"group_info",
"=",
"grp",
".",
"getgrnam",
"(",
"group_name",
")",
"log",
"(",
"'group {0} already exists!'",
".",
"format",
"(",
"grou... | 36.272727 | 17.772727 |
def delete_assessment_taken(self, assessment_taken_id):
"""Deletes an ``AssessmentTaken``.
arg: assessment_taken_id (osid.id.Id): the ``Id`` of the
``AssessmentTaken`` to remove
raise: NotFound - ``assessment_taken_id`` not found
raise: NullArgument - ``assessment_t... | [
"def",
"delete_assessment_taken",
"(",
"self",
",",
"assessment_taken_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.delete_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'assessment'",
",",
"collection",
"=",
"'Assess... | 53.48 | 24.24 |
def levels_for(self, time_op, groups, df):
"""
Compute the partition at each `level` from the dataframe.
"""
levels = {}
for i in range(0, len(groups) + 1):
agg_df = df.groupby(groups[:i]) if i else df
levels[i] = (
agg_df.mean() if time_op... | [
"def",
"levels_for",
"(",
"self",
",",
"time_op",
",",
"groups",
",",
"df",
")",
":",
"levels",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"groups",
")",
"+",
"1",
")",
":",
"agg_df",
"=",
"df",
".",
"groupby",
"(",
... | 36.181818 | 11.454545 |
def getParameters(self, phoneNumber):
"""
Return a C{list} of two liveform parameters, one for editing
C{phoneNumber}'s I{number} attribute, and one for editing its I{label}
attribute.
@type phoneNumber: L{PhoneNumber} or C{NoneType}
@param phoneNumber: If not C{None}, a... | [
"def",
"getParameters",
"(",
"self",
",",
"phoneNumber",
")",
":",
"defaultNumber",
"=",
"u''",
"defaultLabel",
"=",
"PhoneNumber",
".",
"LABELS",
".",
"HOME",
"if",
"phoneNumber",
"is",
"not",
"None",
":",
"defaultNumber",
"=",
"phoneNumber",
".",
"number",
... | 36.233333 | 15.433333 |
def report_server_init_errors(address=None, port=None, **kwargs):
''' A context manager to help print more informative error messages when a
``Server`` cannot be started due to a network problem.
Args:
address (str) : network address that the server will be listening on
port (int) : networ... | [
"def",
"report_server_init_errors",
"(",
"address",
"=",
"None",
",",
"port",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"yield",
"except",
"EnvironmentError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EADDRINUSE",
... | 36.9375 | 28.5625 |
def UpdateShowDirInTVLibrary(self, showID, showDir):
"""
Update show directory entry for given show id in TVLibrary table.
Parameters
----------
showID : int
Show id value.
showDir : string
Show directory name.
"""
goodlogging.Log.Info("DB", "Updating TV library for... | [
"def",
"UpdateShowDirInTVLibrary",
"(",
"self",
",",
"showID",
",",
"showDir",
")",
":",
"goodlogging",
".",
"Log",
".",
"Info",
"(",
"\"DB\"",
",",
"\"Updating TV library for ShowID={0}: ShowDir={1}\"",
".",
"format",
"(",
"showID",
",",
"showDir",
")",
")",
"s... | 32.142857 | 25.714286 |
def members(self, as_set=False):
"""Return the set members tuple/frozenset."""
if as_set:
return frozenset(map(self._members.__getitem__, self._indexes()))
return tuple(map(self._members.__getitem__, self._indexes())) | [
"def",
"members",
"(",
"self",
",",
"as_set",
"=",
"False",
")",
":",
"if",
"as_set",
":",
"return",
"frozenset",
"(",
"map",
"(",
"self",
".",
"_members",
".",
"__getitem__",
",",
"self",
".",
"_indexes",
"(",
")",
")",
")",
"return",
"tuple",
"(",
... | 49.8 | 19.2 |
def drop_column(self, name):
"""Drop the column ``name``.
::
table.drop_column('created_at')
"""
if self.db.engine.dialect.name == 'sqlite':
raise RuntimeError("SQLite does not support dropping columns.")
name = normalize_column_name(name)
with sel... | [
"def",
"drop_column",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"db",
".",
"engine",
".",
"dialect",
".",
"name",
"==",
"'sqlite'",
":",
"raise",
"RuntimeError",
"(",
"\"SQLite does not support dropping columns.\"",
")",
"name",
"=",
"normalize_co... | 33.25 | 14.2 |
def SafeReadBytes(self, length):
"""
Read exactly `length` number of bytes from the stream.
Raises:
ValueError is not enough data
Returns:
bytes: `length` number of bytes
"""
data = self.ReadBytes(length)
if len(data) < length:
... | [
"def",
"SafeReadBytes",
"(",
"self",
",",
"length",
")",
":",
"data",
"=",
"self",
".",
"ReadBytes",
"(",
"length",
")",
"if",
"len",
"(",
"data",
")",
"<",
"length",
":",
"raise",
"ValueError",
"(",
"\"Not enough data available\"",
")",
"else",
":",
"re... | 26.066667 | 15.8 |
def create(self):
"""
Subscribes at the server.
"""
self.logger.debug('Create subscription on server...')
if not self.connection.connected:
self.state = 'connection_pending'
return
data = {
'command': 'subscribe',
'identif... | [
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Create subscription on server...'",
")",
"if",
"not",
"self",
".",
"connection",
".",
"connected",
":",
"self",
".",
"state",
"=",
"'connection_pending'",
"return",
"data",
"... | 24.235294 | 16.823529 |
def get_name(self, plugin):
""" Return name for registered plugin or None if not registered. """
for name, val in self._name2plugin.items():
if plugin == val:
return name | [
"def",
"get_name",
"(",
"self",
",",
"plugin",
")",
":",
"for",
"name",
",",
"val",
"in",
"self",
".",
"_name2plugin",
".",
"items",
"(",
")",
":",
"if",
"plugin",
"==",
"val",
":",
"return",
"name"
] | 42 | 9.6 |
def create_binding(self, key, shard=None, public=False,
special_lobby_binding=False):
'''Used by Interest instances.'''
shard = shard or self.get_shard_id()
factory = recipient.Broadcast if public else recipient.Agent
recp = factory(key, shard)
binding = se... | [
"def",
"create_binding",
"(",
"self",
",",
"key",
",",
"shard",
"=",
"None",
",",
"public",
"=",
"False",
",",
"special_lobby_binding",
"=",
"False",
")",
":",
"shard",
"=",
"shard",
"or",
"self",
".",
"get_shard_id",
"(",
")",
"factory",
"=",
"recipient... | 46.363636 | 12.181818 |
def on_receive_request_vote_response(self, data):
"""Receives response for vote request.
If the vote was granted then check if we got majority and may become Leader
"""
if data.get('vote_granted'):
self.vote_count += 1
if self.state.is_majority(self.vote_count):... | [
"def",
"on_receive_request_vote_response",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"get",
"(",
"'vote_granted'",
")",
":",
"self",
".",
"vote_count",
"+=",
"1",
"if",
"self",
".",
"state",
".",
"is_majority",
"(",
"self",
".",
"vote_count",
... | 35 | 16.1 |
def expand_hostname_range(line = None):
'''
A helper function that expands a given line that contains a pattern
specified in top docstring, and returns a list that consists of the
expanded version.
The '[' and ']' characters are used to maintain the pseudo-code
appearance. They are replaced in ... | [
"def",
"expand_hostname_range",
"(",
"line",
"=",
"None",
")",
":",
"all_hosts",
"=",
"[",
"]",
"if",
"line",
":",
"# A hostname such as db[1:6]-node is considered to consists",
"# three parts:",
"# head: 'db'",
"# nrange: [1:6]; range() is a built-in. Can't use the name",
"# t... | 36.269231 | 22.884615 |
def peel_off_esc_code(s):
r"""Returns processed text, the next token, and unprocessed text
>>> front, d, rest = peel_off_esc_code('some[2Astuff')
>>> front, rest
('some', 'stuff')
>>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'}
True
... | [
"def",
"peel_off_esc_code",
"(",
"s",
")",
":",
"p",
"=",
"r\"\"\"(?P<front>.*?)\n (?P<seq>\n (?P<csi>\n (?:[\u001b]\\[)\n |\n [\"\"\"",
"+",
"'\\x9b'",
"+",
"r\"\"\"])\n (?P<private>)\n ... | 35.119048 | 20.904762 |
def make_op_return_outputs(data, inputs, change_address, fee=OP_RETURN_FEE,
send_amount=0, format='bin'):
""" Builds the outputs for an OP_RETURN transaction.
"""
return [
# main output
{ "script_hex": make_op_return_script(data, format=format), "value": send_amoun... | [
"def",
"make_op_return_outputs",
"(",
"data",
",",
"inputs",
",",
"change_address",
",",
"fee",
"=",
"OP_RETURN_FEE",
",",
"send_amount",
"=",
"0",
",",
"format",
"=",
"'bin'",
")",
":",
"return",
"[",
"# main output",
"{",
"\"script_hex\"",
":",
"make_op_retu... | 40.833333 | 23.916667 |
def unitResponse(self,band):
"""This is used internally for :ref:`pysynphot-formula-effstim`
calculations."""
#sum = asumr(band,nwave)
total = band.throughput.sum()
return 2.5*math.log10(total) | [
"def",
"unitResponse",
"(",
"self",
",",
"band",
")",
":",
"#sum = asumr(band,nwave)",
"total",
"=",
"band",
".",
"throughput",
".",
"sum",
"(",
")",
"return",
"2.5",
"*",
"math",
".",
"log10",
"(",
"total",
")"
] | 38 | 4.5 |
def _slice_cov(self, cov):
"""
Slice the correct dimensions for use in the kernel, as indicated by
`self.active_dims` for covariance matrices. This requires slicing the
rows *and* columns. This will also turn flattened diagonal
matrices into a tensor of full diagonal matrices.
... | [
"def",
"_slice_cov",
"(",
"self",
",",
"cov",
")",
":",
"cov",
"=",
"tf",
".",
"cond",
"(",
"tf",
".",
"equal",
"(",
"tf",
".",
"rank",
"(",
"cov",
")",
",",
"2",
")",
",",
"lambda",
":",
"tf",
".",
"matrix_diag",
"(",
"cov",
")",
",",
"lambd... | 52.904762 | 25.761905 |
def set_metadata(self, metadata, utf8):
"""Sets document metadata.
The ``PDF_METADATA_CREATE_DATE`` and ``PDF_METADATA_MOD_DATE``
values must be in ISO-8601 format: YYYY-MM-DDThh:mm:ss. An optional
timezone of the form "[+/-]hh:mm" or "Z" for UTC time can be appended.
All other ... | [
"def",
"set_metadata",
"(",
"self",
",",
"metadata",
",",
"utf8",
")",
":",
"cairo",
".",
"cairo_pdf_surface_set_metadata",
"(",
"self",
".",
"_pointer",
",",
"metadata",
",",
"_encode_string",
"(",
"utf8",
")",
")",
"self",
".",
"_check_status",
"(",
")"
] | 33.736842 | 20.631579 |
def calculate_recommendations(output_filename, model_name="als"):
""" Generates artist recommendations for each user in the dataset """
# train the model based off input params
artists, users, plays = get_lastfm()
# create a model from the input data
model = get_model(model_name)
# if we're tr... | [
"def",
"calculate_recommendations",
"(",
"output_filename",
",",
"model_name",
"=",
"\"als\"",
")",
":",
"# train the model based off input params",
"artists",
",",
"users",
",",
"plays",
"=",
"get_lastfm",
"(",
")",
"# create a model from the input data",
"model",
"=",
... | 41.555556 | 20.472222 |
def packages(state, host, packages=None, present=True, latest=False):
'''
Add/remove/update gem packages.
+ packages: list of packages to ensure
+ present: whether the packages should be installed
+ latest: whether to upgrade packages without a specified version
Versions:
Package versi... | [
"def",
"packages",
"(",
"state",
",",
"host",
",",
"packages",
"=",
"None",
",",
"present",
"=",
"True",
",",
"latest",
"=",
"False",
")",
":",
"yield",
"ensure_packages",
"(",
"packages",
",",
"host",
".",
"fact",
".",
"gem_packages",
",",
"present",
... | 30.55 | 21.05 |
def enable_one_shot_code_breakpoint(self, dwProcessId, address):
"""
Enables the code breakpoint at the given address for only one shot.
@see:
L{define_code_breakpoint},
L{has_code_breakpoint},
L{get_code_breakpoint},
L{enable_code_breakpoint},
... | [
"def",
"enable_one_shot_code_breakpoint",
"(",
"self",
",",
"dwProcessId",
",",
"address",
")",
":",
"p",
"=",
"self",
".",
"system",
".",
"get_process",
"(",
"dwProcessId",
")",
"bp",
"=",
"self",
".",
"get_code_breakpoint",
"(",
"dwProcessId",
",",
"address"... | 33.434783 | 14.478261 |
def set_vertex_colors(self, colors, indexed=None):
"""Set the vertex color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nv, 4) (indexing by vertex)
or shape (Nf, 3, 4) (vertices indexed by face).
indexed : str | None
... | [
"def",
"set_vertex_colors",
"(",
"self",
",",
"colors",
",",
"indexed",
"=",
"None",
")",
":",
"colors",
"=",
"_fix_colors",
"(",
"np",
".",
"asarray",
"(",
"colors",
")",
")",
"if",
"indexed",
"is",
"None",
":",
"if",
"colors",
".",
"ndim",
"!=",
"2... | 43.655172 | 17.172414 |
async def crawl(self, urls, sem):
"""
:param urls:
:type urls: list/dict
:param sem:
:type sem:
:return:
:rtype:
"""
tasks = [
self._sem_crawl(sem, x)
for x in urls
]
tasks_iter = asyncio.as_completed(tasks)... | [
"async",
"def",
"crawl",
"(",
"self",
",",
"urls",
",",
"sem",
")",
":",
"tasks",
"=",
"[",
"self",
".",
"_sem_crawl",
"(",
"sem",
",",
"x",
")",
"for",
"x",
"in",
"urls",
"]",
"tasks_iter",
"=",
"asyncio",
".",
"as_completed",
"(",
"tasks",
")",
... | 22.916667 | 18.25 |
def wait(self, sensor_name, condition_or_value, timeout=5):
"""Wait for a sensor in this resource to satisfy a condition.
Parameters
----------
sensor_name : string
The name of the sensor to check
condition_or_value : obj or callable, or seq of objs or callables
... | [
"def",
"wait",
"(",
"self",
",",
"sensor_name",
",",
"condition_or_value",
",",
"timeout",
"=",
"5",
")",
":",
"sensor_name",
"=",
"escape_name",
"(",
"sensor_name",
")",
"sensor",
"=",
"self",
".",
"sensor",
"[",
"sensor_name",
"]",
"try",
":",
"yield",
... | 38.783784 | 21.378378 |
def get(name, defval=None):
'''
Return an object from the embedded synapse data folder.
Example:
for tld in syanpse.data.get('iana.tlds'):
dostuff(tld)
NOTE: Files are named synapse/data/<name>.mpk
'''
with s_datfile.openDatFile('synapse.data/%s.mpk' % name) as fd:
... | [
"def",
"get",
"(",
"name",
",",
"defval",
"=",
"None",
")",
":",
"with",
"s_datfile",
".",
"openDatFile",
"(",
"'synapse.data/%s.mpk'",
"%",
"name",
")",
"as",
"fd",
":",
"return",
"s_msgpack",
".",
"un",
"(",
"fd",
".",
"read",
"(",
")",
")"
] | 26.076923 | 23.769231 |
def slug_from_dict(d, max_len=128, delim='-'):
"""Produce a slug (short URI-friendly string) from an iterable Mapping (dict, OrderedDict)
>>> slug_from_dict(OrderedDict([('a', 1), ('b', 'beta'), (' ', 'alpha')]))
'1-beta-alpha'
"""
return slug_from_iter(list(d.values()), max_len=max_len, delim=deli... | [
"def",
"slug_from_dict",
"(",
"d",
",",
"max_len",
"=",
"128",
",",
"delim",
"=",
"'-'",
")",
":",
"return",
"slug_from_iter",
"(",
"list",
"(",
"d",
".",
"values",
"(",
")",
")",
",",
"max_len",
"=",
"max_len",
",",
"delim",
"=",
"delim",
")"
] | 45.142857 | 19.857143 |
def is_identifier(self, is_identifier):
""" Setter for is_identifier """
if is_identifier:
self.is_editable = False
self._is_identifier = is_identifier | [
"def",
"is_identifier",
"(",
"self",
",",
"is_identifier",
")",
":",
"if",
"is_identifier",
":",
"self",
".",
"is_editable",
"=",
"False",
"self",
".",
"_is_identifier",
"=",
"is_identifier"
] | 26.142857 | 14.714286 |
def memoryview_safe(x):
"""Make array safe to run in a Cython memoryview-based kernel. These
kernels typically break down with the error ``ValueError: buffer source
array is read-only`` when running in dask distributed.
See Also
--------
https://github.com/dask/distributed/issues/1978
https... | [
"def",
"memoryview_safe",
"(",
"x",
")",
":",
"if",
"not",
"x",
".",
"flags",
".",
"writeable",
":",
"if",
"not",
"x",
".",
"flags",
".",
"owndata",
":",
"x",
"=",
"x",
".",
"copy",
"(",
"order",
"=",
"'A'",
")",
"x",
".",
"setflags",
"(",
"wri... | 31 | 18.3125 |
def parse_detail(self, response):
"""Parse individual product's detail"""
# Product Information (a start)
product_data = {
'url': response.url,
'name': response.css('div.page-title h1::text').extract_first(),
}
# Inventory Number
inventory_number ... | [
"def",
"parse_detail",
"(",
"self",
",",
"response",
")",
":",
"# Product Information (a start)",
"product_data",
"=",
"{",
"'url'",
":",
"response",
".",
"url",
",",
"'name'",
":",
"response",
".",
"css",
"(",
"'div.page-title h1::text'",
")",
".",
"extract_fir... | 35.222222 | 15.851852 |
def parse(self, **kwargs):
"""
Receives in input a dictionary of retrieved nodes.
Does all the logic here.
"""
from aiida.engine import ExitCode
from aiida.common import NotExistent
try:
out_folder = self.retrieved
except NotExistent:
... | [
"def",
"parse",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"aiida",
".",
"engine",
"import",
"ExitCode",
"from",
"aiida",
".",
"common",
"import",
"NotExistent",
"try",
":",
"out_folder",
"=",
"self",
".",
"retrieved",
"except",
"NotExistent",... | 28.136364 | 17.318182 |
def using(self, alias):
"""
Selects which database this QuerySet should excecute its query against.
"""
clone = self._clone()
clone._index = alias
return clone | [
"def",
"using",
"(",
"self",
",",
"alias",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"clone",
".",
"_index",
"=",
"alias",
"return",
"clone"
] | 28.714286 | 14.142857 |
def _unpack_int_base128(varint, offset):
"""Implement Perl unpack's 'w' option, aka base 128 decoding."""
res = ord(varint[offset])
if ord(varint[offset]) >= 0x80:
offset += 1
res = ((res - 0x80) << 7) + ord(varint[offset])
if ord(varint[offset]) >= 0x80:
... | [
"def",
"_unpack_int_base128",
"(",
"varint",
",",
"offset",
")",
":",
"res",
"=",
"ord",
"(",
"varint",
"[",
"offset",
"]",
")",
"if",
"ord",
"(",
"varint",
"[",
"offset",
"]",
")",
">=",
"0x80",
":",
"offset",
"+=",
"1",
"res",
"=",
"(",
"(",
"r... | 45.6875 | 11.4375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.