text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def extra(self, **params):
"""
Set extra query parameters (eg. filter expressions/attributes that don't validate).
Appends to any previous extras set.
:rtype: Query
"""
q = self._clone()
for key, value in params.items():
q._extra[key].append(value)
... | [
"def",
"extra",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"q",
"=",
"self",
".",
"_clone",
"(",
")",
"for",
"key",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
":",
"q",
".",
"_extra",
"[",
"key",
"]",
".",
"append",
"(",
"valu... | 29.454545 | 0.008982 |
def safe_make_dirs(path, mode=0o777):
"""Create a leaf directory and all intermediate ones in a safe way.
A wrapper to os.makedirs() that handles existing leaf directories while
avoiding os.path.exists() race conditions.
:param path: relative or absolute directory tree to create
:param mode: direc... | [
"def",
"safe_make_dirs",
"(",
"path",
",",
"mode",
"=",
"0o777",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
",",
"mode",
")",
"except",
"OSError",
"as",
"error",
":",
"if",
"error",
".",
"errno",
"!=",
"17",
":",
"# File exists",
"rais... | 30.764706 | 0.001855 |
def _PromptUserForVSSCurrentVolume(self):
"""Prompts the user if the current volume with VSS should be processed.
Returns:
bool: True if the current volume with VSS should be processed.
"""
while True:
self._output_writer.Write(
'Volume Shadow Snapshots (VSS) were selected also pr... | [
"def",
"_PromptUserForVSSCurrentVolume",
"(",
"self",
")",
":",
"while",
"True",
":",
"self",
".",
"_output_writer",
".",
"Write",
"(",
"'Volume Shadow Snapshots (VSS) were selected also process current\\n'",
"'volume? [yes, no]\\n'",
")",
"process_current_volume",
"=",
"self... | 33.884615 | 0.00883 |
def check_child_friendly(self, name):
"""
Check if a module is a container and so can have children
"""
name = name.split()[0]
if name in self.container_modules:
return
root = os.path.dirname(os.path.realpath(__file__))
module_path = os.path.join(root,... | [
"def",
"check_child_friendly",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"name",
".",
"split",
"(",
")",
"[",
"0",
"]",
"if",
"name",
"in",
"self",
".",
"container_modules",
":",
"return",
"root",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
... | 38.628571 | 0.001443 |
def TrTp(self,pot=None,**kwargs):
"""
NAME:
TrTp
PURPOSE:
the 'ratio' between the radial and azimuthal period Tr/Tphi*pi
INPUT:
pot - potential
type= ('staeckel') type of actionAngle module to use
1) 'adiabatic'
... | [
"def",
"TrTp",
"(",
"self",
",",
"pot",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"pot",
"is",
"None",
":",
"pot",
"=",
"flatten_potential",
"(",
"pot",
")",
"_check_consistent_units",
"(",
"self",
",",
"pot",
")",
"self",
".",
"... | 23.931818 | 0.010949 |
def get_most_salient_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None):
"""
Order the words from `vocab` by "saliency score" (Chuang et al. 2012) from most to least salient. Optionally only
return the `n` most salient words.
J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualiz... | [
"def",
"get_most_salient_words",
"(",
"vocab",
",",
"topic_word_distrib",
",",
"doc_topic_distrib",
",",
"doc_lengths",
",",
"n",
"=",
"None",
")",
":",
"return",
"_words_by_salience_score",
"(",
"vocab",
",",
"topic_word_distrib",
",",
"doc_topic_distrib",
",",
"do... | 58.875 | 0.01046 |
def copy_file_upload(self, targetdir):
'''
Copies the currently valid file upload into the given directory.
If possible, the content is un-archived in the target directory.
'''
assert(self.file_upload)
# unpack student data to temporary directory
# os.chro... | [
"def",
"copy_file_upload",
"(",
"self",
",",
"targetdir",
")",
":",
"assert",
"(",
"self",
".",
"file_upload",
")",
"# unpack student data to temporary directory",
"# os.chroot is not working with tarfile support",
"tempdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"... | 47.5 | 0.002063 |
def keys(self) -> Iterator[str]:
"""return all possible paths one can take from this ApiNode"""
if self.param:
yield self.param_name
yield from self.paths.keys() | [
"def",
"keys",
"(",
"self",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"if",
"self",
".",
"param",
":",
"yield",
"self",
".",
"param_name",
"yield",
"from",
"self",
".",
"paths",
".",
"keys",
"(",
")"
] | 38.6 | 0.010152 |
def locate_keys(self, keys, strict=True):
"""Get index locations for the requested keys.
Parameters
----------
keys : array_like
Array of keys to locate.
strict : bool, optional
If True, raise KeyError if any keys are not found in the index.
Retu... | [
"def",
"locate_keys",
"(",
"self",
",",
"keys",
",",
"strict",
"=",
"True",
")",
":",
"# check inputs",
"keys",
"=",
"SortedIndex",
"(",
"keys",
",",
"copy",
"=",
"False",
")",
"# find intersection",
"loc",
",",
"found",
"=",
"self",
".",
"locate_intersect... | 25.45 | 0.001892 |
def _taskify(func):
'''Convert a function into a task.'''
if not isinstance(func, _Task):
func = _Task(func)
spec = inspect.getargspec(func.func)
if spec.args:
num_args = len(spec.args)
num_kwargs = len(spec.defaults or [])
isflag = lambda x, y: '' if x.defaults[y] is False else '='
func.args = sp... | [
"def",
"_taskify",
"(",
"func",
")",
":",
"if",
"not",
"isinstance",
"(",
"func",
",",
"_Task",
")",
":",
"func",
"=",
"_Task",
"(",
"func",
")",
"spec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
".",
"func",
")",
"if",
"spec",
".",
"args",
... | 30.789474 | 0.031509 |
def alts(args):
"""
%prog alts HD
Build alternative loci based on simulation data.
"""
import pysam
from jcvi.utils.iter import pairwise
from jcvi.utils.grouper import Grouper
p = OptionParser(alts.__doc__)
p.set_outfile(outfile="TREDs.alts.csv")
opts, args = p.parse_args(args)... | [
"def",
"alts",
"(",
"args",
")",
":",
"import",
"pysam",
"from",
"jcvi",
".",
"utils",
".",
"iter",
"import",
"pairwise",
"from",
"jcvi",
".",
"utils",
".",
"grouper",
"import",
"Grouper",
"p",
"=",
"OptionParser",
"(",
"alts",
".",
"__doc__",
")",
"p"... | 33.950495 | 0.001984 |
def hkdf(master_secret, # type: bytes
num_keys, # type: int
hash_algo='SHA256', # type: str
salt=None, # type: Optional[bytes]
info=None, # type: Optional[bytes]
key_size=DEFAULT_KEY_SIZE # type: int
):
# type: (...) -> Tuple[bytes, ...]
"""
Execut... | [
"def",
"hkdf",
"(",
"master_secret",
",",
"# type: bytes",
"num_keys",
",",
"# type: int",
"hash_algo",
"=",
"'SHA256'",
",",
"# type: str",
"salt",
"=",
"None",
",",
"# type: Optional[bytes]",
"info",
"=",
"None",
",",
"# type: Optional[bytes]",
"key_size",
"=",
... | 51.28125 | 0.000598 |
def list_endpoints_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_endpoints_for_all_namespaces(async_re... | [
"def",
"list_endpoints_for_all_namespaces",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"list_endpoints_for_all_name... | 168.62963 | 0.002402 |
def match_any_paths(pathnames,
included_patterns=None,
excluded_patterns=None,
case_sensitive=True):
"""
Matches from a set of paths based on acceptable patterns and
ignorable patterns.
:param pathnames:
A list of path names that will ... | [
"def",
"match_any_paths",
"(",
"pathnames",
",",
"included_patterns",
"=",
"None",
",",
"excluded_patterns",
"=",
"None",
",",
"case_sensitive",
"=",
"True",
")",
":",
"included",
"=",
"[",
"\"*\"",
"]",
"if",
"included_patterns",
"is",
"None",
"else",
"includ... | 41.782609 | 0.001525 |
def time_signature_event(self, meter=(4, 4)):
"""Return a time signature event for meter."""
numer = a2b_hex('%02x' % meter[0])
denom = a2b_hex('%02x' % int(log(meter[1], 2)))
return self.delta_time + META_EVENT + TIME_SIGNATURE + '\x04' + numer\
+ denom + '\x18\x08' | [
"def",
"time_signature_event",
"(",
"self",
",",
"meter",
"=",
"(",
"4",
",",
"4",
")",
")",
":",
"numer",
"=",
"a2b_hex",
"(",
"'%02x'",
"%",
"meter",
"[",
"0",
"]",
")",
"denom",
"=",
"a2b_hex",
"(",
"'%02x'",
"%",
"int",
"(",
"log",
"(",
"mete... | 51.166667 | 0.009615 |
def _add_months(p_sourcedate, p_months):
"""
Adds a number of months to the source date.
Takes into account shorter months and leap years and such.
https://stackoverflow.com/questions/4130922/how-to-increment-datetime-month-in-python
"""
month = p_sourcedate.month - 1 + p_months
year = p_s... | [
"def",
"_add_months",
"(",
"p_sourcedate",
",",
"p_months",
")",
":",
"month",
"=",
"p_sourcedate",
".",
"month",
"-",
"1",
"+",
"p_months",
"year",
"=",
"p_sourcedate",
".",
"year",
"+",
"month",
"//",
"12",
"month",
"=",
"month",
"%",
"12",
"+",
"1",... | 33.285714 | 0.002088 |
def add_cmds_cpdir(cpdir,
cmdpkl,
cpfileglob='checkplot*.pkl*',
require_cmd_magcolor=True,
save_cmd_pngs=False):
'''This adds CMDs for each object in cpdir.
Parameters
----------
cpdir : list of str
This is the directo... | [
"def",
"add_cmds_cpdir",
"(",
"cpdir",
",",
"cmdpkl",
",",
"cpfileglob",
"=",
"'checkplot*.pkl*'",
",",
"require_cmd_magcolor",
"=",
"True",
",",
"save_cmd_pngs",
"=",
"False",
")",
":",
"cplist",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"joi... | 28.348837 | 0.001586 |
def list_inverse_take(list_, index_list):
r"""
Args:
list_ (list): list in sorted domain
index_list (list): index list of the unsorted domain
Note:
Seems to be logically equivalent to
ut.take(list_, ut.argsort(index_list)), but faster
Returns:
list: output_list_... | [
"def",
"list_inverse_take",
"(",
"list_",
",",
"index_list",
")",
":",
"output_list_",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"index_list",
")",
"for",
"item",
",",
"index",
"in",
"zip",
"(",
"list_",
",",
"index_list",
")",
":",
"output_list_",
"[",
... | 32.767442 | 0.000689 |
def ducrss(s1, s2):
"""
Compute the unit vector parallel to the cross product of
two 3-dimensional vectors and the derivative of this unit vector.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ducrss_c.html
:param s1: Left hand state for cross product and derivative.
:type s1: 6-Elem... | [
"def",
"ducrss",
"(",
"s1",
",",
"s2",
")",
":",
"assert",
"len",
"(",
"s1",
")",
"is",
"6",
"and",
"len",
"(",
"s2",
")",
"is",
"6",
"s1",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"s1",
")",
"s2",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"... | 38 | 0.001284 |
def _surfdens(self,R,z,phi=0.,t=0.):
"""
NAME:
_surfdens
PURPOSE:
evaluate the surface density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | [
"def",
"_surfdens",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"return",
"(",
"3.",
"-",
"self",
".",
"alpha",
")",
"/",
"2.",
"/",
"nu",
".",
"pi",
"*",
"z",
"*",
"R",
"**",
"-",
"self",
".",
... | 29.055556 | 0.018519 |
def setup(app):
"""
Install the plugin.
Arguments:
app (sphinx.application.Sphinx):
the Sphinx application context
"""
app.add_config_value("cache_path", "_cache", "")
try:
os.makedirs(app.config.cache_path)
except OSError as error:
if error.errno !=... | [
"def",
"setup",
"(",
"app",
")",
":",
"app",
".",
"add_config_value",
"(",
"\"cache_path\"",
",",
"\"_cache\"",
",",
"\"\"",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"app",
".",
"config",
".",
"cache_path",
")",
"except",
"OSError",
"as",
"error",
... | 20.608696 | 0.002016 |
def arg_to_dict(arg):
"""Convert an argument that can be None, list/tuple or dict to dict
Example::
>>> arg_to_dict(None)
[]
>>> arg_to_dict(['a', 'b'])
{'a':{},'b':{}}
>>> arg_to_dict({'a':{'only': 'id'}, 'b':{'only': 'id'}})
{'a':{'only':'id'},'b':{'only':'id'... | [
"def",
"arg_to_dict",
"(",
"arg",
")",
":",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"[",
"]",
"try",
":",
"arg",
"=",
"dict",
"(",
"arg",
")",
"except",
"ValueError",
":",
"arg",
"=",
"dict",
".",
"fromkeys",
"(",
"list",
"(",
"arg",
")",
"... | 23.545455 | 0.001855 |
def _generate_provenance(self):
"""Function to generate provenance at the end of the IF."""
# noinspection PyTypeChecker
exposure = definition(
self._provenance['exposure_keywords']['exposure'])
# noinspection PyTypeChecker
hazard = definition(
self._prov... | [
"def",
"_generate_provenance",
"(",
"self",
")",
":",
"# noinspection PyTypeChecker",
"exposure",
"=",
"definition",
"(",
"self",
".",
"_provenance",
"[",
"'exposure_keywords'",
"]",
"[",
"'exposure'",
"]",
")",
"# noinspection PyTypeChecker",
"hazard",
"=",
"definiti... | 30.933333 | 0.000835 |
def texttoraster(m):
"""Convert the string *m* to a raster image. Any newlines
in *m* will cause more than one line of output. The
resulting raster will be taller. Prior to rendering each
line, it is padded on the right with enough spaces to make
all lines the same length.
"""
lines = m.spl... | [
"def",
"texttoraster",
"(",
"m",
")",
":",
"lines",
"=",
"m",
".",
"split",
"(",
"'\\n'",
")",
"maxlen",
"=",
"max",
"(",
"len",
"(",
"line",
")",
"for",
"line",
"in",
"lines",
")",
"justified",
"=",
"[",
"line",
".",
"ljust",
"(",
"maxlen",
")",... | 38.8125 | 0.001572 |
def delete(self):
"""Delete this file from the device
.. note::
After deleting the file, this object will no longer contain valid information
and further calls to delete or get_data will return :class:`~.ErrorInfo` objects
"""
target = DeviceTarget(self.device_id)
... | [
"def",
"delete",
"(",
"self",
")",
":",
"target",
"=",
"DeviceTarget",
"(",
"self",
".",
"device_id",
")",
"return",
"self",
".",
"_fssapi",
".",
"delete_file",
"(",
"target",
",",
"self",
".",
"path",
")",
"[",
"self",
".",
"device_id",
"]"
] | 42.888889 | 0.010152 |
def build_output(self, fout):
"""Squash self.out into string.
Join every line in self.out with a new line and write the
result to the output file.
"""
fout.write('\n'.join([s for s in self.out])) | [
"def",
"build_output",
"(",
"self",
",",
"fout",
")",
":",
"fout",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"[",
"s",
"for",
"s",
"in",
"self",
".",
"out",
"]",
")",
")"
] | 32.857143 | 0.008475 |
def capture_file_path(self):
"""
Get the path of the capture
"""
if self._capture_file_name:
return os.path.join(self._project.captures_directory, self._capture_file_name)
else:
return None | [
"def",
"capture_file_path",
"(",
"self",
")",
":",
"if",
"self",
".",
"_capture_file_name",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_project",
".",
"captures_directory",
",",
"self",
".",
"_capture_file_name",
")",
"else",
":",
"r... | 27.333333 | 0.011811 |
def set_env(settings=None, setup_dir=''):
"""
Used in management commands or at the module level of a fabfile to
integrate woven project django.conf settings into fabric, and set the local current
working directory to the distribution root (where setup.py lives).
``settings`` is your django set... | [
"def",
"set_env",
"(",
"settings",
"=",
"None",
",",
"setup_dir",
"=",
"''",
")",
":",
"#switch the working directory to the distribution root where setup.py is",
"if",
"hasattr",
"(",
"env",
",",
"'setup_path'",
")",
"and",
"env",
".",
"setup_path",
":",
"setup_pat... | 37.951923 | 0.014319 |
def resize(self, width, height):
'Set the canvas size in pixels'
self.canvas.SetInitialSize(wx.Size(width, height))
self.window.GetSizer().Fit(self.window) | [
"def",
"resize",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"self",
".",
"canvas",
".",
"SetInitialSize",
"(",
"wx",
".",
"Size",
"(",
"width",
",",
"height",
")",
")",
"self",
".",
"window",
".",
"GetSizer",
"(",
")",
".",
"Fit",
"(",
"... | 44 | 0.011173 |
def OauthAuthorizeApplication(self, oauth_duration = 'hour'):
"""
Authorize an application using oauth. If this function returns True, the obtained oauth token can be retrieved using getResponse and will be in url-parameters format.
TODO: allow the option to ask the user himself for p... | [
"def",
"OauthAuthorizeApplication",
"(",
"self",
",",
"oauth_duration",
"=",
"'hour'",
")",
":",
"if",
"self",
".",
"__session_id__",
"==",
"''",
":",
"self",
".",
"__error__",
"=",
"\"not logged in\"",
"return",
"False",
"# automatically get authorization for the app... | 56.3 | 0.011059 |
def get_collections(self, username="", calculate_size=False, ext_preload=False, offset=0, limit=10):
"""Fetch collection folders
:param username: The user to list folders for, if omitted the authenticated user is used
:param calculate_size: The option to include the content count per each coll... | [
"def",
"get_collections",
"(",
"self",
",",
"username",
"=",
"\"\"",
",",
"calculate_size",
"=",
"False",
",",
"ext_preload",
"=",
"False",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"10",
")",
":",
"if",
"not",
"username",
"and",
"self",
".",
"standa... | 33.963636 | 0.008845 |
def get_branches(self):
"""Return a list with the conditional branch and the default branch."""
if self.else_branch:
return [self.then_branch, self.else_branch]
return [self.then_branch] | [
"def",
"get_branches",
"(",
"self",
")",
":",
"if",
"self",
".",
"else_branch",
":",
"return",
"[",
"self",
".",
"then_branch",
",",
"self",
".",
"else_branch",
"]",
"return",
"[",
"self",
".",
"then_branch",
"]"
] | 43.6 | 0.009009 |
def ra(self,*args,**kwargs):
"""
NAME:
ra
PURPOSE:
return the right ascension
INPUT:
t - (optional) time at which to get ra (can be Quantity)
obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity)
(def... | [
"def",
"ra",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"self",
".",
"_orb",
".",
"ra",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"out",
")",
"==",
"1",
":",
"return",
"out",
"[",
... | 24.151515 | 0.014475 |
def extract_relationtypes(rs3_xml_tree):
"""
extracts the allowed RST relation names and relation types from
an RS3 XML file.
Parameters
----------
rs3_xml_tree : lxml.etree._ElementTree
lxml ElementTree representation of an RS3 XML file
Returns
-------
relations : dict of ... | [
"def",
"extract_relationtypes",
"(",
"rs3_xml_tree",
")",
":",
"return",
"{",
"rel",
".",
"attrib",
"[",
"'name'",
"]",
":",
"rel",
".",
"attrib",
"[",
"'type'",
"]",
"for",
"rel",
"in",
"rs3_xml_tree",
".",
"iter",
"(",
"'rel'",
")",
"if",
"'type'",
"... | 30.15 | 0.001608 |
def xy_to_rgb(self, x, y, bri=1):
"""Converts CIE 1931 x and y coordinates and brightness value from 0 to 1
to a CSS hex color."""
r, g, b = self.color.get_rgb_from_xy_and_brightness(x, y, bri)
return (r, g, b) | [
"def",
"xy_to_rgb",
"(",
"self",
",",
"x",
",",
"y",
",",
"bri",
"=",
"1",
")",
":",
"r",
",",
"g",
",",
"b",
"=",
"self",
".",
"color",
".",
"get_rgb_from_xy_and_brightness",
"(",
"x",
",",
"y",
",",
"bri",
")",
"return",
"(",
"r",
",",
"g",
... | 47.6 | 0.012397 |
def greedy_coloring(adj):
"""Determines a vertex coloring.
Args:
adj (dict): The edge structure of the graph to be colored.
`adj` should be of the form {node: neighbors, ...} where
neighbors is a set.
Returns:
dict: the coloring {node: color, ...}
dict: the ... | [
"def",
"greedy_coloring",
"(",
"adj",
")",
":",
"# now let's start coloring",
"coloring",
"=",
"{",
"}",
"colors",
"=",
"{",
"}",
"possible_colors",
"=",
"{",
"n",
":",
"set",
"(",
"range",
"(",
"len",
"(",
"adj",
")",
")",
")",
"for",
"n",
"in",
"ad... | 29.25 | 0.001504 |
def com_google_fonts_check_name_line_breaks(ttFont):
"""Name table entries should not contain line-breaks."""
failed = False
for name in ttFont["name"].names:
string = name.string.decode(name.getEncoding())
if "\n" in string:
failed = True
yield FAIL, ("Name entry {} on platform {} contains"
... | [
"def",
"com_google_fonts_check_name_line_breaks",
"(",
"ttFont",
")",
":",
"failed",
"=",
"False",
"for",
"name",
"in",
"ttFont",
"[",
"\"name\"",
"]",
".",
"names",
":",
"string",
"=",
"name",
".",
"string",
".",
"decode",
"(",
"name",
".",
"getEncoding",
... | 44.153846 | 0.011945 |
def values_from(self, base):
"""
A reusable generator for increasing pointer-sized values from an address
(usually the stack).
"""
word_bytes = self._cpu.address_bit_size // 8
while True:
yield base
base += word_bytes | [
"def",
"values_from",
"(",
"self",
",",
"base",
")",
":",
"word_bytes",
"=",
"self",
".",
"_cpu",
".",
"address_bit_size",
"//",
"8",
"while",
"True",
":",
"yield",
"base",
"base",
"+=",
"word_bytes"
] | 31.222222 | 0.010381 |
def dot(self, other):
"""
Compute the dot product between the Series and the columns of other.
This method computes the dot product between the Series and another
one, or the Series and each columns of a DataFrame, or the Series and
each columns of an array.
It can also... | [
"def",
"dot",
"(",
"self",
",",
"other",
")",
":",
"from",
"pandas",
".",
"core",
".",
"frame",
"import",
"DataFrame",
"if",
"isinstance",
"(",
"other",
",",
"(",
"Series",
",",
"DataFrame",
")",
")",
":",
"common",
"=",
"self",
".",
"index",
".",
... | 35.948052 | 0.000703 |
def vcs_upload():
"""
Uploads the project with the selected VCS tool.
"""
if env.deploy_tool == "git":
remote_path = "ssh://%s@%s%s" % (env.user, env.host_string,
env.repo_path)
if not exists(env.repo_path):
run("mkdir -p %s" % env.rep... | [
"def",
"vcs_upload",
"(",
")",
":",
"if",
"env",
".",
"deploy_tool",
"==",
"\"git\"",
":",
"remote_path",
"=",
"\"ssh://%s@%s%s\"",
"%",
"(",
"env",
".",
"user",
",",
"env",
".",
"host_string",
",",
"env",
".",
"repo_path",
")",
"if",
"not",
"exists",
... | 41.703704 | 0.000868 |
def dict_mirror(d,**kwargs):
'''
d = {1:'a',2:'a',3:'b'}
'''
md = {}
if('sort_func' in kwargs):
sort_func = kwargs['sort_func']
else:
sort_func = sorted
vl = list(d.values())
uvl = elel.uniqualize(vl)
for v in uvl:
kl = _keys_via_value_nonrecur(d,v)
... | [
"def",
"dict_mirror",
"(",
"d",
",",
"*",
"*",
"kwargs",
")",
":",
"md",
"=",
"{",
"}",
"if",
"(",
"'sort_func'",
"in",
"kwargs",
")",
":",
"sort_func",
"=",
"kwargs",
"[",
"'sort_func'",
"]",
"else",
":",
"sort_func",
"=",
"sorted",
"vl",
"=",
"li... | 22.3125 | 0.008065 |
def main (args):
"""Usage: create_sedml output-filename
"""
if (len(args) != 2):
print(main.__doc__)
sys.exit(1);
# create the document
doc = libsedml.SedDocument();
doc.setLevel(1);
doc.setVersion(1);
# create a first model referencing an sbml file
model = doc.createModel();
model.setId("... | [
"def",
"main",
"(",
"args",
")",
":",
"if",
"(",
"len",
"(",
"args",
")",
"!=",
"2",
")",
":",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# create the document",
"doc",
"=",
"libsedml",
".",
"SedDocument",
"(",
... | 28.406504 | 0.055863 |
def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None,
maxifds=None):
"""Read tags from chain of IFDs and return as list of dicts.
The file handle position must be at a valid IFD header.
"""
if offsetsize == 4:
offsetformat = byteorder+'I'
tagnosize = 2
... | [
"def",
"read_tags",
"(",
"fh",
",",
"byteorder",
",",
"offsetsize",
",",
"tagnames",
",",
"customtags",
"=",
"None",
",",
"maxifds",
"=",
"None",
")",
":",
"if",
"offsetsize",
"==",
"4",
":",
"offsetformat",
"=",
"byteorder",
"+",
"'I'",
"tagnosize",
"="... | 35.641509 | 0.000258 |
def end_element(self, name):
"""If end tag is our tag, call add_url()."""
self.in_tag = False
if name == self.tag:
self.add_url() | [
"def",
"end_element",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"in_tag",
"=",
"False",
"if",
"name",
"==",
"self",
".",
"tag",
":",
"self",
".",
"add_url",
"(",
")"
] | 32.2 | 0.012121 |
def getColRowWithinChannel(self, ra, dec, ch, wantZeroOffset=False,
allowIllegalReturnValues=True):
"""Returns (col, row) given a (ra, dec) coordinate and channel number.
"""
# How close is a given ra/dec to the origin of a KeplerModule?
x, y = self.default... | [
"def",
"getColRowWithinChannel",
"(",
"self",
",",
"ra",
",",
"dec",
",",
"ch",
",",
"wantZeroOffset",
"=",
"False",
",",
"allowIllegalReturnValues",
"=",
"True",
")",
":",
"# How close is a given ra/dec to the origin of a KeplerModule?",
"x",
",",
"y",
"=",
"self",... | 42.594595 | 0.002481 |
def _psql_cmd(*args, **kwargs):
'''
Return string with fully composed psql command.
Accepts optional keyword arguments: user, host, port and maintenance_db,
as well as any number of positional arguments to be added to the end of
the command.
'''
(user, host, port, maintenance_db) = _connect... | [
"def",
"_psql_cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"(",
"user",
",",
"host",
",",
"port",
",",
"maintenance_db",
")",
"=",
"_connection_defaults",
"(",
"kwargs",
".",
"get",
"(",
"'user'",
")",
",",
"kwargs",
".",
"get",
"(",
... | 31.066667 | 0.001041 |
def parse_query(self, query):
"""Parse query string using given grammar"""
tree = pypeg2.parse(query, Main, whitespace="")
return tree.accept(self.converter) | [
"def",
"parse_query",
"(",
"self",
",",
"query",
")",
":",
"tree",
"=",
"pypeg2",
".",
"parse",
"(",
"query",
",",
"Main",
",",
"whitespace",
"=",
"\"\"",
")",
"return",
"tree",
".",
"accept",
"(",
"self",
".",
"converter",
")"
] | 44.5 | 0.01105 |
def drop_cache(self):
'''
Drops all changes in the cache.
'''
del self._cache
self._cache = {}
del self._wqueue
self._wqueue = set()
self._cur_size = 0 | [
"def",
"drop_cache",
"(",
"self",
")",
":",
"del",
"self",
".",
"_cache",
"self",
".",
"_cache",
"=",
"{",
"}",
"del",
"self",
".",
"_wqueue",
"self",
".",
"_wqueue",
"=",
"set",
"(",
")",
"self",
".",
"_cur_size",
"=",
"0"
] | 24 | 0.013393 |
def relaxNGNewDocParserCtxt(self):
"""Create an XML RelaxNGs parser context for that document.
Note: since the process of compiling a RelaxNG schemas
modifies the document, the @doc parameter is duplicated
internally. """
ret = libxml2mod.xmlRelaxNGNewDocParserCtxt(self._o... | [
"def",
"relaxNGNewDocParserCtxt",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlRelaxNGNewDocParserCtxt",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlRelaxNGNewDocParserCtxt() failed'",
")",
"__tmp",
... | 50.888889 | 0.008584 |
def normalize_name(self, header_name):
""" Return header name as it is recommended (required) by corresponding http protocol. For
protocol switching use :meth:`.WHTTPHeaders.switch_name_style` method.
All current available protocols (0.9-2) compare header names in a case-insensitive fashion. However,
previous ... | [
"def",
"normalize_name",
"(",
"self",
",",
"header_name",
")",
":",
"if",
"self",
".",
"__normalization_mode",
"in",
"[",
"'0.9'",
",",
"'1.0'",
",",
"'1.1'",
"]",
":",
"return",
"'-'",
".",
"join",
"(",
"[",
"x",
".",
"capitalize",
"(",
")",
"for",
... | 50.625 | 0.02303 |
async def get(self, public_key):
"""Receives public key, looking up document at storage,
sends document id to the balance server
"""
if settings.SIGNATURE_VERIFICATION:
super().verify()
response = await self.account.getnews(public_key=public_key)
# If we`ve got a empty or list with news
if isinstan... | [
"async",
"def",
"get",
"(",
"self",
",",
"public_key",
")",
":",
"if",
"settings",
".",
"SIGNATURE_VERIFICATION",
":",
"super",
"(",
")",
".",
"verify",
"(",
")",
"response",
"=",
"await",
"self",
".",
"account",
".",
"getnews",
"(",
"public_key",
"=",
... | 27.458333 | 0.036657 |
def rts_smooth(kalman_filter, state_count=None):
"""
Compute the Rauch-Tung-Striebel smoothed state estimates and estimate
covariances for a Kalman filter.
Args:
kalman_filter (KalmanFilter): Filter whose smoothed states should be
returned
state_count (int or None): Number o... | [
"def",
"rts_smooth",
"(",
"kalman_filter",
",",
"state_count",
"=",
"None",
")",
":",
"if",
"state_count",
"is",
"None",
":",
"state_count",
"=",
"kalman_filter",
".",
"state_count",
"state_count",
"=",
"int",
"(",
"state_count",
")",
"if",
"state_count",
"<",... | 35.66 | 0.001092 |
def do_update(self, line):
"""update <old-pid> <new-pid> <file> Replace an existing Science Object in a.
:term:`MN` with another.
"""
curr_pid, pid_new, input_file = self._split_args(line, 3, 0)
self._command_processor.science_object_update(curr_pid, input_file, pid_new)
... | [
"def",
"do_update",
"(",
"self",
",",
"line",
")",
":",
"curr_pid",
",",
"pid_new",
",",
"input_file",
"=",
"self",
".",
"_split_args",
"(",
"line",
",",
"3",
",",
"0",
")",
"self",
".",
"_command_processor",
".",
"science_object_update",
"(",
"curr_pid",
... | 39.909091 | 0.011136 |
def setupNodding(self):
"""
Setup Nodding for GTC
"""
g = get_root(self).globals
if not self.nod():
# re-enable clear mode box if not drift
if not self.isDrift():
self.clear.enable()
# clear existing nod pattern
se... | [
"def",
"setupNodding",
"(",
"self",
")",
":",
"g",
"=",
"get_root",
"(",
"self",
")",
".",
"globals",
"if",
"not",
"self",
".",
"nod",
"(",
")",
":",
"# re-enable clear mode box if not drift",
"if",
"not",
"self",
".",
"isDrift",
"(",
")",
":",
"self",
... | 30.027778 | 0.002239 |
def push(self, dir):
"""Push cwd on stack and change to 'dir'.
"""
self.stack.append(os.getcwd())
os.chdir(dir or os.getcwd()) | [
"def",
"push",
"(",
"self",
",",
"dir",
")",
":",
"self",
".",
"stack",
".",
"append",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"os",
".",
"chdir",
"(",
"dir",
"or",
"os",
".",
"getcwd",
"(",
")",
")"
] | 30.8 | 0.012658 |
def _is_valid_dist_file(filename, filetype):
"""
Perform some basic checks to see whether the indicated file could be
a valid distribution file.
"""
# If our file is a zipfile, then ensure that it's members are only
# compressed with supported compression methods.
if zipfile.is_zipfile(file... | [
"def",
"_is_valid_dist_file",
"(",
"filename",
",",
"filetype",
")",
":",
"# If our file is a zipfile, then ensure that it's members are only",
"# compressed with supported compression methods.",
"if",
"zipfile",
".",
"is_zipfile",
"(",
"filename",
")",
":",
"with",
"zipfile",
... | 41.654321 | 0.00029 |
def uniform_html(html):
'''Takes a utf-8-encoded string of HTML as input and returns a new
HTML string with fixed quoting and close tags, which generally
should not break any of the offsets and makes it easier for
functions like
:func:`streamcorpus_pipeline.offsets.char_offsets_to_xpaths` to
ope... | [
"def",
"uniform_html",
"(",
"html",
")",
":",
"doc",
"=",
"html5lib",
".",
"parse",
"(",
"html",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"config",
"=",
"{",
"'omit_optional_tags'",
":",
"False",
",",
"'encoding'",
":",
"'utf-8'",
",",
"'quote_attr_values'... | 35.3125 | 0.001724 |
def open(self):
"""
Obtains the lvm, vg_t and lv_t handle. Usually you would never need to use this
method unless you are doing operations using the ctypes function wrappers in
conversion.py
*Raises:*
* HandleError
"""
self.vg.open()
self._... | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"vg",
".",
"open",
"(",
")",
"self",
".",
"__lvh",
"=",
"lvm_lv_from_uuid",
"(",
"self",
".",
"vg",
".",
"handle",
",",
"self",
".",
"uuid",
")",
"if",
"not",
"bool",
"(",
"self",
".",
"__lvh",
... | 32.5 | 0.008547 |
def add_network_profile(self, obj, params):
"""Add an AP profile for connecting to afterward."""
reason_code = DWORD()
params.process_akm()
profile_data = {}
profile_data['ssid'] = params.ssid
if AKM_TYPE_NONE in params.akm:
profile_data['auth'] = auth_valu... | [
"def",
"add_network_profile",
"(",
"self",
",",
"obj",
",",
"params",
")",
":",
"reason_code",
"=",
"DWORD",
"(",
")",
"params",
".",
"process_akm",
"(",
")",
"profile_data",
"=",
"{",
"}",
"profile_data",
"[",
"'ssid'",
"]",
"=",
"params",
".",
"ssid",
... | 34.376812 | 0.002049 |
async def dump_variant(self, elem, elem_type=None, params=None, obj=None):
"""
Dumps variant type to the writer.
Supports both wrapped and raw variant.
:param elem:
:param elem_type:
:param params:
:param obj:
:return:
"""
fvalue = None
... | [
"async",
"def",
"dump_variant",
"(",
"self",
",",
"elem",
",",
"elem_type",
"=",
"None",
",",
"params",
"=",
"None",
",",
"obj",
"=",
"None",
")",
":",
"fvalue",
"=",
"None",
"if",
"isinstance",
"(",
"elem",
",",
"x",
".",
"VariantType",
")",
"or",
... | 33.472222 | 0.002419 |
def add_if_not_none(cls, dict_, key, value):
"""
:type dict_: dict[str, str]
:type key: str
:type value: float
:rtype: None
"""
if value is not None:
dict_[key] = str(value) | [
"def",
"add_if_not_none",
"(",
"cls",
",",
"dict_",
",",
"key",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"dict_",
"[",
"key",
"]",
"=",
"str",
"(",
"value",
")"
] | 21.181818 | 0.00823 |
def getj9dict(dbname = abrevDBname, manualDB = manualDBname, returnDict ='both'):
"""Returns the dictionary of journal abbreviations mapping to a list of the associated journal names. By default the local database is used. The database is in the file _dbname_ in the same directory as this source file
# Paramet... | [
"def",
"getj9dict",
"(",
"dbname",
"=",
"abrevDBname",
",",
"manualDB",
"=",
"manualDBname",
",",
"returnDict",
"=",
"'both'",
")",
":",
"dbLoc",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")"... | 49.930233 | 0.013705 |
def verify_tokens(self):
"""
Deprecated, will be made private in 2.4
"""
xidentity = key_utils.get_compressed_public_key_from_pem(self.pem)
url = self.uri + "/tokens"
xsignature = key_utils.sign(self.uri + "/tokens", self.pem)
headers = {"content-type": "application/json", 'accept': 'applica... | [
"def",
"verify_tokens",
"(",
"self",
")",
":",
"xidentity",
"=",
"key_utils",
".",
"get_compressed_public_key_from_pem",
"(",
"self",
".",
"pem",
")",
"url",
"=",
"self",
".",
"uri",
"+",
"\"/tokens\"",
"xsignature",
"=",
"key_utils",
".",
"sign",
"(",
"self... | 47.8125 | 0.012821 |
def dist_grid(grid, source, target=None):
"""Distances in a grid by BFS
:param grid: matrix with 4-neighborhood
:param (int,int) source: pair of row, column indices
:param (int,int) target: exploration stops if target is reached
:complexity: linear in grid size
"""
rows = len(grid)
cols... | [
"def",
"dist_grid",
"(",
"grid",
",",
"source",
",",
"target",
"=",
"None",
")",
":",
"rows",
"=",
"len",
"(",
"grid",
")",
"cols",
"=",
"len",
"(",
"grid",
"[",
"0",
"]",
")",
"dirs",
"=",
"[",
"(",
"0",
",",
"+",
"1",
",",
"'>'",
")",
","... | 35.862069 | 0.000936 |
def getP1(self):
"""
Left, upper point
"""
return Point(self.center[0] - self.radius,
self.center[1] - self.radius) | [
"def",
"getP1",
"(",
"self",
")",
":",
"return",
"Point",
"(",
"self",
".",
"center",
"[",
"0",
"]",
"-",
"self",
".",
"radius",
",",
"self",
".",
"center",
"[",
"1",
"]",
"-",
"self",
".",
"radius",
")"
] | 27.166667 | 0.011905 |
def get_absolute_url(self):
"""
URLs for blog posts can either be just their slug, or prefixed
with a portion of the post's publish date, controlled by the
setting ``BLOG_URLS_DATE_FORMAT``, which can contain the value
``year``, ``month``, or ``day``. Each of these maps to the na... | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"url_name",
"=",
"\"blog_post_detail\"",
"kwargs",
"=",
"{",
"\"slug\"",
":",
"self",
".",
"slug",
"}",
"date_parts",
"=",
"(",
"\"year\"",
",",
"\"month\"",
",",
"\"day\"",
")",
"if",
"settings",
".",
"BLO... | 50.68 | 0.001549 |
def Zigrang_Sylvester_1(Re, eD):
r'''Calculates Darcy friction factor using the method in
Zigrang and Sylvester (1982) [2]_ as shown in [1]_.
.. math::
\frac{1}{\sqrt{f_f}} = -4\log\left[\frac{\epsilon}{3.7D}
- \frac{5.02}{Re}\log A_5\right]
A_5 = \frac{\epsilon}{3.7D} + \frac{13}... | [
"def",
"Zigrang_Sylvester_1",
"(",
"Re",
",",
"eD",
")",
":",
"A5",
"=",
"eD",
"/",
"3.7",
"+",
"13",
"/",
"Re",
"ff",
"=",
"(",
"-",
"4",
"*",
"log10",
"(",
"eD",
"/",
"3.7",
"-",
"5.02",
"/",
"Re",
"*",
"log10",
"(",
"A5",
")",
")",
")",
... | 28.181818 | 0.000779 |
def _bnd(self, xloc, dist, cache):
"""Distribution bounds."""
return numpy.log10(evaluation.evaluate_bound(
dist, 10**xloc, cache=cache)) | [
"def",
"_bnd",
"(",
"self",
",",
"xloc",
",",
"dist",
",",
"cache",
")",
":",
"return",
"numpy",
".",
"log10",
"(",
"evaluation",
".",
"evaluate_bound",
"(",
"dist",
",",
"10",
"**",
"xloc",
",",
"cache",
"=",
"cache",
")",
")"
] | 40.5 | 0.012121 |
def lists_eq(list1, list2):
""" recursive """
if len(list1) != len(list2):
return False
for count, (item1, item2) in enumerate(zip(list1, list2)):
if isinstance(item1, np.ndarray) or isinstance(item2, np.ndarray):
failed = not np.all(item1 == item2) # lists_eq(item1, item2)
... | [
"def",
"lists_eq",
"(",
"list1",
",",
"list2",
")",
":",
"if",
"len",
"(",
"list1",
")",
"!=",
"len",
"(",
"list2",
")",
":",
"return",
"False",
"for",
"count",
",",
"(",
"item1",
",",
"item2",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"list1",
",... | 34.5 | 0.002353 |
def zipObject(self, values):
"""
Zip together two arrays -- an array of keys and an array
of values -- into a single object.
"""
result = {}
keys = self.obj
i = 0
l = len(keys)
while i < l:
result[keys[i]] = values[i]
l = le... | [
"def",
"zipObject",
"(",
"self",
",",
"values",
")",
":",
"result",
"=",
"{",
"}",
"keys",
"=",
"self",
".",
"obj",
"i",
"=",
"0",
"l",
"=",
"len",
"(",
"keys",
")",
"while",
"i",
"<",
"l",
":",
"result",
"[",
"keys",
"[",
"i",
"]",
"]",
"=... | 24.466667 | 0.010499 |
def log_raise(log, err_str, err_type=RuntimeError):
"""Log an error message and raise an error.
Arguments
---------
log : `logging.Logger` object
err_str : str
Error message to be logged and raised.
err_type : `Exception` object
Type of error to raise.
"""
log.error(err... | [
"def",
"log_raise",
"(",
"log",
",",
"err_str",
",",
"err_type",
"=",
"RuntimeError",
")",
":",
"log",
".",
"error",
"(",
"err_str",
")",
"# Make sure output is flushed",
"# (happens automatically to `StreamHandlers`, but not `FileHandlers`)",
"for",
"handle",
"in",
"lo... | 27.473684 | 0.001852 |
def add_block_parser(subparsers, parent_parser):
"""Adds arguments parsers for the block list and block show commands
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object
"""
parser = subparsers.add_parser(
'... | [
"def",
"add_block_parser",
"(",
"subparsers",
",",
"parent_parser",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'block'",
",",
"description",
"=",
"'Provides subcommands to display information about the '",
"'blocks in the current blockchain.'",
",",
"he... | 33.113208 | 0.000553 |
def user(self):
"""
Returns the current user set by current context
"""
return self.users.get(self.contexts[self.current_context].get("user", ""), {}) | [
"def",
"user",
"(",
"self",
")",
":",
"return",
"self",
".",
"users",
".",
"get",
"(",
"self",
".",
"contexts",
"[",
"self",
".",
"current_context",
"]",
".",
"get",
"(",
"\"user\"",
",",
"\"\"",
")",
",",
"{",
"}",
")"
] | 35.6 | 0.016484 |
def isdir(path):
"""
Return True if path is an existing directory.
Equivalent to "os.path.isdir".
Args:
path (path-like object): Path or URL.
Returns:
bool: True if directory exists.
"""
system = get_instance(path)
# User may use directory path without trailing '/'
... | [
"def",
"isdir",
"(",
"path",
")",
":",
"system",
"=",
"get_instance",
"(",
"path",
")",
"# User may use directory path without trailing '/'",
"# like on standard file systems",
"return",
"system",
".",
"isdir",
"(",
"system",
".",
"ensure_dir_path",
"(",
"path",
")",
... | 23 | 0.002457 |
def activateAndRaise(self):
""" Activates and raises the window.
"""
logger.debug("Activate and raising window: {}".format(self.windowNumber))
self.activateWindow()
self.raise_() | [
"def",
"activateAndRaise",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Activate and raising window: {}\"",
".",
"format",
"(",
"self",
".",
"windowNumber",
")",
")",
"self",
".",
"activateWindow",
"(",
")",
"self",
".",
"raise_",
"(",
")"
] | 35.5 | 0.013761 |
def resolve_tag(name, **kwargs):
'''
.. versionadded:: 2017.7.2
.. versionchanged:: 2018.3.0
Instead of matching against pulled tags using
:py:func:`docker.list_tags <salt.modules.dockermod.list_tags>`, this
function now simply inspects the passed image name using
:py:func:`d... | [
"def",
"resolve_tag",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"__utils__",
"[",
"'args.clean_kwargs'",
"]",
"(",
"*",
"*",
"kwargs",
")",
"all_",
"=",
"kwargs",
".",
"pop",
"(",
"'all'",
",",
"False",
")",
"if",
"kwargs",
":",
... | 35.969697 | 0.00041 |
def meff_hh_110(self, **kwargs):
'''
Returns the heavy-hole band effective mass in the [110] direction,
meff_hh_110, in units of electron mass.
'''
return 2. / (2 * self.luttinger1(**kwargs) - self.luttinger2(**kwargs)
- 3 * self.luttinger3(**kwargs)) | [
"def",
"meff_hh_110",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"2.",
"/",
"(",
"2",
"*",
"self",
".",
"luttinger1",
"(",
"*",
"*",
"kwargs",
")",
"-",
"self",
".",
"luttinger2",
"(",
"*",
"*",
"kwargs",
")",
"-",
"3",
"*",
"sel... | 43 | 0.009772 |
def rmse(targets, predictions):
r"""
Compute the root mean squared error between two SArrays.
Parameters
----------
targets : SArray[float or int]
An Sarray of ground truth target values.
predictions : SArray[float or int]
The prediction that corresponds to each target value.
... | [
"def",
"rmse",
"(",
"targets",
",",
"predictions",
")",
":",
"_supervised_evaluation_error_checking",
"(",
"targets",
",",
"predictions",
")",
"return",
"_turicreate",
".",
"extensions",
".",
"_supervised_streaming_evaluator",
"(",
"targets",
",",
"predictions",
",",
... | 25.893617 | 0.001584 |
def analysis(self):
"""Get ANALYSIS segment of the FCS file."""
if self._analysis is None:
with open(self.path, 'rb') as f:
self.read_analysis(f)
return self._analysis | [
"def",
"analysis",
"(",
"self",
")",
":",
"if",
"self",
".",
"_analysis",
"is",
"None",
":",
"with",
"open",
"(",
"self",
".",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"self",
".",
"read_analysis",
"(",
"f",
")",
"return",
"self",
".",
"_analysis"... | 35.666667 | 0.009132 |
def fit_mcmc(self,nwalkers=300,nburn=200,niter=100,
p0=None,initial_burn=None,
ninitial=100, loglike_kwargs=None,
**kwargs):
"""Fits stellar model using MCMC.
:param nwalkers: (optional)
Number of walkers to pass to :class:`emcee.EnsembleSa... | [
"def",
"fit_mcmc",
"(",
"self",
",",
"nwalkers",
"=",
"300",
",",
"nburn",
"=",
"200",
",",
"niter",
"=",
"100",
",",
"p0",
"=",
"None",
",",
"initial_burn",
"=",
"None",
",",
"ninitial",
"=",
"100",
",",
"loglike_kwargs",
"=",
"None",
",",
"*",
"*... | 39.646465 | 0.01218 |
def wait_for_processes(processes, size, progress_queue, watcher, item):
"""
Watch progress queue for errors or progress.
Cleanup processes on error or success.
:param processes: [Process]: processes we are waiting to finish downloading a file
:param size: int: how many values we expect to be process... | [
"def",
"wait_for_processes",
"(",
"processes",
",",
"size",
",",
"progress_queue",
",",
"watcher",
",",
"item",
")",
":",
"while",
"size",
">",
"0",
":",
"progress_type",
",",
"value",
"=",
"progress_queue",
".",
"get",
"(",
")",
"if",
"progress_type",
"==... | 44.703704 | 0.002433 |
def write_groovy_script_and_configs(
filename, content, job_configs, view_configs=None):
"""Write out the groovy script and configs to file.
This writes the reconfigure script to the file location
and places the expanded configs in subdirectories 'view_configs' /
'job_configs' that the script c... | [
"def",
"write_groovy_script_and_configs",
"(",
"filename",
",",
"content",
",",
"job_configs",
",",
"view_configs",
"=",
"None",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"h",
":",
"h",
".",
"write",
"(",
"content",
")",
"if",
"vi... | 42.090909 | 0.001407 |
def get_entity_class(resource):
"""
Returns the entity class registered for the given registered resource.
:param resource: registered resource
:type collection: class implementing or instance providing a registered
resource interface.
:return: entity class
(class implementing `ever... | [
"def",
"get_entity_class",
"(",
"resource",
")",
":",
"reg",
"=",
"get_current_registry",
"(",
")",
"if",
"IInterface",
"in",
"provided_by",
"(",
"resource",
")",
":",
"ent_cls",
"=",
"reg",
".",
"getUtility",
"(",
"resource",
",",
"name",
"=",
"'entity-clas... | 36.8125 | 0.001656 |
def get_article(self, url=None, article_id=None, max_pages=25):
"""
Send a GET request to the `parser` endpoint of the parser API to get
back the representation of an article.
The article can be identified by either a URL or an id that exists
in Readability.
Note that e... | [
"def",
"get_article",
"(",
"self",
",",
"url",
"=",
"None",
",",
"article_id",
"=",
"None",
",",
"max_pages",
"=",
"25",
")",
":",
"query_params",
"=",
"{",
"}",
"if",
"url",
"is",
"not",
"None",
":",
"query_params",
"[",
"'url'",
"]",
"=",
"url",
... | 41.5 | 0.001963 |
def typelogged_class(cls):
"""Works like typelogged, but is only applicable to classes.
"""
if not pytypes.typelogging_enabled:
return cls
assert(isclass(cls))
# To play it safe we avoid to modify the dict while iterating over it,
# so we previously cache keys.
# For this we don't us... | [
"def",
"typelogged_class",
"(",
"cls",
")",
":",
"if",
"not",
"pytypes",
".",
"typelogging_enabled",
":",
"return",
"cls",
"assert",
"(",
"isclass",
"(",
"cls",
")",
")",
"# To play it safe we avoid to modify the dict while iterating over it,",
"# so we previously cache k... | 35.444444 | 0.001527 |
def reset_weights(self):
""" Initialize weights to reasonable defaults """
self.input_block.reset_weights()
self.backbone.reset_weights()
self.q_head.reset_weights() | [
"def",
"reset_weights",
"(",
"self",
")",
":",
"self",
".",
"input_block",
".",
"reset_weights",
"(",
")",
"self",
".",
"backbone",
".",
"reset_weights",
"(",
")",
"self",
".",
"q_head",
".",
"reset_weights",
"(",
")"
] | 38.6 | 0.010152 |
def active_multiplex(self, state: 'State') -> Tuple['Multiplex']:
"""
Return a tuple of all the active multiplex in the given state.
"""
return tuple(multiplex for multiplex in self.multiplexes if multiplex.is_active(state)) | [
"def",
"active_multiplex",
"(",
"self",
",",
"state",
":",
"'State'",
")",
"->",
"Tuple",
"[",
"'Multiplex'",
"]",
":",
"return",
"tuple",
"(",
"multiplex",
"for",
"multiplex",
"in",
"self",
".",
"multiplexes",
"if",
"multiplex",
".",
"is_active",
"(",
"st... | 50.4 | 0.011719 |
def get_degradations(self):
"""Extract Degradation INDRA Statements."""
deg_events = self.tree.findall("EVENT/[type='ONT::CONSUME']")
for event in deg_events:
if event.attrib['id'] in self._static_events:
continue
affected = event.find(".//*[@role=':AFFECT... | [
"def",
"get_degradations",
"(",
"self",
")",
":",
"deg_events",
"=",
"self",
".",
"tree",
".",
"findall",
"(",
"\"EVENT/[type='ONT::CONSUME']\"",
")",
"for",
"event",
"in",
"deg_events",
":",
"if",
"event",
".",
"attrib",
"[",
"'id'",
"]",
"in",
"self",
".... | 43.24 | 0.001809 |
def get_chron_data(temp_sheet, row, total_vars):
"""
Capture all data in for a specific chron data row (for csv output)
:param obj temp_sheet:
:param int row:
:param int total_vars:
:return list: data_row
"""
data_row = []
missing_val_list = ['none', 'na', '', '-']
for i in range... | [
"def",
"get_chron_data",
"(",
"temp_sheet",
",",
"row",
",",
"total_vars",
")",
":",
"data_row",
"=",
"[",
"]",
"missing_val_list",
"=",
"[",
"'none'",
",",
"'na'",
",",
"''",
",",
"'-'",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"total_vars",
"... | 30.111111 | 0.001789 |
async def handle_request(self, request):
"""Respond to request if PIN is correct."""
service_name = request.rel_url.query['servicename']
received_code = request.rel_url.query['pairingcode'].lower()
_LOGGER.info('Got pairing request from %s with code %s',
service_name... | [
"async",
"def",
"handle_request",
"(",
"self",
",",
"request",
")",
":",
"service_name",
"=",
"request",
".",
"rel_url",
".",
"query",
"[",
"'servicename'",
"]",
"received_code",
"=",
"request",
".",
"rel_url",
".",
"query",
"[",
"'pairingcode'",
"]",
".",
... | 46.294118 | 0.002491 |
def get_changelog(project_dir=os.curdir, bugtracker_url='', rpm_format=False):
"""
Retrieves the changelog, from the CHANGELOG file (if in a package) or
generates it from the git history. Optionally in rpm-compatible format.
:param project_dir: Path to the git repo of the project.
:type project_dir... | [
"def",
"get_changelog",
"(",
"project_dir",
"=",
"os",
".",
"curdir",
",",
"bugtracker_url",
"=",
"''",
",",
"rpm_format",
"=",
"False",
")",
":",
"changelog",
"=",
"''",
"pkg_info_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"project_dir",
",",
"'PK... | 37.37931 | 0.000899 |
def findPrev( self,
text,
wholeWords = False,
caseSensitive = False,
regexed = False,
wrap = True ):
"""
Looks up the previous iteration for the inputed search term.
:param t... | [
"def",
"findPrev",
"(",
"self",
",",
"text",
",",
"wholeWords",
"=",
"False",
",",
"caseSensitive",
"=",
"False",
",",
"regexed",
"=",
"False",
",",
"wrap",
"=",
"True",
")",
":",
"lineFrom",
",",
"indexFrom",
",",
"lineTo",
",",
"indexTo",
"=",
"self"... | 35.185185 | 0.025615 |
def CreateBlockDeviceMap(self, image_id, instance_type):
"""
If you launch without specifying a manual device block mapping, you may
not get all the ephemeral devices available to the given instance type.
This will build one that ensures all available ephemeral devices are
mapped.
... | [
"def",
"CreateBlockDeviceMap",
"(",
"self",
",",
"image_id",
",",
"instance_type",
")",
":",
"# get the block device mapping stored with the image",
"image",
"=",
"self",
".",
"ec2",
".",
"get_image",
"(",
"image_id",
")",
"block_device_map",
"=",
"image",
".",
"blo... | 50.571429 | 0.018484 |
def step_prev_line(self):
"""Sets cursor as end of previous line."""
#TODO(bps): raise explicit error for unregistered eol
#assert self._eol[-1].index == self._index
if len(self._eol) > 0:
self.position = self._eol.pop() | [
"def",
"step_prev_line",
"(",
"self",
")",
":",
"#TODO(bps): raise explicit error for unregistered eol",
"#assert self._eol[-1].index == self._index",
"if",
"len",
"(",
"self",
".",
"_eol",
")",
">",
"0",
":",
"self",
".",
"position",
"=",
"self",
".",
"_eol",
".",
... | 43.166667 | 0.015152 |
def word_score(word, input_letters, questions=0):
"""Checks the Scrabble score of a single word.
Args:
word: a string to check the Scrabble score of
input_letters: the letters in our rack
questions: integer of the tiles already on the board to build on
Returns:
an integer S... | [
"def",
"word_score",
"(",
"word",
",",
"input_letters",
",",
"questions",
"=",
"0",
")",
":",
"score",
"=",
"0",
"bingo",
"=",
"0",
"filled_by_blanks",
"=",
"[",
"]",
"rack",
"=",
"list",
"(",
"input_letters",
")",
"# make a copy to speed up find_anagrams()",
... | 30.527778 | 0.000882 |
def load_definition_by_name(name: str) -> dict:
"""
Look up and return a definition by name (name is expected to correspond to
the filename of the definition, with the .json extension) and return it or
raise an exception
:param name: A string to use for looking up a labware defintion previously
... | [
"def",
"load_definition_by_name",
"(",
"name",
":",
"str",
")",
"->",
"dict",
":",
"def_path",
"=",
"'shared_data/definitions2/{}.json'",
".",
"format",
"(",
"name",
".",
"lower",
"(",
")",
")",
"labware_def",
"=",
"json",
".",
"loads",
"(",
"pkgutil",
".",
... | 48 | 0.001572 |
def set_up_logging():
"""Configure the TensorFlow logger."""
tf.logging.set_verbosity(tf.logging.INFO)
logging.getLogger('tensorflow').propagate = False | [
"def",
"set_up_logging",
"(",
")",
":",
"tf",
".",
"logging",
".",
"set_verbosity",
"(",
"tf",
".",
"logging",
".",
"INFO",
")",
"logging",
".",
"getLogger",
"(",
"'tensorflow'",
")",
".",
"propagate",
"=",
"False"
] | 38.75 | 0.025316 |
def read_catalog_info_yaml(self, splitkey):
""" Read the yaml file for a particular split key
"""
catalog_info_yaml = self._name_factory.catalog_split_yaml(sourcekey=splitkey,
fullpath=True)
yaml_dict = yaml.safe_load(open... | [
"def",
"read_catalog_info_yaml",
"(",
"self",
",",
"splitkey",
")",
":",
"catalog_info_yaml",
"=",
"self",
".",
"_name_factory",
".",
"catalog_split_yaml",
"(",
"sourcekey",
"=",
"splitkey",
",",
"fullpath",
"=",
"True",
")",
"yaml_dict",
"=",
"yaml",
".",
"sa... | 55.1 | 0.010714 |
def set_items(self, item_list):
"""Set items in the disco#items object.
All previous items are removed.
:Parameters:
- `item_list`: list of items or item properties
(jid,node,name,action).
:Types:
- `item_list`: sequence of `DiscoItem` or sequence ... | [
"def",
"set_items",
"(",
"self",
",",
"item_list",
")",
":",
"for",
"item",
"in",
"self",
".",
"items",
":",
"item",
".",
"remove",
"(",
")",
"for",
"item",
"in",
"item_list",
":",
"try",
":",
"self",
".",
"add_item",
"(",
"item",
".",
"jid",
",",
... | 32.055556 | 0.008418 |
def delete(source_name, size, metadata_backend=None, storage_backend=None):
"""
Deletes a thumbnail file and its relevant metadata.
"""
if storage_backend is None:
storage_backend = backends.storage.get_backend()
if metadata_backend is None:
metadata_backend = backends.metadata.get_b... | [
"def",
"delete",
"(",
"source_name",
",",
"size",
",",
"metadata_backend",
"=",
"None",
",",
"storage_backend",
"=",
"None",
")",
":",
"if",
"storage_backend",
"is",
"None",
":",
"storage_backend",
"=",
"backends",
".",
"storage",
".",
"get_backend",
"(",
")... | 44.2 | 0.002217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.