text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def parse_api_datetime(value):
""" parse a datetime returned from the salesforce API.
in python 3 we should just use a strptime %z, but until then we're just going
to assert that its a fixed offset of +0000 since thats the observed behavior. getting
python 2 to support fixed offset parsing is too compl... | [
"def",
"parse_api_datetime",
"(",
"value",
")",
":",
"dt",
"=",
"datetime",
".",
"strptime",
"(",
"value",
"[",
"0",
":",
"DATETIME_LEN",
"]",
",",
"API_DATE_FORMAT",
")",
"offset_str",
"=",
"value",
"[",
"DATETIME_LEN",
":",
"]",
"assert",
"offset_str",
"... | 55 | 0.008945 |
def get_node_sum(self, age=None):
"""Get sum of all branches in the tree.
Returns:
int: The sum of all nodes grown until the age.
"""
if age is None:
age = self.age
return age if self.comp == 1 else int((pow(self.comp, age+1) - 1) / (self.comp - 1)) | [
"def",
"get_node_sum",
"(",
"self",
",",
"age",
"=",
"None",
")",
":",
"if",
"age",
"is",
"None",
":",
"age",
"=",
"self",
".",
"age",
"return",
"age",
"if",
"self",
".",
"comp",
"==",
"1",
"else",
"int",
"(",
"(",
"pow",
"(",
"self",
".",
"com... | 30.6 | 0.009524 |
def check_bipole(inp, name):
r"""Check di-/bipole parameters.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
inp : list of floats or arrays
... | [
"def",
"check_bipole",
"(",
"inp",
",",
"name",
")",
":",
"def",
"chck_dipole",
"(",
"inp",
",",
"name",
")",
":",
"r\"\"\"Check inp for shape and type.\"\"\"",
"# Check x",
"inp",
"[",
"0",
"]",
"=",
"_check_var",
"(",
"inp",
"[",
"0",
"]",
",",
"float",
... | 31.950495 | 0.000301 |
def annotateTree(bT, fn):
"""
annotate a tree in an external array using the given function
"""
l = [None]*bT.traversalID.midEnd
def fn2(bT):
l[bT.traversalID.mid] = fn(bT)
if bT.internal:
fn2(bT.left)
fn2(bT.right)
fn2(bT)
return l | [
"def",
"annotateTree",
"(",
"bT",
",",
"fn",
")",
":",
"l",
"=",
"[",
"None",
"]",
"*",
"bT",
".",
"traversalID",
".",
"midEnd",
"def",
"fn2",
"(",
"bT",
")",
":",
"l",
"[",
"bT",
".",
"traversalID",
".",
"mid",
"]",
"=",
"fn",
"(",
"bT",
")"... | 24.083333 | 0.01 |
def update(self, res, pk, depth=1, since=None):
"""
Try to sync an object to the local database, in case of failure
where a referenced object is not found, attempt to fetch said
object from the REST api
"""
fetch = lambda: self._fetcher.fetch_latest(res, pk, 1, since=sinc... | [
"def",
"update",
"(",
"self",
",",
"res",
",",
"pk",
",",
"depth",
"=",
"1",
",",
"since",
"=",
"None",
")",
":",
"fetch",
"=",
"lambda",
":",
"self",
".",
"_fetcher",
".",
"fetch_latest",
"(",
"res",
",",
"pk",
",",
"1",
",",
"since",
"=",
"si... | 44.375 | 0.008287 |
def Point2HexColor(a, lfrac, tfrac):
"""
Return web-safe hex triplets.
"""
[H,S,V] = [math.floor(360 * a), lfrac, tfrac]
RGB = hsvToRGB(H, S, V)
H = [hex(int(math.floor(255 * x))) for x in RGB]
HEX = [a[a.find('x') + 1:] for a in H]
HEX = ['0' + h if len(h) == 1 else h for h in HEX]... | [
"def",
"Point2HexColor",
"(",
"a",
",",
"lfrac",
",",
"tfrac",
")",
":",
"[",
"H",
",",
"S",
",",
"V",
"]",
"=",
"[",
"math",
".",
"floor",
"(",
"360",
"*",
"a",
")",
",",
"lfrac",
",",
"tfrac",
"]",
"RGB",
"=",
"hsvToRGB",
"(",
"H",
",",
"... | 21 | 0.008547 |
def untlpydict2dcformatteddict(untl_dict, **kwargs):
"""Convert a UNTL data dictionary to a formatted DC data dictionary."""
ark = kwargs.get('ark', None)
domain_name = kwargs.get('domain_name', None)
scheme = kwargs.get('scheme', 'http')
resolve_values = kwargs.get('resolve_values', None)
resol... | [
"def",
"untlpydict2dcformatteddict",
"(",
"untl_dict",
",",
"*",
"*",
"kwargs",
")",
":",
"ark",
"=",
"kwargs",
".",
"get",
"(",
"'ark'",
",",
"None",
")",
"domain_name",
"=",
"kwargs",
".",
"get",
"(",
"'domain_name'",
",",
"None",
")",
"scheme",
"=",
... | 37.727273 | 0.001175 |
def discover_files(base_path, sub_path='', ext='', trim_base_path=False):
"""Discovers all files with certain extension in given paths."""
file_list = []
for root, dirs, files in walk(path.join(base_path, sub_path)):
if trim_base_path:
root = path.relpath(root, base_path)
file_li... | [
"def",
"discover_files",
"(",
"base_path",
",",
"sub_path",
"=",
"''",
",",
"ext",
"=",
"''",
",",
"trim_base_path",
"=",
"False",
")",
":",
"file_list",
"=",
"[",
"]",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"walk",
"(",
"path",
".",
"join",... | 48.1 | 0.002041 |
def set_item(filename, item):
"""
Save entry to JSON file
"""
with atomic_write(os.fsencode(str(filename))) as temp_file:
with open(os.fsencode(str(filename))) as products_file:
# load the JSON data into memory
products_data = json.load(products_file)
# check if U... | [
"def",
"set_item",
"(",
"filename",
",",
"item",
")",
":",
"with",
"atomic_write",
"(",
"os",
".",
"fsencode",
"(",
"str",
"(",
"filename",
")",
")",
")",
"as",
"temp_file",
":",
"with",
"open",
"(",
"os",
".",
"fsencode",
"(",
"str",
"(",
"filename"... | 38.388889 | 0.001412 |
def parse_doc(obj: dict) -> BioCDocument:
"""Deserialize a dict obj to a BioCDocument object"""
doc = BioCDocument()
doc.id = obj['id']
doc.infons = obj['infons']
for passage in obj['passages']:
doc.add_passage(parse_passage(passage))
for annotation in obj['annotations']:
... | [
"def",
"parse_doc",
"(",
"obj",
":",
"dict",
")",
"->",
"BioCDocument",
":",
"doc",
"=",
"BioCDocument",
"(",
")",
"doc",
".",
"id",
"=",
"obj",
"[",
"'id'",
"]",
"doc",
".",
"infons",
"=",
"obj",
"[",
"'infons'",
"]",
"for",
"passage",
"in",
"obj"... | 38.75 | 0.002101 |
def printable_str(text, keep_newlines=False):
'''Escape any control or non-ASCII characters from string.
This function is intended for use with strings from an untrusted
source such as writing to a console or writing to logs. It is
designed to prevent things like ANSI escape sequences from
showing.... | [
"def",
"printable_str",
"(",
"text",
",",
"keep_newlines",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"new_text",
"=",
"ascii",
"(",
"text",
")",
"[",
"1",
":",
"-",
"1",
"]",
"else",
":",
"new_text",
"=",
"ascii... | 31.05 | 0.001563 |
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
"""
name = name.upper()
try:
return {
'authority': 'okapia.net',
'namespace': 'TextFormats',
'identifier': name,
'... | [
"def",
"get_type_data",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"try",
":",
"return",
"{",
"'authority'",
":",
"'okapia.net'",
",",
"'namespace'",
":",
"'TextFormats'",
",",
"'identifier'",
":",
"name",
",",
"'domain'",
":",
"... | 32.7 | 0.001486 |
def name(self):
"""The process name."""
name = self._platform_impl.get_process_name()
if os.name == 'posix':
# On UNIX the name gets truncated to the first 15 characters.
# If it matches the first part of the cmdline we return that
# one instead because it's u... | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"_platform_impl",
".",
"get_process_name",
"(",
")",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"# On UNIX the name gets truncated to the first 15 characters.",
"# If it matches the first part of the cm... | 41.5 | 0.002356 |
def take(self, indices, axis=0, convert=None, is_copy=True, **kwargs):
"""
Return the elements in the given *positional* indices along an axis.
This means that we are not indexing according to actual values in
the index attribute of the object. We are indexing according to the
a... | [
"def",
"take",
"(",
"self",
",",
"indices",
",",
"axis",
"=",
"0",
",",
"convert",
"=",
"None",
",",
"is_copy",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"convert",
"is",
"not",
"None",
":",
"msg",
"=",
"(",
"\"The 'convert' parameter is ... | 38.582418 | 0.000555 |
def to_array(self, itaper, normalization='4pi', csphase=1):
"""
Return the spherical harmonic coefficients of taper i as a numpy
array.
Usage
-----
coeffs = x.to_array(itaper, [normalization, csphase])
Returns
-------
coeffs : ndarray, shape (2, ... | [
"def",
"to_array",
"(",
"self",
",",
"itaper",
",",
"normalization",
"=",
"'4pi'",
",",
"csphase",
"=",
"1",
")",
":",
"if",
"type",
"(",
"normalization",
")",
"!=",
"str",
":",
"raise",
"ValueError",
"(",
"'normalization must be a string. '",
"+",
"'Input t... | 37.804348 | 0.001121 |
def ice_refractive(file):
"""
Interpolator for the refractive indices of ice.
Inputs:
File to read the refractive index lookup table from.
This is supplied as "ice_refr.dat", retrieved from
http://www.atmos.washington.edu/ice_optical_constants/
Returns:
A callable object th... | [
"def",
"ice_refractive",
"(",
"file",
")",
":",
"D",
"=",
"np",
".",
"loadtxt",
"(",
"file",
")",
"log_wl",
"=",
"np",
".",
"log10",
"(",
"D",
"[",
":",
",",
"0",
"]",
"/",
"1000",
")",
"re",
"=",
"D",
"[",
":",
",",
"1",
"]",
"log_im",
"="... | 28.416667 | 0.009452 |
def _match_magic(self, full_path):
"""Return the first magic that matches this path or None."""
for magic in self.magics:
if magic.matches(full_path):
return magic | [
"def",
"_match_magic",
"(",
"self",
",",
"full_path",
")",
":",
"for",
"magic",
"in",
"self",
".",
"magics",
":",
"if",
"magic",
".",
"matches",
"(",
"full_path",
")",
":",
"return",
"magic"
] | 40.6 | 0.009662 |
def create(cls, photo, title, description=''):
"""Create a new photoset.
photo - primary photo
"""
if not isinstance(photo, Photo):
raise TypeError, "Photo expected"
method = 'flickr.photosets.create'
data = _dopost(method, auth=True, title=title,\
... | [
"def",
"create",
"(",
"cls",
",",
"photo",
",",
"title",
",",
"description",
"=",
"''",
")",
":",
"if",
"not",
"isinstance",
"(",
"photo",
",",
"Photo",
")",
":",
"raise",
"TypeError",
",",
"\"Photo expected\"",
"method",
"=",
"'flickr.photosets.create'",
... | 34.8125 | 0.012238 |
def _any(self, memory, addr, **kwargs):
"""
Gets any solution of an address.
"""
return memory.state.solver.eval(addr, exact=kwargs.pop('exact', self._exact), **kwargs) | [
"def",
"_any",
"(",
"self",
",",
"memory",
",",
"addr",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"memory",
".",
"state",
".",
"solver",
".",
"eval",
"(",
"addr",
",",
"exact",
"=",
"kwargs",
".",
"pop",
"(",
"'exact'",
",",
"self",
".",
"_exa... | 39.2 | 0.015 |
def dim_dc(self, pars):
r"""
:math:`\frac{\partial \hat{\rho''}(\omega)}{\partial c} = \rho_0
\frac{-m sin(\frac{c \pi}{2}) ln(\omega \tau)(\omega \tau)^c - m
(\omega \tau)^c \frac{\pi}{2} cos(\frac{\pi}{2}}{1 + 2 (\omega \tau)^c
cos(\frac{c \pi}{2}) + (\omega \tau)^{2 c}} + \rho... | [
"def",
"dim_dc",
"(",
"self",
",",
"pars",
")",
":",
"self",
".",
"_set_parameters",
"(",
"pars",
")",
"# term1",
"nom1a",
"=",
"-",
"self",
".",
"m",
"*",
"np",
".",
"log",
"(",
"self",
".",
"w",
"*",
"self",
".",
"tau",
")",
"*",
"self",
".",... | 45.724138 | 0.001477 |
def load_configuration():
"""Load the configuration"""
(belbio_conf_fp, belbio_secrets_fp) = get_belbio_conf_files()
log.info(f"Using conf: {belbio_conf_fp} and secrets files: {belbio_secrets_fp} ")
config = {}
if belbio_conf_fp:
with open(belbio_conf_fp, "r") as f:
config = ya... | [
"def",
"load_configuration",
"(",
")",
":",
"(",
"belbio_conf_fp",
",",
"belbio_secrets_fp",
")",
"=",
"get_belbio_conf_files",
"(",
")",
"log",
".",
"info",
"(",
"f\"Using conf: {belbio_conf_fp} and secrets files: {belbio_secrets_fp} \"",
")",
"config",
"=",
"{",
"}",
... | 32.5 | 0.002299 |
def export_pdf(self, filename):
"""
Export the report in PDF format. Specify a path for which
to save the file, including the trailing filename.
:param str filename: path including filename
:return: None
"""
self.make_request(
raw_result=True,... | [
"def",
"export_pdf",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"make_request",
"(",
"raw_result",
"=",
"True",
",",
"resource",
"=",
"'export'",
",",
"filename",
"=",
"filename",
",",
"headers",
"=",
"{",
"'accept'",
":",
"'application/pdf'",
"}... | 32.615385 | 0.013761 |
def apply_grad_processors(opt, gradprocs):
"""
Wrapper around optimizers to apply gradient processors.
Args:
opt (tf.train.Optimizer):
gradprocs (list[GradientProcessor]): gradient processors to add to the
optimizer.
Returns:
a :class:`tf.train.Optimizer` instance w... | [
"def",
"apply_grad_processors",
"(",
"opt",
",",
"gradprocs",
")",
":",
"assert",
"isinstance",
"(",
"gradprocs",
",",
"(",
"list",
",",
"tuple",
")",
")",
",",
"gradprocs",
"for",
"gp",
"in",
"gradprocs",
":",
"assert",
"isinstance",
"(",
"gp",
",",
"Gr... | 33.545455 | 0.000878 |
def _get_broker_offsets(self, instance, topics):
"""
Fetch highwater offsets for each topic/partition from Kafka cluster.
Do this for all partitions in the cluster because even if it has no
consumers, we may want to measure whether producers are successfully
producing. No need t... | [
"def",
"_get_broker_offsets",
"(",
"self",
",",
"instance",
",",
"topics",
")",
":",
"# Connect to Kafka",
"highwater_offsets",
"=",
"{",
"}",
"topic_partitions_without_a_leader",
"=",
"[",
"]",
"topics_to_fetch",
"=",
"defaultdict",
"(",
"set",
")",
"cli",
"=",
... | 45.982143 | 0.001901 |
def kong_61_2007():
r"""Kong 61 pt Hankel filter, as published in [Kong07]_.
Taken from file ``FilterModules.f90`` provided with 1DCSEM_.
License: `Apache License, Version 2.0,
<http://www.apache.org/licenses/LICENSE-2.0>`_.
"""
dlf = DigitalFilter('Kong 61', 'kong_61_2007')
dlf.base = ... | [
"def",
"kong_61_2007",
"(",
")",
":",
"dlf",
"=",
"DigitalFilter",
"(",
"'Kong 61'",
",",
"'kong_61_2007'",
")",
"dlf",
".",
"base",
"=",
"np",
".",
"array",
"(",
"[",
"2.3517745856009100e-02",
",",
"2.6649097336355482e-02",
",",
"3.0197383422318501e-02",
",",
... | 51.77193 | 0.000166 |
def _generate_tokens(pat: GenericAny, text: str) -> Iterator[Token]:
"""Generate a sequence of tokens from `text` that match `pat`
Parameters
----------
pat : compiled regex
The pattern to use for tokenization
text : str
The text to tokenize
"""
rules = _TYPE_RULES
keys... | [
"def",
"_generate_tokens",
"(",
"pat",
":",
"GenericAny",
",",
"text",
":",
"str",
")",
"->",
"Iterator",
"[",
"Token",
"]",
":",
"rules",
"=",
"_TYPE_RULES",
"keys",
"=",
"_TYPE_KEYS",
"groupindex",
"=",
"pat",
".",
"groupindex",
"scanner",
"=",
"pat",
... | 28.8 | 0.001681 |
def delete_item(self, item):
''' removes an item from the db '''
for relation, dst in self.relations_of(item, True):
self.delete_relation(item, relation, dst)
#print(item, relation, dst)
for src, relation in self.relations_to(item, True):
self.delete_relation(... | [
"def",
"delete_item",
"(",
"self",
",",
"item",
")",
":",
"for",
"relation",
",",
"dst",
"in",
"self",
".",
"relations_of",
"(",
"item",
",",
"True",
")",
":",
"self",
".",
"delete_relation",
"(",
"item",
",",
"relation",
",",
"dst",
")",
"#print(item,... | 41.076923 | 0.009158 |
def load_images(self, search_file, source_file):
"""加载待匹配图片."""
self.search_file, self.source_file = search_file, source_file
self.im_search, self.im_source = imread(self.search_file), imread(self.source_file)
# 初始化对象
self.check_macthing_object = CheckKeypointResult(self.im_searc... | [
"def",
"load_images",
"(",
"self",
",",
"search_file",
",",
"source_file",
")",
":",
"self",
".",
"search_file",
",",
"self",
".",
"source_file",
"=",
"search_file",
",",
"source_file",
"self",
".",
"im_search",
",",
"self",
".",
"im_source",
"=",
"imread",
... | 55.5 | 0.011834 |
async def create_virtual_environment(loop=None):
"""
Create a virtual environment, and return the path to the virtual env
directory, which should contain a "bin" directory with the `python` and
`pip` binaries that can be used to a test install of a software package.
:return: the path to the virtual... | [
"async",
"def",
"create_virtual_environment",
"(",
"loop",
"=",
"None",
")",
":",
"tmp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"venv_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp_dir",
",",
"VENV_NAME",
")",
"proc1",
"=",
"await",
"asynci... | 40.545455 | 0.001095 |
def read(key, root=''):
'''
Read from SysFS
:param key: file or path in SysFS; if key is a list then root will be prefixed on each key
:return: the full (tree of) SysFS attributes under key
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/net/em1/statistics
'''
i... | [
"def",
"read",
"(",
"key",
",",
"root",
"=",
"''",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"six",
".",
"string_types",
")",
":",
"res",
"=",
"{",
"}",
"for",
"akey",
"in",
"key",
":",
"ares",
"=",
"read",
"(",
"os",
".",
"path",
... | 32.349206 | 0.001905 |
def mainClassDoc():
"""Function decorator used to automatic adiction of base class MEoS in
subclass __doc__"""
def decorator(f):
# __doc__ is only writable in python3.
# The doc build must be done with python3 so this snnippet do the work
py_version = platform.python_version()
... | [
"def",
"mainClassDoc",
"(",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"# __doc__ is only writable in python3.",
"# The doc build must be done with python3 so this snnippet do the work",
"py_version",
"=",
"platform",
".",
"python_version",
"(",
")",
"if",
"py_versio... | 34.565217 | 0.001224 |
def collapsed_spectrum(fitsfile, ns1, ns2,
method='mean', nwin_background=0,
reverse=False, out_sp=None, debugplot=0):
"""Compute a collapsed spectrum from a 2D image using scans in [ns1,ns2].
Parameters
----------
fitsfile : file object
File name o... | [
"def",
"collapsed_spectrum",
"(",
"fitsfile",
",",
"ns1",
",",
"ns2",
",",
"method",
"=",
"'mean'",
",",
"nwin_background",
"=",
"0",
",",
"reverse",
"=",
"False",
",",
"out_sp",
"=",
"None",
",",
"debugplot",
"=",
"0",
")",
":",
"# read FITS file",
"wit... | 32.38961 | 0.000389 |
def print_computation_log(self, aggregate = False):
"""
Print the computation log of a simulation.
If ``aggregate`` is ``False`` (default), print the value of each computed vector.
If ``aggregate`` is ``True``, only print the minimum, maximum, and average value of each comp... | [
"def",
"print_computation_log",
"(",
"self",
",",
"aggregate",
"=",
"False",
")",
":",
"for",
"line",
"in",
"self",
".",
"computation_log",
"(",
"aggregate",
")",
":",
"print",
"(",
"line",
")"
] | 44.272727 | 0.012072 |
def norm2(self):
"""Squared norm of the vector"""
return self.x * self.x + self.y * self.y + self.z * self.z | [
"def",
"norm2",
"(",
"self",
")",
":",
"return",
"self",
".",
"x",
"*",
"self",
".",
"x",
"+",
"self",
".",
"y",
"*",
"self",
".",
"y",
"+",
"self",
".",
"z",
"*",
"self",
".",
"z"
] | 40.666667 | 0.016129 |
def define_residues_for_plotting_topology(self,cutoff):
"""
This function defines the residues for plotting in case only a topology file has been submitted.
In this case the residence time analysis in not necessary and it is enough just to find all
residues within a cutoff distance.
... | [
"def",
"define_residues_for_plotting_topology",
"(",
"self",
",",
"cutoff",
")",
":",
"#self.protein_selection = self.universe.select_atoms('all and around '+str(cutoff)+' (segid '+str(self.universe.ligand.segids[0])+' and resid '+str(self.universe.ligand.resids[0])+')')",
"#The previous line was ... | 77.47619 | 0.015179 |
def _save_private_file(filename, json_contents):
"""Saves a file with read-write permissions on for the owner.
Args:
filename: String. Absolute path to file.
json_contents: JSON serializable object to be saved.
"""
temp_filename = tempfile.mktemp()
file_desc = os.open(temp_filename,... | [
"def",
"_save_private_file",
"(",
"filename",
",",
"json_contents",
")",
":",
"temp_filename",
"=",
"tempfile",
".",
"mktemp",
"(",
")",
"file_desc",
"=",
"os",
".",
"open",
"(",
"temp_filename",
",",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_CREAT",
",",
... | 42.076923 | 0.001789 |
def set_read_only(self, value):
"""
Sets whether model could be modified or not
"""
if self.__read_only__ != value:
self.__read_only__ = value
self._update_read_only() | [
"def",
"set_read_only",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"__read_only__",
"!=",
"value",
":",
"self",
".",
"__read_only__",
"=",
"value",
"self",
".",
"_update_read_only",
"(",
")"
] | 31 | 0.008969 |
def pretty_format(obj, indent=None):
"""
Pretty formats the given object as a string which is returned.
If indent is None, a single line will be returned.
"""
if indent is None:
if isinstance(obj, TLObject):
obj = obj.to_dict()
if isinstan... | [
"def",
"pretty_format",
"(",
"obj",
",",
"indent",
"=",
"None",
")",
":",
"if",
"indent",
"is",
"None",
":",
"if",
"isinstance",
"(",
"obj",
",",
"TLObject",
")",
":",
"obj",
"=",
"obj",
".",
"to_dict",
"(",
")",
"if",
"isinstance",
"(",
"obj",
","... | 35.753846 | 0.000838 |
def run(self, progress=True, verbose=False):
"""Compute all steps of the simulation. Be careful: if tmax is not set,
this function will result in an infinit loop.
Returns
-------
(t, fields):
last time and result fields.
"""
total_iter = int((self.tm... | [
"def",
"run",
"(",
"self",
",",
"progress",
"=",
"True",
",",
"verbose",
"=",
"False",
")",
":",
"total_iter",
"=",
"int",
"(",
"(",
"self",
".",
"tmax",
"//",
"self",
".",
"user_dt",
")",
"if",
"self",
".",
"tmax",
"else",
"None",
")",
"log",
"=... | 37.535714 | 0.001855 |
def create_installer(self, rpm_py_version, **kwargs):
"""Create Installer object."""
return DebianInstaller(rpm_py_version, self.python, self.rpm, **kwargs) | [
"def",
"create_installer",
"(",
"self",
",",
"rpm_py_version",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DebianInstaller",
"(",
"rpm_py_version",
",",
"self",
".",
"python",
",",
"self",
".",
"rpm",
",",
"*",
"*",
"kwargs",
")"
] | 56.666667 | 0.011628 |
def basic_stats(self):
"""Return a markdown representation of simple statistics."""
comment_score = sum(comment.score for comment in self.comments)
if self.comments:
comment_duration = (self.comments[-1].created_utc -
self.comments[0].created_utc)
... | [
"def",
"basic_stats",
"(",
"self",
")",
":",
"comment_score",
"=",
"sum",
"(",
"comment",
".",
"score",
"for",
"comment",
"in",
"self",
".",
"comments",
")",
"if",
"self",
".",
"comments",
":",
"comment_duration",
"=",
"(",
"self",
".",
"comments",
"[",
... | 47.592593 | 0.001526 |
def _create_kube_dns_instance(self, instance):
"""
Set up kube_dns instance so it can be used in OpenMetricsBaseCheck
"""
kube_dns_instance = deepcopy(instance)
# kube_dns uses 'prometheus_endpoint' and not 'prometheus_url', so we have to rename the key
kube_dns_instance... | [
"def",
"_create_kube_dns_instance",
"(",
"self",
",",
"instance",
")",
":",
"kube_dns_instance",
"=",
"deepcopy",
"(",
"instance",
")",
"# kube_dns uses 'prometheus_endpoint' and not 'prometheus_url', so we have to rename the key",
"kube_dns_instance",
"[",
"'prometheus_url'",
"]... | 49.258065 | 0.008349 |
def select(self, crit):
"""
Select subset of values that match a given index criterion.
Parameters
----------
crit : function, list, str, int
Criterion function to map to indices, specific index value,
or list of indices.
"""
import types
... | [
"def",
"select",
"(",
"self",
",",
"crit",
")",
":",
"import",
"types",
"# handle lists, strings, and ints",
"if",
"not",
"isinstance",
"(",
"crit",
",",
"types",
".",
"FunctionType",
")",
":",
"# set(\"foo\") -> {\"f\", \"o\"}; wrap in list to prevent:",
"if",
"isins... | 34.210526 | 0.001994 |
def decode_raw_stream(self, text, decode_raw, known_encoding, filename):
"""given string/unicode or bytes/string, determine encoding
from magic encoding comment, return body as unicode
or raw if decode_raw=False
"""
if isinstance(text, compat.text_type):
m = se... | [
"def",
"decode_raw_stream",
"(",
"self",
",",
"text",
",",
"decode_raw",
",",
"known_encoding",
",",
"filename",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"compat",
".",
"text_type",
")",
":",
"m",
"=",
"self",
".",
"_coding_re",
".",
"match",
"(",... | 42.205128 | 0.001188 |
def forward_list(self):
'''adb forward --list'''
version = self.version()
if int(version[1]) <= 1 and int(version[2]) <= 0 and int(version[3]) < 31:
raise EnvironmentError("Low adb version.")
lines = self.raw_cmd("forward", "--list").communicate()[0].decode("utf-8").strip().s... | [
"def",
"forward_list",
"(",
"self",
")",
":",
"version",
"=",
"self",
".",
"version",
"(",
")",
"if",
"int",
"(",
"version",
"[",
"1",
"]",
")",
"<=",
"1",
"and",
"int",
"(",
"version",
"[",
"2",
"]",
")",
"<=",
"0",
"and",
"int",
"(",
"version... | 54.428571 | 0.010336 |
def release_branches(self):
"""A dictionary that maps branch names to :class:`Release` objects."""
self.ensure_release_scheme('branches')
return dict((r.revision.branch, r) for r in self.releases.values()) | [
"def",
"release_branches",
"(",
"self",
")",
":",
"self",
".",
"ensure_release_scheme",
"(",
"'branches'",
")",
"return",
"dict",
"(",
"(",
"r",
".",
"revision",
".",
"branch",
",",
"r",
")",
"for",
"r",
"in",
"self",
".",
"releases",
".",
"values",
"(... | 56.5 | 0.008734 |
def full_name(self):
"""Return full name of member"""
if self.prefix is not None:
return '.'.join([self.prefix, self.member])
return self.member | [
"def",
"full_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"prefix",
"is",
"not",
"None",
":",
"return",
"'.'",
".",
"join",
"(",
"[",
"self",
".",
"prefix",
",",
"self",
".",
"member",
"]",
")",
"return",
"self",
".",
"member"
] | 35.2 | 0.011111 |
def _get_type_description(annotation):
'''
Given an annotation, return the (type, description) for the parameter.
If you provide an annotation that is somehow both a string and a callable,
the behavior is undefined.
'''
if annotation is _empty:
return None, None
elif callable(annotat... | [
"def",
"_get_type_description",
"(",
"annotation",
")",
":",
"if",
"annotation",
"is",
"_empty",
":",
"return",
"None",
",",
"None",
"elif",
"callable",
"(",
"annotation",
")",
":",
"return",
"annotation",
",",
"None",
"elif",
"isinstance",
"(",
"annotation",
... | 33.958333 | 0.001193 |
def parse_args(args):
"""
Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace`
"""
parser = argparse.ArgumentParser(
description="Just a Hello World demonstration")
parser.add_argument(
... | [
"def",
"parse_args",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Just a Hello World demonstration\"",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--version'",
",",
"action",
"=",
"'version'",
"... | 30.2 | 0.002141 |
def getAllEncodings(self):
"""Returns encodings for all the records"""
numEncodings=self.fields[0].numEncodings
assert (all(field.numEncodings==numEncodings for field in self.fields))
encodings = [self.getEncoding(index) for index in range(numEncodings)]
return encodings | [
"def",
"getAllEncodings",
"(",
"self",
")",
":",
"numEncodings",
"=",
"self",
".",
"fields",
"[",
"0",
"]",
".",
"numEncodings",
"assert",
"(",
"all",
"(",
"field",
".",
"numEncodings",
"==",
"numEncodings",
"for",
"field",
"in",
"self",
".",
"fields",
"... | 35.75 | 0.010239 |
def calc_2dsplinecoeffs_c(array2d):
"""
NAME:
calc_2dsplinecoeffs_c
PURPOSE:
Use C to calculate spline coefficients for a 2D array
INPUT:
array2d
OUTPUT:
new array with spline coeffs
HISTORY:
2013-01-24 - Written - Bovy (IAS)
"""
#Set up result arrays
... | [
"def",
"calc_2dsplinecoeffs_c",
"(",
"array2d",
")",
":",
"#Set up result arrays",
"out",
"=",
"copy",
".",
"copy",
"(",
"array2d",
")",
"out",
"=",
"numpy",
".",
"require",
"(",
"out",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"requirements",
"=",
... | 31.107143 | 0.018931 |
def setData(self, index, value, role=QtCore.Qt.EditRole):
"""Reimplemented from QtCore.QAbstractItemModel
You can only set the value.
:param index: the index to edit, column should be 1.
:type index: :class:`PySide.QtCore.QModelIndex`
:param value: the new value for the configo... | [
"def",
"setData",
"(",
"self",
",",
"index",
",",
"value",
",",
"role",
"=",
"QtCore",
".",
"Qt",
".",
"EditRole",
")",
":",
"if",
"index",
".",
"isValid",
"(",
")",
":",
"if",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"EditRole",
":",
"if",
"index... | 41.258065 | 0.001528 |
def fix_sec_nseg(secs, dL):
""" Set nseg of sections based on dL param: section.nseg = 1 + 2 * int(section.L / (2*dL))
:param secs: netpyne dictionary with all sections
:param dL: dL from config file
"""
for secName in secs:
secs[secName]['geom']['nseg'] = 1 + 2 * int(secs[secName]['geom']... | [
"def",
"fix_sec_nseg",
"(",
"secs",
",",
"dL",
")",
":",
"for",
"secName",
"in",
"secs",
":",
"secs",
"[",
"secName",
"]",
"[",
"'geom'",
"]",
"[",
"'nseg'",
"]",
"=",
"1",
"+",
"2",
"*",
"int",
"(",
"secs",
"[",
"secName",
"]",
"[",
"'geom'",
... | 41 | 0.01194 |
def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
""" Generate the rst file for a given example.
Returns the amout of code (in characters) of the corresponding
files.
"""
src_file = os.path.join(src_dir, fname)
example_file = os.path.join(target_dir, fname)
shutil.co... | [
"def",
"generate_file_rst",
"(",
"fname",
",",
"target_dir",
",",
"src_dir",
",",
"gallery_conf",
")",
":",
"src_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"src_dir",
",",
"fname",
")",
"example_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"t... | 40.772727 | 0.000272 |
def plot(self, series, series_diff=None, label='', color=None, style=None):
'''
:param pandas.Series series:
The series to be plotted, all values must be positive if stacked
is True.
:param pandas.Series series_diff:
The series representing the diff that will ... | [
"def",
"plot",
"(",
"self",
",",
"series",
",",
"series_diff",
"=",
"None",
",",
"label",
"=",
"''",
",",
"color",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"color",
"=",
"self",
".",
"get_color",
"(",
"color",
")",
"if",
"series_diff",
"is... | 44.833333 | 0.001456 |
def json_conversion(obj: Any) -> JSON:
"""Encode additional objects to JSON."""
try:
# numpy isn't an explicit dependency of bowtie
# so we can't assume it's available
import numpy as np
if isinstance(obj, (np.ndarray, np.generic)):
return obj.tolist()
except Impo... | [
"def",
"json_conversion",
"(",
"obj",
":",
"Any",
")",
"->",
"JSON",
":",
"try",
":",
"# numpy isn't an explicit dependency of bowtie",
"# so we can't assume it's available",
"import",
"numpy",
"as",
"np",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"np",
".",
"ndar... | 34.366667 | 0.001887 |
def get_id(self, item_type, item=None, with_id=False, hostid=None, **args):
"""Return id or ids of zabbix objects.
:type item_type: str
:param item_type: Type of zabbix object. (eg host, item etc.)
:type item: str
:param item: Name of zabbix object. If it is `None`, return list... | [
"def",
"get_id",
"(",
"self",
",",
"item_type",
",",
"item",
"=",
"None",
",",
"with_id",
"=",
"False",
",",
"hostid",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"result",
"=",
"None",
"name",
"=",
"args",
".",
"get",
"(",
"'name'",
",",
"Fals... | 31.644231 | 0.000589 |
def redo(self):
"""This is called when a new image arrives or the data in the
existing image changes.
"""
self.clear()
tab = self.channel.get_current_image()
if not isinstance(tab, AstroTable):
return
# Generate column indices
self.tab = tab.... | [
"def",
"redo",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"tab",
"=",
"self",
".",
"channel",
".",
"get_current_image",
"(",
")",
"if",
"not",
"isinstance",
"(",
"tab",
",",
"AstroTable",
")",
":",
"return",
"# Generate column indices",
"self... | 35.217391 | 0.002404 |
def to_dict(self, lev=0):
"""
Return a dictionary representation of the class
:return: A dict
"""
_spec = self.c_param
_res = {}
lev += 1
for key, val in self._dict.items():
try:
(_, req, _ser, _, null_allowed) = _spec[str(ke... | [
"def",
"to_dict",
"(",
"self",
",",
"lev",
"=",
"0",
")",
":",
"_spec",
"=",
"self",
".",
"c_param",
"_res",
"=",
"{",
"}",
"lev",
"+=",
"1",
"for",
"key",
",",
"val",
"in",
"self",
".",
"_dict",
".",
"items",
"(",
")",
":",
"try",
":",
"(",
... | 29.638889 | 0.001815 |
def translate_to_dbus_type(typeof, value):
"""
Helper function to map values from their native Python types
to Dbus types.
:param type typeof: Target for type conversion e.g., 'dbus.Dictionary'
:param value: Value to assign using type 'typeof'
:return: 'value' converted to type 'typeof'
:rt... | [
"def",
"translate_to_dbus_type",
"(",
"typeof",
",",
"value",
")",
":",
"if",
"(",
"(",
"isinstance",
"(",
"value",
",",
"types",
".",
"UnicodeType",
")",
"or",
"isinstance",
"(",
"value",
",",
"str",
")",
")",
"and",
"typeof",
"is",
"not",
"dbus",
"."... | 35.529412 | 0.001613 |
def _layout(self, node):
"""ETE calls this function to style each node before rendering.
- ETE terms:
- A Style is a specification for how to render the node itself
- A Face defines extra information that is rendered outside of the node
- Face objects are used here to provide mo... | [
"def",
"_layout",
"(",
"self",
",",
"node",
")",
":",
"def",
"set_edge_style",
"(",
")",
":",
"\"\"\"Set the style for edges and make the node invisible.\"\"\"",
"node_style",
"=",
"ete3",
".",
"NodeStyle",
"(",
")",
"node_style",
"[",
"\"vt_line_color\"",
"]",
"=",... | 36.461538 | 0.001643 |
def forward(self, seconds, vx=5):
"""
Move continuously in simulator for seconds and velocity vx.
"""
self.vx = vx
self.sleep(seconds)
self.vx = 0 | [
"def",
"forward",
"(",
"self",
",",
"seconds",
",",
"vx",
"=",
"5",
")",
":",
"self",
".",
"vx",
"=",
"vx",
"self",
".",
"sleep",
"(",
"seconds",
")",
"self",
".",
"vx",
"=",
"0"
] | 26.857143 | 0.010309 |
def is_fifo(name):
'''
Check if a file exists and is a FIFO.
CLI Example:
.. code-block:: bash
salt '*' file.is_fifo /dev/fifo
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
if exc.errno ... | [
"def",
"is_fifo",
"(",
"name",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"name",
")",
"stat_structure",
"=",
"None",
"try",
":",
"stat_structure",
"=",
"os",
".",
"stat",
"(",
"name",
")",
"except",
"OSError",
"as",
"exc",
":"... | 21.863636 | 0.001992 |
def parse_body(self, text):
"""Parse the function body text."""
re_raise = re.findall(r'[ \t]raise ([a-zA-Z0-9_]*)', text)
if len(re_raise) > 0:
self.raise_list = [x.strip() for x in re_raise]
# remove duplicates from list while keeping it in the order
#... | [
"def",
"parse_body",
"(",
"self",
",",
"text",
")",
":",
"re_raise",
"=",
"re",
".",
"findall",
"(",
"r'[ \\t]raise ([a-zA-Z0-9_]*)'",
",",
"text",
")",
"if",
"len",
"(",
"re_raise",
")",
">",
"0",
":",
"self",
".",
"raise_list",
"=",
"[",
"x",
".",
... | 39.313725 | 0.000973 |
def runGenomeSGE(bfile, freqFile, nbJob, outPrefix, options):
"""Runs the genome command from plink, on SGE.
:param bfile: the prefix of the input file.
:param freqFile: the name of the frequency file (from Plink).
:param nbJob: the number of jobs to launch.
:param outPrefix: the prefix of all the ... | [
"def",
"runGenomeSGE",
"(",
"bfile",
",",
"freqFile",
",",
"nbJob",
",",
"outPrefix",
",",
"options",
")",
":",
"# Add the environment variable for DRMAA package",
"if",
"\"DRMAA_LIBRARY_PATH\"",
"not",
"in",
"os",
".",
"environ",
":",
"msg",
"=",
"\"could not load ... | 33.819277 | 0.000346 |
def get(self, key, default=None):
"""Return the value at key ``key``, or default value ``default``
which is None by default.
>>> dc = Dictator()
>>> dc['l0'] = [1, 2, 3, 4]
>>> dc.get('l0')
['1', '2', '3', '4']
>>> dc['l0']
['1', '2', '3', '4']
>>... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"__getitem__",
"(",
"key",
")",
"except",
"KeyError",
":",
"value",
"=",
"None",
"# Py3 Redis compatibiility",
"if",
"isinstance",
"(",
... | 28.071429 | 0.00246 |
def extra_args_parser(parser=None, skip_args=None, **kwargs):
"""Create a parser to parse sampler-specific arguments for loading
samples.
Parameters
----------
parser : argparse.ArgumentParser, optional
Instead of creating a parser, add arguments to the given one. If... | [
"def",
"extra_args_parser",
"(",
"parser",
"=",
"None",
",",
"skip_args",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"parser",
"is",
"None",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"*",
"*",
"kwargs",
")",
"elif",
"kwargs... | 44.623188 | 0.000953 |
def tophat(args):
"""
%prog tophat folder reference
Run tophat on a folder of reads.
"""
from jcvi.apps.bowtie import check_index
from jcvi.formats.fastq import guessoffset
p = OptionParser(tophat.__doc__)
p.add_option("--gtf", help="Reference annotation [default: %default]")
p.add... | [
"def",
"tophat",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"bowtie",
"import",
"check_index",
"from",
"jcvi",
".",
"formats",
".",
"fastq",
"import",
"guessoffset",
"p",
"=",
"OptionParser",
"(",
"tophat",
".",
"__doc__",
")",
"p",
".",
... | 33.981818 | 0.00052 |
def main(league, time, standings, team, live, use12hour, players,
output_format, output_file, upcoming, lookup, listcodes, apikey):
"""
A CLI for live and past football scores from various football leagues.
League codes:
\b
- WC: World Cup
- EC: European Championship
- CL: Champio... | [
"def",
"main",
"(",
"league",
",",
"time",
",",
"standings",
",",
"team",
",",
"live",
",",
"use12hour",
",",
"players",
",",
"output_format",
",",
"output_file",
",",
"upcoming",
",",
"lookup",
",",
"listcodes",
",",
"apikey",
")",
":",
"headers",
"=",
... | 31.903226 | 0.001962 |
def rgstr_stamps_root(rgstr_stamps):
"""
Register stamps with the root timer (see subdivision()).
Args:
rgstr_stamps (list, tuple): Collection of identifiers, passed through
set(), then each is passed through str().
Returns:
list: Implemented registered stamp collection.
... | [
"def",
"rgstr_stamps_root",
"(",
"rgstr_stamps",
")",
":",
"rgstr_stamps",
"=",
"sanitize_rgstr_stamps",
"(",
"rgstr_stamps",
")",
"f",
".",
"root",
".",
"rgstr_stamps",
"=",
"rgstr_stamps",
"return",
"rgstr_stamps"
] | 30.714286 | 0.002257 |
def get_hdrgo2usrgos(self, hdrgos):
"""Return a subset of hdrgo2usrgos."""
get_usrgos = self.hdrgo2usrgos.get
hdrgos_actual = self.get_hdrgos().intersection(hdrgos)
return {h:get_usrgos(h) for h in hdrgos_actual} | [
"def",
"get_hdrgo2usrgos",
"(",
"self",
",",
"hdrgos",
")",
":",
"get_usrgos",
"=",
"self",
".",
"hdrgo2usrgos",
".",
"get",
"hdrgos_actual",
"=",
"self",
".",
"get_hdrgos",
"(",
")",
".",
"intersection",
"(",
"hdrgos",
")",
"return",
"{",
"h",
":",
"get... | 48 | 0.012295 |
def dumps(obj, *args, **kwargs):
"""Serialize a object to string
Basic Usage:
>>> import simplekit.objson
>>> obj = {'name':'wendy'}
>>> print simplekit.objson.dumps(obj)
:param obj: a object which need to dump
:param args: Optional arguments that :func:`json.dumps` takes.
:param kwa... | [
"def",
"dumps",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'default'",
"]",
"=",
"object2dict",
"return",
"json",
".",
"dumps",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 25.833333 | 0.002075 |
def _bind_posix_socket(socket_name=None):
"""
Find a socket to listen on and return it.
Returns (socket_name, sock_obj)
"""
assert socket_name is None or isinstance(socket_name, six.text_type)
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if socket_name:
s.bind(socket_name... | [
"def",
"_bind_posix_socket",
"(",
"socket_name",
"=",
"None",
")",
":",
"assert",
"socket_name",
"is",
"None",
"or",
"isinstance",
"(",
"socket_name",
",",
"six",
".",
"text_type",
")",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_UNIX",
",",... | 31.241379 | 0.002141 |
def digest(instr, checksum='md5'):
'''
Return a checksum digest for a string
instr
A string
checksum : ``md5``
The hashing algorithm to use to generate checksums. Valid options: md5,
sha256, sha512.
CLI Example:
.. code-block:: bash
salt '*' hashutil.digest 'g... | [
"def",
"digest",
"(",
"instr",
",",
"checksum",
"=",
"'md5'",
")",
":",
"hashing_funcs",
"=",
"{",
"'md5'",
":",
"__salt__",
"[",
"'hashutil.md5_digest'",
"]",
",",
"'sha256'",
":",
"__salt__",
"[",
"'hashutil.sha256_digest'",
"]",
",",
"'sha512'",
":",
"__s... | 25.642857 | 0.001342 |
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffe... | [
"def",
"__send_buffer",
"(",
"self",
")",
":",
"bytes_written",
"=",
"self",
".",
"serial",
".",
"write",
"(",
"self",
".",
"__out_buffer",
".",
"raw",
")",
"if",
"self",
".",
"DEBUG_MODE",
":",
"print",
"(",
"\"Wrote: '{}'\"",
".",
"format",
"(",
"binas... | 50 | 0.008183 |
def send_file(self, file):
"""
Send a file to the client, it is a convenient method to avoid duplicated code
"""
if self.logger:
self.logger.debug("[ioc.extra.tornado.RouterHandler] send file %s" % file)
self.send_file_header(file)
fp = open(file, 'rb')
... | [
"def",
"send_file",
"(",
"self",
",",
"file",
")",
":",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"[ioc.extra.tornado.RouterHandler] send file %s\"",
"%",
"file",
")",
"self",
".",
"send_file_header",
"(",
"file",
")",
"fp... | 27.153846 | 0.010959 |
def coupl_model5(self):
""" Toggle switch.
"""
self.Coupl = -0.2*self.Adj
self.Coupl[2,0] *= -1
self.Coupl[3,0] *= -1
self.Coupl[4,1] *= -1
self.Coupl[5,1] *= -1 | [
"def",
"coupl_model5",
"(",
"self",
")",
":",
"self",
".",
"Coupl",
"=",
"-",
"0.2",
"*",
"self",
".",
"Adj",
"self",
".",
"Coupl",
"[",
"2",
",",
"0",
"]",
"*=",
"-",
"1",
"self",
".",
"Coupl",
"[",
"3",
",",
"0",
"]",
"*=",
"-",
"1",
"sel... | 26.25 | 0.02765 |
def nn_filter(S, rec=None, aggregate=None, axis=-1, **kwargs):
'''Filtering by nearest-neighbors.
Each data point (e.g, spectrogram column) is replaced
by aggregating its nearest neighbors in feature space.
This can be useful for de-noising a spectrogram or feature matrix.
The non-local means met... | [
"def",
"nn_filter",
"(",
"S",
",",
"rec",
"=",
"None",
",",
"aggregate",
"=",
"None",
",",
"axis",
"=",
"-",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"aggregate",
"is",
"None",
":",
"aggregate",
"=",
"np",
".",
"mean",
"if",
"rec",
"is",
"... | 34.185185 | 0.000632 |
def _get_profile(self, user_account):
"""Retrieves a user's profile"""
try:
# TODO: Load active profile, not just any
user_profile = objectmodels['profile'].find_one(
{'owner': str(user_account.uuid)})
self.log("Profile: ", user_profile,
... | [
"def",
"_get_profile",
"(",
"self",
",",
"user_account",
")",
":",
"try",
":",
"# TODO: Load active profile, not just any",
"user_profile",
"=",
"objectmodels",
"[",
"'profile'",
"]",
".",
"find_one",
"(",
"{",
"'owner'",
":",
"str",
"(",
"user_account",
".",
"u... | 33.730769 | 0.002217 |
def drawcircle(self, x, y, r = 10, colour = None, label = None):
"""
Draws a circle centered on (x, y) with radius r. All these are in the coordinates of your initial image !
You give these x and y in the usual ds9 pixels, (0,0) is bottom left.
I will convert this into the right PIL coor... | [
"def",
"drawcircle",
"(",
"self",
",",
"x",
",",
"y",
",",
"r",
"=",
"10",
",",
"colour",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"self",
".",
"checkforpilimage",
"(",
")",
"colour",
"=",
"self",
".",
"defaultcolour",
"(",
"colour",
")",
... | 43.727273 | 0.025432 |
def counter(self, key, **dims):
"""Adds counter with dimensions to the registry"""
return super(RegexRegistry, self).counter(self._get_key(key), **dims) | [
"def",
"counter",
"(",
"self",
",",
"key",
",",
"*",
"*",
"dims",
")",
":",
"return",
"super",
"(",
"RegexRegistry",
",",
"self",
")",
".",
"counter",
"(",
"self",
".",
"_get_key",
"(",
"key",
")",
",",
"*",
"*",
"dims",
")"
] | 55.333333 | 0.011905 |
def _execute_helper(self):
"""
The actual scheduler loop. The main steps in the loop are:
#. Harvest DAG parsing results through DagFileProcessorAgent
#. Find and queue executable tasks
#. Change task instance state in DB
#. Queue tasks in executor... | [
"def",
"_execute_helper",
"(",
"self",
")",
":",
"self",
".",
"executor",
".",
"start",
"(",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"Resetting orphaned tasks for active dag runs\"",
")",
"self",
".",
"reset_state_for_orphaned_tasks",
"(",
")",
"# Start after... | 43.007092 | 0.002095 |
def get_word_level_vocab(self):
"""Provides word level vocabulary
Returns
-------
Vocab
Word level vocabulary
"""
def simple_tokenize(source_str, token_delim=' ', seq_delim='\n'):
return list(filter(None, re.split(token_delim + '|' + seq_delim, s... | [
"def",
"get_word_level_vocab",
"(",
"self",
")",
":",
"def",
"simple_tokenize",
"(",
"source_str",
",",
"token_delim",
"=",
"' '",
",",
"seq_delim",
"=",
"'\\n'",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"None",
",",
"re",
".",
"split",
"(",
"toke... | 30.923077 | 0.009662 |
def reset(self, label=None):
"""
clears all measurements, allowing the object to be reused
Args:
label (str, optional) : optionally change the label
Example:
>>> from timerit import Timerit
>>> import math
>>> ti = Timerit(num=10, unit='u... | [
"def",
"reset",
"(",
"self",
",",
"label",
"=",
"None",
")",
":",
"if",
"label",
":",
"self",
".",
"label",
"=",
"label",
"self",
".",
"times",
"=",
"[",
"]",
"self",
".",
"n_loops",
"=",
"None",
"self",
".",
"total_time",
"=",
"None",
"return",
... | 33.708333 | 0.002404 |
async def status(dev: Device):
"""Display status information."""
power = await dev.get_power()
click.echo(click.style("%s" % power, bold=power))
vol = await dev.get_volume_information()
click.echo(vol.pop())
play_info = await dev.get_play_info()
if not play_info.is_idle:
click.echo... | [
"async",
"def",
"status",
"(",
"dev",
":",
"Device",
")",
":",
"power",
"=",
"await",
"dev",
".",
"get_power",
"(",
")",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"\"%s\"",
"%",
"power",
",",
"bold",
"=",
"power",
")",
")",
"vol",
"=... | 28.714286 | 0.001605 |
def aggregationDivide(dividend, divisor):
"""
Return the result from dividing two dicts that represent date and time.
Both dividend and divisor are dicts that contain one or more of the following
keys: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', seconds',
'milliseconds', 'microseconds'.
For ex... | [
"def",
"aggregationDivide",
"(",
"dividend",
",",
"divisor",
")",
":",
"# Convert each into microseconds",
"dividendMonthSec",
"=",
"aggregationToMonthsSeconds",
"(",
"dividend",
")",
"divisorMonthSec",
"=",
"aggregationToMonthsSeconds",
"(",
"divisor",
")",
"# It is a usag... | 35.702703 | 0.010317 |
def _distance_sqr_stats_naive_generic(x, y, matrix_centered, product,
exponent=1):
"""Compute generic squared stats."""
a = matrix_centered(x, exponent=exponent)
b = matrix_centered(y, exponent=exponent)
covariance_xy_sqr = product(a, b)
variance_x_sqr = produc... | [
"def",
"_distance_sqr_stats_naive_generic",
"(",
"x",
",",
"y",
",",
"matrix_centered",
",",
"product",
",",
"exponent",
"=",
"1",
")",
":",
"a",
"=",
"matrix_centered",
"(",
"x",
",",
"exponent",
"=",
"exponent",
")",
"b",
"=",
"matrix_centered",
"(",
"y"... | 36.791667 | 0.001104 |
def get(session, api_key, **kwargs):
"""
Выполняет доступ к API.
session - модуль requests или сессия из него
api_key - строка ключа доступа к API
rate - тариф, может быть `informers` или `forecast`
lat, lon - широта и долгота
```
import yandex_weather_api
import requests as req
... | [
"def",
"get",
"(",
"session",
",",
"api_key",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
",",
"kwargs",
"=",
"validate_args",
"(",
"api_key",
",",
"*",
"*",
"kwargs",
")",
"resp",
"=",
"session",
".",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwar... | 27.947368 | 0.001821 |
def handleThumbDblClick( self, item ):
"""
Handles when a thumbnail item is double clicked on.
:param item | <QListWidgetItem>
"""
if ( isinstance(item, RecordListWidgetItem) ):
self.emitRecordDoubleClicked(item.record()) | [
"def",
"handleThumbDblClick",
"(",
"self",
",",
"item",
")",
":",
"if",
"(",
"isinstance",
"(",
"item",
",",
"RecordListWidgetItem",
")",
")",
":",
"self",
".",
"emitRecordDoubleClicked",
"(",
"item",
".",
"record",
"(",
")",
")"
] | 35.875 | 0.02381 |
def parsed_stream(self, content: str, name: str=None):
"""Push a new Stream into the parser.
All subsequent called functions will parse this new stream,
until the 'popStream' function is called.
"""
self._streams.append(Stream(content, name)) | [
"def",
"parsed_stream",
"(",
"self",
",",
"content",
":",
"str",
",",
"name",
":",
"str",
"=",
"None",
")",
":",
"self",
".",
"_streams",
".",
"append",
"(",
"Stream",
"(",
"content",
",",
"name",
")",
")"
] | 46.166667 | 0.014184 |
def _remove_legacy_bootstrap():
"""Remove bootstrap projects from old path, they'd be really stale by now."""
home = os.environ['HOME']
old_base_dir = os.path.join(home, '.config', 'classpath_project_ensime')
if os.path.isdir(old_base_dir):
shutil.rmtree(old_base_dir, ignore_... | [
"def",
"_remove_legacy_bootstrap",
"(",
")",
":",
"home",
"=",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
"old_base_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"'.config'",
",",
"'classpath_project_ensime'",
")",
"if",
"os",
".",
"path",
... | 54.5 | 0.012048 |
async def getUpdates(self,
offset=None,
limit=None,
timeout=None,
allowed_updates=None):
""" See: https://core.telegram.org/bots/api#getupdates """
p = _strip(locals())
return await self._api_requ... | [
"async",
"def",
"getUpdates",
"(",
"self",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"allowed_updates",
"=",
"None",
")",
":",
"p",
"=",
"_strip",
"(",
"locals",
"(",
")",
")",
"return",
"await",
"self",... | 42.875 | 0.017143 |
def OpenAndRead(relative_path='debugger-blacklist.yaml'):
"""Attempts to find the yaml configuration file, then read it.
Args:
relative_path: Optional relative path override.
Returns:
A Config object if the open and read were successful, None if the file
does not exist (which is not considered an er... | [
"def",
"OpenAndRead",
"(",
"relative_path",
"=",
"'debugger-blacklist.yaml'",
")",
":",
"# Note: This logic follows the convention established by source-context.json",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sys",
".",
"path",
"[",
"0",
... | 30 | 0.009693 |
def set_code_exprs(self, codes):
"""Convenience: sets all the code expressions at once."""
self.code_objs = dict()
self._codes = []
for code in codes:
self.append_code_expr(code) | [
"def",
"set_code_exprs",
"(",
"self",
",",
"codes",
")",
":",
"self",
".",
"code_objs",
"=",
"dict",
"(",
")",
"self",
".",
"_codes",
"=",
"[",
"]",
"for",
"code",
"in",
"codes",
":",
"self",
".",
"append_code_expr",
"(",
"code",
")"
] | 36.166667 | 0.009009 |
def rotation_matrix_from_point(point, ret_inv=False):
"""Compute rotation matrix to go from [0,0,1] to `point`.
First, the matrix rotates to in the polar direction. Then,
a rotation about the y-axis is performed to match the
azimuthal angle in the x-z-plane.
This rotation matrix is required for th... | [
"def",
"rotation_matrix_from_point",
"(",
"point",
",",
"ret_inv",
"=",
"False",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"point",
"# azimuthal angle",
"phi",
"=",
"np",
".",
"arctan2",
"(",
"x",
",",
"z",
")",
"# angle in polar direction (negative)",
"theta"... | 28.54717 | 0.000639 |
def new_tbl(cls, rows, cols, width, height, tableStyleId=None):
"""Return a new ``<p:tbl>`` element tree."""
# working hypothesis is this is the default table style GUID
if tableStyleId is None:
tableStyleId = '{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}'
xml = cls._tbl_tmpl() % ... | [
"def",
"new_tbl",
"(",
"cls",
",",
"rows",
",",
"cols",
",",
"width",
",",
"height",
",",
"tableStyleId",
"=",
"None",
")",
":",
"# working hypothesis is this is the default table style GUID",
"if",
"tableStyleId",
"is",
"None",
":",
"tableStyleId",
"=",
"'{5C2254... | 35.857143 | 0.00194 |
def feed_amount(self, amount):
'''Calling this function sets the form feed amount to the specified setting.
Args:
amount: the form feed setting you desire. Options are '1/8', '1/6', 'x/180', and 'x/60',
with x being your own desired amount. X must be a minimum of 24 for 'x/1... | [
"def",
"feed_amount",
"(",
"self",
",",
"amount",
")",
":",
"n",
"=",
"None",
"if",
"amount",
"==",
"'1/8'",
":",
"amount",
"=",
"'0'",
"elif",
"amount",
"==",
"'1/6'",
":",
"amount",
"=",
"'2'",
"elif",
"re",
".",
"search",
"(",
"'/180'",
",",
"am... | 32.035714 | 0.008658 |
def sls_id(id_, mods, test=None, queue=False, **kwargs):
'''
Call a single ID from the named module(s) and handle all requisites
The state ID comes *before* the module ID(s) on the command line.
id
ID to call
mods
Comma-delimited list of modules to search for given id and its requ... | [
"def",
"sls_id",
"(",
"id_",
",",
"mods",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"retur... | 35.863248 | 0.000928 |
def calc_b_value(magnitudes, completeness, max_mag=None, plotvar=True):
"""
Calculate the b-value for a range of completeness magnitudes.
Calculates a power-law fit to given magnitudes for each completeness
magnitude. Plots the b-values and residuals for the fitted catalogue
against the completene... | [
"def",
"calc_b_value",
"(",
"magnitudes",
",",
"completeness",
",",
"max_mag",
"=",
"None",
",",
"plotvar",
"=",
"True",
")",
":",
"b_values",
"=",
"[",
"]",
"# Calculate the cdf for all magnitudes",
"counts",
"=",
"Counter",
"(",
"magnitudes",
")",
"cdf",
"="... | 41.381443 | 0.000243 |
def need_permissions(object_getter, action, hidden=True):
"""Get permission for buckets or abort.
:param object_getter: The function used to retrieve the object and pass it
to the permission factory.
:param action: The action needed.
:param hidden: Determine which kind of error to return. (Defa... | [
"def",
"need_permissions",
"(",
"object_getter",
",",
"action",
",",
"hidden",
"=",
"True",
")",
":",
"def",
"decorator_builder",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",... | 37.421053 | 0.001372 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.