text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def arbiter(**params):
'''Obtain the ``arbiter``.
It returns the arbiter instance only if we are on the arbiter
context domain, otherwise it returns nothing.
'''
arbiter = get_actor()
if arbiter is None:
# Create the arbiter
return set_actor(_spawn_actor('arbiter', None, **param... | [
"def",
"arbiter",
"(",
"*",
"*",
"params",
")",
":",
"arbiter",
"=",
"get_actor",
"(",
")",
"if",
"arbiter",
"is",
"None",
":",
"# Create the arbiter",
"return",
"set_actor",
"(",
"_spawn_actor",
"(",
"'arbiter'",
",",
"None",
",",
"*",
"*",
"params",
")... | 30.5 | 0.002653 |
def WhereIs(self, prog, path=None, pathext=None, reject=[]):
"""Find prog in the path.
"""
if path is None:
try:
path = self['ENV']['PATH']
except KeyError:
pass
elif SCons.Util.is_String(path):
path = self.subst(path)
... | [
"def",
"WhereIs",
"(",
"self",
",",
"prog",
",",
"path",
"=",
"None",
",",
"pathext",
"=",
"None",
",",
"reject",
"=",
"[",
"]",
")",
":",
"if",
"path",
"is",
"None",
":",
"try",
":",
"path",
"=",
"self",
"[",
"'ENV'",
"]",
"[",
"'PATH'",
"]",
... | 34.52381 | 0.006711 |
def transmit_content_metadata(self, user):
"""
Transmit content metadata to integrated channel.
"""
exporter = self.get_content_metadata_exporter(user)
transmitter = self.get_content_metadata_transmitter()
transmitter.transmit(exporter.export()) | [
"def",
"transmit_content_metadata",
"(",
"self",
",",
"user",
")",
":",
"exporter",
"=",
"self",
".",
"get_content_metadata_exporter",
"(",
"user",
")",
"transmitter",
"=",
"self",
".",
"get_content_metadata_transmitter",
"(",
")",
"transmitter",
".",
"transmit",
... | 41 | 0.006826 |
def where(self, column, operator=Null(), value=None, boolean="and"):
"""
Add a where clause to the query
:param column: The column of the where clause, can also be a QueryBuilder instance for sub where
:type column: str|Builder
:param operator: The operator of the where clause
... | [
"def",
"where",
"(",
"self",
",",
"column",
",",
"operator",
"=",
"Null",
"(",
")",
",",
"value",
"=",
"None",
",",
"boolean",
"=",
"\"and\"",
")",
":",
"if",
"isinstance",
"(",
"column",
",",
"Builder",
")",
":",
"self",
".",
"_query",
".",
"add_n... | 31.4 | 0.003708 |
def find_location(rows, element_to_find):
'''Find the location of a piece in the puzzle.
Returns a tuple: row, column'''
for ir, row in enumerate(rows):
for ic, element in enumerate(row):
if element == element_to_find:
return ir, ic | [
"def",
"find_location",
"(",
"rows",
",",
"element_to_find",
")",
":",
"for",
"ir",
",",
"row",
"in",
"enumerate",
"(",
"rows",
")",
":",
"for",
"ic",
",",
"element",
"in",
"enumerate",
"(",
"row",
")",
":",
"if",
"element",
"==",
"element_to_find",
":... | 39.571429 | 0.003534 |
def gen_slide_seg_list(mm_begin, mm_end, seg_duration, slide_step):
"""
生成时间片开始时刻列表,时间片以slide_step步长进行滑动
:param mm_begin:
:param mm_end:
:param seg_duration:
:param slide_step:
:return:
"""
seg_begin_list = [i for i in
range(mm_begin, mm_end - seg_duration + 1, ... | [
"def",
"gen_slide_seg_list",
"(",
"mm_begin",
",",
"mm_end",
",",
"seg_duration",
",",
"slide_step",
")",
":",
"seg_begin_list",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"mm_begin",
",",
"mm_end",
"-",
"seg_duration",
"+",
"1",
",",
"slide_step",
")"... | 31.692308 | 0.002358 |
def filter_tree(tree):
"""Filter all 401 errors."""
to_remove = []
for elem in tree.findall('urldata'):
valid = elem.find('valid')
if valid is not None and valid.text == '0' and \
valid.attrib.get('result', '').startswith('401'):
to_remove.append(elem)
root = tree.... | [
"def",
"filter_tree",
"(",
"tree",
")",
":",
"to_remove",
"=",
"[",
"]",
"for",
"elem",
"in",
"tree",
".",
"findall",
"(",
"'urldata'",
")",
":",
"valid",
"=",
"elem",
".",
"find",
"(",
"'valid'",
")",
"if",
"valid",
"is",
"not",
"None",
"and",
"va... | 33.818182 | 0.002618 |
def select(read_streams, write_streams, timeout=0):
"""
Select the streams from `read_streams` that are ready for reading, and
streams from `write_streams` ready for writing.
Uses `select.select()` internally but only returns two lists of ready streams.
"""
exception_streams = []
try:
... | [
"def",
"select",
"(",
"read_streams",
",",
"write_streams",
",",
"timeout",
"=",
"0",
")",
":",
"exception_streams",
"=",
"[",
"]",
"try",
":",
"return",
"builtin_select",
".",
"select",
"(",
"read_streams",
",",
"write_streams",
",",
"exception_streams",
",",... | 27.75 | 0.002903 |
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True):
"""Evaluates by creating a MultiIndex containing evaluated data and index.
See `LazyResult`
Returns
-------
MultiIndex
MultiIndex with evaluated data.
"""
... | [
"def",
"evaluate",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"decode",
"=",
"True",
",",
"passes",
"=",
"None",
",",
"num_threads",
"=",
"1",
",",
"apply_experimental",
"=",
"True",
")",
":",
"evaluated_data",
"=",
"[",
"v",
".",
"evaluate",
"(",... | 34.071429 | 0.010204 |
def find_carbon_sources(model):
"""
Find all active carbon source reactions.
Parameters
----------
model : Model
A genome-scale metabolic model.
Returns
-------
list
The medium reactions with carbon input flux.
"""
try:
model.slim_optimize(error_value=N... | [
"def",
"find_carbon_sources",
"(",
"model",
")",
":",
"try",
":",
"model",
".",
"slim_optimize",
"(",
"error_value",
"=",
"None",
")",
"except",
"OptimizationError",
":",
"return",
"[",
"]",
"reactions",
"=",
"model",
".",
"reactions",
".",
"get_by_any",
"("... | 25 | 0.001481 |
def print_pixy_blocks(blocks):
""" Prints the Pixy blocks data."""
print("Detected " + str(len(blocks)) + " Pixy blocks:")
if len(blocks) > 0 and not "signature" in blocks[0]:
print("Something went wrong. This does not appear to be a printable block.")
board.shutdown()
return
fo... | [
"def",
"print_pixy_blocks",
"(",
"blocks",
")",
":",
"print",
"(",
"\"Detected \"",
"+",
"str",
"(",
"len",
"(",
"blocks",
")",
")",
"+",
"\" Pixy blocks:\"",
")",
"if",
"len",
"(",
"blocks",
")",
">",
"0",
"and",
"not",
"\"signature\"",
"in",
"blocks",
... | 51.545455 | 0.006932 |
def stop(self, bIgnoreExceptions = True):
"""
Stops debugging all processes.
If the kill on exit mode is on, debugged processes are killed when the
debugger is stopped. Otherwise when the debugger stops it detaches from
all debugged processes and leaves them running (default). F... | [
"def",
"stop",
"(",
"self",
",",
"bIgnoreExceptions",
"=",
"True",
")",
":",
"# Determine if we have a last debug event that we need to continue.",
"try",
":",
"event",
"=",
"self",
".",
"lastEvent",
"has_event",
"=",
"bool",
"(",
"event",
")",
"except",
"Exception"... | 34.214286 | 0.001353 |
def _searchable_form(self) -> 'Language':
"""
Convert a parsed language tag so that the information it contains is in
the best form for looking up information in the CLDR.
"""
if self._searchable is not None:
return self._searchable
self._searchable = self._f... | [
"def",
"_searchable_form",
"(",
"self",
")",
"->",
"'Language'",
":",
"if",
"self",
".",
"_searchable",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_searchable",
"self",
".",
"_searchable",
"=",
"self",
".",
"_filter_attributes",
"(",
"{",
"'language'"... | 37.833333 | 0.004301 |
def _fake_associatornames(self, namespace, **params):
# pylint: disable=invalid-name
"""
Implements a mock WBEM server responder for
:meth:`~pywbem.WBEMConnection.AssociatorNames`
"""
self._validate_namespace(namespace)
rc = None if params['ResultClass'] is None... | [
"def",
"_fake_associatornames",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"params",
")",
":",
"# pylint: disable=invalid-name",
"self",
".",
"_validate_namespace",
"(",
"namespace",
")",
"rc",
"=",
"None",
"if",
"params",
"[",
"'ResultClass'",
"]",
"is",
"... | 40.428571 | 0.001725 |
def resp_set_power(self, resp, power_level=None):
"""Default callback for get_power/set_power
"""
if power_level is not None:
self.power_level=power_level
elif resp:
self.power_level=resp.power_level | [
"def",
"resp_set_power",
"(",
"self",
",",
"resp",
",",
"power_level",
"=",
"None",
")",
":",
"if",
"power_level",
"is",
"not",
"None",
":",
"self",
".",
"power_level",
"=",
"power_level",
"elif",
"resp",
":",
"self",
".",
"power_level",
"=",
"resp",
"."... | 35.571429 | 0.015686 |
def Exp(self, m=None):
"""Exponentiates the probabilities.
m: how much to shift the ps before exponentiating
If m is None, normalizes so that the largest prob is 1.
"""
if not self.log:
raise ValueError("Pmf/Hist not under a log transform")
self.log = False
... | [
"def",
"Exp",
"(",
"self",
",",
"m",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"log",
":",
"raise",
"ValueError",
"(",
"\"Pmf/Hist not under a log transform\"",
")",
"self",
".",
"log",
"=",
"False",
"if",
"m",
"is",
"None",
":",
"m",
"=",
"se... | 27.5 | 0.004396 |
def existing_versions(self):
"""
Returns data with different cfgstr values that were previously computed
with this cacher.
Example:
>>> from ubelt.util_cache import Cacher
>>> # Ensure that some data exists
>>> known_fnames = set()
>>> cac... | [
"def",
"existing_versions",
"(",
"self",
")",
":",
"import",
"glob",
"pattern",
"=",
"join",
"(",
"self",
".",
"dpath",
",",
"self",
".",
"fname",
"+",
"'_*'",
"+",
"self",
".",
"ext",
")",
"for",
"fname",
"in",
"glob",
".",
"iglob",
"(",
"pattern",
... | 42.066667 | 0.001549 |
def _extract_model_params(self, defaults, **kwargs):
"""this method allows django managers use `objects.get_or_create` and
`objects.update_or_create` on a hashable object.
"""
obj = kwargs.pop(self.object_property_name, None)
if obj is not None:
kwargs['object_hash'] ... | [
"def",
"_extract_model_params",
"(",
"self",
",",
"defaults",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"kwargs",
".",
"pop",
"(",
"self",
".",
"object_property_name",
",",
"None",
")",
"if",
"obj",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'objec... | 46.916667 | 0.003484 |
def which(program, path=None):
"""
Returns the full path of shell commands.
Replicates the functionality of system which (1) command. Looks
for the named program in the directories indicated in the $PATH
environment variable, and returns the full path if found.
Examples:
>>> system.wh... | [
"def",
"which",
"(",
"program",
",",
"path",
"=",
"None",
")",
":",
"# If path is not given, read the $PATH environment variable.",
"path",
"=",
"path",
"or",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"abspath",
... | 27.6875 | 0.000727 |
def update_fit_box(self, new_fit=False):
"""
alters fit_box lists to match with changes in specimen or new/
removed interpretations
Parameters
----------
new_fit : boolean representing if there is a new fit
Alters
------
fit_box selection and cho... | [
"def",
"update_fit_box",
"(",
"self",
",",
"new_fit",
"=",
"False",
")",
":",
"# get new fit data",
"if",
"self",
".",
"s",
"in",
"list",
"(",
"self",
".",
"pmag_results_data",
"[",
"'specimens'",
"]",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"fit... | 32.25641 | 0.001543 |
def import_key(text=None,
filename=None,
user=None,
gnupghome=None):
r'''
Import a key from text or file
text
The text containing to import.
filename
The filename containing the key to import.
user
Which user's keychain to acces... | [
"def",
"import_key",
"(",
"text",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"user",
"=",
"None",
",",
"gnupghome",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'res'",
":",
"True",
",",
"'message'",
":",
"''",
"}",
"gpg",
"=",
"_create_gpg",
"(",... | 31.205479 | 0.000851 |
def PluginTagToContent(self, plugin_name):
"""Returns a dict mapping tags to content specific to that plugin.
Args:
plugin_name: The name of the plugin for which to fetch plugin-specific
content.
Raises:
KeyError: if the plugin name is not found.
Returns:
A dict mapping tags... | [
"def",
"PluginTagToContent",
"(",
"self",
",",
"plugin_name",
")",
":",
"if",
"plugin_name",
"not",
"in",
"self",
".",
"_plugin_to_tag_to_content",
":",
"raise",
"KeyError",
"(",
"'Plugin %r could not be found.'",
"%",
"plugin_name",
")",
"with",
"self",
".",
"_pl... | 38.210526 | 0.00672 |
def _expected_reads(run_info_file):
"""Parse the number of expected reads from the RunInfo.xml file.
"""
reads = []
if os.path.exists(run_info_file):
tree = ElementTree()
tree.parse(run_info_file)
read_elem = tree.find("Run/Reads")
reads = read_elem.findall("Read")
re... | [
"def",
"_expected_reads",
"(",
"run_info_file",
")",
":",
"reads",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"run_info_file",
")",
":",
"tree",
"=",
"ElementTree",
"(",
")",
"tree",
".",
"parse",
"(",
"run_info_file",
")",
"read_elem",
... | 32.6 | 0.002985 |
def feed_identities(self, msg_list, copy=True):
"""Split the identities from the rest of the message.
Feed until DELIM is reached, then return the prefix as idents and
remainder as msg_list. This is easily broken by setting an IDENT to DELIM,
but that would be silly.
Parameters... | [
"def",
"feed_identities",
"(",
"self",
",",
"msg_list",
",",
"copy",
"=",
"True",
")",
":",
"if",
"copy",
":",
"idx",
"=",
"msg_list",
".",
"index",
"(",
"DELIM",
")",
"return",
"msg_list",
"[",
":",
"idx",
"]",
",",
"msg_list",
"[",
"idx",
"+",
"1... | 38.583333 | 0.002809 |
def _archive_extensions():
"""Create translations from file extension to archive format
Returns
-------
dict
The mapping from file extension to archive format
dict
The mapping from archive format to default file extension
"""
if six.PY3:
... | [
"def",
"_archive_extensions",
"(",
")",
":",
"if",
"six",
".",
"PY3",
":",
"ext_map",
"=",
"{",
"}",
"fmt_map",
"=",
"{",
"}",
"for",
"key",
",",
"exts",
",",
"desc",
"in",
"shutil",
".",
"get_unpack_formats",
"(",
")",
":",
"fmt_map",
"[",
"key",
... | 34.09375 | 0.001783 |
def run_filter_radia(job, bams, radia_file, univ_options, radia_options, chrom):
"""
Run filterradia on the RADIA output.
:param dict bams: Dict of bam and bai for tumor DNA-Seq, normal DNA-Seq and tumor RNA-Seq
:param toil.fileStore.FileID radia_file: The vcf from runnning RADIA
:param dict univ_o... | [
"def",
"run_filter_radia",
"(",
"job",
",",
"bams",
",",
"radia_file",
",",
"univ_options",
",",
"radia_options",
",",
"chrom",
")",
":",
"work_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"input_files",
"=",
"{",
"'rna.bam'",
":",
"bams",
"[",
"'tumor_rna'",... | 48.272727 | 0.003076 |
def _mb_model(self, beta, mini_batch):
""" Creates the structure of the model (model matrices etc) for mini batch model
Parameters
----------
beta : np.ndarray
Contains untransformed starting values for the latent variables
mini_batch : int
Mini batch si... | [
"def",
"_mb_model",
"(",
"self",
",",
"beta",
",",
"mini_batch",
")",
":",
"Y",
"=",
"np",
".",
"array",
"(",
"self",
".",
"data",
"[",
"self",
".",
"max_lag",
":",
"]",
")",
"sample",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"len",
"(",
"... | 31.806452 | 0.005906 |
def list_nodes():
'''
List virtual machines
.. code-block:: bash
salt-cloud -Q
'''
session = _get_session()
vms = session.xenapi.VM.get_all_records()
ret = {}
for vm in vms:
record = session.xenapi.VM.get_record(vm)
if not record['is_a_template'] and not re... | [
"def",
"list_nodes",
"(",
")",
":",
"session",
"=",
"_get_session",
"(",
")",
"vms",
"=",
"session",
".",
"xenapi",
".",
"VM",
".",
"get_all_records",
"(",
")",
"ret",
"=",
"{",
"}",
"for",
"vm",
"in",
"vms",
":",
"record",
"=",
"session",
".",
"xe... | 37.870968 | 0.002492 |
def getModule(self, moduleName):
"""
Retrieve a JavaScript module cache from the file path cache.
@returns: Module cache for the named module.
@rtype: L{CachedJSModule}
"""
if moduleName not in self.moduleCache:
modulePath = FilePath(
athena.j... | [
"def",
"getModule",
"(",
"self",
",",
"moduleName",
")",
":",
"if",
"moduleName",
"not",
"in",
"self",
".",
"moduleCache",
":",
"modulePath",
"=",
"FilePath",
"(",
"athena",
".",
"jsDeps",
".",
"getModuleForName",
"(",
"moduleName",
")",
".",
"_cache",
"."... | 37.666667 | 0.003454 |
def _get_list_prefix(self, param_prefix):
"""
Given a query dict like
{
'Steps.member.1.Name': ['example1'],
'Steps.member.1.ActionOnFailure': ['TERMINATE_JOB_FLOW'],
'Steps.member.1.HadoopJarStep.Jar': ['streaming1.jar'],
'Steps.member.2.Name': ['... | [
"def",
"_get_list_prefix",
"(",
"self",
",",
"param_prefix",
")",
":",
"results",
"=",
"[",
"]",
"param_index",
"=",
"1",
"while",
"True",
":",
"index_prefix",
"=",
"\"{0}.{1}.\"",
".",
"format",
"(",
"param_prefix",
",",
"param_index",
")",
"new_items",
"="... | 35.918919 | 0.001465 |
def c_source(self):
"""Return strings."""
relocs = Relocs(
''.join(self.c_self_relocs()), *self.c_module_relocs()
)
return Source(
''.join(self.c_typedefs()),
'' if self.opts.no_structs else self.c_struct(),
''.join(self.c_hashes()),
... | [
"def",
"c_source",
"(",
"self",
")",
":",
"relocs",
"=",
"Relocs",
"(",
"''",
".",
"join",
"(",
"self",
".",
"c_self_relocs",
"(",
")",
")",
",",
"*",
"self",
".",
"c_module_relocs",
"(",
")",
")",
"return",
"Source",
"(",
"''",
".",
"join",
"(",
... | 33.076923 | 0.004525 |
def run_steps(spec, language="en"):
""" Can be called by the user from within a step definition to execute other steps. """
# The way this works is a little exotic, but I couldn't think of a better way to work around
# the fact that this has to be a global function and therefore cannot know about which ste... | [
"def",
"run_steps",
"(",
"spec",
",",
"language",
"=",
"\"en\"",
")",
":",
"# The way this works is a little exotic, but I couldn't think of a better way to work around",
"# the fact that this has to be a global function and therefore cannot know about which step",
"# runner to use (other th... | 47.866667 | 0.008197 |
def _get_popularity_baseline(self):
"""
Returns a new popularity model matching the data set this model was
trained with. Can be used for comparison purposes.
"""
response = self.__proxy__.get_popularity_baseline()
from .popularity_recommender import PopularityRecommen... | [
"def",
"_get_popularity_baseline",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"__proxy__",
".",
"get_popularity_baseline",
"(",
")",
"from",
".",
"popularity_recommender",
"import",
"PopularityRecommender",
"return",
"PopularityRecommender",
"(",
"response",
... | 36.1 | 0.005405 |
def get_rst_relation_root_nodes(docgraph, data=True, rst_namespace='rst'):
"""
yield all nodes that dominate one or more RST relations in the given
document graph (in no particular order).
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph which contains RST annota... | [
"def",
"get_rst_relation_root_nodes",
"(",
"docgraph",
",",
"data",
"=",
"True",
",",
"rst_namespace",
"=",
"'rst'",
")",
":",
"rel_attr",
"=",
"rst_namespace",
"+",
"':rel_name'",
"for",
"node_id",
",",
"node_attrs",
"in",
"docgraph",
".",
"nodes_iter",
"(",
... | 41.035714 | 0.001701 |
def meco_velocity(m1, m2, chi1, chi2):
"""
Returns the velocity of the minimum energy cutoff for 3.5pN (2.5pN spin)
Parameters
----------
m1 : float
First component mass in solar masses
m2 : float
Second component mass in solar masses
chi1 : float
First component dim... | [
"def",
"meco_velocity",
"(",
"m1",
",",
"m2",
",",
"chi1",
",",
"chi2",
")",
":",
"_",
",",
"energy2",
",",
"energy3",
",",
"energy4",
",",
"energy5",
",",
"energy6",
"=",
"_energy_coeffs",
"(",
"m1",
",",
"m2",
",",
"chi1",
",",
"chi2",
")",
"def"... | 29.888889 | 0.006002 |
async def sleep_async(self, seconds):
"""Lock the connection for a given number of seconds.
:param seconds: Length of time to lock the connection.
:type seconds: int
"""
try:
await self.lock_async()
await asyncio.sleep(seconds)
except asyncio.Time... | [
"async",
"def",
"sleep_async",
"(",
"self",
",",
"seconds",
")",
":",
"try",
":",
"await",
"self",
".",
"lock_async",
"(",
")",
"await",
"asyncio",
".",
"sleep",
"(",
"seconds",
")",
"except",
"asyncio",
".",
"TimeoutError",
":",
"_logger",
".",
"debug",... | 36.538462 | 0.00616 |
def IsEnabled(self, *args, **kwargs):
"check if all top menus are enabled"
for i in range(self.GetMenuCount()):
if not self.IsEnabledTop(i):
return False
return True | [
"def",
"IsEnabled",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"GetMenuCount",
"(",
")",
")",
":",
"if",
"not",
"self",
".",
"IsEnabledTop",
"(",
"i",
")",
":",
"return",
"False"... | 36.166667 | 0.009009 |
def experiments_predictions_image_set_create(self, experiment_id, run_id, filename):
"""Create a prediction image set from a given tar archive that was
produced as the result of a successful model run.
Returns None if the specified model run does not exist or did not
finish successfully... | [
"def",
"experiments_predictions_image_set_create",
"(",
"self",
",",
"experiment_id",
",",
"run_id",
",",
"filename",
")",
":",
"# Ensure that the model run exists and is in state SUCCESS",
"model_run",
"=",
"self",
".",
"experiments_predictions_get",
"(",
"experiment_id",
",... | 41.125 | 0.00212 |
def createTable(dbconn, pd):
"""Creates a database table for the given PacketDefinition."""
cols = ('%s %s' % (defn.name, getTypename(defn)) for defn in pd.fields)
sql = 'CREATE TABLE IF NOT EXISTS %s (%s)' % (pd.name, ', '.join(cols))
dbconn.execute(sql)
dbconn.commit() | [
"def",
"createTable",
"(",
"dbconn",
",",
"pd",
")",
":",
"cols",
"=",
"(",
"'%s %s'",
"%",
"(",
"defn",
".",
"name",
",",
"getTypename",
"(",
"defn",
")",
")",
"for",
"defn",
"in",
"pd",
".",
"fields",
")",
"sql",
"=",
"'CREATE TABLE IF NOT EXISTS %s ... | 41 | 0.006826 |
async def request(
self,
method: str,
endpoint: str,
*,
base_url: str = API_URL_SCAFFOLD,
headers: dict = None,
params: dict = None,
json: dict = None) -> dict:
"""Make a request against AirVisual."""
if not ... | [
"async",
"def",
"request",
"(",
"self",
",",
"method",
":",
"str",
",",
"endpoint",
":",
"str",
",",
"*",
",",
"base_url",
":",
"str",
"=",
"API_URL_SCAFFOLD",
",",
"headers",
":",
"dict",
"=",
"None",
",",
"params",
":",
"dict",
"=",
"None",
",",
... | 31.884615 | 0.002342 |
def unpack_bytes(self, obj_bytes, encoding=None):
"""Unpack a byte stream into a dictionary."""
assert self.bytes_to_dict or self.string_to_dict
encoding = encoding or self.default_encoding
LOGGER.debug('%r decoding %d bytes with encoding of %s',
self, len(obj_bytes)... | [
"def",
"unpack_bytes",
"(",
"self",
",",
"obj_bytes",
",",
"encoding",
"=",
"None",
")",
":",
"assert",
"self",
".",
"bytes_to_dict",
"or",
"self",
".",
"string_to_dict",
"encoding",
"=",
"encoding",
"or",
"self",
".",
"default_encoding",
"LOGGER",
".",
"deb... | 54.666667 | 0.004 |
def json2value(json_string, params=Null, flexible=False, leaves=False):
"""
:param json_string: THE JSON
:param params: STANDARD JSON PARAMS
:param flexible: REMOVE COMMENTS
:param leaves: ASSUME JSON KEYS ARE DOT-DELIMITED
:return: Python value
"""
if not is_text(json_string):
L... | [
"def",
"json2value",
"(",
"json_string",
",",
"params",
"=",
"Null",
",",
"flexible",
"=",
"False",
",",
"leaves",
"=",
"False",
")",
":",
"if",
"not",
"is_text",
"(",
"json_string",
")",
":",
"Log",
".",
"error",
"(",
"\"only unicode json accepted\"",
")"... | 38.971014 | 0.003627 |
def _from_dict(cls, _dict):
"""Initialize a KeywordsResult object from a json dictionary."""
args = {}
if 'count' in _dict:
args['count'] = _dict.get('count')
if 'relevance' in _dict:
args['relevance'] = _dict.get('relevance')
if 'text' in _dict:
... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'count'",
"in",
"_dict",
":",
"args",
"[",
"'count'",
"]",
"=",
"_dict",
".",
"get",
"(",
"'count'",
")",
"if",
"'relevance'",
"in",
"_dict",
":",
"args",
"[",
... | 41.133333 | 0.00317 |
def supported_versions(django, cms):
"""
Convert numeric and literal version information to numeric format
"""
cms_version = None
django_version = None
try:
cms_version = Decimal(cms)
except (ValueError, InvalidOperation):
try:
cms_version = CMS_VERSION_MATRIX[st... | [
"def",
"supported_versions",
"(",
"django",
",",
"cms",
")",
":",
"cms_version",
"=",
"None",
"django_version",
"=",
"None",
"try",
":",
"cms_version",
"=",
"Decimal",
"(",
"cms",
")",
"except",
"(",
"ValueError",
",",
"InvalidOperation",
")",
":",
"try",
... | 34.325581 | 0.003294 |
def analyzeParameters(expName, suite):
"""
Analyze the impact of each list parameter in this experiment
"""
print("\n================",expName,"=====================")
try:
expParams = suite.get_params(expName)
pprint.pprint(expParams)
for p in ["boost_strength", "k", "learning_rate", "weight_spa... | [
"def",
"analyzeParameters",
"(",
"expName",
",",
"suite",
")",
":",
"print",
"(",
"\"\\n================\"",
",",
"expName",
",",
"\"=====================\"",
")",
"try",
":",
"expParams",
"=",
"suite",
".",
"get_params",
"(",
"expName",
")",
"pprint",
".",
"p... | 37.125 | 0.017227 |
def _add_node(self, node, depth):
"""Add a node to the graph, and the stack."""
self._topmost_node.add_child(node, bool(depth[1]))
self._stack.append((depth, node)) | [
"def",
"_add_node",
"(",
"self",
",",
"node",
",",
"depth",
")",
":",
"self",
".",
"_topmost_node",
".",
"add_child",
"(",
"node",
",",
"bool",
"(",
"depth",
"[",
"1",
"]",
")",
")",
"self",
".",
"_stack",
".",
"append",
"(",
"(",
"depth",
",",
"... | 46.25 | 0.010638 |
def ekgi(selidx, row, element):
"""
Return an element of an entry in a column of integer type in a specified
row.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgi_c.html
:param selidx: Index of parent column in SELECT clause.
:type selidx: int
:param row: Row to fetch from.
... | [
"def",
"ekgi",
"(",
"selidx",
",",
"row",
",",
"element",
")",
":",
"selidx",
"=",
"ctypes",
".",
"c_int",
"(",
"selidx",
")",
"row",
"=",
"ctypes",
".",
"c_int",
"(",
"row",
")",
"element",
"=",
"ctypes",
".",
"c_int",
"(",
"element",
")",
"idata"... | 33.333333 | 0.00108 |
def split_by_extensions(filename):
""" Splits the filename string by the extension of the file
"""
parts = filename.split('.')
idx = len(parts) - 1
while FileFormat.is_file_format(parts[idx]):
parts[idx] = FileFormat(parts[idx])
idx -= 1
return ['.... | [
"def",
"split_by_extensions",
"(",
"filename",
")",
":",
"parts",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
"idx",
"=",
"len",
"(",
"parts",
")",
"-",
"1",
"while",
"FileFormat",
".",
"is_file_format",
"(",
"parts",
"[",
"idx",
"]",
")",
":",
"... | 39.333333 | 0.005525 |
def reproduce(past_analysis, plotting=False, data_folder=None,
srm_table=None, custom_stat_functions=None):
"""
Reproduce a previous analysis exported with :func:`latools.analyse.minimal_export`
For normal use, supplying `log_file` and specifying a plotting option should be
enough to repr... | [
"def",
"reproduce",
"(",
"past_analysis",
",",
"plotting",
"=",
"False",
",",
"data_folder",
"=",
"None",
",",
"srm_table",
"=",
"None",
",",
"custom_stat_functions",
"=",
"None",
")",
":",
"if",
"'.zip'",
"in",
"past_analysis",
":",
"dirpath",
"=",
"utils",... | 40.310811 | 0.003927 |
def birth(self):
'''
Create the individual (compute the spline curve)
'''
spline = scipy.interpolate.splrep(self.x, self.y)
self.y_int = scipy.interpolate.splev(self.x_int,spline) | [
"def",
"birth",
"(",
"self",
")",
":",
"spline",
"=",
"scipy",
".",
"interpolate",
".",
"splrep",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
")",
"self",
".",
"y_int",
"=",
"scipy",
".",
"interpolate",
".",
"splev",
"(",
"self",
".",
"x_int",
... | 30.666667 | 0.042328 |
def wrap_text(translations, linewrap=0):
"""Pretty print translations.
If linewrap is set to 0 disble line wrapping.
Parameters
----------
translations : list
List of word translations.
linewrap : int
Maximum line length before wrapping.
"""
# pylint: disable=too-many-l... | [
"def",
"wrap_text",
"(",
"translations",
",",
"linewrap",
"=",
"0",
")",
":",
"# pylint: disable=too-many-locals",
"def",
"wrap",
"(",
"text",
",",
"width",
"=",
"linewrap",
",",
"findent",
"=",
"0",
",",
"sindent",
"=",
"0",
",",
"bold",
"=",
"False",
"... | 33.836364 | 0.001044 |
def init(library: typing.Union[str, types.ModuleType]) -> None:
'''
Must be called at some point after import and before your event loop
is run.
Populates the asynclib instance of _AsyncLib with methods relevant to the
async library you are using.
The supported libraries at the moment are:
... | [
"def",
"init",
"(",
"library",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"types",
".",
"ModuleType",
"]",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"library",
",",
"types",
".",
"ModuleType",
")",
":",
"library",
"=",
"library",
".",
"__na... | 34.076923 | 0.003293 |
def update(cls,table, dic, Id):
""" Update row with Id from table. Set fields given by dic."""
if dic:
req = "UPDATE {table} SET {SET} WHERE id = " + cls.named_style.format('__id') + " RETURNING * "
r = abstractRequetesSQL.formate(req, SET=dic, table=table, args=dict(dic, __id=I... | [
"def",
"update",
"(",
"cls",
",",
"table",
",",
"dic",
",",
"Id",
")",
":",
"if",
"dic",
":",
"req",
"=",
"\"UPDATE {table} SET {SET} WHERE id = \"",
"+",
"cls",
".",
"named_style",
".",
"format",
"(",
"'__id'",
")",
"+",
"\" RETURNING * \"",
"r",
"=",
"... | 62.25 | 0.013861 |
def single_gate_params(gate, params=None):
"""Apply a single qubit gate to the qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
tuple: a tuple of U gate parameters (theta, phi, lam)
Raises:
QiskitError: if th... | [
"def",
"single_gate_params",
"(",
"gate",
",",
"params",
"=",
"None",
")",
":",
"if",
"gate",
"in",
"(",
"'U'",
",",
"'u3'",
")",
":",
"return",
"params",
"[",
"0",
"]",
",",
"params",
"[",
"1",
"]",
",",
"params",
"[",
"2",
"]",
"elif",
"gate",
... | 32.4 | 0.001499 |
def decode(self, session_data):
"""decodes the data to get back the session dict """
pickled = decodebytes(utf8(session_data))
return pickle.loads(pickled) | [
"def",
"decode",
"(",
"self",
",",
"session_data",
")",
":",
"pickled",
"=",
"decodebytes",
"(",
"utf8",
"(",
"session_data",
")",
")",
"return",
"pickle",
".",
"loads",
"(",
"pickled",
")"
] | 44 | 0.011173 |
def move_to(self, location):
"""Changes the location of this medium. Some medium types may support
changing the storage unit location by simply changing the value of the
associated property. In this case the operation is performed
immediately, and @a progress is returning a @c null refer... | [
"def",
"move_to",
"(",
"self",
",",
"location",
")",
":",
"if",
"not",
"isinstance",
"(",
"location",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"location can only be an instance of type basestring\"",
")",
"progress",
"=",
"self",
".",
"_call",
"... | 49.102564 | 0.003584 |
def reset(self):
"""
Resets state and uid set. To be called asap to free memory
"""
self.reached_limit = False
self.count = 0
self.seen.clear() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"reached_limit",
"=",
"False",
"self",
".",
"count",
"=",
"0",
"self",
".",
"seen",
".",
"clear",
"(",
")"
] | 26.428571 | 0.010471 |
def gen_stack_patches(patch_list,
nr_row=None, nr_col=None, border=None,
max_width=1000, max_height=1000,
bgcolor=255, viz=False, lclick_cb=None):
"""
Similar to :func:`stack_patches` but with a generator interface.
It takes a much-longer lis... | [
"def",
"gen_stack_patches",
"(",
"patch_list",
",",
"nr_row",
"=",
"None",
",",
"nr_col",
"=",
"None",
",",
"border",
"=",
"None",
",",
"max_width",
"=",
"1000",
",",
"max_height",
"=",
"1000",
",",
"bgcolor",
"=",
"255",
",",
"viz",
"=",
"False",
",",... | 34.421053 | 0.001487 |
def _gen_new_subtoken_list(
subtoken_counts, min_count, alphabet, reserved_tokens=None):
"""Generate candidate subtokens ordered by count, and new max subtoken length.
Add subtokens to the candiate list in order of length (longest subtokens
first). When a subtoken is added, the counts of each of its prefixes... | [
"def",
"_gen_new_subtoken_list",
"(",
"subtoken_counts",
",",
"min_count",
",",
"alphabet",
",",
"reserved_tokens",
"=",
"None",
")",
":",
"if",
"reserved_tokens",
"is",
"None",
":",
"reserved_tokens",
"=",
"RESERVED_TOKENS",
"# Create a list of (count, subtoken) for each... | 41.171429 | 0.010166 |
def compute_score(attr, mcmap, NN, feature, inst, nan_entries, headers, class_type, X, y, labels_std, data_type, near=True):
"""Flexible feature scoring method that can be used with any core Relief-based method. Scoring proceeds differently
based on whether endpoint is binary, multiclass, or continuous. This ... | [
"def",
"compute_score",
"(",
"attr",
",",
"mcmap",
",",
"NN",
",",
"feature",
",",
"inst",
",",
"nan_entries",
",",
"headers",
",",
"class_type",
",",
"X",
",",
"y",
",",
"labels_std",
",",
"data_type",
",",
"near",
"=",
"True",
")",
":",
"fname",
"=... | 63.67364 | 0.008023 |
def delete_lambda_deprecated(awsclient, function_name, s3_event_sources=[],
time_event_sources=[], delete_logs=False):
# FIXME: mutable default arguments!
"""Deprecated: please use delete_lambda!
:param awsclient:
:param function_name:
:param s3_event_sources:
:para... | [
"def",
"delete_lambda_deprecated",
"(",
"awsclient",
",",
"function_name",
",",
"s3_event_sources",
"=",
"[",
"]",
",",
"time_event_sources",
"=",
"[",
"]",
",",
"delete_logs",
"=",
"False",
")",
":",
"# FIXME: mutable default arguments!",
"unwire_deprecated",
"(",
... | 39.166667 | 0.002077 |
def save(filepath, obj, compressed=True):
"""
Save the object to a .npz file.
Parameters
----------
filepath : str
The path to save the file.
obj: `pypianoroll.Multitrack` objects
The object to be saved.
"""
if not isinstance(obj, Multitrack):
raise TypeError("S... | [
"def",
"save",
"(",
"filepath",
",",
"obj",
",",
"compressed",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"Multitrack",
")",
":",
"raise",
"TypeError",
"(",
"\"Support only `pypianoroll.Multitrack` class objects\"",
")",
"obj",
".",
"sa... | 26.2 | 0.002457 |
def unmount(self, remove_rw=False, allow_lazy=False):
"""Removes all ties of this disk to the filesystem, so the image can be unmounted successfully.
:raises SubsystemError: when one of the underlying commands fails. Some are swallowed.
:raises CleanupError: when actual cleanup fails. Some are ... | [
"def",
"unmount",
"(",
"self",
",",
"remove_rw",
"=",
"False",
",",
"allow_lazy",
"=",
"False",
")",
":",
"for",
"m",
"in",
"list",
"(",
"sorted",
"(",
"self",
".",
"volumes",
",",
"key",
"=",
"lambda",
"v",
":",
"v",
".",
"mountpoint",
"or",
"\"\"... | 39.527778 | 0.004801 |
def get_stats_summary_dict(self):
"""Returns basic stats.
Returns a `dict` with various counts and stats, see below.
"""
uptime = time.time() - self._established_time \
if self._established_time != 0 else -1
return {
stats.UPDATE_MSG_IN: self.get_count(Pe... | [
"def",
"get_stats_summary_dict",
"(",
"self",
")",
":",
"uptime",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_established_time",
"if",
"self",
".",
"_established_time",
"!=",
"0",
"else",
"-",
"1",
"return",
"{",
"stats",
".",
"UPDATE_MSG_IN",
... | 37.368421 | 0.002747 |
def get_reposts(self):
"""
https://vk.com/dev/wall.getReposts
"""
return self._session.fetch_items('wall.getReposts', self.from_json, count=1000, owner_id=self.from_id, post_id=self.id) | [
"def",
"get_reposts",
"(",
"self",
")",
":",
"return",
"self",
".",
"_session",
".",
"fetch_items",
"(",
"'wall.getReposts'",
",",
"self",
".",
"from_json",
",",
"count",
"=",
"1000",
",",
"owner_id",
"=",
"self",
".",
"from_id",
",",
"post_id",
"=",
"se... | 42.6 | 0.013825 |
def getObjDebugName(self, obj: Union[Interface, Unit, Param]) -> str:
"""
:see: doc of method on parent class
"""
return obj._getFullName() | [
"def",
"getObjDebugName",
"(",
"self",
",",
"obj",
":",
"Union",
"[",
"Interface",
",",
"Unit",
",",
"Param",
"]",
")",
"->",
"str",
":",
"return",
"obj",
".",
"_getFullName",
"(",
")"
] | 33.4 | 0.011696 |
def list_job_ids(self, skip=0, limit=20):
""" Returns a list of job ids on a queue """
return [str(x["_id"]) for x in self.collection.find(
{"status": "queued"},
sort=[("_id", -1 if self.is_reverse else 1)],
projection={"_id": 1})
] | [
"def",
"list_job_ids",
"(",
"self",
",",
"skip",
"=",
"0",
",",
"limit",
"=",
"20",
")",
":",
"return",
"[",
"str",
"(",
"x",
"[",
"\"_id\"",
"]",
")",
"for",
"x",
"in",
"self",
".",
"collection",
".",
"find",
"(",
"{",
"\"status\"",
":",
"\"queu... | 35.75 | 0.006826 |
def create_child(self, nurest_object, response_choice=None, async=False, callback=None, commit=True):
""" Add given nurest_object to the current object
For example, to add a child into a parent, you can call
parent.create_child(nurest_object=child)
Args:
nur... | [
"def",
"create_child",
"(",
"self",
",",
"nurest_object",
",",
"response_choice",
"=",
"None",
",",
"async",
"=",
"False",
",",
"callback",
"=",
"None",
",",
"commit",
"=",
"True",
")",
":",
"# if nurest_object.id:",
"# raise InternalConsitencyError(\"Cannot cre... | 50.633333 | 0.007106 |
def server_hardreset(host=None,
admin_username=None,
admin_password=None,
module=None):
'''
Performs a reset (reboot) operation on the managed server.
host
The chassis host.
admin_username
The username used to access the ch... | [
"def",
"server_hardreset",
"(",
"host",
"=",
"None",
",",
"admin_username",
"=",
"None",
",",
"admin_password",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"return",
"__execute_cmd",
"(",
"'serveraction hardreset'",
",",
"host",
"=",
"host",
",",
"adm... | 27.625 | 0.001093 |
def _filter_cache(self, dmap, kdims):
"""
Returns a filtered version of the DynamicMap cache leaving only
keys consistently with the newly specified values
"""
filtered = []
for key, value in dmap.data.items():
if not any(kd.values and v not in kd.values for k... | [
"def",
"_filter_cache",
"(",
"self",
",",
"dmap",
",",
"kdims",
")",
":",
"filtered",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"dmap",
".",
"data",
".",
"items",
"(",
")",
":",
"if",
"not",
"any",
"(",
"kd",
".",
"values",
"and",
"v",
"... | 40.6 | 0.007229 |
def column_or_1d(y, warn=False):
""" Ravel column or 1d numpy array, else raises an error
Parameters
----------
y : array-like
Returns
-------
y : array
"""
shape = np.shape(y)
if len(shape) == 1:
return np.ravel(y)
if len(shape) == 2 and shape[1] == 1:
if ... | [
"def",
"column_or_1d",
"(",
"y",
",",
"warn",
"=",
"False",
")",
":",
"shape",
"=",
"np",
".",
"shape",
"(",
"y",
")",
"if",
"len",
"(",
"shape",
")",
"==",
"1",
":",
"return",
"np",
".",
"ravel",
"(",
"y",
")",
"if",
"len",
"(",
"shape",
")"... | 27.958333 | 0.001441 |
def check_complete(self):
""" Runs completion flow for this task if it's finished. """
logger.debug('Running check_complete for task {0}'.format(self.name))
# Tasks not completed
if self.remote_not_complete() or self.local_not_complete():
self._start_check_timer()
... | [
"def",
"check_complete",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Running check_complete for task {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"# Tasks not completed",
"if",
"self",
".",
"remote_not_complete",
"(",
")",
"or",
"self",
... | 38.482759 | 0.001748 |
def get_mix_gen(self, sample):
"""Returns function that returns sequence of characters of a
given length from a given sample
"""
def mix(length):
result = "".join(random.choice(sample) for _ in xrange(length)).strip()
if len(result) == length:
retu... | [
"def",
"get_mix_gen",
"(",
"self",
",",
"sample",
")",
":",
"def",
"mix",
"(",
"length",
")",
":",
"result",
"=",
"\"\"",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"sample",
")",
"for",
"_",
"in",
"xrange",
"(",
"length",
")",
")",
".",
"st... | 37 | 0.007916 |
def add(self, source_id=None, file_path=None, profile_reference="",
timestamp_reception=None, training_metadata=[]):
"""
Add a profile resume to a sourced id.
Args:
source_id: <string>
source id
file_path: ... | [
"def",
"add",
"(",
"self",
",",
"source_id",
"=",
"None",
",",
"file_path",
"=",
"None",
",",
"profile_reference",
"=",
"\"\"",
",",
"timestamp_reception",
"=",
"None",
",",
"training_metadata",
"=",
"[",
"]",
")",
":",
"data",
"=",
"{",
"}",
"data",
"... | 45.387097 | 0.005567 |
def create_temporary_table(from_table, name=None, on_commit=None):
"""
Create a new temporary table from another table.
"""
from_table = from_table.__table__ if hasattr(from_table, "__table__") else from_table
name = name or f"temporary_{from_table.name}"
# copy the origin table into the meta... | [
"def",
"create_temporary_table",
"(",
"from_table",
",",
"name",
"=",
"None",
",",
"on_commit",
"=",
"None",
")",
":",
"from_table",
"=",
"from_table",
".",
"__table__",
"if",
"hasattr",
"(",
"from_table",
",",
"\"__table__\"",
")",
"else",
"from_table",
"name... | 35.592593 | 0.002026 |
def include(self, pattern):
"""Include files that match 'pattern'."""
found = [f for f in glob(pattern) if not os.path.isdir(f)]
self.extend(found)
return bool(found) | [
"def",
"include",
"(",
"self",
",",
"pattern",
")",
":",
"found",
"=",
"[",
"f",
"for",
"f",
"in",
"glob",
"(",
"pattern",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"f",
")",
"]",
"self",
".",
"extend",
"(",
"found",
")",
"return"... | 38.8 | 0.010101 |
def disassociate_success_node(self, parent, child):
"""Remove success node.
The resulatant 2 nodes will both become root nodes.
=====API DOCS=====
Remove success node.
:param parent: Primary key of parent node to disassociate success node from.
:type parent: int
... | [
"def",
"disassociate_success_node",
"(",
"self",
",",
"parent",
",",
"child",
")",
":",
"return",
"self",
".",
"_disassoc",
"(",
"self",
".",
"_forward_rel_name",
"(",
"'success'",
")",
",",
"parent",
",",
"child",
")"
] | 36.277778 | 0.00597 |
def cbk_qptdm_workflow(self, cbk):
"""
This callback is executed by the flow when bands_work.nscf_task reaches S_OK.
It computes the list of q-points for the W(q,G,G'), creates nqpt tasks
in the second work (QptdmWork), and connect the signals.
"""
scr_input = cbk.data["... | [
"def",
"cbk_qptdm_workflow",
"(",
"self",
",",
"cbk",
")",
":",
"scr_input",
"=",
"cbk",
".",
"data",
"[",
"\"input\"",
"]",
"# Use the WFK file produced by the second",
"# Task in the first Work (NSCF step).",
"nscf_task",
"=",
"self",
"[",
"0",
"]",
"[",
"1",
"]... | 32.068966 | 0.004175 |
def LoadChecksFromFiles(file_paths, overwrite_if_exists=True):
"""Load the checks defined in the specified files."""
loaded = []
for file_path in file_paths:
configs = LoadConfigsFromFile(file_path)
for conf in itervalues(configs):
check = Check(**conf)
# Validate will raise if the check doesn... | [
"def",
"LoadChecksFromFiles",
"(",
"file_paths",
",",
"overwrite_if_exists",
"=",
"True",
")",
":",
"loaded",
"=",
"[",
"]",
"for",
"file_path",
"in",
"file_paths",
":",
"configs",
"=",
"LoadConfigsFromFile",
"(",
"file_path",
")",
"for",
"conf",
"in",
"iterva... | 37.25 | 0.018003 |
def parse(self, argv):
"""Pop, parse and return the first self.nargs items from args.
if self.nargs > 1 a list of parsed values will be returned.
Raise BadNumberOfArguments or BadArgument on errors.
NOTE: argv may be modified in place by this method.
"""
... | [
"def",
"parse",
"(",
"self",
",",
"argv",
")",
":",
"if",
"len",
"(",
"argv",
")",
"<",
"self",
".",
"nargs",
":",
"raise",
"BadNumberOfArguments",
"(",
"self",
".",
"nargs",
",",
"len",
"(",
"argv",
")",
")",
"if",
"self",
".",
"nargs",
"==",
"1... | 39.785714 | 0.007018 |
def evaluate_at(self, eval_at, testcases, mode=None):
""" Sets the evaluation interation indices.
:param list eval_at: iteration indices where an evaluation should be performed
:param numpy.array testcases: testcases used for evaluation
"""
self.eval_at = eval_at
... | [
"def",
"evaluate_at",
"(",
"self",
",",
"eval_at",
",",
"testcases",
",",
"mode",
"=",
"None",
")",
":",
"self",
".",
"eval_at",
"=",
"eval_at",
"self",
".",
"log",
".",
"eval_at",
"=",
"eval_at",
"if",
"mode",
"is",
"None",
":",
"if",
"self",
".",
... | 37.25 | 0.009162 |
def makedirs(name):
"""helper function for python 2 and 3 to call os.makedirs()
avoiding an error if the directory to be created already exists"""
import os, errno
try:
os.makedirs(name)
except OSError as ex:
if ex.errno == errno.EEXIST and os.path.isdir(name):
# ign... | [
"def",
"makedirs",
"(",
"name",
")",
":",
"import",
"os",
",",
"errno",
"try",
":",
"os",
".",
"makedirs",
"(",
"name",
")",
"except",
"OSError",
"as",
"ex",
":",
"if",
"ex",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
"and",
"os",
".",
"path",
"... | 27.866667 | 0.00463 |
def get(name, function=None):
"""Get a setting.
`name` should be the name of the setting to look for. If the
optional argument `function` is passed, this will look for a
value local to the function before retrieving the global
value.
"""
if function is not None:... | [
"def",
"get",
"(",
"name",
",",
"function",
"=",
"None",
")",
":",
"if",
"function",
"is",
"not",
"None",
":",
"if",
"hasattr",
"(",
"function",
",",
"Settings",
".",
"FUNCTION_SETTINGS_NAME",
")",
":",
"if",
"name",
"in",
"getattr",
"(",
"function",
"... | 45.538462 | 0.004967 |
def get_fields(model, fields=None):
"""
Assigns fields for model.
"""
include = [f.strip() for f in fields.split(',')] if fields else None
return utils.get_fields(
model,
include
) | [
"def",
"get_fields",
"(",
"model",
",",
"fields",
"=",
"None",
")",
":",
"include",
"=",
"[",
"f",
".",
"strip",
"(",
")",
"for",
"f",
"in",
"fields",
".",
"split",
"(",
"','",
")",
"]",
"if",
"fields",
"else",
"None",
"return",
"utils",
".",
"ge... | 23.555556 | 0.004545 |
def register(model):
"""
Register the given model class and wrapped AlgoliaIndex class with the Algolia engine:
@register(Author)
class AuthorIndex(AlgoliaIndex):
pass
"""
from algoliasearch_django import AlgoliaIndex, register
def _algolia_engine_wrapper(index_class):
if ... | [
"def",
"register",
"(",
"model",
")",
":",
"from",
"algoliasearch_django",
"import",
"AlgoliaIndex",
",",
"register",
"def",
"_algolia_engine_wrapper",
"(",
"index_class",
")",
":",
"if",
"not",
"issubclass",
"(",
"index_class",
",",
"AlgoliaIndex",
")",
":",
"r... | 27.315789 | 0.003724 |
def send_command(self, cmd, priority=False):
"""
Flushes a command to the server as a bytes payload.
"""
if priority:
self._pending.insert(0, cmd)
else:
self._pending.append(cmd)
self._pending_size += len(cmd)
if self._pending_size > DEFAU... | [
"def",
"send_command",
"(",
"self",
",",
"cmd",
",",
"priority",
"=",
"False",
")",
":",
"if",
"priority",
":",
"self",
".",
"_pending",
".",
"insert",
"(",
"0",
",",
"cmd",
")",
"else",
":",
"self",
".",
"_pending",
".",
"append",
"(",
"cmd",
")",... | 30.416667 | 0.005319 |
def as_srec(self, number_of_data_bytes=32, address_length_bits=32):
"""Format the binary file as Motorola S-Records records and return
them as a string.
`number_of_data_bytes` is the number of data bytes in each
record.
`address_length_bits` is the number of address bits in eac... | [
"def",
"as_srec",
"(",
"self",
",",
"number_of_data_bytes",
"=",
"32",
",",
"address_length_bits",
"=",
"32",
")",
":",
"header",
"=",
"[",
"]",
"if",
"self",
".",
"_header",
"is",
"not",
"None",
":",
"record",
"=",
"pack_srec",
"(",
"'0'",
",",
"0",
... | 35.942308 | 0.001563 |
def _generate_iam_invoke_role_policy(self):
"""
Generate the policy for the IAM role used by API Gateway to invoke
the lambda function.
Terraform name: aws_iam_role.invoke_role
"""
invoke_pol = {
"Version": "2012-10-17",
"Statement": [
... | [
"def",
"_generate_iam_invoke_role_policy",
"(",
"self",
")",
":",
"invoke_pol",
"=",
"{",
"\"Version\"",
":",
"\"2012-10-17\"",
",",
"\"Statement\"",
":",
"[",
"{",
"\"Effect\"",
":",
"\"Allow\"",
",",
"\"Resource\"",
":",
"[",
"\"*\"",
"]",
",",
"\"Action\"",
... | 32.681818 | 0.002703 |
def islink(path):
'''
Equivalent to os.path.islink()
'''
if six.PY3 or not salt.utils.platform.is_windows():
return os.path.islink(path)
if not HAS_WIN32FILE:
log.error('Cannot check if %s is a link, missing required modules', path)
if not _is_reparse_point(path):
retur... | [
"def",
"islink",
"(",
"path",
")",
":",
"if",
"six",
".",
"PY3",
"or",
"not",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"islink",
"(",
"path",
")",
"if",
"not",
"HAS_WIN32FILE",
":",
... | 31.484848 | 0.002801 |
def add_key(self, key, label, notes=None):
"""Adds a new SSH key to the account.
:param string key: The SSH key to add
:param string label: The label for the key
:param string notes: Additional notes for the key
:returns: A dictionary of the new key's information.
"""
... | [
"def",
"add_key",
"(",
"self",
",",
"key",
",",
"label",
",",
"notes",
"=",
"None",
")",
":",
"order",
"=",
"{",
"'key'",
":",
"key",
",",
"'label'",
":",
"label",
",",
"'notes'",
":",
"notes",
",",
"}",
"return",
"self",
".",
"sshkey",
".",
"cre... | 30.6 | 0.004228 |
def _build_models_query(self, query):
"""
Builds a query from `query` that filters to documents only from registered models.
"""
registered_models_ct = self.build_models_list()
if registered_models_ct:
restrictions = [xapian.Query('%s%s' % (TERM_PREFIXES[DJANGO_CT], m... | [
"def",
"_build_models_query",
"(",
"self",
",",
"query",
")",
":",
"registered_models_ct",
"=",
"self",
".",
"build_models_list",
"(",
")",
"if",
"registered_models_ct",
":",
"restrictions",
"=",
"[",
"xapian",
".",
"Query",
"(",
"'%s%s'",
"%",
"(",
"TERM_PREF... | 42.538462 | 0.00708 |
def _find_dependant_trees(self, tree_obj):
""" returns list of trees that are dependent_on given tree_obj """
dependant_trees = []
for tree_name, tree in self.trees.items():
if tree_obj in tree.dependent_on:
dependant_trees.append(tree)
return dependant_trees | [
"def",
"_find_dependant_trees",
"(",
"self",
",",
"tree_obj",
")",
":",
"dependant_trees",
"=",
"[",
"]",
"for",
"tree_name",
",",
"tree",
"in",
"self",
".",
"trees",
".",
"items",
"(",
")",
":",
"if",
"tree_obj",
"in",
"tree",
".",
"dependent_on",
":",
... | 44.714286 | 0.00627 |
def parse_rrule(component, tz=UTC):
"""
Extract a dateutil.rrule object from an icalendar component. Also includes
the component's dtstart and exdate properties. The rdate and exrule
properties are not yet supported.
:param component: icalendar component
:param tz: timezone for DST handling... | [
"def",
"parse_rrule",
"(",
"component",
",",
"tz",
"=",
"UTC",
")",
":",
"if",
"component",
".",
"get",
"(",
"'rrule'",
")",
":",
"# component['rrule'] can be both a scalar and a list",
"rrules",
"=",
"component",
"[",
"'rrule'",
"]",
"if",
"not",
"isinstance",
... | 37.108696 | 0.005137 |
def set_timer(self, timer="wall"):
"""Set the timer function
Parameters
----------
timer : {'wall', 'cpu', or callable}
Timer function used to measure task running times.
'wall' uses `time.time`, 'cpu' uses `time.process_time`
Returns
---... | [
"def",
"set_timer",
"(",
"self",
",",
"timer",
"=",
"\"wall\"",
")",
":",
"if",
"timer",
"==",
"\"wall\"",
":",
"timer",
"=",
"time",
".",
"time",
"elif",
"timer",
"==",
"\"cpu\"",
":",
"try",
":",
"timer",
"=",
"time",
".",
"process_time",
"except",
... | 30.25 | 0.00267 |
def do_dots(self, value, *dots):
"""Evaluate dotted expressions at runtime."""
for dot in dots:
try:
value = getattr(value, dot)
except AttributeError:
value = value[dot]
if hasattr(value, '__call__'):
value = value()
... | [
"def",
"do_dots",
"(",
"self",
",",
"value",
",",
"*",
"dots",
")",
":",
"for",
"dot",
"in",
"dots",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"value",
",",
"dot",
")",
"except",
"AttributeError",
":",
"value",
"=",
"value",
"[",
"dot",
"]",
... | 32.9 | 0.005917 |
def difference(self, *iterables):
"""
Return a new set with elements in the set that are not in the
*iterables*.
"""
diff = self._set.difference(*iterables)
return self._fromset(diff, key=self._key) | [
"def",
"difference",
"(",
"self",
",",
"*",
"iterables",
")",
":",
"diff",
"=",
"self",
".",
"_set",
".",
"difference",
"(",
"*",
"iterables",
")",
"return",
"self",
".",
"_fromset",
"(",
"diff",
",",
"key",
"=",
"self",
".",
"_key",
")"
] | 34.285714 | 0.00813 |
def nn_dims(self, x, y, dims_x, dims_y, k=1, radius=np.inf, eps=0.0, p=2):
"""Find the k nearest neighbors of a subset of dims of x and y in the observed output data
@see Databag.nn() for argument description
@return distance and indexes of found nearest neighbors.
"""
assert le... | [
"def",
"nn_dims",
"(",
"self",
",",
"x",
",",
"y",
",",
"dims_x",
",",
"dims_y",
",",
"k",
"=",
"1",
",",
"radius",
"=",
"np",
".",
"inf",
",",
"eps",
"=",
"0.0",
",",
"p",
"=",
"2",
")",
":",
"assert",
"len",
"(",
"x",
")",
"==",
"len",
... | 56.904762 | 0.01893 |
def _create_bvals_bvecs(multiframe_dicom, bval_file, bvec_file, nifti, nifti_file):
"""
Write the bvals from the sorted dicom files to a bval file
Inspired by https://github.com/IBIC/ibicUtils/blob/master/ibicBvalsBvecs.py
"""
# create the empty arrays
number_of_stack_slices = common.get_ss_val... | [
"def",
"_create_bvals_bvecs",
"(",
"multiframe_dicom",
",",
"bval_file",
",",
"bvec_file",
",",
"nifti",
",",
"nifti_file",
")",
":",
"# create the empty arrays",
"number_of_stack_slices",
"=",
"common",
".",
"get_ss_value",
"(",
"multiframe_dicom",
"[",
"Tag",
"(",
... | 46.228571 | 0.005448 |
def data_group_type(self, group_data):
"""Return dict representation of group data.
Args:
group_data (dict|obj): The group data dict or object.
Returns:
dict: The group data in dict format.
"""
if isinstance(group_data, dict):
# process file ... | [
"def",
"data_group_type",
"(",
"self",
",",
"group_data",
")",
":",
"if",
"isinstance",
"(",
"group_data",
",",
"dict",
")",
":",
"# process file content",
"file_content",
"=",
"group_data",
".",
"pop",
"(",
"'fileContent'",
",",
"None",
")",
"if",
"file_conte... | 38.708333 | 0.003151 |
def show_run():
'''
Shortcut to run `show run` on switch
.. code-block:: bash
salt '*' onyx.cmd show_run
'''
try:
enable()
configure_terminal()
ret = sendline('show running-config')
configure_terminal_exit()
disable()
except TerminalException as ... | [
"def",
"show_run",
"(",
")",
":",
"try",
":",
"enable",
"(",
")",
"configure_terminal",
"(",
")",
"ret",
"=",
"sendline",
"(",
"'show running-config'",
")",
"configure_terminal_exit",
"(",
")",
"disable",
"(",
")",
"except",
"TerminalException",
"as",
"e",
"... | 22.111111 | 0.00241 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.