text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def compose(self, sources, client=None):
"""Concatenate source blobs into this one.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type sources: list of :class:`Blob`
:param sources: blobs whose contents will be composed into this blob.
... | [
"def",
"compose",
"(",
"self",
",",
"sources",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"self",
".",
"_require_client",
"(",
"client",
")",
"query_params",
"=",
"{",
"}",
"if",
"self",
".",
"user_project",
"is",
"not",
"None",
":",
"query_p... | 36.28125 | 0.001678 |
def strip_agent_context(stmts_in, **kwargs):
"""Strip any context on agents within each statement.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements whose agent context should be stripped.
save : Optional[str]
The name of a pickle file to save th... | [
"def",
"strip_agent_context",
"(",
"stmts_in",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"info",
"(",
"'Stripping agent context on %d statements...'",
"%",
"len",
"(",
"stmts_in",
")",
")",
"stmts_out",
"=",
"[",
"]",
"for",
"st",
"in",
"stmts_in",
"... | 31.40625 | 0.000965 |
def SetParametros(self, cuit, token, sign):
"Establece un parámetro general"
self.Token = token
self.Sign = sign
self.Cuit = cuit
return True | [
"def",
"SetParametros",
"(",
"self",
",",
"cuit",
",",
"token",
",",
"sign",
")",
":",
"self",
".",
"Token",
"=",
"token",
"self",
".",
"Sign",
"=",
"sign",
"self",
".",
"Cuit",
"=",
"cuit",
"return",
"True"
] | 29.333333 | 0.01105 |
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action ... | [
"def",
"destroy",
"(",
"name",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called with -d, --destroy, '",
"'-a ... | 33.637931 | 0.001743 |
def google(self, qs):
"""CSV format suitable for importing into google GMail"""
csvf = writer(sys.stdout)
csvf.writerow(['Name', 'Email'])
for ent in qs:
csvf.writerow([full_name(**ent), ent['email']]) | [
"def",
"google",
"(",
"self",
",",
"qs",
")",
":",
"csvf",
"=",
"writer",
"(",
"sys",
".",
"stdout",
")",
"csvf",
".",
"writerow",
"(",
"[",
"'Name'",
",",
"'Email'",
"]",
")",
"for",
"ent",
"in",
"qs",
":",
"csvf",
".",
"writerow",
"(",
"[",
"... | 40 | 0.008163 |
def build_url (self):
"""
Call super.build_url(), set default telnet port and initialize
the login credentials.
"""
super(TelnetUrl, self).build_url()
# default port
if self.port is None:
self.port = 23
# set user/pass
self.user, self.p... | [
"def",
"build_url",
"(",
"self",
")",
":",
"super",
"(",
"TelnetUrl",
",",
"self",
")",
".",
"build_url",
"(",
")",
"# default port",
"if",
"self",
".",
"port",
"is",
"None",
":",
"self",
".",
"port",
"=",
"23",
"# set user/pass",
"self",
".",
"user",
... | 31.272727 | 0.008475 |
def ScaleSmaller(self):
"""Decreases the zoom of the graph one step(0.1 units)."""
newfactor = self._zoomfactor - 0.1
if float(newfactor) > 0 and float(newfactor) < self._MAX_ZOOM:
self._zoomfactor = newfactor | [
"def",
"ScaleSmaller",
"(",
"self",
")",
":",
"newfactor",
"=",
"self",
".",
"_zoomfactor",
"-",
"0.1",
"if",
"float",
"(",
"newfactor",
")",
">",
"0",
"and",
"float",
"(",
"newfactor",
")",
"<",
"self",
".",
"_MAX_ZOOM",
":",
"self",
".",
"_zoomfactor... | 44.6 | 0.008811 |
def _get_manager(cluster_info, host, executor_id):
"""Returns this executor's "singleton" instance of the multiprocessing.Manager, reconnecting per python-worker if needed.
Args:
:cluster_info: cluster node reservations
:host: host IP address
:executor_id: unique id per executor (created during initial... | [
"def",
"_get_manager",
"(",
"cluster_info",
",",
"host",
",",
"executor_id",
")",
":",
"for",
"node",
"in",
"cluster_info",
":",
"if",
"node",
"[",
"'host'",
"]",
"==",
"host",
"and",
"node",
"[",
"'executor_id'",
"]",
"==",
"executor_id",
":",
"addr",
"... | 40.074074 | 0.01083 |
def interact(banner=None, readfunc=None, local=None):
"""Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole
class. When readfunc is not specified, it attempts to import the
readline module to enable GNU readline if it is available.
... | [
"def",
"interact",
"(",
"banner",
"=",
"None",
",",
"readfunc",
"=",
"None",
",",
"local",
"=",
"None",
")",
":",
"console",
"=",
"InteractiveConsole",
"(",
"local",
")",
"if",
"readfunc",
"is",
"not",
"None",
":",
"console",
".",
"raw_input",
"=",
"re... | 33.391304 | 0.001266 |
def rspr(self, disallow_sibling_sprs=False,
keep_entire_edge=False, rescale=False):
""" Random SPR, with prune and regraft edges chosen randomly, and
lengths drawn uniformly from the available edge lengths.
N1: disallow_sibling_sprs prevents sprs that don't alter the topology
... | [
"def",
"rspr",
"(",
"self",
",",
"disallow_sibling_sprs",
"=",
"False",
",",
"keep_entire_edge",
"=",
"False",
",",
"rescale",
"=",
"False",
")",
":",
"starting_length",
"=",
"self",
".",
"tree",
".",
"_tree",
".",
"length",
"(",
")",
"excl",
"=",
"[",
... | 41.658537 | 0.002288 |
def set_exception(self, exception):
'''
Set an exception to Future object, wake up all the waiters
:param exception: exception to set
'''
if hasattr(self, '_result'):
raise ValueError('Cannot set the result twice')
self._result = None
self._ex... | [
"def",
"set_exception",
"(",
"self",
",",
"exception",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_result'",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot set the result twice'",
")",
"self",
".",
"_result",
"=",
"None",
"self",
".",
"_exception",
"=",
... | 36.909091 | 0.012019 |
def Aitken(s):
"""Accelerate the convergence of the a series
using Aitken's delta-squared process (SCIP calls it Euler).
"""
def accel():
s0, s1, s2 = s >> item[:3]
while 1:
yield s2 - (s2 - s1)**2 / (s0 - 2*s1 + s2)
s0, s1, s2 = s1, s2, next(s)
return accel() | [
"def",
"Aitken",
"(",
"s",
")",
":",
"def",
"accel",
"(",
")",
":",
"s0",
",",
"s1",
",",
"s2",
"=",
"s",
">>",
"item",
"[",
":",
"3",
"]",
"while",
"1",
":",
"yield",
"s2",
"-",
"(",
"s2",
"-",
"s1",
")",
"**",
"2",
"/",
"(",
"s0",
"-"... | 26.6 | 0.036364 |
def syslog(server, enable=True, host=None,
admin_username=None, admin_password=None, module=None):
'''
Configure syslog remote logging, by default syslog will automatically be
enabled if a server is specified. However, if you want to disable syslog
you will need to specify a server followed b... | [
"def",
"syslog",
"(",
"server",
",",
"enable",
"=",
"True",
",",
"host",
"=",
"None",
",",
"admin_username",
"=",
"None",
",",
"admin_password",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"if",
"enable",
"and",
"__execute_cmd",
"(",
"'config -g c... | 43.6875 | 0.0007 |
def except_handle(tokens):
"""Process except statements."""
if len(tokens) == 1:
errs, asname = tokens[0], None
elif len(tokens) == 2:
errs, asname = tokens
else:
raise CoconutInternalException("invalid except tokens", tokens)
out = "except "
if "list" in tokens:
... | [
"def",
"except_handle",
"(",
"tokens",
")",
":",
"if",
"len",
"(",
"tokens",
")",
"==",
"1",
":",
"errs",
",",
"asname",
"=",
"tokens",
"[",
"0",
"]",
",",
"None",
"elif",
"len",
"(",
"tokens",
")",
"==",
"2",
":",
"errs",
",",
"asname",
"=",
"... | 26.9375 | 0.002242 |
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
"""
name = name.upper()
try:
return {
'authority': 'okapia.net',
'namespace': 'string match types',
'identifier': name,
... | [
"def",
"get_type_data",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"try",
":",
"return",
"{",
"'authority'",
":",
"'okapia.net'",
",",
"'namespace'",
":",
"'string match types'",
",",
"'identifier'",
":",
"name",
",",
"'domain'",
"... | 33.25 | 0.001462 |
def save(self, designName=""):
# type: (ASaveDesign) -> None
"""Save the current design to file"""
self.try_stateful_function(
ss.SAVING, ss.READY, self.do_save, designName) | [
"def",
"save",
"(",
"self",
",",
"designName",
"=",
"\"\"",
")",
":",
"# type: (ASaveDesign) -> None",
"self",
".",
"try_stateful_function",
"(",
"ss",
".",
"SAVING",
",",
"ss",
".",
"READY",
",",
"self",
".",
"do_save",
",",
"designName",
")"
] | 41 | 0.014354 |
def issueQueingServiceJobs(self):
"""Issues any queuing service jobs up to the limit of the maximum allowed."""
while len(self.serviceJobsToBeIssued) > 0 and self.serviceJobsIssued < self.config.maxServiceJobs:
self.issueJob(self.serviceJobsToBeIssued.pop())
self.serviceJobsIssue... | [
"def",
"issueQueingServiceJobs",
"(",
"self",
")",
":",
"while",
"len",
"(",
"self",
".",
"serviceJobsToBeIssued",
")",
">",
"0",
"and",
"self",
".",
"serviceJobsIssued",
"<",
"self",
".",
"config",
".",
"maxServiceJobs",
":",
"self",
".",
"issueJob",
"(",
... | 72.625 | 0.008503 |
def _unicode(value):
"""Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
if isinstance(value, _TO_UNICODE_TYPES):
return value
if not isinstance(... | [
"def",
"_unicode",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"_TO_UNICODE_TYPES",
")",
":",
"return",
"value",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bytes_type",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected bytes, unicode, or ... | 35.692308 | 0.002101 |
def s2p(self):
"""Return 2 proton separation energy"""
M_P = 7.28897050 # proton mass excess in MeV
f = lambda parent, daugther: -parent + daugther + 2 * M_P
return self.derived('s2p', (-2, 0), f) | [
"def",
"s2p",
"(",
"self",
")",
":",
"M_P",
"=",
"7.28897050",
"# proton mass excess in MeV",
"f",
"=",
"lambda",
"parent",
",",
"daugther",
":",
"-",
"parent",
"+",
"daugther",
"+",
"2",
"*",
"M_P",
"return",
"self",
".",
"derived",
"(",
"'s2p'",
",",
... | 46.4 | 0.012712 |
def matrix2cube(data_matrix, im_shape):
r"""Matrix to Cube
This method transforms a 2D matrix to a 3D cube
Parameters
----------
data_matrix : np.ndarray
Input data cube, 2D array
im_shape : tuple
2D shape of the individual images
Returns
-------
np.ndarray 3D cube... | [
"def",
"matrix2cube",
"(",
"data_matrix",
",",
"im_shape",
")",
":",
"return",
"data_matrix",
".",
"T",
".",
"reshape",
"(",
"[",
"data_matrix",
".",
"shape",
"[",
"1",
"]",
"]",
"+",
"list",
"(",
"im_shape",
")",
")"
] | 20.351351 | 0.001267 |
def percentage_of_reoccurring_values_to_all_values(x):
"""
Returns the ratio of unique values, that are present in the time series
more than once.
# of data points occurring more than once / # of all data points
This means the ratio is normalized to the number of data points in the time series... | [
"def",
"percentage_of_reoccurring_values_to_all_values",
"(",
"x",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"pd",
".",
"Series",
")",
":",
"x",
"=",
"pd",
".",
"Series",
"(",
"x",
")",
"if",
"x",
".",
"size",
"==",
"0",
":",
"return",
"np"... | 29.5 | 0.002345 |
def lookup(self):
"""
The meat of this middleware.
Returns None and sets settings.SITE_ID if able to find a Site
object by domain and its subdomain is valid.
Returns an HttpResponsePermanentRedirect to the Site's default
subdomain if a site is found but the requested su... | [
"def",
"lookup",
"(",
"self",
")",
":",
"# check to see if this hostname is actually a env hostname",
"if",
"self",
".",
"domain",
":",
"if",
"self",
".",
"subdomain",
":",
"self",
".",
"domain_unsplit",
"=",
"'%s.%s'",
"%",
"(",
"self",
".",
"subdomain",
",",
... | 33.408163 | 0.001187 |
def sum(self, only_valid=True) -> ErrorValue:
"""Calculate the sum of pixels, not counting the masked ones if only_valid is True."""
if not only_valid:
mask = 1
else:
mask = self.mask
return ErrorValue((self.intensity * mask).sum(),
((sel... | [
"def",
"sum",
"(",
"self",
",",
"only_valid",
"=",
"True",
")",
"->",
"ErrorValue",
":",
"if",
"not",
"only_valid",
":",
"mask",
"=",
"1",
"else",
":",
"mask",
"=",
"self",
".",
"mask",
"return",
"ErrorValue",
"(",
"(",
"self",
".",
"intensity",
"*",... | 43.5 | 0.008451 |
def natural_sort(item):
"""
Sort strings that contain numbers correctly.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> print l
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
if item is None:
return 0... | [
"def",
"natural_sort",
"(",
"item",
")",
":",
"if",
"item",
"is",
"None",
":",
"return",
"0",
"def",
"try_int",
"(",
"s",
")",
":",
"try",
":",
"return",
"int",
"(",
"s",
")",
"except",
"ValueError",
":",
"return",
"s",
"return",
"tuple",
"(",
"map... | 26.333333 | 0.002037 |
def main():
"""
NAME
thellier_magic_redo.py
DESCRIPTION
Calculates paleointensity parameters for thellier-thellier type data using bounds
stored in the "redo" file
SYNTAX
thellier_magic_redo [command line options]
OPTIONS
-h prints help message
-usr... | [
"def",
"main",
"(",
")",
":",
"dir_path",
"=",
"'.'",
"critout",
"=",
"\"\"",
"version_num",
"=",
"pmag",
".",
"get_version",
"(",
")",
"field",
",",
"first_save",
"=",
"-",
"1",
",",
"1",
"spec",
",",
"recnum",
",",
"start",
",",
"end",
"=",
"0",
... | 49.875 | 0.026244 |
def orientation(self, newaxis=None, rotation=0, rad=False):
"""
Set/Get actor orientation.
:param rotation: If != 0 rotate actor around newaxis.
:param rad: set to True if angle is in radians.
.. hint:: |gyroscope2| |gyroscope2.py|_
"""
if rad:
rotat... | [
"def",
"orientation",
"(",
"self",
",",
"newaxis",
"=",
"None",
",",
"rotation",
"=",
"0",
",",
"rad",
"=",
"False",
")",
":",
"if",
"rad",
":",
"rotation",
"*=",
"57.29578",
"initaxis",
"=",
"utils",
".",
"versor",
"(",
"self",
".",
"top",
"-",
"s... | 32.344828 | 0.00207 |
def to_list_of(self, state):
# type: (S) -> List[B]
'''Returns a list of all the foci within `state`.
Requires kind Fold. This method will raise TypeError if the
optic has no way to get any foci.
'''
if not self._is_kind(Fold):
raise TypeError('Must be an ins... | [
"def",
"to_list_of",
"(",
"self",
",",
"state",
")",
":",
"# type: (S) -> List[B]",
"if",
"not",
"self",
".",
"_is_kind",
"(",
"Fold",
")",
":",
"raise",
"TypeError",
"(",
"'Must be an instance of Fold to .to_list_of()'",
")",
"pure",
"=",
"lambda",
"a",
":",
... | 35.846154 | 0.01046 |
def _process_routers(self, routers, removed_routers,
device_id=None, all_routers=False):
"""Process the set of routers.
Iterating on the set of routers received and comparing it with the
set of routers already in the routing service helper, new routers
which are... | [
"def",
"_process_routers",
"(",
"self",
",",
"routers",
",",
"removed_routers",
",",
"device_id",
"=",
"None",
",",
"all_routers",
"=",
"False",
")",
":",
"try",
":",
"ids_previously_hosted_routers",
"=",
"(",
"set",
"(",
"r_id",
"for",
"r_id",
",",
"rdata",... | 48.863248 | 0.000857 |
def unholdAction(self):
"""
Unholds the action from being blocked on the leave event.
"""
self._actionHeld = False
point = self.mapFromGlobal(QCursor.pos())
self.setCurrentAction(self.actionAt(point)) | [
"def",
"unholdAction",
"(",
"self",
")",
":",
"self",
".",
"_actionHeld",
"=",
"False",
"point",
"=",
"self",
".",
"mapFromGlobal",
"(",
"QCursor",
".",
"pos",
"(",
")",
")",
"self",
".",
"setCurrentAction",
"(",
"self",
".",
"actionAt",
"(",
"point",
... | 32.125 | 0.011364 |
def as_constraint(cls, constraint, model, constraint_type=None, **init_kwargs):
"""
Initiate a Model which should serve as a constraint. Such a
constraint-model should be initiated with knowledge of another
``BaseModel``, from which it will take its parameters::
model = Mode... | [
"def",
"as_constraint",
"(",
"cls",
",",
"constraint",
",",
"model",
",",
"constraint_type",
"=",
"None",
",",
"*",
"*",
"init_kwargs",
")",
":",
"allowed_types",
"=",
"[",
"sympy",
".",
"Eq",
",",
"sympy",
".",
"Ge",
",",
"sympy",
".",
"Le",
"]",
"i... | 42.661017 | 0.000777 |
def from_boto_instance(cls, instance):
"""
Loads a ``HostEntry`` from a boto instance.
:param instance: A boto instance object.
:type instance: :py:class:`boto.ec2.instanceInstance`
:rtype: :py:class:`HostEntry`
"""
return cls(
name=instance.tags.get... | [
"def",
"from_boto_instance",
"(",
"cls",
",",
"instance",
")",
":",
"return",
"cls",
"(",
"name",
"=",
"instance",
".",
"tags",
".",
"get",
"(",
"'Name'",
")",
",",
"private_ip",
"=",
"instance",
".",
"private_ip_address",
",",
"public_ip",
"=",
"instance"... | 40.791667 | 0.001996 |
def full(self, name, fill_value, **kwargs):
"""Create an array. Keyword arguments as per
:func:`zarr.creation.full`."""
return self._write_op(self._full_nosync, name, fill_value, **kwargs) | [
"def",
"full",
"(",
"self",
",",
"name",
",",
"fill_value",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_write_op",
"(",
"self",
".",
"_full_nosync",
",",
"name",
",",
"fill_value",
",",
"*",
"*",
"kwargs",
")"
] | 52.25 | 0.009434 |
def aggregate_gradients_using_copy_with_device_selection(
tower_grads, avail_devices, use_mean=True, check_inf_nan=False):
"""Aggregate gradients, controlling device for the aggregation.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over towers. The inner li... | [
"def",
"aggregate_gradients_using_copy_with_device_selection",
"(",
"tower_grads",
",",
"avail_devices",
",",
"use_mean",
"=",
"True",
",",
"check_inf_nan",
"=",
"False",
")",
":",
"agg_grads",
"=",
"[",
"]",
"has_nan_or_inf_list",
"=",
"[",
"]",
"for",
"i",
",",
... | 46.666667 | 0.000875 |
def check_overlap(current, hit, overlap = 200):
"""
determine if sequence has already hit the same part of the model,
indicating that this hit is for another 16S rRNA gene
"""
for prev in current:
p_coords = prev[2:4]
coords = hit[2:4]
if get_overlap(coords, p_coords) >= over... | [
"def",
"check_overlap",
"(",
"current",
",",
"hit",
",",
"overlap",
"=",
"200",
")",
":",
"for",
"prev",
"in",
"current",
":",
"p_coords",
"=",
"prev",
"[",
"2",
":",
"4",
"]",
"coords",
"=",
"hit",
"[",
"2",
":",
"4",
"]",
"if",
"get_overlap",
"... | 32.272727 | 0.008219 |
def _prepend_name(self, prefix, dict_):
'''changes the keys of the dictionary prepending them with "name."'''
return dict(['.'.join([prefix, name]), msg]
for name, msg in dict_.iteritems()) | [
"def",
"_prepend_name",
"(",
"self",
",",
"prefix",
",",
"dict_",
")",
":",
"return",
"dict",
"(",
"[",
"'.'",
".",
"join",
"(",
"[",
"prefix",
",",
"name",
"]",
")",
",",
"msg",
"]",
"for",
"name",
",",
"msg",
"in",
"dict_",
".",
"iteritems",
"(... | 55.5 | 0.008889 |
def save_module(self, path, module, change_time=None):
"""Saves the specified module and its contents to the file system
so that it doesn't have to be parsed again unless it has changed."""
#First, get a list of the module paths that have already been
#pickled. We will add to that list ... | [
"def",
"save_module",
"(",
"self",
",",
"path",
",",
"module",
",",
"change_time",
"=",
"None",
")",
":",
"#First, get a list of the module paths that have already been ",
"#pickled. We will add to that list of pickling this module.",
"if",
"settings",
".",
"use_filesystem_cach... | 36.64 | 0.008511 |
def partially_matched_crossover(random, mom, dad, args):
"""Return the offspring of partially matched crossover on the candidates.
This function performs partially matched crossover (PMX). This type of
crossover assumes that candidates are composed of discrete values that
are permutations of a given se... | [
"def",
"partially_matched_crossover",
"(",
"random",
",",
"mom",
",",
"dad",
",",
"args",
")",
":",
"crossover_rate",
"=",
"args",
".",
"setdefault",
"(",
"'crossover_rate'",
",",
"1.0",
")",
"if",
"random",
".",
"random",
"(",
")",
"<",
"crossover_rate",
... | 36.769231 | 0.002038 |
def poke(self, context):
"""
Execute the bash command in a temporary directory
which will be cleaned afterwards
"""
bash_command = self.bash_command
self.log.info("Tmp dir root location: \n %s", gettempdir())
with TemporaryDirectory(prefix='airflowtmp') as tmp_dir... | [
"def",
"poke",
"(",
"self",
",",
"context",
")",
":",
"bash_command",
"=",
"self",
".",
"bash_command",
"self",
".",
"log",
".",
"info",
"(",
"\"Tmp dir root location: \\n %s\"",
",",
"gettempdir",
"(",
")",
")",
"with",
"TemporaryDirectory",
"(",
"prefix",
... | 41.09375 | 0.002229 |
def load_notebook(self, name):
"""Loads a notebook file into memory."""
with open(self.get_path('%s.ipynb'%name)) as f:
nb = nbformat.read(f, as_version=4)
return nb,f | [
"def",
"load_notebook",
"(",
"self",
",",
"name",
")",
":",
"with",
"open",
"(",
"self",
".",
"get_path",
"(",
"'%s.ipynb'",
"%",
"name",
")",
")",
"as",
"f",
":",
"nb",
"=",
"nbformat",
".",
"read",
"(",
"f",
",",
"as_version",
"=",
"4",
")",
"r... | 33.166667 | 0.019608 |
def mouseMoveEvent( self, event ):
"""
Sets the value for the slider at the event position.
:param event | <QMouseEvent>
"""
self.setValue(self.valueAt(event.pos().x())) | [
"def",
"mouseMoveEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"setValue",
"(",
"self",
".",
"valueAt",
"(",
"event",
".",
"pos",
"(",
")",
".",
"x",
"(",
")",
")",
")"
] | 31.857143 | 0.021834 |
def _var_isomorphic(a, b, check_varprops=True):
"""
Two Xmrs objects are isomorphic if they have the same structure as
determined by variable linkages between preds.
"""
# first some quick checks
if len(a.eps()) != len(b.eps()): return False
if len(a.variables()) != len(b.variables()): retur... | [
"def",
"_var_isomorphic",
"(",
"a",
",",
"b",
",",
"check_varprops",
"=",
"True",
")",
":",
"# first some quick checks",
"if",
"len",
"(",
"a",
".",
"eps",
"(",
")",
")",
"!=",
"len",
"(",
"b",
".",
"eps",
"(",
")",
")",
":",
"return",
"False",
"if... | 35.269231 | 0.002122 |
def FibreMode(gridSize,modeDiameter):
"""
Return a pupil-plane Gaussian mode with 1/e diameter given by
*modeDiameter*, normalised so that integral power over the mode is unity
"""
rmode=modeDiameter/2
return np.exp(-(RadiusGrid(gridSize)/rmode)**2)/(np.sqrt(np.pi/2)*rmode) | [
"def",
"FibreMode",
"(",
"gridSize",
",",
"modeDiameter",
")",
":",
"rmode",
"=",
"modeDiameter",
"/",
"2",
"return",
"np",
".",
"exp",
"(",
"-",
"(",
"RadiusGrid",
"(",
"gridSize",
")",
"/",
"rmode",
")",
"**",
"2",
")",
"/",
"(",
"np",
".",
"sqrt... | 41.857143 | 0.013378 |
def get_name_levels(node):
"""Return a list of ``(name, level)`` tuples for assigned names
The `level` is `None` for simple assignments and is a list of
numbers for tuple assignments for example in::
a, (b, c) = x
The levels for for `a` is ``[0]``, for `b` is ``[1, 0]`` and for
`c` is ``[1,... | [
"def",
"get_name_levels",
"(",
"node",
")",
":",
"visitor",
"=",
"_NodeNameCollector",
"(",
")",
"ast",
".",
"walk",
"(",
"node",
",",
"visitor",
")",
"return",
"visitor",
".",
"names"
] | 27.266667 | 0.002364 |
def iodp_kly4s_lore(kly4s_file, meas_out='measurements.txt',
spec_infile='specimens.txt', spec_out='specimens.txt', instrument='IODP-KLY4S',
actual_volume="",dir_path='.', input_dir_path=''):
"""
Converts ascii files generated by SUFAR ver.4.0 and downloaded from the LIMS online
repos... | [
"def",
"iodp_kly4s_lore",
"(",
"kly4s_file",
",",
"meas_out",
"=",
"'measurements.txt'",
",",
"spec_infile",
"=",
"'specimens.txt'",
",",
"spec_out",
"=",
"'specimens.txt'",
",",
"instrument",
"=",
"'IODP-KLY4S'",
",",
"actual_volume",
"=",
"\"\"",
",",
"dir_path",
... | 45.509091 | 0.02007 |
def p_field_optional2_4(self, p):
"""
field : alias name selection_set
"""
p[0] = Field(name=p[2], alias=p[1], selections=p[3]) | [
"def",
"p_field_optional2_4",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Field",
"(",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"alias",
"=",
"p",
"[",
"1",
"]",
",",
"selections",
"=",
"p",
"[",
"3",
"]",
")"
] | 31 | 0.012579 |
def name_replace(self, to_replace, replacement):
"""Replaces part of tag name with new value"""
self.name = self.name.replace(to_replace, replacement) | [
"def",
"name_replace",
"(",
"self",
",",
"to_replace",
",",
"replacement",
")",
":",
"self",
".",
"name",
"=",
"self",
".",
"name",
".",
"replace",
"(",
"to_replace",
",",
"replacement",
")"
] | 54.666667 | 0.012048 |
def write_across_link(self, address, data, x, y, link):
"""Write a bytestring to an address in memory on a neigbouring chip.
.. warning::
This function is intended for low-level debug use only and is not
optimised for performance nor intended for more general use.
This... | [
"def",
"write_across_link",
"(",
"self",
",",
"address",
",",
"data",
",",
"x",
",",
"y",
",",
"link",
")",
":",
"if",
"address",
"%",
"4",
":",
"raise",
"ValueError",
"(",
"\"Addresses must be word-aligned.\"",
")",
"if",
"len",
"(",
"data",
")",
"%",
... | 41.673077 | 0.000902 |
def search(cls, query, search_opts=None):
""" Search tags.
For more information, see the backend function
:py:func:`nipap.backend.Nipap.search_tag`.
"""
if search_opts is None:
search_opts = {}
xmlrpc = XMLRPCConnection()
try:
se... | [
"def",
"search",
"(",
"cls",
",",
"query",
",",
"search_opts",
"=",
"None",
")",
":",
"if",
"search_opts",
"is",
"None",
":",
"search_opts",
"=",
"{",
"}",
"xmlrpc",
"=",
"XMLRPCConnection",
"(",
")",
"try",
":",
"search_result",
"=",
"xmlrpc",
".",
"c... | 30.607143 | 0.002262 |
def _commit_with_retry(client, write_pbs, transaction_id):
"""Call ``Commit`` on the GAPIC client with retry / sleep.
Retries the ``Commit`` RPC on Unavailable. Usually this RPC-level
retry is handled by the underlying GAPICd client, but in this case it
doesn't because ``Commit`` is not always idempote... | [
"def",
"_commit_with_retry",
"(",
"client",
",",
"write_pbs",
",",
"transaction_id",
")",
":",
"current_sleep",
"=",
"_INITIAL_SLEEP",
"while",
"True",
":",
"try",
":",
"return",
"client",
".",
"_firestore_api",
".",
"commit",
"(",
"client",
".",
"_database_stri... | 37.75 | 0.000646 |
def _get_keywords(self, **kwargs):
"""Format GET request parameters and keywords."""
if self.jurisdiction and 'jurisdiction_id' not in kwargs:
kwargs['jurisdiction_id'] = self.jurisdiction
if 'count' in kwargs:
kwargs['page_size'] = kwargs.pop('count')
if 'start' ... | [
"def",
"_get_keywords",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"jurisdiction",
"and",
"'jurisdiction_id'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'jurisdiction_id'",
"]",
"=",
"self",
".",
"jurisdiction",
"if",
"'count'",
"... | 41.285714 | 0.002255 |
def add_or_update(self, app_id):
'''
Add or update the category.
'''
logger.info('Collect info: user-{0}, uid-{1}'.format(self.userinfo.uid, app_id))
MCollect.add_or_update(self.userinfo.uid, app_id)
out_dic = {'success': True}
return json.dump(out_dic, self) | [
"def",
"add_or_update",
"(",
"self",
",",
"app_id",
")",
":",
"logger",
".",
"info",
"(",
"'Collect info: user-{0}, uid-{1}'",
".",
"format",
"(",
"self",
".",
"userinfo",
".",
"uid",
",",
"app_id",
")",
")",
"MCollect",
".",
"add_or_update",
"(",
"self",
... | 38.5 | 0.009524 |
def create(cls, train_ds, valid_ds, test_ds=None, path:PathOrStr='.', no_check:bool=False, bs=64, val_bs:int=None,
num_workers:int=0, device:torch.device=None, collate_fn:Callable=data_collate,
dl_tfms:Optional[Collection[Callable]]=None, bptt:int=70, backwards:bool=False, **dl_kwargs) -> ... | [
"def",
"create",
"(",
"cls",
",",
"train_ds",
",",
"valid_ds",
",",
"test_ds",
"=",
"None",
",",
"path",
":",
"PathOrStr",
"=",
"'.'",
",",
"no_check",
":",
"bool",
"=",
"False",
",",
"bs",
"=",
"64",
",",
"val_bs",
":",
"int",
"=",
"None",
",",
... | 89.545455 | 0.045226 |
def generate_non_rabs(self):
""" Shrink the non-Rab DB size by reducing sequence redundancy.
"""
logging.info('Building non-Rab DB')
run_cmd([self.pathfinder['cd-hit'], '-i', self.path['non_rab_db'], '-o', self.output['non_rab_db'],
'-d', '100', '-c', str(config['param'... | [
"def",
"generate_non_rabs",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Building non-Rab DB'",
")",
"run_cmd",
"(",
"[",
"self",
".",
"pathfinder",
"[",
"'cd-hit'",
"]",
",",
"'-i'",
",",
"self",
".",
"path",
"[",
"'non_rab_db'",
"]",
",",
"'-o... | 54.125 | 0.009091 |
def ServiceWorker_dispatchSyncEvent(self, origin, registrationId, tag,
lastChance):
"""
Function path: ServiceWorker.dispatchSyncEvent
Domain: ServiceWorker
Method name: dispatchSyncEvent
Parameters:
Required arguments:
'origin' (type: string) -> No description
'registrationId' (type:... | [
"def",
"ServiceWorker_dispatchSyncEvent",
"(",
"self",
",",
"origin",
",",
"registrationId",
",",
"tag",
",",
"lastChance",
")",
":",
"assert",
"isinstance",
"(",
"origin",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'origin' must be of type '['str']'. Received... | 37.21875 | 0.047463 |
def skipDryRun(logger, dryRun, level=logging.DEBUG):
""" Return logging function.
When logging function called, will return True if action should be skipped.
Log will indicate if skipped because of dry run.
"""
# This is an undocumented "feature" of logging module:
# logging.log() requires a nu... | [
"def",
"skipDryRun",
"(",
"logger",
",",
"dryRun",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"# This is an undocumented \"feature\" of logging module:",
"# logging.log() requires a numeric level",
"# logging.getLevelName() maps names to numbers",
"if",
"not",
"isins... | 38.6 | 0.001686 |
def size(self):
""" Returns the size of the belief state.
Initially if there are $n$ consistent members, (the result of `self.number_of_singleton_referents()`)
then there are generally $2^{n}-1$ valid belief states.
"""
n = self.number_of_singleton_referents()
targets =... | [
"def",
"size",
"(",
"self",
")",
":",
"n",
"=",
"self",
".",
"number_of_singleton_referents",
"(",
")",
"targets",
"=",
"list",
"(",
"self",
".",
"iter_referents_tuples",
"(",
")",
")",
"n_targets",
"=",
"len",
"(",
"targets",
")",
"if",
"n",
"==",
"0"... | 39.111111 | 0.009709 |
def decode(self, encoded_packet):
"""Decode a transmitted package.
The return value indicates how many binary attachment packets are
necessary to fully decode the packet.
"""
ep = encoded_packet
try:
self.packet_type = int(ep[0:1])
except TypeError:
... | [
"def",
"decode",
"(",
"self",
",",
"encoded_packet",
")",
":",
"ep",
"=",
"encoded_packet",
"try",
":",
"self",
".",
"packet_type",
"=",
"int",
"(",
"ep",
"[",
"0",
":",
"1",
"]",
")",
"except",
"TypeError",
":",
"self",
".",
"packet_type",
"=",
"ep"... | 31.435897 | 0.001582 |
def create_size_estimators():
"""Create a dict of name to a function that returns an estimated size for a given target.
The estimated size is used to build the largest targets first (subject to dependency constraints).
Choose 'random' to choose random sizes for each target, which may be useful for distributed
... | [
"def",
"create_size_estimators",
"(",
")",
":",
"def",
"line_count",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fh",
":",
"return",
"sum",
"(",
"1",
"for",
"line",
"in",
"fh",
")",
"return",
"{",
"'linecount'",... | 42.666667 | 0.010191 |
def register_aggregations():
"""Register sample aggregations."""
return [dict(
aggregation_name='file-download-agg',
templates='invenio_stats.contrib.aggregations.aggr_file_download',
aggregator_class=StatAggregator,
aggregator_config=dict(
client=current_search_clien... | [
"def",
"register_aggregations",
"(",
")",
":",
"return",
"[",
"dict",
"(",
"aggregation_name",
"=",
"'file-download-agg'",
",",
"templates",
"=",
"'invenio_stats.contrib.aggregations.aggr_file_download'",
",",
"aggregator_class",
"=",
"StatAggregator",
",",
"aggregator_conf... | 38 | 0.000641 |
def _named_tuple_converter(tuple_type):
# type: (Type[Tuple]) -> _AggregateConverter
"""Return an _AggregateConverter for named tuples of the given type."""
def _from_dict(dict_value):
if dict_value:
return tuple_type(**dict_value)
# Cannot construct a namedtuple value from an e... | [
"def",
"_named_tuple_converter",
"(",
"tuple_type",
")",
":",
"# type: (Type[Tuple]) -> _AggregateConverter",
"def",
"_from_dict",
"(",
"dict_value",
")",
":",
"if",
"dict_value",
":",
"return",
"tuple_type",
"(",
"*",
"*",
"dict_value",
")",
"# Cannot construct a named... | 29.666667 | 0.001815 |
async def cas(self, value: Any, **kwargs) -> bool:
"""
Checks and sets the specified value for the locked key. If the value has changed
since the lock was created, it will raise an :class:`aiocache.lock.OptimisticLockError`
exception.
:raises: :class:`aiocache.lock.OptimisticLoc... | [
"async",
"def",
"cas",
"(",
"self",
",",
"value",
":",
"Any",
",",
"*",
"*",
"kwargs",
")",
"->",
"bool",
":",
"success",
"=",
"await",
"self",
".",
"client",
".",
"set",
"(",
"self",
".",
"key",
",",
"value",
",",
"_cas_token",
"=",
"self",
".",... | 45.416667 | 0.010791 |
def links(self):
"""Get all links.
Returns:
list[gkeepapi.node.WebLink]: A list of links.
"""
return [annotation for annotation in self._annotations.values()
if isinstance(annotation, WebLink)
] | [
"def",
"links",
"(",
"self",
")",
":",
"return",
"[",
"annotation",
"for",
"annotation",
"in",
"self",
".",
"_annotations",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"annotation",
",",
"WebLink",
")",
"]"
] | 27.888889 | 0.015444 |
def convert_dist(feed: "Feed", new_dist_units: str) -> "Feed":
"""
Convert the distances recorded in the ``shape_dist_traveled``
columns of the given Feed to the given distance units.
New distance units must lie in :const:`.constants.DIST_UNITS`.
Return the resulting feed.
"""
feed = feed.co... | [
"def",
"convert_dist",
"(",
"feed",
":",
"\"Feed\"",
",",
"new_dist_units",
":",
"str",
")",
"->",
"\"Feed\"",
":",
"feed",
"=",
"feed",
".",
"copy",
"(",
")",
"if",
"feed",
".",
"dist_units",
"==",
"new_dist_units",
":",
"# Nothing to do",
"return",
"feed... | 31.37931 | 0.001066 |
def tange_debyetemp(v, v0, gamma0, a, b, theta0):
"""
calculate Debye temperature for the Tange equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param a: volume-independent adjustable parameters
:param b: vol... | [
"def",
"tange_debyetemp",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"a",
",",
"b",
",",
"theta0",
")",
":",
"x",
"=",
"v",
"/",
"v0",
"gamma",
"=",
"tange_grun",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"a",
",",
"b",
")",
"if",
"isuncertainties... | 37.714286 | 0.001232 |
def __updateJobResultsPeriodic(self):
"""
Periodic check to see if this is the best model. This should only have an
effect if this is the *first* model to report its progress
"""
if self._isBestModelStored and not self._isBestModel:
return
while True:
jobResultsStr = self._jobsDAO.j... | [
"def",
"__updateJobResultsPeriodic",
"(",
"self",
")",
":",
"if",
"self",
".",
"_isBestModelStored",
"and",
"not",
"self",
".",
"_isBestModel",
":",
"return",
"while",
"True",
":",
"jobResultsStr",
"=",
"self",
".",
"_jobsDAO",
".",
"jobGetFields",
"(",
"self"... | 37.288462 | 0.015578 |
def conglomerate(self, messages, **config):
""" Given N messages, return another list that has some of them
grouped together into a common 'item'.
A conglomeration of messages should be of the following form::
{
'subtitle': 'relrod pushed commits to ghc and 487 other pack... | [
"def",
"conglomerate",
"(",
"self",
",",
"messages",
",",
"*",
"*",
"config",
")",
":",
"for",
"conglomerator",
"in",
"self",
".",
"conglomerator_objects",
":",
"messages",
"=",
"conglomerator",
".",
"conglomerate",
"(",
"messages",
",",
"*",
"*",
"config",
... | 41.095238 | 0.001132 |
def _collect(self, lines):
""" This routine reads the following from the Siesta file:
- atomic positions
- cell_parameters
- atomic_species
"""
for tag,value,unit in re.findall(
'([\.A-Za-z]+)\s+%s\s+([A-Za-z]+)?' %
self._num_re... | [
"def",
"_collect",
"(",
"self",
",",
"lines",
")",
":",
"for",
"tag",
",",
"value",
",",
"unit",
"in",
"re",
".",
"findall",
"(",
"'([\\.A-Za-z]+)\\s+%s\\s+([A-Za-z]+)?'",
"%",
"self",
".",
"_num_regex",
",",
"lines",
")",
":",
"tag",
"=",
"tag",
".",
... | 45.52459 | 0.01128 |
def trace_memory_start(self):
""" Starts measuring memory consumption """
self.trace_memory_clean_caches()
objgraph.show_growth(limit=30)
gc.collect()
self._memory_start = self.worker.get_memory()["total"] | [
"def",
"trace_memory_start",
"(",
"self",
")",
":",
"self",
".",
"trace_memory_clean_caches",
"(",
")",
"objgraph",
".",
"show_growth",
"(",
"limit",
"=",
"30",
")",
"gc",
".",
"collect",
"(",
")",
"self",
".",
"_memory_start",
"=",
"self",
".",
"worker",
... | 26.666667 | 0.008065 |
def authorize(login, password, scopes, note='', note_url='', client_id='',
client_secret='', two_factor_callback=None):
"""Obtain an authorization token for the GitHub API.
:param str login: (required)
:param str password: (required)
:param list scopes: (required), areas you want this tok... | [
"def",
"authorize",
"(",
"login",
",",
"password",
",",
"scopes",
",",
"note",
"=",
"''",
",",
"note_url",
"=",
"''",
",",
"client_id",
"=",
"''",
",",
"client_secret",
"=",
"''",
",",
"two_factor_callback",
"=",
"None",
")",
":",
"gh",
"=",
"GitHub",
... | 46.826087 | 0.00091 |
def lcsubstrings(seq1, seq2, positions=False):
"""Find the longest common substring(s) in the sequences `seq1` and `seq2`.
If positions evaluates to `True` only their positions will be returned,
together with their length, in a tuple:
(length, [(start pos in seq1, start pos in seq2)..])
Otherwise, the subst... | [
"def",
"lcsubstrings",
"(",
"seq1",
",",
"seq2",
",",
"positions",
"=",
"False",
")",
":",
"L1",
",",
"L2",
"=",
"len",
"(",
"seq1",
")",
",",
"len",
"(",
"seq2",
")",
"ms",
"=",
"[",
"]",
"mlen",
"=",
"last",
"=",
"0",
"if",
"L1",
"<",
"L2",... | 23.717391 | 0.047535 |
def copy(self, target):
"""Copies this file the `target`, which might be a directory.
The permissions are copied.
"""
shutil.copy(self.path, self._to_backend(target)) | [
"def",
"copy",
"(",
"self",
",",
"target",
")",
":",
"shutil",
".",
"copy",
"(",
"self",
".",
"path",
",",
"self",
".",
"_to_backend",
"(",
"target",
")",
")"
] | 32.333333 | 0.01005 |
def get_pod_container(self,
volume_mounts,
persistence_outputs=None,
persistence_data=None,
outputs_refs_jobs=None,
outputs_refs_experiments=None,
secret_refs=None,... | [
"def",
"get_pod_container",
"(",
"self",
",",
"volume_mounts",
",",
"persistence_outputs",
"=",
"None",
",",
"persistence_data",
"=",
"None",
",",
"outputs_refs_jobs",
"=",
"None",
",",
"outputs_refs_experiments",
"=",
"None",
",",
"secret_refs",
"=",
"None",
",",... | 44.113636 | 0.008569 |
def get_channel_comment(self, name=None, group=None, index=None):
"""Gets channel comment.
Channel can be specified in two ways:
* using the first positional argument *name*
* if there are multiple occurrences for this channel then the
*group* and *index* arguments c... | [
"def",
"get_channel_comment",
"(",
"self",
",",
"name",
"=",
"None",
",",
"group",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"gp_nr",
",",
"ch_nr",
"=",
"self",
".",
"_validate_channel_selection",
"(",
"name",
",",
"group",
",",
"index",
")",
"... | 29.581395 | 0.001522 |
def export_java(
self,
java_template=JAVA_TEMPLATE,
java_indent=JAVA_INDENTATION,
java_package=JAVA_PACKAGE,
is_public=True):
'''Export the grammar to a Java file which can be
used with the jleri module.'''
language = []
enums ... | [
"def",
"export_java",
"(",
"self",
",",
"java_template",
"=",
"JAVA_TEMPLATE",
",",
"java_indent",
"=",
"JAVA_INDENTATION",
",",
"java_package",
"=",
"JAVA_PACKAGE",
",",
"is_public",
"=",
"True",
")",
":",
"language",
"=",
"[",
"]",
"enums",
"=",
"set",
"("... | 36.323077 | 0.000825 |
def infer_namespace(ac):
"""Infer the single namespace of the given accession
This function is convenience wrapper around infer_namespaces().
Returns:
* None if no namespaces are inferred
* The (single) namespace if only one namespace is inferred
* Raises an exception if more than one nam... | [
"def",
"infer_namespace",
"(",
"ac",
")",
":",
"namespaces",
"=",
"infer_namespaces",
"(",
"ac",
")",
"if",
"not",
"namespaces",
":",
"return",
"None",
"if",
"len",
"(",
"namespaces",
")",
">",
"1",
":",
"raise",
"BioutilsError",
"(",
"\"Multiple namespaces ... | 28.277778 | 0.00095 |
def stop(self):
"""Stop the timer."""
dd = time() - self._start
self.ms = int(round(1000 * dd)) | [
"def",
"stop",
"(",
"self",
")",
":",
"dd",
"=",
"time",
"(",
")",
"-",
"self",
".",
"_start",
"self",
".",
"ms",
"=",
"int",
"(",
"round",
"(",
"1000",
"*",
"dd",
")",
")"
] | 29 | 0.016807 |
def should_use(intersection):
"""Check if an intersection can be used as part of a curved polygon.
Will return :data:`True` if the intersection is classified as
:attr:`~.IntersectionClassification.FIRST`,
:attr:`~.IntersectionClassification.SECOND` or
:attr:`~.IntersectionClassification.COINCIDENT`... | [
"def",
"should_use",
"(",
"intersection",
")",
":",
"if",
"intersection",
".",
"interior_curve",
"in",
"ACCEPTABLE_CLASSIFICATIONS",
":",
"return",
"True",
"if",
"intersection",
".",
"interior_curve",
"in",
"TANGENT_CLASSIFICATIONS",
":",
"return",
"intersection",
"."... | 37 | 0.001098 |
def _write(self, data, length, progress_callback=None):
"""Sends the data to the device, tracking progress with the callback."""
if progress_callback:
progress = self._handle_progress(length, progress_callback)
six.next(progress)
while length:
tmp = data.read(FASTBOOT_DOWNLOAD_CHUNK_SIZE_K... | [
"def",
"_write",
"(",
"self",
",",
"data",
",",
"length",
",",
"progress_callback",
"=",
"None",
")",
":",
"if",
"progress_callback",
":",
"progress",
"=",
"self",
".",
"_handle_progress",
"(",
"length",
",",
"progress_callback",
")",
"six",
".",
"next",
"... | 35.833333 | 0.015873 |
def get_file_range(ase, offsets, timeout=None):
# type: (blobxfer.models.azure.StorageEntity,
# blobxfer.models.download.Offsets, int) -> bytes
"""Retrieve file range
:param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity
:param blobxfer.models.download.Offsets offsets: download ... | [
"def",
"get_file_range",
"(",
"ase",
",",
"offsets",
",",
"timeout",
"=",
"None",
")",
":",
"# type: (blobxfer.models.azure.StorageEntity,",
"# blobxfer.models.download.Offsets, int) -> bytes",
"dir",
",",
"fpath",
",",
"_",
"=",
"parse_file_path",
"(",
"ase",
".... | 37.714286 | 0.001232 |
def skip_class_parameters():
"""
Can be used with :meth:`add_parametric_object_params`, this removes
duplicate variables cluttering the sphinx docs.
This is only intended to be used with *sphinx autodoc*
In your *sphinx* ``config.py`` file::
from cqparts.utils.sphinx import skip_class_par... | [
"def",
"skip_class_parameters",
"(",
")",
":",
"from",
".",
".",
"params",
"import",
"Parameter",
"def",
"callback",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"skip",
",",
"options",
")",
":",
"if",
"(",
"what",
"==",
"'class'",
")",
"an... | 29.681818 | 0.001484 |
def _get_taxon(taxon):
"""Return Interacting taxon ID | optional | 0 or 1 | gaf column 13."""
if not taxon:
return None
## assert taxon[:6] == 'taxon:', 'UNRECOGNIZED Taxon({Taxon})'.format(Taxon=taxon)
## taxid = taxon[6:]
## assert taxon[:10] == 'NCBITaxon:', 'UNREC... | [
"def",
"_get_taxon",
"(",
"taxon",
")",
":",
"if",
"not",
"taxon",
":",
"return",
"None",
"## assert taxon[:6] == 'taxon:', 'UNRECOGNIZED Taxon({Taxon})'.format(Taxon=taxon)",
"## taxid = taxon[6:]",
"## assert taxon[:10] == 'NCBITaxon:', 'UNRECOGNIZED Taxon({Taxon})'.format(Taxon=taxon)... | 45.769231 | 0.01318 |
def get_type_name(type_name, sub_type=None):
""" Returns a c# type according to a spec type
"""
if type_name == "enum":
return type_name
elif type_name == "boolean":
return "bool"
elif type_name == "integer":
return "long"
elif type_name == "time":
return "long"
... | [
"def",
"get_type_name",
"(",
"type_name",
",",
"sub_type",
"=",
"None",
")",
":",
"if",
"type_name",
"==",
"\"enum\"",
":",
"return",
"type_name",
"elif",
"type_name",
"==",
"\"boolean\"",
":",
"return",
"\"bool\"",
"elif",
"type_name",
"==",
"\"integer\"",
":... | 24.8 | 0.001942 |
def from_ashrae_dict_cooling(cls, ashrae_dict, location,
use_010=False, pressure=None, tau=None):
"""Create a heating design day object from a ASHRAE HOF dictionary.
Args:
ashrae_dict: A dictionary with 32 keys that match those in the
cooling... | [
"def",
"from_ashrae_dict_cooling",
"(",
"cls",
",",
"ashrae_dict",
",",
"location",
",",
"use_010",
"=",
"False",
",",
"pressure",
"=",
"None",
",",
"tau",
"=",
"None",
")",
":",
"db_key",
"=",
"'DB004'",
"if",
"use_010",
"is",
"False",
"else",
"'DB010'",
... | 58.648649 | 0.002267 |
def template_engine(self, entry, startnode):
"""The format template interpetation engine. See the comment at the
beginning of this module for the how we interpret format
specifications such as %c, %C, and so on.
"""
# print("-----")
# print(startnode)
# print(en... | [
"def",
"template_engine",
"(",
"self",
",",
"entry",
",",
"startnode",
")",
":",
"# print(\"-----\")",
"# print(startnode)",
"# print(entry[0])",
"# print('======')",
"startnode_start",
"=",
"len",
"(",
"self",
".",
"f",
".",
"getvalue",
"(",
")",
")",
"start",
... | 36.617834 | 0.002202 |
def absolute_symlink(source_path, target_path):
"""Create a symlink at target pointing to source using the absolute path.
:param source_path: Absolute path to source file
:param target_path: Absolute path to intended symlink
:raises ValueError if source_path or link_path are not unique, absolute paths
:raise... | [
"def",
"absolute_symlink",
"(",
"source_path",
",",
"target_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"source_path",
")",
":",
"raise",
"ValueError",
"(",
"\"Path for source : {} must be absolute\"",
".",
"format",
"(",
"source_path",
"... | 44.153846 | 0.011083 |
def month_interval(year, month, return_str=False):
"""
Usage Example::
>>> timewrapper.day_interval(2014, 12)
(datetime(2014, 12, 1, 0, 0, 0), datetime(2014, 12, 31, 23, 59, 59))
"""
if month == 12:
start, end = datetime(year, month, ... | [
"def",
"month_interval",
"(",
"year",
",",
"month",
",",
"return_str",
"=",
"False",
")",
":",
"if",
"month",
"==",
"12",
":",
"start",
",",
"end",
"=",
"datetime",
"(",
"year",
",",
"month",
",",
"1",
")",
",",
"datetime",
"(",
"year",
"+",
"1",
... | 34.823529 | 0.013158 |
def readheaders(self):
"""Read header lines.
Read header lines up to the entirely blank line that terminates them.
The (normally blank) line that ends the headers is skipped, but not
included in the returned list. If a non-header line ends the headers,
(which is an error), an a... | [
"def",
"readheaders",
"(",
"self",
")",
":",
"self",
".",
"dict",
"=",
"{",
"}",
"self",
".",
"unixfrom",
"=",
"''",
"self",
".",
"headers",
"=",
"lst",
"=",
"[",
"]",
"self",
".",
"status",
"=",
"''",
"headerseen",
"=",
"\"\"",
"firstline",
"=",
... | 39.240506 | 0.000629 |
def read(fobj, **kwargs):
"""Read a WAV file into a `TimeSeries`
Parameters
----------
fobj : `file`, `str`
open file-like object or filename to read from
**kwargs
all keyword arguments are passed onto :func:`scipy.io.wavfile.read`
See also
--------
scipy.io.wavfile.re... | [
"def",
"read",
"(",
"fobj",
",",
"*",
"*",
"kwargs",
")",
":",
"fsamp",
",",
"arr",
"=",
"wavfile",
".",
"read",
"(",
"fobj",
",",
"*",
"*",
"kwargs",
")",
"return",
"TimeSeries",
"(",
"arr",
",",
"sample_rate",
"=",
"fsamp",
")"
] | 24.826087 | 0.001686 |
def _yum_pkginfo(output):
'''
Parse yum/dnf output (which could contain irregular line breaks if package
names are long) retrieving the name, version, etc., and return a list of
pkginfo namedtuples.
'''
cur = {}
keys = itertools.cycle(('name', 'version', 'repoid'))
values = salt.utils.it... | [
"def",
"_yum_pkginfo",
"(",
"output",
")",
":",
"cur",
"=",
"{",
"}",
"keys",
"=",
"itertools",
".",
"cycle",
"(",
"(",
"'name'",
",",
"'version'",
",",
"'repoid'",
")",
")",
"values",
"=",
"salt",
".",
"utils",
".",
"itertools",
".",
"split",
"(",
... | 41.75 | 0.00065 |
def p_delays_floatnumber(self, p):
'delays : DELAY floatnumber'
p[0] = DelayStatement(FloatConst(
p[2], lineno=p.lineno(1)), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_delays_floatnumber",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"DelayStatement",
"(",
"FloatConst",
"(",
"p",
"[",
"2",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
",",
"lineno",
"=",
"p",
".",
"li... | 41 | 0.009569 |
def _mk_connectivity_flats(self, i12, j1, j2, mat_data, flats, elev, mag):
"""
Helper function for _mk_adjacency_matrix. This calcualtes the
connectivity for flat regions. Every pixel in the flat will drain
to a random pixel in the flat. This accumulates all the area in the
flat ... | [
"def",
"_mk_connectivity_flats",
"(",
"self",
",",
"i12",
",",
"j1",
",",
"j2",
",",
"mat_data",
",",
"flats",
",",
"elev",
",",
"mag",
")",
":",
"nn",
",",
"mm",
"=",
"flats",
".",
"shape",
"NN",
"=",
"np",
".",
"prod",
"(",
"flats",
".",
"shape... | 45.683824 | 0.000945 |
def fake_exc_info(exc_info, filename, lineno):
"""Helper for `translate_exception`."""
exc_type, exc_value, tb = exc_info
# figure the real context out
if tb is not None:
# if there is a local called __tonnikala_exception__, we get
# rid of it to not break the debug functionality.
... | [
"def",
"fake_exc_info",
"(",
"exc_info",
",",
"filename",
",",
"lineno",
")",
":",
"exc_type",
",",
"exc_value",
",",
"tb",
"=",
"exc_info",
"# figure the real context out",
"if",
"tb",
"is",
"not",
"None",
":",
"# if there is a local called __tonnikala_exception__, w... | 37.226667 | 0.000698 |
def zipf_random_sample(distr_map, sample_len):
"""Helper function: Generate a random Zipf sample of given length.
Args:
distr_map: list of float, Zipf's distribution over nbr_symbols.
sample_len: integer, length of sequence to generate.
Returns:
sample: list of integer, Zipf's random sample over nbr... | [
"def",
"zipf_random_sample",
"(",
"distr_map",
",",
"sample_len",
")",
":",
"u",
"=",
"np",
".",
"random",
".",
"random",
"(",
"sample_len",
")",
"# Random produces values in range [0.0,1.0); even if it is almost",
"# improbable(but possible) that it can generate a clear 0.000.... | 35.866667 | 0.01087 |
def answer_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None):
"""
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On succe... | [
"def",
"answer_callback_query",
"(",
"self",
",",
"callback_query_id",
",",
"text",
"=",
"None",
",",
"show_alert",
"=",
"None",
",",
"url",
"=",
"None",
",",
"cache_time",
"=",
"None",
")",
":",
"assert_type_or_raise",
"(",
"callback_query_id",
",",
"unicode_... | 54.473684 | 0.009491 |
def parse(self, plist):
"""Update the builder using the provided `plist`. `plist` can
be either a Packet() or a PacketList().
"""
if not isinstance(plist, PacketList):
plist = PacketList(plist)
for pkt in plist[LLTD]:
if LLTDQueryLargeTlv in pkt:
... | [
"def",
"parse",
"(",
"self",
",",
"plist",
")",
":",
"if",
"not",
"isinstance",
"(",
"plist",
",",
"PacketList",
")",
":",
"plist",
"=",
"PacketList",
"(",
"plist",
")",
"for",
"pkt",
"in",
"plist",
"[",
"LLTD",
"]",
":",
"if",
"LLTDQueryLargeTlv",
"... | 47.178571 | 0.001484 |
def addValue(self, source, value):
"""Adds a value from the given source."""
if self.source is None or self.fn(self.value, value):
self.value = value
self.source = source | [
"def",
"addValue",
"(",
"self",
",",
"source",
",",
"value",
")",
":",
"if",
"self",
".",
"source",
"is",
"None",
"or",
"self",
".",
"fn",
"(",
"self",
".",
"value",
",",
"value",
")",
":",
"self",
".",
"value",
"=",
"value",
"self",
".",
"source... | 37.2 | 0.015789 |
def cmyk_to_cmy(c, m=None, y=None, k=None):
"""Convert the color from CMYK coordinates to CMY.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:k:
The Black component value [0...1]
Returns:
... | [
"def",
"cmyk_to_cmy",
"(",
"c",
",",
"m",
"=",
"None",
",",
"y",
"=",
"None",
",",
"k",
"=",
"None",
")",
":",
"if",
"type",
"(",
"c",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"c",
",",
"m",
",",
"y",
",",
"k",
"=",
"c",
"mk",
"=... | 21 | 0.010118 |
def get_table():
"""Provides table of scheduling block instance metadata for use with AJAX
tables"""
response = dict(blocks=[])
block_ids = DB.get_sched_block_instance_ids()
for index, block_id in enumerate(block_ids):
block = DB.get_block_details([block_id]).__next__()
info = [
... | [
"def",
"get_table",
"(",
")",
":",
"response",
"=",
"dict",
"(",
"blocks",
"=",
"[",
"]",
")",
"block_ids",
"=",
"DB",
".",
"get_sched_block_instance_ids",
"(",
")",
"for",
"index",
",",
"block_id",
"in",
"enumerate",
"(",
"block_ids",
")",
":",
"block",... | 33.933333 | 0.001912 |
def remove_reader(self, fd):
" Stop watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
if h in self._read_fds:
del self._read_fds[h] | [
"def",
"remove_reader",
"(",
"self",
",",
"fd",
")",
":",
"h",
"=",
"msvcrt",
".",
"get_osfhandle",
"(",
"fd",
")",
"if",
"h",
"in",
"self",
".",
"_read_fds",
":",
"del",
"self",
".",
"_read_fds",
"[",
"h",
"]"
] | 39.2 | 0.01 |
def warp(self, order):
"""对order/market的封装
[description]
Arguments:
order {[type]} -- [description]
Returns:
[type] -- [description]
"""
# 因为成交模式对时间的封装
if order.order_model == ORDER_MODEL.MARKET:
if order.frequence is FREQ... | [
"def",
"warp",
"(",
"self",
",",
"order",
")",
":",
"# 因为成交模式对时间的封装",
"if",
"order",
".",
"order_model",
"==",
"ORDER_MODEL",
".",
"MARKET",
":",
"if",
"order",
".",
"frequence",
"is",
"FREQUENCE",
".",
"DAY",
":",
"# exact_time = str(datetime.datetime.strptime(... | 38.115385 | 0.001229 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.