text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _inverse_permutation_indices(positions):
"""Like inverse_permutation, but also handles slices.
Parameters
----------
positions : list of np.ndarray or slice objects.
If slice objects, all are assumed to be slices.
Returns
-------
np.ndarray of indices or None, if no permutation... | [
"def",
"_inverse_permutation_indices",
"(",
"positions",
")",
":",
"if",
"not",
"positions",
":",
"return",
"None",
"if",
"isinstance",
"(",
"positions",
"[",
"0",
"]",
",",
"slice",
")",
":",
"positions",
"=",
"_consolidate_slices",
"(",
"positions",
")",
"... | 29.73913 | 0.001416 |
def _next_partition(self, topic, key=None):
"""get the next partition to which to publish
Check with our client for the latest partitions for the topic, then
ask our partitioner for the next partition to which we should publish
for the give key. If needed, create a new partitioner for t... | [
"def",
"_next_partition",
"(",
"self",
",",
"topic",
",",
"key",
"=",
"None",
")",
":",
"# check if the client has metadata for the topic",
"while",
"self",
".",
"client",
".",
"metadata_error_for_topic",
"(",
"topic",
")",
":",
"# client doesn't have good metadata for ... | 48.676471 | 0.001185 |
def Builder(**kw):
"""A factory for builder objects."""
composite = None
if 'generator' in kw:
if 'action' in kw:
raise UserError("You must not specify both an action and a generator.")
kw['action'] = SCons.Action.CommandGeneratorAction(kw['generator'], {})
del kw['genera... | [
"def",
"Builder",
"(",
"*",
"*",
"kw",
")",
":",
"composite",
"=",
"None",
"if",
"'generator'",
"in",
"kw",
":",
"if",
"'action'",
"in",
"kw",
":",
"raise",
"UserError",
"(",
"\"You must not specify both an action and a generator.\"",
")",
"kw",
"[",
"'action'... | 40.682927 | 0.002342 |
def _remove_qualifiers(obj):
"""
Remove all qualifiers from the input objectwhere the object may
be an CIMInstance or CIMClass. Removes qualifiers from the object and
from properties, methods, and parameters
This is used to process the IncludeQualifier parameter for classes
... | [
"def",
"_remove_qualifiers",
"(",
"obj",
")",
":",
"assert",
"isinstance",
"(",
"obj",
",",
"(",
"CIMInstance",
",",
"CIMClass",
")",
")",
"obj",
".",
"qualifiers",
"=",
"NocaseDict",
"(",
")",
"for",
"prop",
"in",
"obj",
".",
"properties",
":",
"obj",
... | 43.684211 | 0.002358 |
def taper(self, side='leftright'):
"""Taper the ends of this `TimeSeries` smoothly to zero.
Parameters
----------
side : `str`, optional
the side of the `TimeSeries` to taper, must be one of `'left'`,
`'right'`, or `'leftright'`
Returns
-------
... | [
"def",
"taper",
"(",
"self",
",",
"side",
"=",
"'leftright'",
")",
":",
"# check window properties",
"if",
"side",
"not",
"in",
"(",
"'left'",
",",
"'right'",
",",
"'leftright'",
")",
":",
"raise",
"ValueError",
"(",
"\"side must be one of 'left', 'right', \"",
... | 35.939394 | 0.000821 |
def on_data(self, ws, message, message_type, fin):
"""
Callback executed when message is received from the server.
:param ws: Websocket client
:param message: utf-8 string which we get from the server.
:param message_type: Message type which is either ABNF.OPCODE_TEXT or ABNF.OP... | [
"def",
"on_data",
"(",
"self",
",",
"ws",
",",
"message",
",",
"message_type",
",",
"fin",
")",
":",
"try",
":",
"json_object",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"except",
"Exception",
":",
"self",
".",
"on_error",
"(",
"ws",
",",
"'Una... | 39.803922 | 0.002404 |
def remove_wirevector(self, wirevector):
""" Remove a wirevector object to the block."""
self.wirevector_set.remove(wirevector)
del self.wirevector_by_name[wirevector.name] | [
"def",
"remove_wirevector",
"(",
"self",
",",
"wirevector",
")",
":",
"self",
".",
"wirevector_set",
".",
"remove",
"(",
"wirevector",
")",
"del",
"self",
".",
"wirevector_by_name",
"[",
"wirevector",
".",
"name",
"]"
] | 48.25 | 0.010204 |
def get_scrim(path=None, auto_write=None, shell=None, script=None, cache={}):
'''Get a :class:`Scrim` instance. Each instance is cached so if you call
get_scrim again with the same arguments you get the same instance.
See also:
:class:`Scrim`
'''
args = (path, auto_write, shell, script)
... | [
"def",
"get_scrim",
"(",
"path",
"=",
"None",
",",
"auto_write",
"=",
"None",
",",
"shell",
"=",
"None",
",",
"script",
"=",
"None",
",",
"cache",
"=",
"{",
"}",
")",
":",
"args",
"=",
"(",
"path",
",",
"auto_write",
",",
"shell",
",",
"script",
... | 32.5 | 0.002494 |
def make_choice_validator(
choices, default_key=None, normalizer=None):
"""
Returns a callable that accepts the choices provided.
Choices should be provided as a list of 2-tuples, where the first
element is a string that should match user input (the key); the
second being the value associat... | [
"def",
"make_choice_validator",
"(",
"choices",
",",
"default_key",
"=",
"None",
",",
"normalizer",
"=",
"None",
")",
":",
"def",
"normalize_all",
"(",
"_choices",
")",
":",
"# normalize all the keys for easier comparison",
"if",
"normalizer",
":",
"_choices",
"=",
... | 33.254902 | 0.000573 |
def default(self, obj):
"""If input object is an ndarray it will be converted into a dict
holding dtype, shape and the data, base64 encoded.
"""
if isinstance(obj, np.ndarray):
if obj.flags['C_CONTIGUOUS']:
obj_data = obj.data
else:
... | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"obj",
".",
"flags",
"[",
"'C_CONTIGUOUS'",
"]",
":",
"obj_data",
"=",
"obj",
".",
"data",
"else",
":",
"cont_obj",
"=",... | 42.263158 | 0.002436 |
def UV_H(Hg,gw):
"""
Constructs implications and intents based on H
gw = g width
Hg = H(g), g is the binary coding of the attribute set
UV = all non-trivial (!V⊂U) implications U->V with UuV closed; in ternary coding (1=V,2=U)
K = all closed sets
"""
lefts = set()
K = []
UV = []
... | [
"def",
"UV_H",
"(",
"Hg",
",",
"gw",
")",
":",
"lefts",
"=",
"set",
"(",
")",
"K",
"=",
"[",
"]",
"UV",
"=",
"[",
"]",
"p",
"=",
"Hwidth",
"(",
"gw",
")",
"pp",
"=",
"2",
"**",
"p",
"while",
"p",
":",
"pp",
"=",
"pp",
">>",
"1",
"p",
... | 26.076923 | 0.01707 |
def cli_check_normalize_args(args):
'''Check and normalize arguments
This function checks that basis set names, families, roles, etc, are
valid (and raise an exception if they aren't)
The original data passed to this function is not modified. A modified
copy is returned.
'''
ar... | [
"def",
"cli_check_normalize_args",
"(",
"args",
")",
":",
"args_keys",
"=",
"vars",
"(",
"args",
")",
".",
"keys",
"(",
")",
"# What args we have",
"args_copy",
"=",
"copy",
".",
"copy",
"(",
"args",
")",
"if",
"'data_dir'",
"in",
"args_keys",
":",
"args_c... | 40.242424 | 0.000735 |
def to_str(obj, encoding='utf-8', **encode_args):
r"""
Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For
example::
>>> some_str = b"\xff"
>>> some_unicode = u"\u1234"
>>> some_exception = Exception(u'Error: ' + some_unicode)
>>> r(to_str(some_str))
... | [
"def",
"to_str",
"(",
"obj",
",",
"encoding",
"=",
"'utf-8'",
",",
"*",
"*",
"encode_args",
")",
":",
"# Note: On py3, ``b'x'.__str__()`` returns ``\"b'x'\"``, so we need to do the",
"# explicit check first.",
"if",
"isinstance",
"(",
"obj",
",",
"binary_type",
")",
":"... | 34.78125 | 0.000874 |
def ranking_game(n, steps=10, random_state=None):
"""
Return a NormalFormGame instance of (the 2-player version of) the
"ranking game" studied by Goldberg et al. (2013), where each player
chooses an effort level associated with a score and a cost which are
both increasing functions with randomly gen... | [
"def",
"ranking_game",
"(",
"n",
",",
"steps",
"=",
"10",
",",
"random_state",
"=",
"None",
")",
":",
"payoff_arrays",
"=",
"tuple",
"(",
"np",
".",
"empty",
"(",
"(",
"n",
",",
"n",
")",
")",
"for",
"i",
"in",
"range",
"(",
"2",
")",
")",
"ran... | 40.242424 | 0.000368 |
def _handle_read_chunk(self):
"""Some data can be read"""
new_data = b''
buffer_length = len(self.read_buffer)
try:
while buffer_length < self.MAX_BUFFER_SIZE:
try:
piece = self.recv(4096)
except OSError as e:
... | [
"def",
"_handle_read_chunk",
"(",
"self",
")",
":",
"new_data",
"=",
"b''",
"buffer_length",
"=",
"len",
"(",
"self",
".",
"read_buffer",
")",
"try",
":",
"while",
"buffer_length",
"<",
"self",
".",
"MAX_BUFFER_SIZE",
":",
"try",
":",
"piece",
"=",
"self",... | 34.935484 | 0.001797 |
def guess_file_name_stream_type_header(args):
"""
Guess filename, file stream, file type, file header from args.
:param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj,
contentype) or 4-tuples (filename, fileobj, contentype, custom_headers).
:return: filena... | [
"def",
"guess_file_name_stream_type_header",
"(",
"args",
")",
":",
"ftype",
"=",
"None",
"fheader",
"=",
"None",
"if",
"isinstance",
"(",
"args",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"2",
":",
"fname",
... | 33.730769 | 0.002217 |
def isNumber(self, value):
"""
Validate whether a value is a number or not
"""
try:
str(value)
float(value)
return True
except ValueError:
return False | [
"def",
"isNumber",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"str",
"(",
"value",
")",
"float",
"(",
"value",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False"
] | 20.909091 | 0.008333 |
def get_all_tasks(conf):
"""Returns a list with every task registred on Hamster.
"""
db = HamsterDB(conf)
fact_list = db.all_facts_id
security_days = int(conf.get_option('tasks.security_days'))
today = datetime.today()
tasks = {}
for fact_id in fact_list:
ht = HamsterTask(fac... | [
"def",
"get_all_tasks",
"(",
"conf",
")",
":",
"db",
"=",
"HamsterDB",
"(",
"conf",
")",
"fact_list",
"=",
"db",
".",
"all_facts_id",
"security_days",
"=",
"int",
"(",
"conf",
".",
"get_option",
"(",
"'tasks.security_days'",
")",
")",
"today",
"=",
"dateti... | 25.583333 | 0.00157 |
def purge_key(surrogate_key, service_id, api_key):
"""Instant purge URLs with a given surrogate key from the Fastly caches.
Parameters
----------
surrogate_key : `str`
Surrogate key header (``x-amz-meta-surrogate-key``) value of objects
to purge from the Fastly cache.
service_id : `... | [
"def",
"purge_key",
"(",
"surrogate_key",
",",
"service_id",
",",
"api_key",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"api_root",
"=",
"'https://api.fastly.com'",
"path",
"=",
"'/service/{service}/purge/{surrogate_key}'",
".",
"for... | 30.871795 | 0.000805 |
def handler(self):
'Parametrized handler function'
return ft.partial(self.base.handler, parameter=self.parameter)\
if self.parameter else self.base.handler | [
"def",
"handler",
"(",
"self",
")",
":",
"return",
"ft",
".",
"partial",
"(",
"self",
".",
"base",
".",
"handler",
",",
"parameter",
"=",
"self",
".",
"parameter",
")",
"if",
"self",
".",
"parameter",
"else",
"self",
".",
"base",
".",
"handler"
] | 39.75 | 0.030864 |
def as_dictionary(self, is_proof=True):
"""
Return the DDO as a JSON dict.
:param if is_proof: if False then do not include the 'proof' element.
:return: dict
"""
if self._created is None:
self._created = DDO._get_timestamp()
data = {
'@c... | [
"def",
"as_dictionary",
"(",
"self",
",",
"is_proof",
"=",
"True",
")",
":",
"if",
"self",
".",
"_created",
"is",
"None",
":",
"self",
".",
"_created",
"=",
"DDO",
".",
"_get_timestamp",
"(",
")",
"data",
"=",
"{",
"'@context'",
":",
"DID_DDO_CONTEXT_URL... | 31.823529 | 0.001794 |
def reduce_by(self, package_request):
"""Reduce this scope wrt a package request.
Returns:
A (_PackageScope, [Reduction]) tuple, where the scope is a new
scope copy with reductions applied, or self if there were no
reductions, or None if the scope was completely redu... | [
"def",
"reduce_by",
"(",
"self",
",",
"package_request",
")",
":",
"self",
".",
"solver",
".",
"reduction_broad_tests_count",
"+=",
"1",
"if",
"self",
".",
"package_request",
".",
"conflict",
":",
"# conflict scopes don't reduce. Instead, other scopes will be",
"# reduc... | 34.452381 | 0.001344 |
def create_task_log(self, task_id, case_task_log):
"""
:param task_id: Task identifier
:param case_task_log: TheHive log
:type case_task_log: CaseTaskLog defined in models.py
:return: TheHive log
:rtype: json
"""
req = self.url + "/api/case/task/{}/log".... | [
"def",
"create_task_log",
"(",
"self",
",",
"task_id",
",",
"case_task_log",
")",
":",
"req",
"=",
"self",
".",
"url",
"+",
"\"/api/case/task/{}/log\"",
".",
"format",
"(",
"task_id",
")",
"data",
"=",
"{",
"'_json'",
":",
"json",
".",
"dumps",
"(",
"{",... | 51.083333 | 0.008006 |
def fbank(wav_path, flat=True):
""" Currently grabs log Mel filterbank, deltas and double deltas."""
(rate, sig) = wav.read(wav_path)
if len(sig) == 0:
logger.warning("Empty wav: {}".format(wav_path))
fbank_feat = python_speech_features.logfbank(sig, rate, nfilt=40)
energy = extract_energy(... | [
"def",
"fbank",
"(",
"wav_path",
",",
"flat",
"=",
"True",
")",
":",
"(",
"rate",
",",
"sig",
")",
"=",
"wav",
".",
"read",
"(",
"wav_path",
")",
"if",
"len",
"(",
"sig",
")",
"==",
"0",
":",
"logger",
".",
"warning",
"(",
"\"Empty wav: {}\"",
".... | 40.375 | 0.001008 |
def delete_record(table, sys_id):
'''
Delete an existing record
:param table: The table name, e.g. sys_user
:type table: ``str``
:param sys_id: The unique ID of the record
:type sys_id: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.delete_record sys_co... | [
"def",
"delete_record",
"(",
"table",
",",
"sys_id",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"client",
".",
"table",
"=",
"table",
"response",
"=",
"client",
".",
"delete",
"(",
"sys_id",
")",
"return",
"response"
] | 21.6 | 0.002217 |
def diagonalize_collision_matrix(collision_matrices,
i_sigma=None,
i_temp=None,
pinv_solver=0,
log_level=0):
"""Diagonalize collision matrices.
Note
----
collision_matrici... | [
"def",
"diagonalize_collision_matrix",
"(",
"collision_matrices",
",",
"i_sigma",
"=",
"None",
",",
"i_temp",
"=",
"None",
",",
"pinv_solver",
"=",
"0",
",",
"log_level",
"=",
"0",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"# Matrix size of coll... | 34.853448 | 0.000241 |
def filter_intensity(df, label="", with_multiplicity=False):
"""
Filter to include only the Intensity values with optional specified label, excluding other
Intensity measurements, but retaining all other columns.
"""
label += ".*__\d" if with_multiplicity else ""
dft = df.filter(regex="^(?!Int... | [
"def",
"filter_intensity",
"(",
"df",
",",
"label",
"=",
"\"\"",
",",
"with_multiplicity",
"=",
"False",
")",
":",
"label",
"+=",
"\".*__\\d\"",
"if",
"with_multiplicity",
"else",
"\"\"",
"dft",
"=",
"df",
".",
"filter",
"(",
"regex",
"=",
"\"^(?!Intensity).... | 38.727273 | 0.013761 |
def create_append(filename: str, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], row_attrs: Dict[str, np.ndarray], col_attrs: Dict[str, np.ndarray], *, file_attrs: Dict[str, str] = None, fill_values: Dict[str, np.ndarray] = None) -> None:
"""
**DEPRECATED** - Use `new` instead; see https://gith... | [
"def",
"create_append",
"(",
"filename",
":",
"str",
",",
"layers",
":",
"Union",
"[",
"np",
".",
"ndarray",
",",
"Dict",
"[",
"str",
",",
"np",
".",
"ndarray",
"]",
",",
"loompy",
".",
"LayerManager",
"]",
",",
"row_attrs",
":",
"Dict",
"[",
"str",
... | 65.8 | 0.01949 |
def cbpdnmd_xstep(k):
"""Do the X step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables.
"""
YU0 = mp_Z_Y0[k] + mp_S[k] - mp_Z_U0[k]
YU1 = mp_Z_Y1[k] - mp_Z_U1[k]
if mp_cri.Cd == 1:
... | [
"def",
"cbpdnmd_xstep",
"(",
"k",
")",
":",
"YU0",
"=",
"mp_Z_Y0",
"[",
"k",
"]",
"+",
"mp_S",
"[",
"k",
"]",
"-",
"mp_Z_U0",
"[",
"k",
"]",
"YU1",
"=",
"mp_Z_Y1",
"[",
"k",
"]",
"-",
"mp_Z_U1",
"[",
"k",
"]",
"if",
"mp_cri",
".",
"Cd",
"==",... | 44.210526 | 0.002331 |
def _hash(self, iv, value):
"""
Generate and hmac signature for this encrypted data
:param key:
:param iv:
:param value:
:return string:
"""
return hmac.new(self.key, msg=iv+value, digestmod=hashlib.sha256).hexdigest() | [
"def",
"_hash",
"(",
"self",
",",
"iv",
",",
"value",
")",
":",
"return",
"hmac",
".",
"new",
"(",
"self",
".",
"key",
",",
"msg",
"=",
"iv",
"+",
"value",
",",
"digestmod",
"=",
"hashlib",
".",
"sha256",
")",
".",
"hexdigest",
"(",
")"
] | 30.444444 | 0.010638 |
def roles(self):
"""List[:class:`Role`]: A :class:`list` of roles that is allowed to use this emoji.
If roles is empty, the emoji is unrestricted.
"""
guild = self.guild
if guild is None:
return []
return [role for role in guild.roles if self._roles.has(role... | [
"def",
"roles",
"(",
"self",
")",
":",
"guild",
"=",
"self",
".",
"guild",
"if",
"guild",
"is",
"None",
":",
"return",
"[",
"]",
"return",
"[",
"role",
"for",
"role",
"in",
"guild",
".",
"roles",
"if",
"self",
".",
"_roles",
".",
"has",
"(",
"rol... | 31.6 | 0.009231 |
def qgis_composer_extractor(impact_report, component_metadata):
"""Extract composer context.
This method extract necessary context for a given impact report and
component metadata and save the context so it can be used in composer
rendering phase
:param impact_report: the impact report that acts a... | [
"def",
"qgis_composer_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"# QGIS Composer needed certain context to generate the output",
"# - Map Settings",
"# - Substitution maps",
"# - Element settings, such as icon for picture file or image source",
"# Generate map se... | 38.330159 | 0.000161 |
def namespace(self, elem=None):
"""return the URL, if any, for the doc root or elem, if given."""
if elem is None:
elem = self.root
return XML.tag_namespace(elem.tag) | [
"def",
"namespace",
"(",
"self",
",",
"elem",
"=",
"None",
")",
":",
"if",
"elem",
"is",
"None",
":",
"elem",
"=",
"self",
".",
"root",
"return",
"XML",
".",
"tag_namespace",
"(",
"elem",
".",
"tag",
")"
] | 40.4 | 0.009709 |
def add_child(self, name, child):
"""
Add a new child to the node.
:param name: Name of the child that must be used to access that child. Should not contain anything that could interfere with the operator `.` (dot).
:param child: The new child, an instance of :any:`Scale` or :any:`Param... | [
"def",
"add_child",
"(",
"self",
",",
"name",
",",
"child",
")",
":",
"if",
"name",
"in",
"self",
".",
"children",
":",
"raise",
"ValueError",
"(",
"\"{} has already a child named {}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"name",
")",
")",
"if... | 59.846154 | 0.008861 |
def binOp(op, indx, amap, bmap, fill_vec):
'''
Combines the values from two map objects using the indx values
using the op operator. In situations where there is a missing value
it will use the callable function handle_missing
'''
def op_or_missing(id):
va = amap.get(id, None)
... | [
"def",
"binOp",
"(",
"op",
",",
"indx",
",",
"amap",
",",
"bmap",
",",
"fill_vec",
")",
":",
"def",
"op_or_missing",
"(",
"id",
")",
":",
"va",
"=",
"amap",
".",
"get",
"(",
"id",
",",
"None",
")",
"vb",
"=",
"bmap",
".",
"get",
"(",
"id",
",... | 34.347826 | 0.001232 |
def read_atoms(fn, cycfn=None, pos_only=False, conv=1.0):
"""
Read atom information from an atoms.dat file (i.e., tblmd, MDCORE input file)
"""
f = paropen(fn, "r")
l = f.readline().lstrip()
while len(l) > 0 and ( l[0] == '#' or l[0] == '<' ):
l = f.readline().lstrip()
n_atoms = in... | [
"def",
"read_atoms",
"(",
"fn",
",",
"cycfn",
"=",
"None",
",",
"pos_only",
"=",
"False",
",",
"conv",
"=",
"1.0",
")",
":",
"f",
"=",
"paropen",
"(",
"fn",
",",
"\"r\"",
")",
"l",
"=",
"f",
".",
"readline",
"(",
")",
".",
"lstrip",
"(",
")",
... | 28.300813 | 0.022481 |
def paste_format(self):
"""Pastes cell formats
Pasting starts at cursor or at top left bbox corner
"""
row, col, tab = self.grid.actions.cursor
selection = self.get_selection()
if selection:
# Use selection rather than cursor for top left cell if present
... | [
"def",
"paste_format",
"(",
"self",
")",
":",
"row",
",",
"col",
",",
"tab",
"=",
"self",
".",
"grid",
".",
"actions",
".",
"cursor",
"selection",
"=",
"self",
".",
"get_selection",
"(",
")",
"if",
"selection",
":",
"# Use selection rather than cursor for to... | 34.791667 | 0.001165 |
def determine_master(port=4000):
"""Determine address of master so that workers
can connect to it. If the environment variable
SPARK_LOCAL_IP is set, that address will be used.
:param port: port on which the application runs
:return: Master address
Example usage:
SPARK_LOCAL_IP=127.0.0... | [
"def",
"determine_master",
"(",
"port",
"=",
"4000",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'SPARK_LOCAL_IP'",
")",
":",
"return",
"os",
".",
"environ",
"[",
"'SPARK_LOCAL_IP'",
"]",
"+",
"\":\"",
"+",
"str",
"(",
"port",
")",
"else",
... | 34.8125 | 0.001748 |
async def parse_response(self):
"""
:py:func:`asyncio.coroutine`
Parsing full server response (all lines).
:return: (code, lines)
:rtype: (:py:class:`aioftp.Code`, :py:class:`list` of :py:class:`str`)
:raises aioftp.StatusCodeError: if received code does not matches al... | [
"async",
"def",
"parse_response",
"(",
"self",
")",
":",
"code",
",",
"rest",
"=",
"await",
"self",
".",
"parse_line",
"(",
")",
"info",
"=",
"[",
"rest",
"]",
"curr_code",
"=",
"code",
"while",
"rest",
".",
"startswith",
"(",
"\"-\"",
")",
"or",
"no... | 34.333333 | 0.002361 |
def add_requirement(
self,
install_req, # type: InstallRequirement
parent_req_name=None, # type: Optional[str]
extras_requested=None # type: Optional[Iterable[str]]
):
# type: (...) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]] # noqa: E501
"""A... | [
"def",
"add_requirement",
"(",
"self",
",",
"install_req",
",",
"# type: InstallRequirement",
"parent_req_name",
"=",
"None",
",",
"# type: Optional[str]",
"extras_requested",
"=",
"None",
"# type: Optional[Iterable[str]]",
")",
":",
"# type: (...) -> Tuple[List[InstallRequirem... | 42.094828 | 0.0008 |
def find_item_in_path_by_type(self, si, path, obj_type):
"""
This function finds the first item of that type in path
:param ServiceInstance si: pyvmomi ServiceInstance
:param str path: the path to search in
:param type obj_type: the vim type of the object
:return: pyvmomi... | [
"def",
"find_item_in_path_by_type",
"(",
"self",
",",
"si",
",",
"path",
",",
"obj_type",
")",
":",
"if",
"obj_type",
"is",
"None",
":",
"return",
"None",
"search_index",
"=",
"si",
".",
"content",
".",
"searchIndex",
"sub_folder",
"=",
"si",
".",
"content... | 31.37037 | 0.002291 |
def align_two_alignments(aln1, aln2, moltype, params=None):
"""Returns an Alignment object from two existing Alignments.
aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be
used to build them.
params: dict of parameters to pass in to the Clustal app controller.
"""
#create... | [
"def",
"align_two_alignments",
"(",
"aln1",
",",
"aln2",
",",
"moltype",
",",
"params",
"=",
"None",
")",
":",
"#create SequenceCollection object from seqs",
"aln1",
"=",
"Alignment",
"(",
"aln1",
",",
"MolType",
"=",
"moltype",
")",
"#Create mapping between abbrevi... | 35.666667 | 0.016371 |
def run(connection):
"""
Parse arguments and start upload/download
"""
parser = argparse.ArgumentParser(description="""
Process database dumps.
Either download of upload a dump file to the objectstore.
downloads the latest dump and uploads with envronment and date
into given container... | [
"def",
"run",
"(",
"connection",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"\"\"\n Process database dumps.\n\n Either download of upload a dump file to the objectstore.\n\n downloads the latest dump and uploads with envronment and dat... | 23.898551 | 0.000582 |
def url_for(context, __route_name, **parts):
"""Filter for generating urls.
Usage: {{ url('the-view-name') }} might become "/path/to/view" or
{{ url('item-details', id=123, query={'active': 'true'}) }}
might become "/items/1?active=true".
"""
app = context['app']
query = None
if 'query... | [
"def",
"url_for",
"(",
"context",
",",
"__route_name",
",",
"*",
"*",
"parts",
")",
":",
"app",
"=",
"context",
"[",
"'app'",
"]",
"query",
"=",
"None",
"if",
"'query_'",
"in",
"parts",
":",
"query",
"=",
"parts",
".",
"pop",
"(",
"'query_'",
")",
... | 32.548387 | 0.000962 |
def complete(text, state):
"""On tab press, return the next possible completion"""
global completion_results
if state == 0:
line = readline.get_line_buffer()
if line.startswith(':'):
# Control command completion
completion_results = complete_control_command(line, text... | [
"def",
"complete",
"(",
"text",
",",
"state",
")",
":",
"global",
"completion_results",
"if",
"state",
"==",
"0",
":",
"line",
"=",
"readline",
".",
"get_line_buffer",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"':'",
")",
":",
"# Control command comp... | 42.030303 | 0.002114 |
def _get_rev(self, fpath):
"""
Get an SCM version number. Try svn and git.
"""
rev = None
try:
cmd = ["git", "log", "-n1", "--pretty=format:\"%h\"", fpath]
rev = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()[0]
except:
pas... | [
"def",
"_get_rev",
"(",
"self",
",",
"fpath",
")",
":",
"rev",
"=",
"None",
"try",
":",
"cmd",
"=",
"[",
"\"git\"",
",",
"\"log\"",
",",
"\"-n1\"",
",",
"\"--pretty=format:\\\"%h\\\"\"",
",",
"fpath",
"]",
"rev",
"=",
"Popen",
"(",
"cmd",
",",
"stdout"... | 30.615385 | 0.008526 |
def newline(self, copy_margin=True):
"""
Insert a line ending at the current position.
"""
if copy_margin:
self.insert_text('\n' + self.document.leading_whitespace_in_current_line)
else:
self.insert_text('\n') | [
"def",
"newline",
"(",
"self",
",",
"copy_margin",
"=",
"True",
")",
":",
"if",
"copy_margin",
":",
"self",
".",
"insert_text",
"(",
"'\\n'",
"+",
"self",
".",
"document",
".",
"leading_whitespace_in_current_line",
")",
"else",
":",
"self",
".",
"insert_text... | 33.25 | 0.010989 |
def Produce_Predictions(FileName,train,test):
"""
Produces predictions for testing set, based off of training set.
:param FileName: This is the csv file name we wish to have our predictions exported to.
:param train: This is the file name of a csv file that will be the training set.
:param test... | [
"def",
"Produce_Predictions",
"(",
"FileName",
",",
"train",
",",
"test",
")",
":",
"TestFileName",
"=",
"test",
"TrainFileName",
"=",
"train",
"trainDF",
"=",
"pd",
".",
"read_csv",
"(",
"train",
")",
"train",
"=",
"Feature_Engineering",
"(",
"train",
",",
... | 47.45 | 0.020661 |
def get_dir_walker(recursive, topdown=True, followlinks=False):
"""
Returns a recursive or a non-recursive directory walker.
:param recursive:
``True`` produces a recursive walker; ``False`` produces a non-recursive
walker.
:returns:
A walker function.
"""
if recursive:
... | [
"def",
"get_dir_walker",
"(",
"recursive",
",",
"topdown",
"=",
"True",
",",
"followlinks",
"=",
"False",
")",
":",
"if",
"recursive",
":",
"walk",
"=",
"partial",
"(",
"os",
".",
"walk",
",",
"topdown",
"=",
"topdown",
",",
"followlinks",
"=",
"followli... | 36.684211 | 0.008392 |
def close(self):
"""
Finalize the GDSII stream library.
"""
self._outfile.write(struct.pack('>2h', 4, 0x0400))
if self._close:
self._outfile.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_outfile",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'>2h'",
",",
"4",
",",
"0x0400",
")",
")",
"if",
"self",
".",
"_close",
":",
"self",
".",
"_outfile",
".",
"close",
"(",
")"
] | 27.714286 | 0.01 |
def preferred_height(self, cli, width, max_available_height, wrap_lines):
"""
Preferred height: as much as needed in order to display all the completions.
"""
complete_state = cli.current_buffer.complete_state
column_width = self._get_column_width(complete_state)
column_c... | [
"def",
"preferred_height",
"(",
"self",
",",
"cli",
",",
"width",
",",
"max_available_height",
",",
"wrap_lines",
")",
":",
"complete_state",
"=",
"cli",
".",
"current_buffer",
".",
"complete_state",
"column_width",
"=",
"self",
".",
"_get_column_width",
"(",
"c... | 52 | 0.008403 |
def cli():
"""Run the command line interface."""
args = docopt.docopt(__doc__, version=__VERSION__)
secure = args['--secure']
numberofwords = int(args['<numberofwords>'])
dictpath = args['--dict']
if dictpath is not None:
dictfile = open(dictpath)
else:
dictfile = load_strea... | [
"def",
"cli",
"(",
")",
":",
"args",
"=",
"docopt",
".",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"__VERSION__",
")",
"secure",
"=",
"args",
"[",
"'--secure'",
"]",
"numberofwords",
"=",
"int",
"(",
"args",
"[",
"'<numberofwords>'",
"]",
")",
"di... | 29.75 | 0.002037 |
def infer_returned_object(pyfunction, args):
"""Infer the `PyObject` this `PyFunction` returns after calling"""
object_info = pyfunction.pycore.object_info
result = object_info.get_exact_returned(pyfunction, args)
if result is not None:
return result
result = _infer_returned(pyfunction, args... | [
"def",
"infer_returned_object",
"(",
"pyfunction",
",",
"args",
")",
":",
"object_info",
"=",
"pyfunction",
".",
"pycore",
".",
"object_info",
"result",
"=",
"object_info",
".",
"get_exact_returned",
"(",
"pyfunction",
",",
"args",
")",
"if",
"result",
"is",
"... | 45.35 | 0.00216 |
def _parsed_pkg_info(self):
"""Parse and cache metadata"""
try:
return self._pkg_info
except AttributeError:
from email.parser import Parser
self._pkg_info = Parser().parsestr(self.get_metadata(self.PKG_INFO))
return self._pkg_info | [
"def",
"_parsed_pkg_info",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_pkg_info",
"except",
"AttributeError",
":",
"from",
"email",
".",
"parser",
"import",
"Parser",
"self",
".",
"_pkg_info",
"=",
"Parser",
"(",
")",
".",
"parsestr",
"(",
... | 37 | 0.009901 |
def delete(self, accountId):
"""Delete an account"""
acct = BaseAccount.get(accountId)
if not acct:
raise Exception('No such account found')
acct.delete()
auditlog(event='account.delete', actor=session['user'].username, data={'accountId': accountId})
return ... | [
"def",
"delete",
"(",
"self",
",",
"accountId",
")",
":",
"acct",
"=",
"BaseAccount",
".",
"get",
"(",
"accountId",
")",
"if",
"not",
"acct",
":",
"raise",
"Exception",
"(",
"'No such account found'",
")",
"acct",
".",
"delete",
"(",
")",
"auditlog",
"("... | 34.8 | 0.008403 |
def recipe(recipe):
"""Apply the given recipe to a node
Sets the run_list to the given recipe
If no nodes/hostname.json file exists, it creates one
"""
env.host_string = lib.get_env_host_string()
lib.print_header(
"Applying recipe '{0}' on node {1}".format(recipe, env.host_string))
... | [
"def",
"recipe",
"(",
"recipe",
")",
":",
"env",
".",
"host_string",
"=",
"lib",
".",
"get_env_host_string",
"(",
")",
"lib",
".",
"print_header",
"(",
"\"Applying recipe '{0}' on node {1}\"",
".",
"format",
"(",
"recipe",
",",
"env",
".",
"host_string",
")",
... | 34.117647 | 0.001678 |
def get_stakes(self):
"""List all your stakes.
Returns:
list of dicts: stakes
Each stake is a dict with the following fields:
* confidence (`decimal.Decimal`)
* roundNumber (`int`)
* tournamentId (`int`)
* soc (`d... | [
"def",
"get_stakes",
"(",
"self",
")",
":",
"query",
"=",
"\"\"\"\n query {\n user {\n stakeTxs {\n confidence\n insertedAt\n roundNumber\n tournamentId\n soc\n staker\n ... | 32.7 | 0.001979 |
def time(self):
"""!
@brief (list) Returns sampling times when dynamic is measured during simulation.
"""
if ( (self._ccore_sync_dynamic_pointer is not None) and ( (self._time is None) or (len(self._time) == 0) ) ):
self._time = wrapper.sync_dynamic_get_time(se... | [
"def",
"time",
"(",
"self",
")",
":",
"if",
"(",
"(",
"self",
".",
"_ccore_sync_dynamic_pointer",
"is",
"not",
"None",
")",
"and",
"(",
"(",
"self",
".",
"_time",
"is",
"None",
")",
"or",
"(",
"len",
"(",
"self",
".",
"_time",
")",
"==",
"0",
")"... | 42.444444 | 0.033333 |
def xyplot(points, title="", c="b", corner=1, lines=False):
"""
Return a ``vtkXYPlotActor`` that is a plot of `x` versus `y`,
where `points` is a list of `(x,y)` points.
:param int corner: assign position:
- 1, topleft,
- 2, topright,
- 3, bottomleft,
- 4, bottomrigh... | [
"def",
"xyplot",
"(",
"points",
",",
"title",
"=",
"\"\"",
",",
"c",
"=",
"\"b\"",
",",
"corner",
"=",
"1",
",",
"lines",
"=",
"False",
")",
":",
"c",
"=",
"vc",
".",
"getColor",
"(",
"c",
")",
"# allow different codings",
"array_x",
"=",
"vtk",
".... | 30.397059 | 0.000469 |
def all_nonperiodic_features(times, mags, errs,
magsarefluxes=False,
stetson_weightbytimediff=True):
'''This rolls up the feature functions above and returns a single dict.
NOTE: this doesn't calculate the CDPP to save time since binning and
smoothi... | [
"def",
"all_nonperiodic_features",
"(",
"times",
",",
"mags",
",",
"errs",
",",
"magsarefluxes",
"=",
"False",
",",
"stetson_weightbytimediff",
"=",
"True",
")",
":",
"# remove nans first",
"finiteind",
"=",
"npisfinite",
"(",
"times",
")",
"&",
"npisfinite",
"(... | 33.06 | 0.001763 |
def dumps(obj, protocol=None):
"""Serialize obj as a string of bytes allocated in memory
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed
between processes running the same Python version.
Set protocol=p... | [
"def",
"dumps",
"(",
"obj",
",",
"protocol",
"=",
"None",
")",
":",
"file",
"=",
"StringIO",
"(",
")",
"try",
":",
"cp",
"=",
"CloudPickler",
"(",
"file",
",",
"protocol",
"=",
"protocol",
")",
"cp",
".",
"dump",
"(",
"obj",
")",
"return",
"file",
... | 34.176471 | 0.001675 |
def __process_node(self, node: yaml.Node,
expected_type: Type) -> yaml.Node:
"""Processes a node.
This is the main function that implements yatiml's \
functionality. It figures out how to interpret this node \
(recognition), then applies syntactic sugar, and final... | [
"def",
"__process_node",
"(",
"self",
",",
"node",
":",
"yaml",
".",
"Node",
",",
"expected_type",
":",
"Type",
")",
"->",
"yaml",
".",
"Node",
":",
"logger",
".",
"info",
"(",
"'Processing node {} expecting type {}'",
".",
"format",
"(",
"node",
",",
"exp... | 42.647887 | 0.000968 |
def kallisto_table(kallisto_dir, index):
"""
convert kallisto output to a count table where the rows are
equivalence classes and the columns are cells
"""
quant_dir = os.path.join(kallisto_dir, "quant")
out_file = os.path.join(quant_dir, "matrix.csv")
if file_exists(out_file):
return... | [
"def",
"kallisto_table",
"(",
"kallisto_dir",
",",
"index",
")",
":",
"quant_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"kallisto_dir",
",",
"\"quant\"",
")",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"quant_dir",
",",
"\"matrix.csv\"",
... | 41.826087 | 0.001016 |
def _parse_00(ofile):
"""
return 00 outfile as a pandas DataFrame
"""
with open(ofile) as infile:
## read in the results summary from the end of the outfile
arr = np.array(
[" "] + infile.read().split("Summary of MCMC results\n\n\n")[1:][0]\
.strip().split())
... | [
"def",
"_parse_00",
"(",
"ofile",
")",
":",
"with",
"open",
"(",
"ofile",
")",
"as",
"infile",
":",
"## read in the results summary from the end of the outfile",
"arr",
"=",
"np",
".",
"array",
"(",
"[",
"\" \"",
"]",
"+",
"infile",
".",
"read",
"(",
")",
... | 28.272727 | 0.015552 |
def query_cached_package_list(self):
"""Return list of pickled package names from PYPI"""
if self.debug:
self.logger.debug("DEBUG: reading pickled cache file")
return cPickle.load(open(self.pkg_cache_file, "r")) | [
"def",
"query_cached_package_list",
"(",
"self",
")",
":",
"if",
"self",
".",
"debug",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"DEBUG: reading pickled cache file\"",
")",
"return",
"cPickle",
".",
"load",
"(",
"open",
"(",
"self",
".",
"pkg_cache_file... | 48.6 | 0.008097 |
def network_del_notif(self, tenant_id, tenant_name, net_id):
"""Network delete notification. """
if not self.fw_init:
return
self.network_delete_notif(tenant_id, tenant_name, net_id) | [
"def",
"network_del_notif",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
",",
"net_id",
")",
":",
"if",
"not",
"self",
".",
"fw_init",
":",
"return",
"self",
".",
"network_delete_notif",
"(",
"tenant_id",
",",
"tenant_name",
",",
"net_id",
")"
] | 42.8 | 0.009174 |
def _printTraceback(self, test, err):
"""Print a nicely formatted traceback.
:arg err: exc_info()-style traceback triple
:arg test: the test that precipitated this call
"""
# Don't bind third item to a local var; that can create
# circular refs which are expensive to co... | [
"def",
"_printTraceback",
"(",
"self",
",",
"test",
",",
"err",
")",
":",
"# Don't bind third item to a local var; that can create",
"# circular refs which are expensive to collect. See the",
"# sys.exc_info() docs.",
"exception_type",
",",
"exception_value",
"=",
"err",
"[",
"... | 40.282609 | 0.001054 |
def _advapi32_encrypt(cipher, key, data, iv, padding):
"""
Encrypts plaintext via CryptoAPI
:param cipher:
A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
"rc2", "rc4"
:param key:
The encryption key - a byte string 5-16 bytes long
:param data:
... | [
"def",
"_advapi32_encrypt",
"(",
"cipher",
",",
"key",
",",
"data",
",",
"iv",
",",
"padding",
")",
":",
"context_handle",
"=",
"None",
"key_handle",
"=",
"None",
"try",
":",
"context_handle",
",",
"key_handle",
"=",
"_advapi32_create_handles",
"(",
"cipher",
... | 26.189873 | 0.000932 |
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
"""
Combines signals from multiple instruments within
given bounds.
Parameters
----------
bounds1 : (min, max)
Bounds for selecting data on the axis of label1
D... | [
"def",
"add",
"(",
"self",
",",
"bounds1",
",",
"label1",
",",
"bounds2",
",",
"label2",
",",
"bin3",
",",
"label3",
",",
"data_label",
")",
":",
"# TODO Update for 2.7 compatability.",
"if",
"isinstance",
"(",
"data_label",
",",
"str",
")",
":",
"data_label... | 38.25 | 0.00236 |
def _analyze(self):
'''Run-once function to generate analysis over all series, considering both full and partial data.
Initializes the self.analysis dict which maps:
(non-reference) column/series -> 'full' and/or 'partial' -> stats dict returned by get_xy_dataset_statistics
'''... | [
"def",
"_analyze",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"analysis",
":",
"for",
"dseries",
"in",
"self",
".",
"data_series",
":",
"# Count number of non-NaN rows",
"dseries_count",
"=",
"self",
".",
"df",
"[",
"dseries",
"]",
".",
"count",
"(",... | 68.05 | 0.027888 |
def to_dict(self, **kw):
u"""Converts the lxml object to a dict.
possible kwargs:
without_comments: bool
"""
_, value = helpers.etree_to_dict(self._xml, **kw).popitem()
return value | [
"def",
"to_dict",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"_",
",",
"value",
"=",
"helpers",
".",
"etree_to_dict",
"(",
"self",
".",
"_xml",
",",
"*",
"*",
"kw",
")",
".",
"popitem",
"(",
")",
"return",
"value"
] | 28.375 | 0.008547 |
def networkBibCoupling(self, weighted = True, fullInfo = False, addCR = False):
"""Creates a bibliographic coupling network based on citations for the RecordCollection.
# Parameters
_weighted_ : `optional bool`
> Default `True`, if `True` the weight of the edges will be added to the n... | [
"def",
"networkBibCoupling",
"(",
"self",
",",
"weighted",
"=",
"True",
",",
"fullInfo",
"=",
"False",
",",
"addCR",
"=",
"False",
")",
":",
"progArgs",
"=",
"(",
"0",
",",
"\"Make a citation network for coupling\"",
")",
"if",
"metaknowledge",
".",
"VERBOSE_M... | 44.218182 | 0.016492 |
def put(self):
"""Update a credential by file path"""
cred_payload = utils.uni_to_str(json.loads(request.get_data()))
return self.manager.update_credential(cred_payload) | [
"def",
"put",
"(",
"self",
")",
":",
"cred_payload",
"=",
"utils",
".",
"uni_to_str",
"(",
"json",
".",
"loads",
"(",
"request",
".",
"get_data",
"(",
")",
")",
")",
"return",
"self",
".",
"manager",
".",
"update_credential",
"(",
"cred_payload",
")"
] | 47.5 | 0.010363 |
def publish_collated_document(cursor, model, parent_model):
"""Publish a given `module`'s collated content in the context of
the `parent_model`. Note, the model's content is expected to already
have the collated content. This will just persist that content to
the archive.
"""
html = bytes(cnxep... | [
"def",
"publish_collated_document",
"(",
"cursor",
",",
"model",
",",
"parent_model",
")",
":",
"html",
"=",
"bytes",
"(",
"cnxepub",
".",
"DocumentContentFormatter",
"(",
"model",
")",
")",
"sha1",
"=",
"hashlib",
".",
"new",
"(",
"'sha1'",
",",
"html",
"... | 35.315789 | 0.000725 |
def get_config(self, force=False):
"""
Returns a dictionary of all config.xml properties
If `force = True` then ignore any cached state and read config.xml
if possible
setup_omero_cli() must be called before this method to import the
correct omero module to minimise the... | [
"def",
"get_config",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
"and",
"not",
"self",
".",
"has_config",
"(",
")",
":",
"raise",
"Exception",
"(",
"'No config file'",
")",
"configxml",
"=",
"os",
".",
"path",
".",
"join",
... | 35.275862 | 0.001903 |
def chop(self, bits=1):
"""
Chops a BV into consecutive sub-slices. Obviously, the length of this BV must be a multiple of bits.
:returns: A list of smaller bitvectors, each ``bits`` in length. The first one will be the left-most (i.e.
most significant) bits.
"""
... | [
"def",
"chop",
"(",
"self",
",",
"bits",
"=",
"1",
")",
":",
"s",
"=",
"len",
"(",
"self",
")",
"if",
"s",
"%",
"bits",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"expression length (%d) should be a multiple of 'bits' (%d)\"",
"%",
"(",
"len",
"(",
"s... | 44.714286 | 0.015649 |
def getCall(self, n): #pylint: disable=invalid-name
"""
Args:
n: integer (index of function call)
Return:
SpyCall object (or None if the index is not valid)
"""
call_list = super(SinonSpy, self)._get_wrapper().call_list
if n >= 0 and n < len(call_l... | [
"def",
"getCall",
"(",
"self",
",",
"n",
")",
":",
"#pylint: disable=invalid-name",
"call_list",
"=",
"super",
"(",
"SinonSpy",
",",
"self",
")",
".",
"_get_wrapper",
"(",
")",
".",
"call_list",
"if",
"n",
">=",
"0",
"and",
"n",
"<",
"len",
"(",
"call_... | 32.214286 | 0.008621 |
def get_access_token(self):
'''
Returns an access token for the specified subscription.
This method uses a cache to limit the number of requests to the token service.
A fresh token can be re-used during its lifetime of 10 minutes. After a successful
request to the token service,... | [
"def",
"get_access_token",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"token",
"is",
"None",
")",
"or",
"(",
"datetime",
".",
"utcnow",
"(",
")",
">",
"self",
".",
"reuse_token_until",
")",
":",
"headers",
"=",
"{",
"'Ocp-Apim-Subscription-Key'",
":"... | 48.35 | 0.008114 |
def _code2xls(self, worksheets):
"""Writes code to xls file
Format: <row>\t<col>\t<tab>\t<code>\n
"""
code_array = self.code_array
xls_max_shape = self.xls_max_rows, self.xls_max_cols, self.xls_max_tabs
for key in code_array:
if all(kele < mele for kele, ... | [
"def",
"_code2xls",
"(",
"self",
",",
"worksheets",
")",
":",
"code_array",
"=",
"self",
".",
"code_array",
"xls_max_shape",
"=",
"self",
".",
"xls_max_rows",
",",
"self",
".",
"xls_max_cols",
",",
"self",
".",
"xls_max_tabs",
"for",
"key",
"in",
"code_array... | 38.555556 | 0.000937 |
def stop(self, signum=None, frame=None):
"""
handel's a termination signal
"""
BackgroundProcess.objects.filter(pk=self.process_id
).update(pid=0, last_update=now(), message='stopping..')
# run the cleanup
self.cleanup()
Ba... | [
"def",
"stop",
"(",
"self",
",",
"signum",
"=",
"None",
",",
"frame",
"=",
"None",
")",
":",
"BackgroundProcess",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"self",
".",
"process_id",
")",
".",
"update",
"(",
"pid",
"=",
"0",
",",
"last_update",
... | 49.818182 | 0.008961 |
def on_draw(self, e):
"""Draw all visuals."""
gloo.clear()
for visual in self.visuals:
logger.log(5, "Draw visual `%s`.", visual)
visual.on_draw() | [
"def",
"on_draw",
"(",
"self",
",",
"e",
")",
":",
"gloo",
".",
"clear",
"(",
")",
"for",
"visual",
"in",
"self",
".",
"visuals",
":",
"logger",
".",
"log",
"(",
"5",
",",
"\"Draw visual `%s`.\"",
",",
"visual",
")",
"visual",
".",
"on_draw",
"(",
... | 31.5 | 0.010309 |
def get_init_container(self,
init_command,
init_args,
env_vars,
context_mounts,
persistence_outputs,
persistence_data):
"""Pod init container for sett... | [
"def",
"get_init_container",
"(",
"self",
",",
"init_command",
",",
"init_args",
",",
"env_vars",
",",
"context_mounts",
",",
"persistence_outputs",
",",
"persistence_data",
")",
":",
"env_vars",
"=",
"to_list",
"(",
"env_vars",
",",
"check_none",
"=",
"True",
"... | 40.333333 | 0.009227 |
def list(self, search_opts=None, limit=None,
marker=None, sort_by=None, reverse=None):
"""Get a list of Jobs."""
query = base.get_query_string(search_opts, limit=limit, marker=marker,
sort_by=sort_by, reverse=reverse)
url = "/jobs%s" % query
... | [
"def",
"list",
"(",
"self",
",",
"search_opts",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"sort_by",
"=",
"None",
",",
"reverse",
"=",
"None",
")",
":",
"query",
"=",
"base",
".",
"get_query_string",
"(",
"search_opts",
... | 50.857143 | 0.008287 |
def next(self, start):
"""
Return a (marker_code, segment_offset) 2-tuple identifying and
locating the first marker in *stream* occuring after offset *start*.
The returned *segment_offset* points to the position immediately
following the 2-byte marker code, the start of the marke... | [
"def",
"next",
"(",
"self",
",",
"start",
")",
":",
"position",
"=",
"start",
"while",
"True",
":",
"# skip over any non-\\xFF bytes",
"position",
"=",
"self",
".",
"_offset_of_next_ff_byte",
"(",
"start",
"=",
"position",
")",
"# skip over any \\xFF padding bytes",... | 45.952381 | 0.00203 |
def minimal_residual(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None,
callback=None, residuals=None):
"""Minimal residual (MR) algorithm.
Solves the linear system Ax = b. Left preconditioning is supported.
Parameters
----------
A : array, matrix, sparse matrix, Linea... | [
"def",
"minimal_residual",
"(",
"A",
",",
"b",
",",
"x0",
"=",
"None",
",",
"tol",
"=",
"1e-5",
",",
"maxiter",
"=",
"None",
",",
"xtype",
"=",
"None",
",",
"M",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"residuals",
"=",
"None",
")",
":",
... | 29.676056 | 0.000689 |
def autodiscover(path=None, plugin_prefix='intake_'):
"""Scan for Intake plugin packages and return a dict of plugins.
This function searches path (or sys.path) for packages with names that
start with plugin_prefix. Those modules will be imported and scanned for
subclasses of intake.source.base.Plugin... | [
"def",
"autodiscover",
"(",
"path",
"=",
"None",
",",
"plugin_prefix",
"=",
"'intake_'",
")",
":",
"plugins",
"=",
"{",
"}",
"for",
"importer",
",",
"name",
",",
"ispkg",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"path",
"=",
"path",
")",
":",
"if",
... | 43.3125 | 0.000706 |
def _compile_control_flow_expression(self,
expr: Expression,
scope: Dict[str, TensorFluent],
batch_size: Optional[int] = None,
noise: Optional[List[tf.Tenso... | [
"def",
"_compile_control_flow_expression",
"(",
"self",
",",
"expr",
":",
"Expression",
",",
"scope",
":",
"Dict",
"[",
"str",
",",
"TensorFluent",
"]",
",",
"batch_size",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"noise",
":",
"Optional",
"[",
... | 51.615385 | 0.010973 |
def objwalk(obj, path=(), memo=None):
"""
Walks an arbitrary python pbject.
:param mixed obj: Any python object
:param tuple path: A tuple of the set attributes representing the path to the value
:param set memo: The list of attributes traversed thus far
:rtype <tuple<tuple>, <mixed>>: The pat... | [
"def",
"objwalk",
"(",
"obj",
",",
"path",
"=",
"(",
")",
",",
"memo",
"=",
"None",
")",
":",
"if",
"len",
"(",
"path",
")",
">",
"MAX_DEPTH",
"+",
"1",
":",
"yield",
"path",
",",
"obj",
"# Truncate it!",
"if",
"memo",
"is",
"None",
":",
"memo",
... | 36.764706 | 0.010133 |
def open_file(orig_file_path):
"""
Taking in a file path, attempt to open mock data files with it.
"""
unquoted = unquote(orig_file_path)
paths = [
convert_to_platform_safe(orig_file_path),
"%s/index.html" % (convert_to_platform_safe(orig_file_path)),
orig_file_path,
... | [
"def",
"open_file",
"(",
"orig_file_path",
")",
":",
"unquoted",
"=",
"unquote",
"(",
"orig_file_path",
")",
"paths",
"=",
"[",
"convert_to_platform_safe",
"(",
"orig_file_path",
")",
",",
"\"%s/index.html\"",
"%",
"(",
"convert_to_platform_safe",
"(",
"orig_file_pa... | 26.666667 | 0.00134 |
def connect_callbacks(self, callbacks_bag):
"""Connect callbacks specified in callbacks_bag with callbacks
defined in the ui definition.
Return a list with the name of the callbacks not connected.
"""
notconnected = []
for wname, builderobj in self.objects.items():
... | [
"def",
"connect_callbacks",
"(",
"self",
",",
"callbacks_bag",
")",
":",
"notconnected",
"=",
"[",
"]",
"for",
"wname",
",",
"builderobj",
"in",
"self",
".",
"objects",
".",
"items",
"(",
")",
":",
"missing",
"=",
"builderobj",
".",
"connect_commands",
"("... | 42 | 0.002328 |
def validate_intervals(intervals):
"""Checks that an (n, 2) interval ndarray is well-formed, and raises errors
if not.
Parameters
----------
intervals : np.ndarray, shape=(n, 2)
Array of interval start/end locations.
"""
# Validate interval shape
if intervals.ndim != 2 or inte... | [
"def",
"validate_intervals",
"(",
"intervals",
")",
":",
"# Validate interval shape",
"if",
"intervals",
".",
"ndim",
"!=",
"2",
"or",
"intervals",
".",
"shape",
"[",
"1",
"]",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'Intervals should be n-by-2 numpy ndarray,... | 33.521739 | 0.001261 |
def poke_array(self, store, name, elemtype, elements, container, visited, _stack):
"""abstract method"""
raise NotImplementedError | [
"def",
"poke_array",
"(",
"self",
",",
"store",
",",
"name",
",",
"elemtype",
",",
"elements",
",",
"container",
",",
"visited",
",",
"_stack",
")",
":",
"raise",
"NotImplementedError"
] | 48 | 0.020548 |
def controller_event(self, channel, contr_nr, contr_val):
"""Return the bytes for a MIDI controller event."""
return self.midi_event(CONTROLLER, channel, contr_nr, contr_val) | [
"def",
"controller_event",
"(",
"self",
",",
"channel",
",",
"contr_nr",
",",
"contr_val",
")",
":",
"return",
"self",
".",
"midi_event",
"(",
"CONTROLLER",
",",
"channel",
",",
"contr_nr",
",",
"contr_val",
")"
] | 62.666667 | 0.010526 |
def add(data, id, medium, credentials):
"""Adds the [medium] with the given id and data to the user's [medium]List.
:param data The data for the [medium] to add.
:param id The id of the data to add.
:param medium Anime or manga (tokens.Medium.ANIME or tokens.Medium.MANGA).
:raise ValueError Fo... | [
"def",
"add",
"(",
"data",
",",
"id",
",",
"medium",
",",
"credentials",
")",
":",
"_op",
"(",
"data",
",",
"id",
",",
"medium",
",",
"tokens",
".",
"Operations",
".",
"ADD",
",",
"credentials",
")"
] | 49.875 | 0.002463 |
def _bind_key(self, key, func):
u"""setup the mapping from key to call the function."""
if not callable(func):
print u"Trying to bind non method to keystroke:%s,%s"%(key,func)
raise ReadlineError(u"Trying to bind non method to keystroke:%s,%s,%s,%s"%(key,func,type(func),type(... | [
"def",
"_bind_key",
"(",
"self",
",",
"key",
",",
"func",
")",
":",
"if",
"not",
"callable",
"(",
"func",
")",
":",
"print",
"u\"Trying to bind non method to keystroke:%s,%s\"",
"%",
"(",
"key",
",",
"func",
")",
"raise",
"ReadlineError",
"(",
"u\"Trying to bi... | 62.125 | 0.021825 |
def mesh_other(mesh,
other,
samples=500,
scale=False,
icp_first=10,
icp_final=50):
"""
Align a mesh with another mesh or a PointCloud using
the principal axes of inertia as a starting point which
is refined by iterative closest p... | [
"def",
"mesh_other",
"(",
"mesh",
",",
"other",
",",
"samples",
"=",
"500",
",",
"scale",
"=",
"False",
",",
"icp_first",
"=",
"10",
",",
"icp_final",
"=",
"50",
")",
":",
"def",
"key_points",
"(",
"m",
",",
"count",
")",
":",
"\"\"\"\n Return a... | 33.871622 | 0.000388 |
def csv(self, path, mode=None, compression=None, sep=None, quote=None, escape=None,
header=None, nullValue=None, escapeQuotes=None, quoteAll=None, dateFormat=None,
timestampFormat=None, ignoreLeadingWhiteSpace=None, ignoreTrailingWhiteSpace=None,
charToEscapeQuoteEscaping=None, encod... | [
"def",
"csv",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"None",
",",
"compression",
"=",
"None",
",",
"sep",
"=",
"None",
",",
"quote",
"=",
"None",
",",
"escape",
"=",
"None",
",",
"header",
"=",
"None",
",",
"nullValue",
"=",
"None",
",",
"es... | 75.236111 | 0.008746 |
def _interval_to_seconds(interval, valid_units='smhdw'):
"""Convert the timeout duration to seconds.
The value must be of the form "<integer><unit>" where supported
units are s, m, h, d, w (seconds, minutes, hours, days, weeks).
Args:
interval: A "<integer><unit>" string.
valid_units: A list of suppor... | [
"def",
"_interval_to_seconds",
"(",
"interval",
",",
"valid_units",
"=",
"'smhdw'",
")",
":",
"if",
"not",
"interval",
":",
"return",
"None",
"try",
":",
"last_char",
"=",
"interval",
"[",
"-",
"1",
"]",
"if",
"last_char",
"==",
"'s'",
"and",
"'s'",
"in"... | 34.685714 | 0.009615 |
def to_unicode(s):
"""Return the object as unicode (only matters for Python 2.x).
If s is already Unicode, return s as is.
Otherwise, assume that s is UTF-8 encoded, and convert to Unicode.
:param (basestring) s: a str, unicode or other basestring object
:return (unicode): the object as unicode
... | [
"def",
"to_unicode",
"(",
"s",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"\"{} must be str or unicode.\"",
".",
"format",
"(",
"s",
")",
")",
"if",
"not",
"isinstance",
"(",
"s",... | 36.642857 | 0.001901 |
def list(region, profile):
"""
List all the CloudFormation stacks in the given region.
"""
ini_data = {}
environment = {}
if region:
environment['region'] = region
else:
environment['region'] = find_myself()
if profile:
environment['profile'] = profile
ini_... | [
"def",
"list",
"(",
"region",
",",
"profile",
")",
":",
"ini_data",
"=",
"{",
"}",
"environment",
"=",
"{",
"}",
"if",
"region",
":",
"environment",
"[",
"'region'",
"]",
"=",
"region",
"else",
":",
"environment",
"[",
"'region'",
"]",
"=",
"find_mysel... | 20.65 | 0.002315 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.