text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def range(self, axis=None):
""" Return range tuple along specified axis """
return (self.min(axis=axis), self.max(axis=axis)) | [
"def",
"range",
"(",
"self",
",",
"axis",
"=",
"None",
")",
":",
"return",
"(",
"self",
".",
"min",
"(",
"axis",
"=",
"axis",
")",
",",
"self",
".",
"max",
"(",
"axis",
"=",
"axis",
")",
")"
] | 46.333333 | 0.014184 |
def moving_average(a, length, mode='valid'):
"""
From ``bruges``
Computes the mean in a moving window. Naive implementation.
Example:
>>> test = np.array([1,9,9,9,9,9,9,2,3,9,2,2,3,1,1,1,1,3,4,9,9,9,8,3])
>>> moving_average(test, 7, mode='same')
[ 4.42857143, 5.57142857, 6.71... | [
"def",
"moving_average",
"(",
"a",
",",
"length",
",",
"mode",
"=",
"'valid'",
")",
":",
"pad",
"=",
"np",
".",
"floor",
"(",
"length",
"/",
"2",
")",
"if",
"mode",
"==",
"'full'",
":",
"pad",
"*=",
"2",
"pad",
"=",
"int",
"(",
"pad",
")",
"# M... | 30.444444 | 0.000707 |
def verify(self, key, alg=None):
"""Verifies a JWS token.
:param key: The (:class:`jwcrypto.jwk.JWK`) verification key.
:param alg: The signing algorithm (optional). usually the algorithm
is known as it is provided with the JOSE Headers of the token.
:raises InvalidJWSSigna... | [
"def",
"verify",
"(",
"self",
",",
"key",
",",
"alg",
"=",
"None",
")",
":",
"self",
".",
"verifylog",
"=",
"list",
"(",
")",
"self",
".",
"objects",
"[",
"'valid'",
"]",
"=",
"False",
"obj",
"=",
"self",
".",
"objects",
"if",
"'signature'",
"in",
... | 40.761905 | 0.001141 |
def _validate_charm(url, service_name, add_error):
"""Validate the given charm URL.
Use the given service name to describe possible errors.
Use the given add_error callable to register validation error.
If the URL is valid, return the corresponding charm reference object.
Return None otherwise.
... | [
"def",
"_validate_charm",
"(",
"url",
",",
"service_name",
",",
"add_error",
")",
":",
"if",
"url",
"is",
"None",
":",
"add_error",
"(",
"'no charm specified for service {}'",
".",
"format",
"(",
"service_name",
")",
")",
"return",
"None",
"if",
"not",
"isstri... | 33.769231 | 0.000738 |
def F(self,value):
""" set phenotype """
assert value.shape[0]==self._N, 'Dimension mismatch'
self._K = value.shape[1]
self._F = value
self.clear_cache('predict','Yres') | [
"def",
"F",
"(",
"self",
",",
"value",
")",
":",
"assert",
"value",
".",
"shape",
"[",
"0",
"]",
"==",
"self",
".",
"_N",
",",
"'Dimension mismatch'",
"self",
".",
"_K",
"=",
"value",
".",
"shape",
"[",
"1",
"]",
"self",
".",
"_F",
"=",
"value",
... | 34 | 0.023923 |
def _prepare_io_handler(self, handler):
"""Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done.
"""
logger.debug(" preparing handler: {0!r}".format(handler))
self._unprepared_pending.discard(handler)
ret = handler.p... | [
"def",
"_prepare_io_handler",
"(",
"self",
",",
"handler",
")",
":",
"logger",
".",
"debug",
"(",
"\" preparing handler: {0!r}\"",
".",
"format",
"(",
"handler",
")",
")",
"self",
".",
"_unprepared_pending",
".",
"discard",
"(",
"handler",
")",
"ret",
"=",
"... | 44.517241 | 0.002274 |
def handler(self, signum, frame): # pragma: no cover
'''Signal handler for this process'''
if signum == signal.SIGQUIT:
# QUIT - Finish processing, but don't do any more work after that
self.stop()
elif signum == signal.SIGUSR1:
# USR1 - Print the backtrace
... | [
"def",
"handler",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"# pragma: no cover",
"if",
"signum",
"==",
"signal",
".",
"SIGQUIT",
":",
"# QUIT - Finish processing, but don't do any more work after that",
"self",
".",
"stop",
"(",
")",
"elif",
"signum",
"... | 50.761905 | 0.001842 |
def set_mark(self):
"""Mark the current location and return its id so that the buffer can return later."""
self._bookmarks.append(self._offset)
return len(self._bookmarks) - 1 | [
"def",
"set_mark",
"(",
"self",
")",
":",
"self",
".",
"_bookmarks",
".",
"append",
"(",
"self",
".",
"_offset",
")",
"return",
"len",
"(",
"self",
".",
"_bookmarks",
")",
"-",
"1"
] | 49 | 0.015075 |
def get_artist_hotttnesss(self, cache=True):
"""Get our numerical description of how hottt a song's artist currently is
Args:
Kwargs:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
... | [
"def",
"get_artist_hotttnesss",
"(",
"self",
",",
"cache",
"=",
"True",
")",
":",
"if",
"not",
"(",
"cache",
"and",
"(",
"'artist_hotttnesss'",
"in",
"self",
".",
"cache",
")",
")",
":",
"response",
"=",
"self",
".",
"get_attribute",
"(",
"'profile'",
",... | 37.041667 | 0.013158 |
def rolling_windows(a, window):
"""Creates rolling-window 'blocks' of length `window` from `a`.
Note that the orientation of rows/columns follows that of pandas.
Example
-------
import numpy as np
onedim = np.arange(20)
twodim = onedim.reshape((5,4))
print(twodim)
[[ 0... | [
"def",
"rolling_windows",
"(",
"a",
",",
"window",
")",
":",
"if",
"window",
">",
"a",
".",
"shape",
"[",
"0",
"]",
":",
"raise",
"ValueError",
"(",
"\"Specified `window` length of {0} exceeds length of\"",
"\" `a`, {1}.\"",
".",
"format",
"(",
"window",
",",
... | 25.189655 | 0.000659 |
def fix_examples_dir(lib_dir):
"""rename examples dir to ``examples``"""
for x in lib_dir.dirs():
if x.name.lower() == EXAMPLES:
return
for x in lib_dir.dirs():
if x.name.lower() == EXAMPLES:
_fix_dir(x)
return
for x in lib_dir.dirs():
if 'exam... | [
"def",
"fix_examples_dir",
"(",
"lib_dir",
")",
":",
"for",
"x",
"in",
"lib_dir",
".",
"dirs",
"(",
")",
":",
"if",
"x",
".",
"name",
".",
"lower",
"(",
")",
"==",
"EXAMPLES",
":",
"return",
"for",
"x",
"in",
"lib_dir",
".",
"dirs",
"(",
")",
":"... | 29.176471 | 0.001953 |
def post_process(self):
""" Apply last 2D transforms"""
self.image.putdata(self.pixels)
self.image = self.image.transpose(Image.ROTATE_90) | [
"def",
"post_process",
"(",
"self",
")",
":",
"self",
".",
"image",
".",
"putdata",
"(",
"self",
".",
"pixels",
")",
"self",
".",
"image",
"=",
"self",
".",
"image",
".",
"transpose",
"(",
"Image",
".",
"ROTATE_90",
")"
] | 39.75 | 0.012346 |
def validate_settings(settings):
"""
`settings` is either a dictionary or an object containing Kronos settings
(e.g., the contents of conf/settings.py). This function checks that all
required settings are present and valid.
"""
# Validate `storage`
storage = _validate_and_get_value(settings, 'settings', ... | [
"def",
"validate_settings",
"(",
"settings",
")",
":",
"# Validate `storage`",
"storage",
"=",
"_validate_and_get_value",
"(",
"settings",
",",
"'settings'",
",",
"'storage'",
",",
"dict",
")",
"for",
"name",
",",
"options",
"in",
"storage",
".",
"iteritems",
"(... | 40.046154 | 0.009749 |
def crypto_sign(msg, sk):
"""Return signature+message given message and secret key.
The signature is the first SIGNATUREBYTES bytes of the return value.
A copy of msg is in the remainder."""
if len(sk) != SECRETKEYBYTES:
raise ValueError("Bad signing key length %d" % len(sk))
vkbytes = sk[PU... | [
"def",
"crypto_sign",
"(",
"msg",
",",
"sk",
")",
":",
"if",
"len",
"(",
"sk",
")",
"!=",
"SECRETKEYBYTES",
":",
"raise",
"ValueError",
"(",
"\"Bad signing key length %d\"",
"%",
"len",
"(",
"sk",
")",
")",
"vkbytes",
"=",
"sk",
"[",
"PUBLICKEYBYTES",
":... | 42.9 | 0.002283 |
def del_client(self, **kwargs):
"""
Registers a new client to the specified network.
Usage:
======= ===================================
Method URI
======= ===================================
DELETE /vtep/networks/{vni}/clients/{mac}
... | [
"def",
"del_client",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"body",
"=",
"self",
".",
"vtep_app",
".",
"del_client",
"(",
"*",
"*",
"kwargs",
")",
"except",
"(",
"BGPSpeakerNotFound",
",",
"DatapathNotFound",
",",
"VniNotFound",
",",... | 32.851064 | 0.001887 |
def team_absent(name, profile="github", **kwargs):
'''
Ensure a team is absent.
Example:
.. code-block:: yaml
ensure team test is present in github:
github.team_absent:
- name: 'test'
The following parameters are required:
name
This is the name o... | [
"def",
"team_absent",
"(",
"name",
",",
"profile",
"=",
"\"github\"",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"targe... | 26.04 | 0.00148 |
def get_all_parent_edges(self):
"""Return tuples for all parent GO IDs, containing current GO ID and parent GO ID."""
all_parent_edges = set()
for parent in self.parents:
all_parent_edges.add((self.item_id, parent.item_id))
all_parent_edges |= parent.get_all_parent_edges(... | [
"def",
"get_all_parent_edges",
"(",
"self",
")",
":",
"all_parent_edges",
"=",
"set",
"(",
")",
"for",
"parent",
"in",
"self",
".",
"parents",
":",
"all_parent_edges",
".",
"add",
"(",
"(",
"self",
".",
"item_id",
",",
"parent",
".",
"item_id",
")",
")",... | 49.571429 | 0.008499 |
def procesa_data_dia(self, key_dia, datos_para_procesar):
"""Procesa los datos descargados correspondientes a un día `key_dia`."""
return pvpc_procesa_datos_dia(key_dia, datos_para_procesar, verbose=self.verbose) | [
"def",
"procesa_data_dia",
"(",
"self",
",",
"key_dia",
",",
"datos_para_procesar",
")",
":",
"return",
"pvpc_procesa_datos_dia",
"(",
"key_dia",
",",
"datos_para_procesar",
",",
"verbose",
"=",
"self",
".",
"verbose",
")"
] | 75.333333 | 0.017544 |
def socket_ready(hostport):
"""
:param hostport: a pair (host, port) or a string (tcp://)host:port
:returns: True if the socket is ready and False otherwise
"""
if hasattr(hostport, 'startswith'):
# string representation of the hostport combination
if hostport.startswith('tcp://'):
... | [
"def",
"socket_ready",
"(",
"hostport",
")",
":",
"if",
"hasattr",
"(",
"hostport",
",",
"'startswith'",
")",
":",
"# string representation of the hostport combination",
"if",
"hostport",
".",
"startswith",
"(",
"'tcp://'",
")",
":",
"hostport",
"=",
"hostport",
"... | 35.882353 | 0.001597 |
def tempfile_get(target):
'''Get a temp filename for atomic download.'''
fn = '%s-%s.tmp' % (target, ''.join(random.Random().sample("0123456789abcdefghijklmnopqrstuvwxyz", 15)))
TEMP_FILES.add(fn)
return fn | [
"def",
"tempfile_get",
"(",
"target",
")",
":",
"fn",
"=",
"'%s-%s.tmp'",
"%",
"(",
"target",
",",
"''",
".",
"join",
"(",
"random",
".",
"Random",
"(",
")",
".",
"sample",
"(",
"\"0123456789abcdefghijklmnopqrstuvwxyz\"",
",",
"15",
")",
")",
")",
"TEMP_... | 42 | 0.028037 |
def _load_plugin_class(menu, name):
"""Load Custodia plugin
Entry points are preferred over dotted import path.
"""
group = 'custodia.{}'.format(menu)
eps = list(pkg_resources.iter_entry_points(group, name))
if len(eps) > 1:
raise ValueError(
"Multiple entry points for {} {}... | [
"def",
"_load_plugin_class",
"(",
"menu",
",",
"name",
")",
":",
"group",
"=",
"'custodia.{}'",
".",
"format",
"(",
"menu",
")",
"eps",
"=",
"list",
"(",
"pkg_resources",
".",
"iter_entry_points",
"(",
"group",
",",
"name",
")",
")",
"if",
"len",
"(",
... | 34.083333 | 0.001189 |
def extract(self, destination):
"""Extract the archive."""
with tarfile.open(self.archive, 'r:') as tar:
tar.extractall(path=destination) | [
"def",
"extract",
"(",
"self",
",",
"destination",
")",
":",
"with",
"tarfile",
".",
"open",
"(",
"self",
".",
"archive",
",",
"'r:'",
")",
"as",
"tar",
":",
"tar",
".",
"extractall",
"(",
"path",
"=",
"destination",
")"
] | 40.5 | 0.012121 |
def _get_meta_options(self) -> List[MetaOption]:
"""
Returns a list of :class:`MetaOption` instances that this factory supports.
"""
return [option if isinstance(option, MetaOption) else option()
for option in self._options] | [
"def",
"_get_meta_options",
"(",
"self",
")",
"->",
"List",
"[",
"MetaOption",
"]",
":",
"return",
"[",
"option",
"if",
"isinstance",
"(",
"option",
",",
"MetaOption",
")",
"else",
"option",
"(",
")",
"for",
"option",
"in",
"self",
".",
"_options",
"]"
] | 44.5 | 0.011029 |
def FillDepressions(
dem,
epsilon = False,
in_place = False,
topology = 'D8'
):
"""Fills all depressions in a DEM.
Args:
dem (rdarray): An elevation model
epsilon (float): If True, an epsilon gradient is imposed to all flat regions.
This ensures that ... | [
"def",
"FillDepressions",
"(",
"dem",
",",
"epsilon",
"=",
"False",
",",
"in_place",
"=",
"False",
",",
"topology",
"=",
"'D8'",
")",
":",
"if",
"type",
"(",
"dem",
")",
"is",
"not",
"rdarray",
":",
"raise",
"Exception",
"(",
"\"A richdem.rdarray or numpy.... | 26.765957 | 0.023006 |
def after_deactivate_transition_event(self):
"""Method triggered after a 'deactivate' transition for the current
AnalysisService is performed. Removes this service from the Analysis
Profiles or Analysis Request Templates where is assigned.
This function is called automatically by
... | [
"def",
"after_deactivate_transition_event",
"(",
"self",
")",
":",
"# Remove the service from profiles to which is assigned",
"profiles",
"=",
"self",
".",
"getBackReferences",
"(",
"'AnalysisProfileAnalysisService'",
")",
"for",
"profile",
"in",
"profiles",
":",
"profile",
... | 48.111111 | 0.002265 |
def prt_ver(self, prt):
"""Print version of GO-DAG for the GO and for GO slims."""
if self.ver_list is not None:
prt.write("# Versions:\n# {VER}\n\n".format(VER="\n# ".join(self.ver_list))) | [
"def",
"prt_ver",
"(",
"self",
",",
"prt",
")",
":",
"if",
"self",
".",
"ver_list",
"is",
"not",
"None",
":",
"prt",
".",
"write",
"(",
"\"# Versions:\\n# {VER}\\n\\n\"",
".",
"format",
"(",
"VER",
"=",
"\"\\n# \"",
".",
"join",
"(",
"self",
".",
... | 55 | 0.013453 |
def get_dsl_by_hash(self, node_hash: str) -> Optional[BaseEntity]:
"""Look up a node by the hash and returns the corresponding PyBEL node tuple."""
node = self.get_node_by_hash(node_hash)
if node is not None:
return node.as_bel() | [
"def",
"get_dsl_by_hash",
"(",
"self",
",",
"node_hash",
":",
"str",
")",
"->",
"Optional",
"[",
"BaseEntity",
"]",
":",
"node",
"=",
"self",
".",
"get_node_by_hash",
"(",
"node_hash",
")",
"if",
"node",
"is",
"not",
"None",
":",
"return",
"node",
".",
... | 52.2 | 0.011321 |
def store_mo(self, state, new_mo, overwrite=True): #pylint:disable=unused-argument
"""
Stores a memory object.
:param new_mo: the memory object
:param overwrite: whether to overwrite objects already in memory (if false, just fill in the holes)
"""
start, end = self._reso... | [
"def",
"store_mo",
"(",
"self",
",",
"state",
",",
"new_mo",
",",
"overwrite",
"=",
"True",
")",
":",
"#pylint:disable=unused-argument",
"start",
",",
"end",
"=",
"self",
".",
"_resolve_range",
"(",
"new_mo",
")",
"if",
"overwrite",
":",
"self",
".",
"stor... | 40.25 | 0.012146 |
def schemaSetValidOptions(self, options):
"""Sets the options to be used during the validation. """
ret = libxml2mod.xmlSchemaSetValidOptions(self._o, options)
return ret | [
"def",
"schemaSetValidOptions",
"(",
"self",
",",
"options",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlSchemaSetValidOptions",
"(",
"self",
".",
"_o",
",",
"options",
")",
"return",
"ret"
] | 47.75 | 0.010309 |
def _get_belief_package(stmt):
"""Return the belief packages of a given statement recursively."""
# This list will contain the belief packages for the given statement
belief_packages = []
# Iterate over all the support parents
for st in stmt.supports:
# Recursively get all the belief package... | [
"def",
"_get_belief_package",
"(",
"stmt",
")",
":",
"# This list will contain the belief packages for the given statement",
"belief_packages",
"=",
"[",
"]",
"# Iterate over all the support parents",
"for",
"st",
"in",
"stmt",
".",
"supports",
":",
"# Recursively get all the b... | 52.117647 | 0.001109 |
def do_revert(self, subcmd, opts, *args):
"""Restore pristine working copy file (undo most local edits).
usage:
revert PATH...
Note: this subcommand does not require network access, and resolves
any conflicted states. However, it does not restore removed directori... | [
"def",
"do_revert",
"(",
"self",
",",
"subcmd",
",",
"opts",
",",
"*",
"args",
")",
":",
"print",
"\"'svn %s' opts: %s\"",
"%",
"(",
"subcmd",
",",
"opts",
")",
"print",
"\"'svn %s' args: %s\"",
"%",
"(",
"subcmd",
",",
"args",
")"
] | 34.846154 | 0.008602 |
def load(self):
"""load ALL_VERS_DATA from disk"""
basepath = os.path.dirname(os.path.abspath(__file__))
filename = os.sep.join([basepath, c.FOLDER_JSON, c.FILE_GAME_VERSIONS])
Handler.ALL_VERS_DATA = {} # reset known data; do not retain defunct information
with open(filename, "r... | [
"def",
"load",
"(",
"self",
")",
":",
"basepath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"filename",
"=",
"os",
".",
"sep",
".",
"join",
"(",
"[",
"basepath",
",",
"c",
".",
"F... | 46.444444 | 0.014085 |
def pipe_loop(context=None, _INPUT=None, conf=None, embed=None, **kwargs):
"""An operator that loops over the input and performs the embedded
submodule. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipe2py.modules pipe like object (iterable of items)
embed :... | [
"def",
"pipe_loop",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"embed",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cust_func",
"=",
"get_cust_func",
"(",
"context",
",",
"conf",
",",
"embed",
",",
... | 35.967742 | 0.000873 |
def _genBgTerm_fromSNPs(self,vTot=0.5,vCommon=0.1,pCausal=0.5,plot=False):
""" generate """
if self.X is None:
print('Reading in all SNPs. This is slow.')
rv = plink_reader.readBED(self.bfile,useMAFencoding=True)
X = rv['snps']
else:
X = self.X... | [
"def",
"_genBgTerm_fromSNPs",
"(",
"self",
",",
"vTot",
"=",
"0.5",
",",
"vCommon",
"=",
"0.1",
",",
"pCausal",
"=",
"0.5",
",",
"plot",
"=",
"False",
")",
":",
"if",
"self",
".",
"X",
"is",
"None",
":",
"print",
"(",
"'Reading in all SNPs. This is slow.... | 31.25641 | 0.031822 |
def get_audio_metadata_old(fname):
""" retrieve the metadata from an MP3 file """
audio_dict = {}
print("IDv2 tag info for %s:" % fname)
try:
audio = mutagenx.id3.ID3(fname, translate=False)
except StandardError as err:
print("ERROR = " + str(err))
#else:
#print(audio.ppr... | [
"def",
"get_audio_metadata_old",
"(",
"fname",
")",
":",
"audio_dict",
"=",
"{",
"}",
"print",
"(",
"\"IDv2 tag info for %s:\"",
"%",
"fname",
")",
"try",
":",
"audio",
"=",
"mutagenx",
".",
"id3",
".",
"ID3",
"(",
"fname",
",",
"translate",
"=",
"False",
... | 25.472222 | 0.013655 |
def subvolume_get_default(path):
'''
Get the default subvolume of the filesystem path
path
Mount point for the subvolume
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_get_default /var/volumes/tmp
'''
cmd = ['btrfs', 'subvolume', 'get-default', path]
res... | [
"def",
"subvolume_get_default",
"(",
"path",
")",
":",
"cmd",
"=",
"[",
"'btrfs'",
",",
"'subvolume'",
",",
"'get-default'",
",",
"path",
"]",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
")",
"salt",
".",
"utils",
".",
"fsutils",
".",
... | 21.571429 | 0.001267 |
def run(self):
""" Append version number to vegas/__init__.py """
with open('src/vegas/__init__.py', 'a') as vfile:
vfile.write("\n__version__ = '%s'\n" % VEGAS_VERSION)
_build_py.run(self) | [
"def",
"run",
"(",
"self",
")",
":",
"with",
"open",
"(",
"'src/vegas/__init__.py'",
",",
"'a'",
")",
"as",
"vfile",
":",
"vfile",
".",
"write",
"(",
"\"\\n__version__ = '%s'\\n\"",
"%",
"VEGAS_VERSION",
")",
"_build_py",
".",
"run",
"(",
"self",
")"
] | 44.2 | 0.008889 |
def generate(data, format="auto"):
"""Converts input chemical formats to json and optimizes structure.
Args:
data: A string or file representing a chemical
format: The format of the `data` variable (default is 'auto')
The `format` can be any value specified by Open Babel
(http://openba... | [
"def",
"generate",
"(",
"data",
",",
"format",
"=",
"\"auto\"",
")",
":",
"# Support both files and strings and attempt to infer file type",
"try",
":",
"with",
"open",
"(",
"data",
")",
"as",
"in_file",
":",
"if",
"format",
"==",
"'auto'",
":",
"format",
"=",
... | 37.545455 | 0.002361 |
def _get_connection(self):
"""Make SSH connection to the IOS XE device.
The external ncclient library is used for creating this connection.
This method keeps state of any existing connections and reuses them if
already connected. Also interfaces (except management) are typically
... | [
"def",
"_get_connection",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_ncc_connection",
"and",
"self",
".",
"_ncc_connection",
".",
"connected",
":",
"return",
"self",
".",
"_ncc_connection",
"else",
":",
"# ncclient needs 'name' to be 'csr' in order to c... | 52.344828 | 0.001294 |
def apply_transformation(self, structure, return_ranked_list=False):
"""
Apply the transformation.
Args:
structure: input structure
return_ranked_list (bool): Whether or not multiple structures are
returned. If return_ranked_list is a number, that number ... | [
"def",
"apply_transformation",
"(",
"self",
",",
"structure",
",",
"return_ranked_list",
"=",
"False",
")",
":",
"num_remove_dict",
"=",
"{",
"}",
"total_combis",
"=",
"0",
"for",
"indices",
",",
"frac",
"in",
"zip",
"(",
"self",
".",
"indices",
",",
"self... | 46.968254 | 0.000662 |
def is_url(default_scheme='http', **kwargs):
"""Return a converter that converts a clean string to an URL."""
def converter(value):
if value is None:
return value
if '://' not in value and default_scheme:
value = '://'.join((default_scheme, value.strip()))
try:
... | [
"def",
"is_url",
"(",
"default_scheme",
"=",
"'http'",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"converter",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"value",
"if",
"'://'",
"not",
"in",
"value",
"and",
"default_scheme",
":"... | 37.166667 | 0.002188 |
def hxbyterle_decode(output_size, data):
"""Decode HxRLE data stream
If C-extension is not compiled it will use a (slower) Python equivalent
:param int output_size: the number of items when ``data`` is uncompressed
:param str data: a raw stream of data to be unpacked
:return numpy.array ou... | [
"def",
"hxbyterle_decode",
"(",
"output_size",
",",
"data",
")",
":",
"output",
"=",
"byterle_decoder",
"(",
"data",
",",
"output_size",
")",
"assert",
"len",
"(",
"output",
")",
"==",
"output_size",
"return",
"output"
] | 38.25 | 0.008511 |
def node_filters(self):
""" Dict[str, NodeFilter]: Returns the node filters for this selector. """
return {
name: filter for name, filter in iter(self.filters.items())
if isinstance(filter, NodeFilter)} | [
"def",
"node_filters",
"(",
"self",
")",
":",
"return",
"{",
"name",
":",
"filter",
"for",
"name",
",",
"filter",
"in",
"iter",
"(",
"self",
".",
"filters",
".",
"items",
"(",
")",
")",
"if",
"isinstance",
"(",
"filter",
",",
"NodeFilter",
")",
"}"
] | 39.666667 | 0.012346 |
def create(cls, event):
"""Create a new Release model."""
# Check if the release has already been received
release_id = event.payload['release']['id']
existing_release = Release.query.filter_by(
release_id=release_id,
).first()
if existing_release:
... | [
"def",
"create",
"(",
"cls",
",",
"event",
")",
":",
"# Check if the release has already been received",
"release_id",
"=",
"event",
".",
"payload",
"[",
"'release'",
"]",
"[",
"'id'",
"]",
"existing_release",
"=",
"Release",
".",
"query",
".",
"filter_by",
"(",... | 37.228571 | 0.001496 |
def add_pseudo_parameter_values(self):
"""
Add pseudo parameter values
:return: parameter values that have pseudo parameter in it
"""
if 'AWS::Region' not in self.parameter_values:
self.parameter_values['AWS::Region'] = boto3.session.Session().region_name | [
"def",
"add_pseudo_parameter_values",
"(",
"self",
")",
":",
"if",
"'AWS::Region'",
"not",
"in",
"self",
".",
"parameter_values",
":",
"self",
".",
"parameter_values",
"[",
"'AWS::Region'",
"]",
"=",
"boto3",
".",
"session",
".",
"Session",
"(",
")",
".",
"r... | 43 | 0.009772 |
def session_bus(**kwargs) :
"returns a Connection object for the current D-Bus session bus."
return \
Connection(dbus.Connection.bus_get(DBUS.BUS_SESSION, private = False)) \
.register_additional_standard(**kwargs) | [
"def",
"session_bus",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"Connection",
"(",
"dbus",
".",
"Connection",
".",
"bus_get",
"(",
"DBUS",
".",
"BUS_SESSION",
",",
"private",
"=",
"False",
")",
")",
".",
"register_additional_standard",
"(",
"*",
"*",
... | 46.8 | 0.021008 |
def check_block(block_id):
"""
Verify that a block ID is valid
>>> check_block(FIRST_BLOCK_MAINNET)
True
>>> check_block(FIRST_BLOCK_MAINNET-1)
False
>>> check_block(-1)
False
>>> check_block("abc")
False
>>> check_block(int(1e7) + 1)
False
>>> check_block(int(1e7) -... | [
"def",
"check_block",
"(",
"block_id",
")",
":",
"if",
"type",
"(",
"block_id",
")",
"not",
"in",
"[",
"int",
",",
"long",
"]",
":",
"return",
"False",
"if",
"BLOCKSTACK_TEST",
":",
"if",
"block_id",
"<=",
"0",
":",
"return",
"False",
"else",
":",
"i... | 19.242424 | 0.001499 |
def get_field_value_from_context(field_name, context_list):
"""
Helper to get field value from string path.
String '<context>' is used to go up on context stack. It just
can be used at the beginning of path: <context>.<context>.field_name_1
On the other hand, '<root>' is used to start lookup from fi... | [
"def",
"get_field_value_from_context",
"(",
"field_name",
",",
"context_list",
")",
":",
"field_path",
"=",
"field_name",
".",
"split",
"(",
"'.'",
")",
"if",
"field_path",
"[",
"0",
"]",
"==",
"'<root>'",
":",
"context_index",
"=",
"0",
"field_path",
".",
"... | 33.604651 | 0.001345 |
def sanitize_gff_file(gff_fname,
in_memory=True,
in_place=False):
"""
Sanitize a GFF file.
"""
db = None
if is_gff_db(gff_fname):
# It's a database filename, so load it
db = gffutils.FeatureDB(gff_fname)
else:
# Need to create a... | [
"def",
"sanitize_gff_file",
"(",
"gff_fname",
",",
"in_memory",
"=",
"True",
",",
"in_place",
"=",
"False",
")",
":",
"db",
"=",
"None",
"if",
"is_gff_db",
"(",
"gff_fname",
")",
":",
"# It's a database filename, so load it",
"db",
"=",
"gffutils",
".",
"Featu... | 33.307692 | 0.001122 |
def cmd_host(verbose):
"""Collect information about the host where habu is running.
Example:
\b
$ habu.host
{
"kernel": [
"Linux",
"demo123",
"5.0.6-200.fc29.x86_64",
"#1 SMP Wed Apr 3 15:09:51 UTC 2019",
"x86_64",
"x8... | [
"def",
"cmd_host",
"(",
"verbose",
")",
":",
"if",
"verbose",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"'%(message)s'",
")",
"print",
"(",
"\"Gather information about the host...\"",
",",
"file",
"=",
... | 22.066667 | 0.000964 |
def _verify(waiveredHdul):
"""
Verify that the input HDUList is for a waivered FITS file.
Parameters:
waiveredHdul HDUList object to be verified
Returns: None
Exceptions:
ValueError Input HDUList is not for a waivered FITS file
"""
if len... | [
"def",
"_verify",
"(",
"waiveredHdul",
")",
":",
"if",
"len",
"(",
"waiveredHdul",
")",
"==",
"2",
":",
"#",
"# There must be exactly 2 HDU's",
"#",
"if",
"waiveredHdul",
"[",
"0",
"]",
".",
"header",
"[",
"'NAXIS'",
"]",
">",
"0",
":",
"#",
"# The Prima... | 30.536585 | 0.002322 |
def DbExportDevice(self, argin):
""" Export a device to the database
:param argin: Str[0] = Device name
Str[1] = CORBA IOR
Str[2] = Device server process host name
Str[3] = Device server process PID or string ``null``
Str[4] = Device server process version
:type: tango.DevVarStringArray
... | [
"def",
"DbExportDevice",
"(",
"self",
",",
"argin",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"In DbExportDevice()\"",
")",
"if",
"len",
"(",
"argin",
")",
"<",
"5",
":",
"self",
".",
"warn_stream",
"(",
"\"DataBase::DbExportDevice(): insufficient ex... | 35.826087 | 0.002364 |
def hquad(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH,
zetaV, xdirect, quadargs, use_ne_eval, msrc, mrec):
r"""Hankel Transform using the ``QUADPACK`` library.
This routine uses the ``scipy.integrate.quad`` module, which in turn makes
use of the Fortran library ``QUADPACK``... | [
"def",
"hquad",
"(",
"zsrc",
",",
"zrec",
",",
"lsrc",
",",
"lrec",
",",
"off",
",",
"factAng",
",",
"depth",
",",
"ab",
",",
"etaH",
",",
"etaV",
",",
"zetaH",
",",
"zetaV",
",",
"xdirect",
",",
"quadargs",
",",
"use_ne_eval",
",",
"msrc",
",",
... | 33.690476 | 0.000343 |
def pop_event(self, event_name, timeout=DEFAULT_TIMEOUT):
"""Pop an event from its queue.
Return and remove the oldest entry of an event.
Block until an event of specified name is available or
times out if timeout is set.
Args:
event_name: Name of the event to be po... | [
"def",
"pop_event",
"(",
"self",
",",
"event_name",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"if",
"not",
"self",
".",
"started",
":",
"raise",
"IllegalStateError",
"(",
"\"Dispatcher needs to be started before popping.\"",
")",
"e_queue",
"=",
"self",
".... | 33.833333 | 0.001368 |
def connect(self):
"""Connect to vCenter server"""
try:
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
if self.config['no_ssl_verify']:
requests.packages.urllib3.disable_warnings()
context.verify_mode = ssl.CERT_NONE
self.si = Smart... | [
"def",
"connect",
"(",
"self",
")",
":",
"try",
":",
"context",
"=",
"ssl",
".",
"SSLContext",
"(",
"ssl",
".",
"PROTOCOL_TLSv1_2",
")",
"if",
"self",
".",
"config",
"[",
"'no_ssl_verify'",
"]",
":",
"requests",
".",
"packages",
".",
"urllib3",
".",
"d... | 36.205882 | 0.001582 |
def delete_instance(self, *args, **kwargs):
"""Send signals."""
self.pre_delete.send(self)
super(Model, self).delete_instance(*args, **kwargs)
self.post_delete.send(self) | [
"def",
"delete_instance",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"pre_delete",
".",
"send",
"(",
"self",
")",
"super",
"(",
"Model",
",",
"self",
")",
".",
"delete_instance",
"(",
"*",
"args",
",",
"*",
"*",
... | 39.6 | 0.009901 |
def dht_query(self, peer_id, *peer_ids, **kwargs):
"""Finds the closest Peer IDs to a given Peer ID by querying the DHT.
.. code-block:: python
>>> c.dht_query("/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDM … uvuJ")
[{'ID': 'QmPkFbxAQ7DeKD5VGSh9HQrdS574pyNzDmxJeGrRJxoucF',
... | [
"def",
"dht_query",
"(",
"self",
",",
"peer_id",
",",
"*",
"peer_ids",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"peer_id",
",",
")",
"+",
"peer_ids",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/dht/query'",
",",
"args",
",",... | 38.75 | 0.001799 |
def transform_rest_response(self, response_body):
"""Translates an apiserving REST response so it's ready to return.
Currently, the only thing that needs to be fixed here is indentation,
so it's consistent with what the live app will return.
Args:
response_body: A string containing the backend r... | [
"def",
"transform_rest_response",
"(",
"self",
",",
"response_body",
")",
":",
"body_json",
"=",
"json",
".",
"loads",
"(",
"response_body",
")",
"return",
"json",
".",
"dumps",
"(",
"body_json",
",",
"indent",
"=",
"1",
",",
"sort_keys",
"=",
"True",
")"
... | 34.857143 | 0.001996 |
def can_update_topics_to_announces(self, forum, user):
""" Given a forum, checks whether the user can change its topic types to announces. """
return (
self._perform_basic_permission_check(forum, user, 'can_edit_posts') and
self._perform_basic_permission_check(forum, user, 'can_p... | [
"def",
"can_update_topics_to_announces",
"(",
"self",
",",
"forum",
",",
"user",
")",
":",
"return",
"(",
"self",
".",
"_perform_basic_permission_check",
"(",
"forum",
",",
"user",
",",
"'can_edit_posts'",
")",
"and",
"self",
".",
"_perform_basic_permission_check",
... | 57.333333 | 0.014327 |
def expand(cls, match, expand):
"""
If use expand directly, the url-decoded context will be decoded again, which create a security
issue. Hack expand to quote the text before expanding
"""
return re._expand(match.re, cls._EncodedMatch(match), expand) | [
"def",
"expand",
"(",
"cls",
",",
"match",
",",
"expand",
")",
":",
"return",
"re",
".",
"_expand",
"(",
"match",
".",
"re",
",",
"cls",
".",
"_EncodedMatch",
"(",
"match",
")",
",",
"expand",
")"
] | 47.5 | 0.010345 |
def get_parent(self):
"""Return tile from previous zoom level."""
return None if self.zoom == 0 else self.tile_pyramid.tile(
self.zoom - 1, self.row // 2, self.col // 2
) | [
"def",
"get_parent",
"(",
"self",
")",
":",
"return",
"None",
"if",
"self",
".",
"zoom",
"==",
"0",
"else",
"self",
".",
"tile_pyramid",
".",
"tile",
"(",
"self",
".",
"zoom",
"-",
"1",
",",
"self",
".",
"row",
"//",
"2",
",",
"self",
".",
"col",... | 40.4 | 0.009709 |
def bottomAt(self, offset=0):
""" Returns point in the center of the region's bottom side (offset to the bottom
by ``offset``) """
return Location(self.getX() + (self.getW() / 2), self.getY() + self.getH() + offset) | [
"def",
"bottomAt",
"(",
"self",
",",
"offset",
"=",
"0",
")",
":",
"return",
"Location",
"(",
"self",
".",
"getX",
"(",
")",
"+",
"(",
"self",
".",
"getW",
"(",
")",
"/",
"2",
")",
",",
"self",
".",
"getY",
"(",
")",
"+",
"self",
".",
"getH",... | 59 | 0.016736 |
def show_prediction(estimator, doc, **kwargs):
""" Return an explanation of estimator prediction
as an IPython.display.HTML object. Use this function
to show information about classifier prediction in IPython.
:func:`show_prediction` accepts all
:func:`eli5.explain_prediction` arguments and all
... | [
"def",
"show_prediction",
"(",
"estimator",
",",
"doc",
",",
"*",
"*",
"kwargs",
")",
":",
"format_kwargs",
",",
"explain_kwargs",
"=",
"_split_kwargs",
"(",
"kwargs",
")",
"expl",
"=",
"explain_prediction",
"(",
"estimator",
",",
"doc",
",",
"*",
"*",
"ex... | 44.57047 | 0.000295 |
def segment_text(text, seg_regex=SEG_REGEX):
"""Return an iterator of segments in the text.
Args:
text (unicode): string of IPA Unicode text
seg_regex (_regex.Pattern): compiled regex defining a segment (base +
modifiers)
Return:
generator: segme... | [
"def",
"segment_text",
"(",
"text",
",",
"seg_regex",
"=",
"SEG_REGEX",
")",
":",
"for",
"m",
"in",
"seg_regex",
".",
"finditer",
"(",
"text",
")",
":",
"yield",
"m",
".",
"group",
"(",
"0",
")"
] | 30.846154 | 0.002421 |
def p_portfolio(I,sigma,r,alpha,beta):
"""p_portfolio -- modified markowitz model for portfolio optimization.
Parameters:
- I: set of items
- sigma[i]: standard deviation of item i
- r[i]: revenue of item i
- alpha: acceptance threshold
- beta: desired confidence level
... | [
"def",
"p_portfolio",
"(",
"I",
",",
"sigma",
",",
"r",
",",
"alpha",
",",
"beta",
")",
":",
"model",
"=",
"Model",
"(",
"\"p_portfolio\"",
")",
"x",
"=",
"{",
"}",
"for",
"i",
"in",
"I",
":",
"x",
"[",
"i",
"]",
"=",
"model",
".",
"addVar",
... | 31.62069 | 0.01164 |
def _post_process_apply(self, result_data, axis, try_scale=True):
"""Recompute the index after applying function.
Args:
result_data: a BaseFrameManager object.
axis: Target axis along which function was applied.
Returns:
A new PandasQueryCompiler.
""... | [
"def",
"_post_process_apply",
"(",
"self",
",",
"result_data",
",",
"axis",
",",
"try_scale",
"=",
"True",
")",
":",
"if",
"try_scale",
":",
"try",
":",
"internal_index",
"=",
"self",
".",
"compute_index",
"(",
"0",
",",
"result_data",
",",
"True",
")",
... | 43 | 0.001706 |
def listify(fn=None, wrapper=list):
"""
A decorator which wraps a function's return value in ``list(...)``.
Useful when an algorithm can be expressed more cleanly as a generator but
the function should return an list.
Example::
>>> @listify
... def get_lengths(iterable):
.... | [
"def",
"listify",
"(",
"fn",
"=",
"None",
",",
"wrapper",
"=",
"list",
")",
":",
"def",
"listify_return",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"listify_helper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"wrap... | 28.258065 | 0.001104 |
def check(text):
"""Check the text."""
err = "links.valid"
msg = u"Broken link: {}"
regex = re.compile(
r"""(?i)\b((?:https?://|www\d{0,3}[.]
|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+
|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)
|[^\s`!()\[\... | [
"def",
"check",
"(",
"text",
")",
":",
"err",
"=",
"\"links.valid\"",
"msg",
"=",
"u\"Broken link: {}\"",
"regex",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"(?i)\\b((?:https?://|www\\d{0,3}[.]\n |[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+\n |(\\([^\\s(... | 29.913043 | 0.001408 |
def log_to_file(status=True, filename=default_log_file, level=None):
"""Log events to a file.
Args:
status (bool, Optional, Default=True)
whether logging to file should be turned on(True) or off(False)
filename (string, Optional, Default=None) :
path of file to log to
... | [
"def",
"log_to_file",
"(",
"status",
"=",
"True",
",",
"filename",
"=",
"default_log_file",
",",
"level",
"=",
"None",
")",
":",
"if",
"status",
":",
"if",
"level",
"is",
"not",
"None",
":",
"logger",
".",
"setLevel",
"(",
"level",
")",
"try",
":",
"... | 33.371429 | 0.002496 |
def copyright(self) -> str: # noqa: A003
"""Generate a random copyright.
:return: Copyright of company.
"""
return '© {}, {}'.format(
self.company(),
self.company_type(abbr=True),
) | [
"def",
"copyright",
"(",
"self",
")",
"->",
"str",
":",
"# noqa: A003",
"return",
"'© {}, {}'.",
"f",
"ormat(",
"",
"self",
".",
"company",
"(",
")",
",",
"self",
".",
"company_type",
"(",
"abbr",
"=",
"True",
")",
",",
")"
] | 26.555556 | 0.008097 |
def _complete_values(self, symbol = ""):
"""Compiles a list of possible symbols that can hold a value in
place. These consist of local vars, global vars, and functions."""
result = {}
#Also add the subroutines from the module and its dependencies.
moddict = self._generic_filter_e... | [
"def",
"_complete_values",
"(",
"self",
",",
"symbol",
"=",
"\"\"",
")",
":",
"result",
"=",
"{",
"}",
"#Also add the subroutines from the module and its dependencies.",
"moddict",
"=",
"self",
".",
"_generic_filter_execs",
"(",
"self",
".",
"context",
".",
"module"... | 56.975 | 0.010354 |
def mppe_chap2_gen_keys(password, nt_response):
"""
3.3. Generating 128-bit Session Keys
When used in conjunction with MS-CHAP-2 authentication, the initial
MPPE session keys are derived from the peer's Windows NT password.
The first step is to obfuscate the peer's password using
NtPasswordHash() fun... | [
"def",
"mppe_chap2_gen_keys",
"(",
"password",
",",
"nt_response",
")",
":",
"password_hash",
"=",
"mschap",
".",
"nt_password_hash",
"(",
"password",
")",
"password_hash_hash",
"=",
"mschap",
".",
"hash_nt_password_hash",
"(",
"password_hash",
")",
"master_key",
"=... | 40.673469 | 0.00049 |
def _get_parent(self):
""":return: Remote origin as Proxy instance"""
_dir = os.path.dirname(self.path)
if is_repo(_dir):
return Local(_dir)
else:
return None | [
"def",
"_get_parent",
"(",
"self",
")",
":",
"_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"path",
")",
"if",
"is_repo",
"(",
"_dir",
")",
":",
"return",
"Local",
"(",
"_dir",
")",
"else",
":",
"return",
"None"
] | 29.714286 | 0.009346 |
def full_load_hours(network, boundaries=[], filename=None, two_cb=False):
"""Plot loading of lines in equivalten full load hours.
Parameters
----------
network: PyPSA network container
Holds topology of grid including results from powerflow analysis
filename: str or None
Save fi... | [
"def",
"full_load_hours",
"(",
"network",
",",
"boundaries",
"=",
"[",
"]",
",",
"filename",
"=",
"None",
",",
"two_cb",
"=",
"False",
")",
":",
"cmap",
"=",
"plt",
".",
"cm",
".",
"jet",
"array_line",
"=",
"[",
"[",
"'Line'",
"]",
"*",
"len",
"(",... | 33.783333 | 0.001438 |
def cublasDgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for real general matrix.
"""
status = _libcublas.cublasDgemv_v2(handle,
_CUBLAS_OP[trans], m, n,
ctypes.byref(ctypes.c_do... | [
"def",
"cublasDgemv",
"(",
"handle",
",",
"trans",
",",
"m",
",",
"n",
",",
"alpha",
",",
"A",
",",
"lda",
",",
"x",
",",
"incx",
",",
"beta",
",",
"y",
",",
"incy",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasDgemv_v2",
"(",
"handle",
","... | 42 | 0.001792 |
def calc_influence_arrays_for_abc(model_obj,
mle_est,
init_values,
epsilon,
**fit_kwargs):
"""
Calculates the empirical influence array and the 2nd order empirical
influenc... | [
"def",
"calc_influence_arrays_for_abc",
"(",
"model_obj",
",",
"mle_est",
",",
"init_values",
",",
"epsilon",
",",
"*",
"*",
"fit_kwargs",
")",
":",
"# Calculate the two arrays of finite difference terms needed for the",
"# various influence arrays that we want to calculate.",
"t... | 48.737705 | 0.00033 |
def _residual(self, x, in_filter, out_filter, stride,
activate_before_residual=False):
"""Residual unit with 2 sub layers."""
if activate_before_residual:
with tf.variable_scope('shared_activation'):
x = self._layer_norm('init_bn', x)
x = self._relu(x, self.hps.relu_leakine... | [
"def",
"_residual",
"(",
"self",
",",
"x",
",",
"in_filter",
",",
"out_filter",
",",
"stride",
",",
"activate_before_residual",
"=",
"False",
")",
":",
"if",
"activate_before_residual",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'shared_activation'",
")",
... | 35.6875 | 0.008525 |
def parse_string_unsafe(s, system=SI):
"""Attempt to parse a string with ambiguous units and try to make a
bitmath object out of it.
This may produce inaccurate results if parsing shell output. For
example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB
~= 2.666 KiB. See the documentation for all of... | [
"def",
"parse_string_unsafe",
"(",
"s",
",",
"system",
"=",
"SI",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"(",
"str",
",",
"unicode",
")",
")",
"and",
"not",
"isinstance",
"(",
"s",
",",
"numbers",
".",
"Number",
")",
":",
"raise",
"Val... | 34.780488 | 0.000682 |
def to_api_data(self, restrict_keys=None):
""" Returns a dict representation of this message prepared to be send
to the cloud
:param restrict_keys: a set of keys to restrict the returned
data to
:type restrict_keys: dict or set
:return: converted to cloud based keys
... | [
"def",
"to_api_data",
"(",
"self",
",",
"restrict_keys",
"=",
"None",
")",
":",
"cc",
"=",
"self",
".",
"_cc",
"# alias to shorten the code",
"message",
"=",
"{",
"cc",
"(",
"'subject'",
")",
":",
"self",
".",
"subject",
",",
"cc",
"(",
"'body'",
")",
... | 41.971429 | 0.000998 |
def get_cache_data(request):
if 'init' in request.POST:
init = bool(float(request.POST['init']))
else:
init = False
active_variables = []
if 'variables[]' in request.POST:
active_variables = request.POST.getlist('variables[]')
"""
else:
active_variables = list(
... | [
"def",
"get_cache_data",
"(",
"request",
")",
":",
"if",
"'init'",
"in",
"request",
".",
"POST",
":",
"init",
"=",
"bool",
"(",
"float",
"(",
"request",
".",
"POST",
"[",
"'init'",
"]",
")",
")",
"else",
":",
"init",
"=",
"False",
"active_variables",
... | 35.557143 | 0.002346 |
def parse(self):
"""
Parse the netstat output file
:return: status of the metric parse
"""
# sample netstat output: 2014-04-02 15:44:02.86612 tcp 9600 0 host1.localdomain.com.:21567 remote.remotedomain.com:51168 ESTABLISH pid/process
data = {} # stores the data of each sub-metric
f... | [
"def",
"parse",
"(",
"self",
")",
":",
"# sample netstat output: 2014-04-02 15:44:02.86612\ttcp 9600 0 host1.localdomain.com.:21567 remote.remotedomain.com:51168 ESTABLISH pid/process",
"data",
"=",
"{",
"}",
"# stores the data of each sub-metric",
"for",
"infile",
"in",
"self... | 44.277778 | 0.013505 |
def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
'''
nlines = []
edited = False
value = six.text_type(value)
# create /e... | [
"def",
"persist",
"(",
"name",
",",
"value",
",",
"config",
"=",
"'/etc/sysctl.conf'",
")",
":",
"nlines",
"=",
"[",
"]",
"edited",
"=",
"False",
"value",
"=",
"six",
".",
"text_type",
"(",
"value",
")",
"# create /etc/sysctl.conf if not present",
"if",
"not... | 30.508772 | 0.000557 |
def listing(self):
"Return a list of filename entries currently in the archive"
return ['.'.join([f,ext]) if ext else f for (f,ext) in self._files.keys()] | [
"def",
"listing",
"(",
"self",
")",
":",
"return",
"[",
"'.'",
".",
"join",
"(",
"[",
"f",
",",
"ext",
"]",
")",
"if",
"ext",
"else",
"f",
"for",
"(",
"f",
",",
"ext",
")",
"in",
"self",
".",
"_files",
".",
"keys",
"(",
")",
"]"
] | 56 | 0.029412 |
def namedb_get_name_preorder( db, preorder_hash, current_block ):
"""
Get a (singular) name preorder record outstanding at the given block, given the preorder hash.
NOTE: returns expired preorders.
Return the preorder record on success.
Return None if not found.
"""
select_query = "SEL... | [
"def",
"namedb_get_name_preorder",
"(",
"db",
",",
"preorder_hash",
",",
"current_block",
")",
":",
"select_query",
"=",
"\"SELECT * FROM preorders WHERE preorder_hash = ? AND op = ? AND block_number < ?;\"",
"args",
"=",
"(",
"preorder_hash",
",",
"NAME_PREORDER",
",",
"curr... | 34.047619 | 0.015636 |
def natsorted(seq, key=lambda x: x, number_type=float, signed=True, exp=True):
"""\
Sorts a sequence naturally (alphabetically and numerically),
not lexicographically.
>>> a = ['num3', 'num5', 'num2']
>>> natsorted(a)
['num2', 'num3', 'num5']
>>> b = [('a', 'num3'), ('b', 'n... | [
"def",
"natsorted",
"(",
"seq",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
",",
"number_type",
"=",
"float",
",",
"signed",
"=",
"True",
",",
"exp",
"=",
"True",
")",
":",
"return",
"sorted",
"(",
"seq",
",",
"key",
"=",
"lambda",
"x",
":",
"natso... | 40.058824 | 0.001435 |
def publish(self, publications, jar, entry, repo, published):
"""Run ivy to publish a jar. ivyxml_path is the path to the ivy file; published
is a list of jars published so far (including this one). entry is a pushdb entry."""
try:
ivy = Bootstrapper.default_ivy()
except Bootstrapper.Error as e:... | [
"def",
"publish",
"(",
"self",
",",
"publications",
",",
"jar",
",",
"entry",
",",
"repo",
",",
"published",
")",
":",
"try",
":",
"ivy",
"=",
"Bootstrapper",
".",
"default_ivy",
"(",
")",
"except",
"Bootstrapper",
".",
"Error",
"as",
"e",
":",
"raise"... | 39.06383 | 0.009033 |
def dflin2dfbinarymap(dflin,col1,col2,params_df2submap={'aggfunc':'sum','binary':True,'binaryby':'nan'},test=False):
"""
if not binary:
dropna the df by value [col index and value] column
"""
# get the submap ready
df_map=df2submap(df=dflin,
col=col1,idx=col2,**params_df2submap... | [
"def",
"dflin2dfbinarymap",
"(",
"dflin",
",",
"col1",
",",
"col2",
",",
"params_df2submap",
"=",
"{",
"'aggfunc'",
":",
"'sum'",
",",
"'binary'",
":",
"True",
",",
"'binaryby'",
":",
"'nan'",
"}",
",",
"test",
"=",
"False",
")",
":",
"# get the submap rea... | 37.681818 | 0.028235 |
def delete(cls, id):
'''
Destroy a Union object
'''
client = cls._new_api_client()
return client.make_request(cls, 'delete', url_params={'id': id}) | [
"def",
"delete",
"(",
"cls",
",",
"id",
")",
":",
"client",
"=",
"cls",
".",
"_new_api_client",
"(",
")",
"return",
"client",
".",
"make_request",
"(",
"cls",
",",
"'delete'",
",",
"url_params",
"=",
"{",
"'id'",
":",
"id",
"}",
")"
] | 30.333333 | 0.010695 |
def _store_meta_info(self):
"""Update the meta dictionary with the current chunk of meta data details
"""
# In the mass bank msp files, sometimes the precursor_mz is missing but we have the neutral mass and
# the precursor_type (e.g. adduct) so we can calculate the precursor_mz
i... | [
"def",
"_store_meta_info",
"(",
"self",
")",
":",
"# In the mass bank msp files, sometimes the precursor_mz is missing but we have the neutral mass and",
"# the precursor_type (e.g. adduct) so we can calculate the precursor_mz",
"if",
"not",
"self",
".",
"meta_info",
"[",
"'precursor_mz'... | 50.5 | 0.008328 |
def update_exif_for_rotated_image(exif):
"""Modifies the Exif tag if rotation has been performed.
0th, 1st
--------
ImageWidth = 256
ImageLength = 257
XResolution = 282
YResolution = 283
TileWidth = 322
TileLength = 323
Exif
----
PixelXDimension = 40962
PixelYDimens... | [
"def",
"update_exif_for_rotated_image",
"(",
"exif",
")",
":",
"orientation_value",
"=",
"exif",
".",
"get",
"(",
"'0th'",
",",
")",
".",
"get",
"(",
"piexif",
".",
"ImageIFD",
".",
"Orientation",
",",
"exif",
".",
"get",
"(",
"'1st'",
",",
")",
".",
"... | 40.581081 | 0.001625 |
def get_attribute(obj, value):
"""
Normally the result of list_items for listviews are a set of model objects.
But when you want a GROUP_BY query (with 'values' method), than
the result will be a dict. This method will help you find an item for
either objects or dictionaries.
"""
if type(obj... | [
"def",
"get_attribute",
"(",
"obj",
",",
"value",
")",
":",
"if",
"type",
"(",
"obj",
")",
"==",
"dict",
":",
"return",
"dict",
".",
"get",
"(",
"obj",
",",
"value",
")",
"else",
":",
"return",
"getattr",
"(",
"obj",
",",
"value",
")"
] | 36.454545 | 0.002433 |
def connect(
creator, maxusage=None, setsession=None,
failures=None, ping=1, closeable=True, *args, **kwargs):
"""A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 c... | [
"def",
"connect",
"(",
"creator",
",",
"maxusage",
"=",
"None",
",",
"setsession",
"=",
"None",
",",
"failures",
"=",
"None",
",",
"ping",
"=",
"1",
",",
"closeable",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Stea... | 57.310345 | 0.000592 |
def get_file_meta(filepath):
"""
Get meta-information about a file.
Parameters
----------
filepath : str
Returns
-------
meta : dict
"""
meta = {}
meta['filepath'] = os.path.abspath(filepath)
meta['creation_datetime'] = get_creation_datetime(filepath)
meta['last_acc... | [
"def",
"get_file_meta",
"(",
"filepath",
")",
":",
"meta",
"=",
"{",
"}",
"meta",
"[",
"'filepath'",
"]",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filepath",
")",
"meta",
"[",
"'creation_datetime'",
"]",
"=",
"get_creation_datetime",
"(",
"filepath",
... | 28.269231 | 0.001316 |
def create_spatial_index(layer):
"""Helper function to create the spatial index on a vector layer.
This function is mainly used to see the processing time with the decorator.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:return: The index.
:rtype: QgsSpatialIndex
"""
re... | [
"def",
"create_spatial_index",
"(",
"layer",
")",
":",
"request",
"=",
"QgsFeatureRequest",
"(",
")",
".",
"setSubsetOfAttributes",
"(",
"[",
"]",
")",
"try",
":",
"spatial_index",
"=",
"QgsSpatialIndex",
"(",
"layer",
".",
"getFeatures",
"(",
"request",
")",
... | 42.023256 | 0.000541 |
def get_font(self, weight='medium', slant='upright', width='normal'):
"""Return the font matching or closest to the given style
If a font with the given weight, slant and width is available, return
it. Otherwise, return the font that is closest in style.
Args:
weight (FontW... | [
"def",
"get_font",
"(",
"self",
",",
"weight",
"=",
"'medium'",
",",
"slant",
"=",
"'upright'",
",",
"width",
"=",
"'normal'",
")",
":",
"def",
"find_closest_style",
"(",
"style",
",",
"styles",
",",
"alternatives",
")",
":",
"try",
":",
"return",
"style... | 42 | 0.001485 |
def _list_objects(self, client_kwargs, path, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
... | [
"def",
"_list_objects",
"(",
"self",
",",
"client_kwargs",
",",
"path",
",",
"max_request_entries",
")",
":",
"client_kwargs",
"=",
"client_kwargs",
".",
"copy",
"(",
")",
"if",
"max_request_entries",
":",
"client_kwargs",
"[",
"'MaxKeys'",
"]",
"=",
"max_reques... | 33.457143 | 0.00166 |
def fling_backward_horizontally(self, *args, **selectors):
"""
Perform fling backward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be fling or not.
"""
return self.device(**selectors).fling.horiz.backward() | [
"def",
"fling_backward_horizontally",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"selectors",
")",
":",
"return",
"self",
".",
"device",
"(",
"*",
"*",
"selectors",
")",
".",
"fling",
".",
"horiz",
".",
"backward",
"(",
")"
] | 42.142857 | 0.009967 |
def build_fake_data():
"""Build fake CIFAR10-style data for unit testing."""
num_examples = 10
x_train = np.random.rand(num_examples, *IMAGE_SHAPE).astype(np.float32)
y_train = np.random.permutation(np.arange(num_examples)).astype(np.int32)
x_test = np.random.rand(num_examples, *IMAGE_SHAPE).astype(np.float32... | [
"def",
"build_fake_data",
"(",
")",
":",
"num_examples",
"=",
"10",
"x_train",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"num_examples",
",",
"*",
"IMAGE_SHAPE",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"y_train",
"=",
"np",
".",
"random",... | 54.375 | 0.0181 |
def execute(self, query, *parameters, **kwparameters):
"""Executes the given query, returning the lastrowid from the query."""
return self.execute_lastrowid(query, *parameters, **kwparameters) | [
"def",
"execute",
"(",
"self",
",",
"query",
",",
"*",
"parameters",
",",
"*",
"*",
"kwparameters",
")",
":",
"return",
"self",
".",
"execute_lastrowid",
"(",
"query",
",",
"*",
"parameters",
",",
"*",
"*",
"kwparameters",
")"
] | 68.666667 | 0.009615 |
def _Rzderiv(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rzderiv
PURPOSE:
evaluate the mixed R,z derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | [
"def",
"_Rzderiv",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"Rz",
"=",
"R",
"**",
"2.",
"+",
"z",
"**",
"2.",
"sqrtRz",
"=",
"numpy",
".",
"sqrt",
"(",
"Rz",
")",
"return",
"-",
"R",
"*",
"z",... | 31.157895 | 0.014754 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.