text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def column_rename(self, existing_name, hsh=None):
"""
Like unique_name, but in addition must be unique to each column of this
feature. accomplishes this by prepending readable string to existing
column name and replacing unique hash at end of column name.
"""
try:
... | [
"def",
"column_rename",
"(",
"self",
",",
"existing_name",
",",
"hsh",
"=",
"None",
")",
":",
"try",
":",
"existing_name",
"=",
"str",
"(",
"existing_name",
")",
"except",
"UnicodeEncodeError",
":",
"pass",
"if",
"hsh",
"is",
"None",
":",
"hsh",
"=",
"se... | 39.294118 | 0.010234 |
def create_random_ind_full(self, depth=0):
"Random individual using full method"
lst = []
self._create_random_ind_full(depth=depth, output=lst)
return lst | [
"def",
"create_random_ind_full",
"(",
"self",
",",
"depth",
"=",
"0",
")",
":",
"lst",
"=",
"[",
"]",
"self",
".",
"_create_random_ind_full",
"(",
"depth",
"=",
"depth",
",",
"output",
"=",
"lst",
")",
"return",
"lst"
] | 36.4 | 0.010753 |
def _find_files(dl_paths, publisher, url_dict):
"""Find files corresponding to urls."""
if publisher == 'cnn':
top_dir = os.path.join(dl_paths['cnn_stories'], 'cnn', 'stories')
elif publisher == 'dm':
top_dir = os.path.join(dl_paths['dm_stories'], 'dailymail', 'stories')
else:
logging.fatal('Unsuppo... | [
"def",
"_find_files",
"(",
"dl_paths",
",",
"publisher",
",",
"url_dict",
")",
":",
"if",
"publisher",
"==",
"'cnn'",
":",
"top_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dl_paths",
"[",
"'cnn_stories'",
"]",
",",
"'cnn'",
",",
"'stories'",
")",
... | 35.625 | 0.017094 |
def download_ts(self, path, chunk, process_last_line=True):
"""
This will look for a download ts link.
It will then download that file and replace the
link with the local file.
:param process_last_line:
:param path: str of the path to put the file
:param chunk: s... | [
"def",
"download_ts",
"(",
"self",
",",
"path",
",",
"chunk",
",",
"process_last_line",
"=",
"True",
")",
":",
"import",
"glob",
"ret_chunk",
"=",
"[",
"]",
"partial_chunk",
"=",
"''",
"lines",
"=",
"chunk",
".",
"strip",
"(",
")",
".",
"split",
"(",
... | 40.44186 | 0.001123 |
def deliver_hook(instance, target, payload_override=None):
"""
Deliver the payload to the target URL.
By default it serializes to JSON and POSTs.
"""
payload = payload_override or serialize_hook(instance)
if hasattr(settings, 'HOOK_DELIVERER'):
deliverer = get_module(settings.HOOK_DELIV... | [
"def",
"deliver_hook",
"(",
"instance",
",",
"target",
",",
"payload_override",
"=",
"None",
")",
":",
"payload",
"=",
"payload_override",
"or",
"serialize_hook",
"(",
"instance",
")",
"if",
"hasattr",
"(",
"settings",
",",
"'HOOK_DELIVERER'",
")",
":",
"deliv... | 32.166667 | 0.001678 |
def gen_hash(crypt_salt=None, password=None, algorithm='sha512'):
'''
Generate /etc/shadow hash
'''
if not HAS_CRYPT:
raise SaltInvocationError('No crypt module for windows')
hash_algorithms = dict(
md5='$1$', blowfish='$2a$', sha256='$5$', sha512='$6$'
)
if algorithm not in... | [
"def",
"gen_hash",
"(",
"crypt_salt",
"=",
"None",
",",
"password",
"=",
"None",
",",
"algorithm",
"=",
"'sha512'",
")",
":",
"if",
"not",
"HAS_CRYPT",
":",
"raise",
"SaltInvocationError",
"(",
"'No crypt module for windows'",
")",
"hash_algorithms",
"=",
"dict"... | 27.541667 | 0.001462 |
def run(self, dag):
"""Run the CommutativeCancellation pass on a dag
Args:
dag (DAGCircuit): the DAG to be optimized.
Returns:
DAGCircuit: the optimized DAG.
Raises:
TranspilerError: when the 1 qubit rotation gates are not found
"""
... | [
"def",
"run",
"(",
"self",
",",
"dag",
")",
":",
"q_gate_list",
"=",
"[",
"'cx'",
",",
"'cy'",
",",
"'cz'",
",",
"'h'",
",",
"'x'",
",",
"'y'",
",",
"'z'",
"]",
"# Gate sets to be cancelled",
"cancellation_sets",
"=",
"defaultdict",
"(",
"lambda",
":",
... | 44.538462 | 0.002253 |
def notimplemented (func):
"""Raises a NotImplementedError if the function is called."""
def newfunc (*args, **kwargs):
"""Raise NotImplementedError"""
co = func.func_code
attrs = (co.co_name, co.co_filename, co.co_firstlineno)
raise NotImplementedError("function %s at %s:%d is n... | [
"def",
"notimplemented",
"(",
"func",
")",
":",
"def",
"newfunc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Raise NotImplementedError\"\"\"",
"co",
"=",
"func",
".",
"func_code",
"attrs",
"=",
"(",
"co",
".",
"co_name",
",",
"co",
".",
... | 47.5 | 0.010336 |
def add_source_override(self, fullname, path, source, is_pkg):
"""
See :meth:`ModuleFinder.add_source_override.
"""
self._finder.add_source_override(fullname, path, source, is_pkg) | [
"def",
"add_source_override",
"(",
"self",
",",
"fullname",
",",
"path",
",",
"source",
",",
"is_pkg",
")",
":",
"self",
".",
"_finder",
".",
"add_source_override",
"(",
"fullname",
",",
"path",
",",
"source",
",",
"is_pkg",
")"
] | 41.6 | 0.009434 |
def close(self):
"""Close child subprocess"""
if self._subprocess is not None:
os.killpg(self._subprocess.pid, signal.SIGTERM)
self._subprocess = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subprocess",
"is",
"not",
"None",
":",
"os",
".",
"killpg",
"(",
"self",
".",
"_subprocess",
".",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"self",
".",
"_subprocess",
"=",
"None"
] | 37.2 | 0.010526 |
def _gen_recurse_managed_files(
name,
source,
keep_symlinks=False,
include_pat=None,
exclude_pat=None,
maxdepth=None,
include_empty=False,
**kwargs):
'''
Generate the list of files managed by a recurse state
'''
# Convert a relative path g... | [
"def",
"_gen_recurse_managed_files",
"(",
"name",
",",
"source",
",",
"keep_symlinks",
"=",
"False",
",",
"include_pat",
"=",
"None",
",",
"exclude_pat",
"=",
"None",
",",
"maxdepth",
"=",
"None",
",",
"include_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
... | 36.420635 | 0.000212 |
def send_email(from_addr: str,
host: str,
user: str,
password: str,
port: int = None,
use_tls: bool = True,
date: str = None,
sender: str = "",
reply_to: Union[str, List[str]] = "",
to:... | [
"def",
"send_email",
"(",
"from_addr",
":",
"str",
",",
"host",
":",
"str",
",",
"user",
":",
"str",
",",
"password",
":",
"str",
",",
"port",
":",
"int",
"=",
"None",
",",
"use_tls",
":",
"bool",
"=",
"True",
",",
"date",
":",
"str",
"=",
"None"... | 34.099291 | 0.000202 |
def find(self, **filter_args):
"""
Find exactly one resource in scope of this manager, by matching
resource properties against the specified filter arguments, and return
its Python resource object (e.g. for a CPC, a :class:`~zhmcclient.Cpc`
object is returned).
Any resou... | [
"def",
"find",
"(",
"self",
",",
"*",
"*",
"filter_args",
")",
":",
"obj_list",
"=",
"self",
".",
"findall",
"(",
"*",
"*",
"filter_args",
")",
"num_objs",
"=",
"len",
"(",
"obj_list",
")",
"if",
"num_objs",
"==",
"0",
":",
"raise",
"NotFound",
"(",
... | 37.679487 | 0.000663 |
def dalignbedqueriesseq2dalignbedstats(cfg):
"""
Gets scores for queries
step#7
:param cfg: configuration dict
"""
datatmpd=cfg['datatmpd']
dalignbedqueriesseq=del_Unnamed(pd.read_csv(cfg['dalignbedqueriesseqp'],sep='\t'))
dalignbedstatsp=cfg['dalignbedstatsp']
logging.info(b... | [
"def",
"dalignbedqueriesseq2dalignbedstats",
"(",
"cfg",
")",
":",
"datatmpd",
"=",
"cfg",
"[",
"'datatmpd'",
"]",
"dalignbedqueriesseq",
"=",
"del_Unnamed",
"(",
"pd",
".",
"read_csv",
"(",
"cfg",
"[",
"'dalignbedqueriesseqp'",
"]",
",",
"sep",
"=",
"'\\t'",
... | 37.363636 | 0.024911 |
def modification_time(self):
"""dfdatetime.DateTimeValues: modification time or None if not available."""
timestamp = getattr(
self._cpio_archive_file_entry, 'modification_time', None)
if timestamp is None:
return None
return dfdatetime_posix_time.PosixTime(timestamp=timestamp) | [
"def",
"modification_time",
"(",
"self",
")",
":",
"timestamp",
"=",
"getattr",
"(",
"self",
".",
"_cpio_archive_file_entry",
",",
"'modification_time'",
",",
"None",
")",
"if",
"timestamp",
"is",
"None",
":",
"return",
"None",
"return",
"dfdatetime_posix_time",
... | 43.142857 | 0.00974 |
def wrap_function_cols(self, name, package_name=None, object_name=None, java_class_instance=None, doc=""):
"""Utility method for wrapping a scala/java function that returns a spark sql Column.
This assumes that the function that you are wrapping takes a list of spark sql Column objects as its arguments... | [
"def",
"wrap_function_cols",
"(",
"self",
",",
"name",
",",
"package_name",
"=",
"None",
",",
"object_name",
"=",
"None",
",",
"java_class_instance",
"=",
"None",
",",
"doc",
"=",
"\"\"",
")",
":",
"def",
"_",
"(",
"*",
"cols",
")",
":",
"jcontainer",
... | 52.5625 | 0.008178 |
def get_locus(sequences, kir=False, verbose=False, refdata=None, evalue=10):
"""
Gets the locus of the sequence by running blastn
:param sequences: sequenences to blast
:param kir: bool whether the sequences are KIR or not
:rtype: ``str``
Example usage:
>>> from Bio.Seq import Seq
... | [
"def",
"get_locus",
"(",
"sequences",
",",
"kir",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"refdata",
"=",
"None",
",",
"evalue",
"=",
"10",
")",
":",
"if",
"not",
"refdata",
":",
"refdata",
"=",
"ReferenceData",
"(",
")",
"file_id",
"=",
"st... | 29.983051 | 0.001095 |
def engage(self, **kwargs):
'''
Move the magnet to either:
the default height for the labware loaded on magdeck
[engage()]
or a +/- 'offset' from the default height for the labware
[engage(offset=2)]
or a 'height' value specified as mm from magdeck h... | [
"def",
"engage",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'height'",
"in",
"kwargs",
":",
"height",
"=",
"kwargs",
".",
"get",
"(",
"'height'",
")",
"else",
":",
"height",
"=",
"LABWARE_ENGAGE_HEIGHT",
".",
"get",
"(",
"self",
".",
"lab... | 42.392857 | 0.001647 |
def create(config_name, srmfile=None, dataformat=None, base_on='DEFAULT', make_default=False):
"""
Adds a new configuration to latools.cfg.
Parameters
----------
config_name : str
The name of the new configuration. This should be descriptive
(e.g. UC Davis Foram Group)
srmfile :... | [
"def",
"create",
"(",
"config_name",
",",
"srmfile",
"=",
"None",
",",
"dataformat",
"=",
"None",
",",
"base_on",
"=",
"'DEFAULT'",
",",
"make_default",
"=",
"False",
")",
":",
"base_config",
"=",
"read_configuration",
"(",
"base_on",
")",
"# read config file"... | 30.039216 | 0.001896 |
def ensure_alt_ids_are_only_in_one_nest(nest_spec, list_elements):
"""
Ensures that the alternative id's in `nest_spec` are only associated with
a single nest. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings... | [
"def",
"ensure_alt_ids_are_only_in_one_nest",
"(",
"nest_spec",
",",
"list_elements",
")",
":",
"try",
":",
"assert",
"len",
"(",
"set",
"(",
"list_elements",
")",
")",
"==",
"len",
"(",
"list_elements",
")",
"except",
"AssertionError",
":",
"msg",
"=",
"\"Eac... | 34.111111 | 0.001056 |
def _connect(self):
"Wrap the socket with SSL support"
sock = super(SSLConnection, self)._connect()
if hasattr(ssl, "create_default_context"):
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = self.cert_reqs
... | [
"def",
"_connect",
"(",
"self",
")",
":",
"sock",
"=",
"super",
"(",
"SSLConnection",
",",
"self",
")",
".",
"_connect",
"(",
")",
"if",
"hasattr",
"(",
"ssl",
",",
"\"create_default_context\"",
")",
":",
"context",
"=",
"ssl",
".",
"create_default_context... | 48.136364 | 0.001852 |
def tonal_distance(pianoroll_1, pianoroll_2, beat_resolution, r1=1.0, r2=1.0,
r3=0.5):
"""Return the tonal distance [1] between the two input pianorolls.
[1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting
harmonic change in musical audio. In Proc. ACM Workshop on Audio... | [
"def",
"tonal_distance",
"(",
"pianoroll_1",
",",
"pianoroll_2",
",",
"beat_resolution",
",",
"r1",
"=",
"1.0",
",",
"r2",
"=",
"1.0",
",",
"r3",
"=",
"0.5",
")",
":",
"_validate_pianoroll",
"(",
"pianoroll_1",
")",
"_validate_pianoroll",
"(",
"pianoroll_2",
... | 47.277778 | 0.001151 |
def spacegroup_from_data(no=None, symbol=None, setting=1,
centrosymmetric=None, scaled_primitive_cell=None,
reciprocal_cell=None, subtrans=None, sitesym=None,
rotations=None, translations=None, datafile=None):
"""Manually create a new spa... | [
"def",
"spacegroup_from_data",
"(",
"no",
"=",
"None",
",",
"symbol",
"=",
"None",
",",
"setting",
"=",
"1",
",",
"centrosymmetric",
"=",
"None",
",",
"scaled_primitive_cell",
"=",
"None",
",",
"reciprocal_cell",
"=",
"None",
",",
"subtrans",
"=",
"None",
... | 43.307692 | 0.002316 |
def csv_dict_format(csv_data, c_headers=None, r_headers=None):
"""
Format csv rows parsed to Dict.
"""
# format dict if has row_headers
if r_headers:
result = {}
for k_index in range(0, len(csv_data)):
if r_headers[k_index]:
result[r_headers[k_index]] = co... | [
"def",
"csv_dict_format",
"(",
"csv_data",
",",
"c_headers",
"=",
"None",
",",
"r_headers",
"=",
"None",
")",
":",
"# format dict if has row_headers",
"if",
"r_headers",
":",
"result",
"=",
"{",
"}",
"for",
"k_index",
"in",
"range",
"(",
"0",
",",
"len",
"... | 31.333333 | 0.001475 |
def cols_(df,col_list,func,*args,**kwargs):
""" Do a function over a list of columns and return the result
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to coerce
func - function
function to use
"""
return _pd.DataFrame... | [
"def",
"cols_",
"(",
"df",
",",
"col_list",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_pd",
".",
"DataFrame",
"(",
"{",
"col_name",
":",
"func",
"(",
"df",
",",
"col_name",
",",
"*",
"args",
",",
"*",
"*",
"kw... | 34.545455 | 0.025641 |
def calc_ea_sm_v1(self):
"""Calculate soil evaporation and update soil moisture.
Required control parameters:
|NmbZones|
|ZoneType|
|FC|
|LP|
|ERed|
Required fluxes sequences:
|EPC|
|EI|
Required state sequence:
|SP|
Calculated flux sequence:
... | [
"def",
"calc_ea_sm_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"sta",
"=",
"self",
".",
"sequences",
".",
"states",
".",
"... | 30.892308 | 0.000241 |
def get_nodes(environment=None):
"""Gets all nodes found in the nodes/ directory"""
if not os.path.exists('nodes'):
return []
nodes = []
for filename in sorted(
[f for f in os.listdir('nodes')
if (not os.path.isdir(f)
and f.endswith(".json") and not f.st... | [
"def",
"get_nodes",
"(",
"environment",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"'nodes'",
")",
":",
"return",
"[",
"]",
"nodes",
"=",
"[",
"]",
"for",
"filename",
"in",
"sorted",
"(",
"[",
"f",
"for",
"f",
"in"... | 39.785714 | 0.001754 |
def create_backend_noexc(log: logging.Logger, name: str=None, git_index: GitIndex=None,
args: str=None) -> Optional[StorageBackend]:
"""Initialize a new Backend, return None if there was a known problem."""
try:
return create_backend(name, git_index, args)
except KeyError:
... | [
"def",
"create_backend_noexc",
"(",
"log",
":",
"logging",
".",
"Logger",
",",
"name",
":",
"str",
"=",
"None",
",",
"git_index",
":",
"GitIndex",
"=",
"None",
",",
"args",
":",
"str",
"=",
"None",
")",
"->",
"Optional",
"[",
"StorageBackend",
"]",
":"... | 45.25 | 0.01444 |
def leapyear_observed(self, value=None):
"""Corresponds to IDD Field `leapyear_observed` Yes if Leap Year will
be observed for this file No if Leap Year days (29 Feb) should be
ignored in this file.
Args:
value (str): value for IDD Field `leapyear_observed`
A... | [
"def",
"leapyear_observed",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"str",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of typ... | 38.647059 | 0.001485 |
def new_credentials(cls):
"""Create a new Security object with a new certificate/key pair."""
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serial... | [
"def",
"new_credentials",
"(",
"cls",
")",
":",
"from",
"cryptography",
"import",
"x509",
"from",
"cryptography",
".",
"hazmat",
".",
"backends",
"import",
"default_backend",
"from",
"cryptography",
".",
"hazmat",
".",
"primitives",
"import",
"hashes",
"from",
"... | 46.625 | 0.001313 |
def request(self, url, method, body="", headers={}, retry=True):
"""Execute an HTTP request and return a dict containing the response
and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project I... | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"method",
",",
"body",
"=",
"\"\"",
",",
"headers",
"=",
"{",
"}",
",",
"retry",
"=",
"True",
")",
":",
"if",
"headers",
":",
"headers",
"=",
"dict",
"(",
"list",
"(",
"headers",
".",
"items",
"(",
... | 37.467742 | 0.001258 |
def delete(args):
"""Deletes the jobs from the job manager. If the jobs are still running in the grid, they are stopped."""
jm = setup(args)
# first, stop the jobs if they are running in the grid
if not args.local and 'executing' in args.status:
stop(args)
# then, delete them from the database
jm.delete... | [
"def",
"delete",
"(",
"args",
")",
":",
"jm",
"=",
"setup",
"(",
"args",
")",
"# first, stop the jobs if they are running in the grid",
"if",
"not",
"args",
".",
"local",
"and",
"'executing'",
"in",
"args",
".",
"status",
":",
"stop",
"(",
"args",
")",
"# th... | 58.625 | 0.018908 |
def array_scanlines_interlace(self, pixels):
"""
Generator for interlaced scanlines from an array. `pixels` is
the full source image in flat row flat pixel format. The
generator yields each scanline of the reduced passes in turn, in
boxed row flat pixel format.
"""
... | [
"def",
"array_scanlines_interlace",
"(",
"self",
",",
"pixels",
")",
":",
"# http://www.w3.org/TR/PNG/#8InterlaceMethods",
"# Array type.",
"fmt",
"=",
"'BH'",
"[",
"self",
".",
"bitdepth",
">",
"8",
"]",
"# Value per row",
"vpr",
"=",
"self",
".",
"width",
"*",
... | 42.228571 | 0.001323 |
def _get_list(self, value, context=None):
"""
Get a configuration value. The result is None if "value" is None,
otherwise the result is a list.
"value" may be a list, dict, or str value.
If a list, each element of the list may be a list, dict, or
str value, and the val... | [
"def",
"_get_list",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"log",
"=",
"self",
".",
"_params",
".",
"get",
"(",
"'log'",
",",
"self",
".",
"_discard",
")",
"res",
"=",
"[",
"]",
"if",
"value",
"is",
"None",
":",
"return... | 37.657895 | 0.001362 |
def _get_field(self, field):
"""
Queries the api for a single field for the record by `id`.
This method should only be called indirectly by cached properties.
:param field: name of the record field to load
"""
if not hasattr(self, "id") or self.id is None:
rai... | [
"def",
"_get_field",
"(",
"self",
",",
"field",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"id\"",
")",
"or",
"self",
".",
"id",
"is",
"None",
":",
"raise",
"APIResponseError",
"(",
"\"Cannot query an article without an id\"",
")",
"sq",
"=",
"n... | 45.863636 | 0.001942 |
def _fit_strel_to_im_2d(im, strel, r, x, y):
r"""
Helper function to add a structuring element to a 2D image.
Used by RSA. Makes sure if center is less than r pixels from edge of image
that the strel is sliced to fit.
"""
elem = strel.copy()
x_dim, y_dim = im.shape
x_min = x-r
x_max ... | [
"def",
"_fit_strel_to_im_2d",
"(",
"im",
",",
"strel",
",",
"r",
",",
"x",
",",
"y",
")",
":",
"elem",
"=",
"strel",
".",
"copy",
"(",
")",
"x_dim",
",",
"y_dim",
"=",
"im",
".",
"shape",
"x_min",
"=",
"x",
"-",
"r",
"x_max",
"=",
"x",
"+",
"... | 26.551724 | 0.001253 |
def plotwrapper(f):
"""
This decorator allows for PyMC arguments of various types to be passed to
the plotting functions. It identifies the type of object and locates its
trace(s), then passes the data to the wrapped plotting function.
"""
def wrapper(pymc_obj, *args, **kwargs):
start ... | [
"def",
"plotwrapper",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"pymc_obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"start",
"=",
"0",
"if",
"'start'",
"in",
"kwargs",
":",
"start",
"=",
"kwargs",
".",
"pop",
"(",
"'start'",
")",
"#... | 32.426471 | 0.00088 |
def _iter_year_month(year_info):
""" Iter the month days in a lunar year.
"""
# info => month, days, leap
leap_month, leap_days = _parse_leap(year_info)
months = [(i, 0) for i in range(1, 13)]
if leap_month > 0:
months.insert(leap_month, (leap_month, 1))
for month, leap in months:
... | [
"def",
"_iter_year_month",
"(",
"year_info",
")",
":",
"# info => month, days, leap",
"leap_month",
",",
"leap_days",
"=",
"_parse_leap",
"(",
"year_info",
")",
"months",
"=",
"[",
"(",
"i",
",",
"0",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"13",
... | 30.133333 | 0.002146 |
def process(self, data_changed_callback):
"""Process data; returns when the reader signals EOF.
Callback is notified when any data changes."""
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
while True:
byte = self._reader.read(1)
while Tr... | [
"def",
"process",
"(",
"self",
",",
"data_changed_callback",
")",
":",
"# pylint: disable=too-many-locals,too-many-branches,too-many-statements",
"while",
"True",
":",
"byte",
"=",
"self",
".",
"_reader",
".",
"read",
"(",
"1",
")",
"while",
"True",
":",
"# Search f... | 45.458333 | 0.000256 |
def String(self, str):
"""Get an interned string from the reader, allows for example
to speedup string name comparisons """
ret = libxml2mod.xmlTextReaderConstString(self._o, str)
return ret | [
"def",
"String",
"(",
"self",
",",
"str",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlTextReaderConstString",
"(",
"self",
".",
"_o",
",",
"str",
")",
"return",
"ret"
] | 44.2 | 0.008889 |
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Set CPC Power Capping (any CPC mode)."""
assert wait_for_completion is True # async not supported yet
cpc_oid = uri_parms[0]
try:
cpc = hmc.cpcs.lookup_by_oid(cpc_oid... | [
"def",
"post",
"(",
"method",
",",
"hmc",
",",
"uri",
",",
"uri_parms",
",",
"body",
",",
"logon_required",
",",
"wait_for_completion",
")",
":",
"assert",
"wait_for_completion",
"is",
"True",
"# async not supported yet",
"cpc_oid",
"=",
"uri_parms",
"[",
"0",
... | 50.071429 | 0.002099 |
def deprecated(since, message='', name='', alternative='', pending=False,
addendum='', removal=''):
"""
Decorator to mark a function or a class as deprecated.
Parameters
----------
since : str
The release at which this API became deprecated. This is
required.
mess... | [
"def",
"deprecated",
"(",
"since",
",",
"message",
"=",
"''",
",",
"name",
"=",
"''",
",",
"alternative",
"=",
"''",
",",
"pending",
"=",
"False",
",",
"addendum",
"=",
"''",
",",
"removal",
"=",
"''",
")",
":",
"def",
"deprecate",
"(",
"obj",
",",... | 37.563107 | 0.000252 |
def get_env(path, ignore_git_branch=False):
"""Determine environment name."""
if 'DEPLOY_ENVIRONMENT' in os.environ:
return os.environ['DEPLOY_ENVIRONMENT']
if ignore_git_branch:
LOGGER.info('Skipping environment lookup from current git branch '
'("ignore_git_branch" is ... | [
"def",
"get_env",
"(",
"path",
",",
"ignore_git_branch",
"=",
"False",
")",
":",
"if",
"'DEPLOY_ENVIRONMENT'",
"in",
"os",
".",
"environ",
":",
"return",
"os",
".",
"environ",
"[",
"'DEPLOY_ENVIRONMENT'",
"]",
"if",
"ignore_git_branch",
":",
"LOGGER",
".",
"... | 39.222222 | 0.000922 |
def arctic_setting(setting_name, valid_options=None):
"""
Tries to get a setting from the django settings, if not available defaults
to the one defined in defaults.py
"""
try:
value = getattr(settings, setting_name)
if valid_options and value not in valid_options:
error_m... | [
"def",
"arctic_setting",
"(",
"setting_name",
",",
"valid_options",
"=",
"None",
")",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"settings",
",",
"setting_name",
")",
"if",
"valid_options",
"and",
"value",
"not",
"in",
"valid_options",
":",
"error_message"... | 39.866667 | 0.001634 |
def channels_set_type(self, room_id, a_type, **kwargs):
"""Sets the type of room this channel should be. The type of room this channel should be, either c or p."""
return self.__call_api_post('channels.setType', roomId=room_id, type=a_type, kwargs=kwargs) | [
"def",
"channels_set_type",
"(",
"self",
",",
"room_id",
",",
"a_type",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'channels.setType'",
",",
"roomId",
"=",
"room_id",
",",
"type",
"=",
"a_type",
",",
"kwargs",
"=",
... | 89.666667 | 0.01476 |
def enum(self):
"""
Enumeration of allowed object values.
The enumeration must not contain duplicates.
"""
value = self._schema.get("enum", None)
if value is None:
return
if not isinstance(value, list):
raise SchemaError(
"... | [
"def",
"enum",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"_schema",
".",
"get",
"(",
"\"enum\"",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"raise",
"SchemaE... | 31.92 | 0.002433 |
def _wait_for_consistency(checker):
"""Eventual consistency: wait until GCS reports something is true.
This is necessary for e.g. create/delete where the operation might return,
but won't be reflected for a bit.
"""
for _ in xrange(EVENTUAL_CONSISTENCY_MAX_SLEEPS):
if checker():
... | [
"def",
"_wait_for_consistency",
"(",
"checker",
")",
":",
"for",
"_",
"in",
"xrange",
"(",
"EVENTUAL_CONSISTENCY_MAX_SLEEPS",
")",
":",
"if",
"checker",
"(",
")",
":",
"return",
"time",
".",
"sleep",
"(",
"EVENTUAL_CONSISTENCY_SLEEP_INTERVAL",
")",
"logger",
"."... | 37.5 | 0.001859 |
def _get_disksize_MiB(iLOIP, cred):
"""Reads the dictionary of parsed MIBs and gets the disk size.
:param iLOIP: IP address of the server on which SNMP discovery
has to be executed.
:param snmp_credentials in a dictionary having following mandatory
keys.
auth_user: S... | [
"def",
"_get_disksize_MiB",
"(",
"iLOIP",
",",
"cred",
")",
":",
"# '1.3.6.1.4.1.232.5.5.1.1', # cpqscsi SAS HBA Table",
"# '1.3.6.1.4.1.232.3.2.3.1', # cpqida Drive Array Logical Drive Table",
"result",
"=",
"_parse_mibs",
"(",
"iLOIP",
",",
"cred",
")",
"disksize",
"=",
"... | 41.285714 | 0.000845 |
def enabled(name):
'''
Ensure an Apache conf is enabled.
name
Name of the Apache conf
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
is_enabled = __salt__['apache.check_conf_enabled'](name)
if not is_enabled:
if __opts__['test']:
msg = 'A... | [
"def",
"enabled",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"is_enabled",
"=",
"__salt__",
"[",
"'apache.check_conf_enabled'",
"]",
"(... | 35 | 0.000869 |
def put_log_events(awsclient, log_group_name, log_stream_name, log_events,
sequence_token=None):
"""Put log events for the specified log group and stream.
:param log_group_name: log group name
:param log_stream_name: log stream name
:param log_events: [{'timestamp': 123, 'message': '... | [
"def",
"put_log_events",
"(",
"awsclient",
",",
"log_group_name",
",",
"log_stream_name",
",",
"log_events",
",",
"sequence_token",
"=",
"None",
")",
":",
"client_logs",
"=",
"awsclient",
".",
"get_client",
"(",
"'logs'",
")",
"request",
"=",
"{",
"'logGroupName... | 36.666667 | 0.001107 |
def _read_para_nat_traversal_mode(self, code, cbit, clen, *, desc, length, version):
"""Read HIP NAT_TRAVERSAL_MODE parameter.
Structure of HIP NAT_TRAVERSAL_MODE parameter [RFC 5770]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 ... | [
"def",
"_read_para_nat_traversal_mode",
"(",
"self",
",",
"code",
",",
"cbit",
",",
"clen",
",",
"*",
",",
"desc",
",",
"length",
",",
"version",
")",
":",
"if",
"clen",
"%",
"2",
"!=",
"0",
":",
"raise",
"ProtocolError",
"(",
"f'HIPv{version}: [Parano {co... | 46.217391 | 0.001842 |
def dfs2wfsmat(dfs):
'''
dfs = [[0], [1], [2], [3], [4], [4, 0], [4, 1], [5], [6], [7], [8], [9], [10], [11], [11, 0], [11, 1], [11, 1, 0], [11, 1, 1], [11, 1, 2], [11, 1, 3], [11, 1, 4], [11, 1, 5], [11, 1, 6], [11, 1, 6, 0], [11, 1, 6, 0, 0], [11, 1, 6, 0, 1], [11, 1, 6, 1], [11, 1, 6, 2], [11, 1, 6, 3], ... | [
"def",
"dfs2wfsmat",
"(",
"dfs",
")",
":",
"wfsmat",
"=",
"[",
"]",
"depth",
"=",
"0",
"level",
"=",
"filter",
"(",
"dfs",
",",
"lambda",
"ele",
":",
"ele",
".",
"__len__",
"(",
")",
"==",
"1",
")",
"while",
"(",
"level",
".",
"__len__",
"(",
"... | 54.466667 | 0.012034 |
def setCurveModel(self, model):
"""Sets the stimulus model for the calibration curve test
:param model: Stimulus model that has a tone curve configured
:type model: :class:`StimulusModel <sparkle.stim.stimulus_model.StimulusModel>`
"""
self.stimModel = model
self.ui.curv... | [
"def",
"setCurveModel",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"stimModel",
"=",
"model",
"self",
".",
"ui",
".",
"curveWidget",
".",
"setModel",
"(",
"model",
")"
] | 42 | 0.008746 |
def move(ctx, client, sources, destination):
"""Move files and check repository for potential problems."""
from renku.api._git import _expand_directories
dst = Path(destination)
def fmt_path(path):
"""Format path as relative to the client path."""
return str(Path(path).absolute().relat... | [
"def",
"move",
"(",
"ctx",
",",
"client",
",",
"sources",
",",
"destination",
")",
":",
"from",
"renku",
".",
"api",
".",
"_git",
"import",
"_expand_directories",
"dst",
"=",
"Path",
"(",
"destination",
")",
"def",
"fmt_path",
"(",
"path",
")",
":",
"\... | 33.186813 | 0.000322 |
def _write_data(self, symbols, err_recs, nr_recordings,
total_error_count, percentages, time_max_list):
"""Write all obtained data to a file.
Parameters
----------
symbols : list of tuples (String, non-negative int)
List of all symbols with the count of r... | [
"def",
"_write_data",
"(",
"self",
",",
"symbols",
",",
"err_recs",
",",
"nr_recordings",
",",
"total_error_count",
",",
"percentages",
",",
"time_max_list",
")",
":",
"write_file",
"=",
"open",
"(",
"self",
".",
"filename",
",",
"\"a\"",
")",
"s",
"=",
"\... | 43.211268 | 0.000956 |
def _detect_quotes( sentence_text, wid, fromRight = True ):
''' Searches for quotation marks (both opening and closing) closest to
given location in sentence (given as word index *wid*);
If *fromRight == True* (default), searches from the right (all the
words having index greater ... | [
"def",
"_detect_quotes",
"(",
"sentence_text",
",",
"wid",
",",
"fromRight",
"=",
"True",
")",
":",
"i",
"=",
"wid",
"while",
"(",
"i",
">",
"-",
"1",
"and",
"i",
"<",
"len",
"(",
"sentence_text",
"[",
"WORDS",
"]",
")",
")",
":",
"token",
"=",
"... | 41.947368 | 0.01227 |
def doc_to_lines(self, doc, format_func=None):
"""
Generator that converts a doc to a sequence of lines.
:param doc: A dictionary
:param format_func: customisable formatter defaults to pformat
:return: a generator yielding a line at a time
"""
if format_func:
... | [
"def",
"doc_to_lines",
"(",
"self",
",",
"doc",
",",
"format_func",
"=",
"None",
")",
":",
"if",
"format_func",
":",
"for",
"l",
"in",
"format_func",
"(",
"doc",
")",
".",
"splitlines",
"(",
")",
":",
"yield",
"l",
"elif",
"self",
".",
"pretty_print",
... | 35.5625 | 0.008562 |
def _updateKW(image, filename, exten, skyKW, Value):
"""update the header with the kw,value"""
# Update the value in memory
image.header[skyKW] = Value
# Now update the value on disk
if isinstance(exten,tuple):
strexten = '[%s,%s]'%(exten[0],str(exten[1]))
else:
strexten = '[%s]... | [
"def",
"_updateKW",
"(",
"image",
",",
"filename",
",",
"exten",
",",
"skyKW",
",",
"Value",
")",
":",
"# Update the value in memory",
"image",
".",
"header",
"[",
"skyKW",
"]",
"=",
"Value",
"# Now update the value on disk",
"if",
"isinstance",
"(",
"exten",
... | 39.5 | 0.008834 |
def metadata_converter_help_content():
"""Helper method that returns just the content in extent mode.
This method was added so that the text could be reused in the
wizard.
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message
"""
message = m.Message()
... | [
"def",
"metadata_converter_help_content",
"(",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"paragraph",
"=",
"m",
".",
"Paragraph",
"(",
"tr",
"(",
"'This tool will convert InaSAFE 4.x keyword metadata into the '",
"'metadata format used by InaSAFE 3.5. The pri... | 40.615385 | 0.000925 |
def get_td_at_index(tr, index):
"""
When calculating the rowspan for a given cell it is required to find all
table cells 'below' the initial cell with a v_merge. This function will
return the td element at the passed in index, taking into account colspans.
"""
current = 0
for td in tr.xpath(... | [
"def",
"get_td_at_index",
"(",
"tr",
",",
"index",
")",
":",
"current",
"=",
"0",
"for",
"td",
"in",
"tr",
".",
"xpath",
"(",
"'.//w:tc'",
",",
"namespaces",
"=",
"tr",
".",
"nsmap",
")",
":",
"if",
"index",
"==",
"current",
":",
"return",
"td",
"c... | 39.090909 | 0.002273 |
def inherit_flags(toolset, base, prohibited_properties = []):
"""Brings all flag definitions from the 'base' toolset into the 'toolset'
toolset. Flag definitions whose conditions make use of properties in
'prohibited-properties' are ignored. Don't confuse property and feature, for
example <debug-symbols... | [
"def",
"inherit_flags",
"(",
"toolset",
",",
"base",
",",
"prohibited_properties",
"=",
"[",
"]",
")",
":",
"assert",
"isinstance",
"(",
"toolset",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"base",
",",
"basestring",
")",
"assert",
"is_iterable_type... | 44.566667 | 0.008053 |
def _build_zmat(self, construction_table):
"""Create the Zmatrix from a construction table.
Args:
Construction table (pd.DataFrame):
Returns:
Zmat: A new instance of :class:`Zmat`.
"""
c_table = construction_table
default_cols = ['atom', 'b', 'bo... | [
"def",
"_build_zmat",
"(",
"self",
",",
"construction_table",
")",
":",
"c_table",
"=",
"construction_table",
"default_cols",
"=",
"[",
"'atom'",
",",
"'b'",
",",
"'bond'",
",",
"'a'",
",",
"'angle'",
",",
"'d'",
",",
"'dihedral'",
"]",
"optional_cols",
"=",... | 38.857143 | 0.001794 |
def toggleCollapseAfter( self ):
"""
Collapses the splitter after this handle.
"""
if ( self.isCollapsed() ):
self.uncollapse()
else:
self.collapse( XSplitterHandle.CollapseDirection.After ) | [
"def",
"toggleCollapseAfter",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"isCollapsed",
"(",
")",
")",
":",
"self",
".",
"uncollapse",
"(",
")",
"else",
":",
"self",
".",
"collapse",
"(",
"XSplitterHandle",
".",
"CollapseDirection",
".",
"After",
")"... | 30.875 | 0.031496 |
def get_program_duration(program):
'''
Get a program's duration in seconds
'''
program_start = program.get('start_time')
program_end = program.get('end_time')
if not program_start or not program_end:
_LOGGER.error('Could not determine program start and/or end times.')
_LOGGER.deb... | [
"def",
"get_program_duration",
"(",
"program",
")",
":",
"program_start",
"=",
"program",
".",
"get",
"(",
"'start_time'",
")",
"program_end",
"=",
"program",
".",
"get",
"(",
"'end_time'",
")",
"if",
"not",
"program_start",
"or",
"not",
"program_end",
":",
... | 36.833333 | 0.002208 |
def parse(self, content):
"""Parse raw response content for a list of remote artifact cache URLs.
:API: public
"""
if self.format == 'json_map':
try:
return assert_list(json.loads(content.decode(self.encoding))[self.index])
except (KeyError, UnicodeDecodeError, ValueError) as e:
... | [
"def",
"parse",
"(",
"self",
",",
"content",
")",
":",
"if",
"self",
".",
"format",
"==",
"'json_map'",
":",
"try",
":",
"return",
"assert_list",
"(",
"json",
".",
"loads",
"(",
"content",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
")",
"[",
... | 38.923077 | 0.009653 |
def add_user(self, uid, nodes, weights):
"""Add a user."""
for i, node in enumerate(nodes):
self.file.write("{},{},{}\n".format(uid, node, weights[i])) | [
"def",
"add_user",
"(",
"self",
",",
"uid",
",",
"nodes",
",",
"weights",
")",
":",
"for",
"i",
",",
"node",
"in",
"enumerate",
"(",
"nodes",
")",
":",
"self",
".",
"file",
".",
"write",
"(",
"\"{},{},{}\\n\"",
".",
"format",
"(",
"uid",
",",
"node... | 44 | 0.011173 |
def _build_array_type(var, property_path=None):
""" Builds schema definitions for array type values.
:param var: The array type value
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:param property_path: [type], optional
:return: The built s... | [
"def",
"_build_array_type",
"(",
"var",
",",
"property_path",
"=",
"None",
")",
":",
"if",
"not",
"property_path",
":",
"property_path",
"=",
"[",
"]",
"schema",
"=",
"{",
"\"type\"",
":",
"\"array\"",
",",
"\"items\"",
":",
"{",
"\"$id\"",
":",
"f\"#/{'/'... | 31.136364 | 0.001415 |
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only available on GNU/Linux
# Only process if stats exist and display plugin enable...
if not LINUX or not self.stats or not self... | [
"def",
"msg_curse",
"(",
"self",
",",
"args",
"=",
"None",
",",
"max_width",
"=",
"None",
")",
":",
"# Init the return message",
"ret",
"=",
"[",
"]",
"# Only available on GNU/Linux",
"# Only process if stats exist and display plugin enable...",
"if",
"not",
"LINUX",
... | 36.034483 | 0.001864 |
def help_info(self, exc, decorated_function, arg_name, arg_spec):
""" Print debug information to stderr. (Do nothing if object was constructed with silent_checks=True)
:param exc: raised exception
:param decorated_function: target function (function to decorate)
:param arg_name: function parameter name
:para... | [
"def",
"help_info",
"(",
"self",
",",
"exc",
",",
"decorated_function",
",",
"arg_name",
",",
"arg_spec",
")",
":",
"if",
"self",
".",
"_silent_checks",
"is",
"not",
"True",
":",
"print",
"(",
"'Exception raised:'",
",",
"file",
"=",
"sys",
".",
"stderr",
... | 41.291667 | 0.023669 |
def anchor_text_cursor(object):
"""
Anchors the text cursor position.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
"""
@functools.wraps(object)
def anchor_text_cursorWrapper(*args, **kwargs):
"""
Anchors the text cursor pos... | [
"def",
"anchor_text_cursor",
"(",
"object",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"object",
")",
"def",
"anchor_text_cursorWrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Anchors the text cursor position.\n\n :param \\*a... | 27.222222 | 0.013793 |
def put(self, robj, w=None, dw=None, pw=None, return_body=None,
if_none_match=None, timeout=None):
"""
Stores an object.
"""
raise NotImplementedError | [
"def",
"put",
"(",
"self",
",",
"robj",
",",
"w",
"=",
"None",
",",
"dw",
"=",
"None",
",",
"pw",
"=",
"None",
",",
"return_body",
"=",
"None",
",",
"if_none_match",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"raise",
"NotImplementedError"
] | 31.5 | 0.015464 |
def get_template_directory(self):
"""
Get path to migrations templates
This will get used when you run the db init command
"""
dir = os.path.join(os.path.dirname(__file__), 'templates')
return dir | [
"def",
"get_template_directory",
"(",
"self",
")",
":",
"dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'templates'",
")",
"return",
"dir"
] | 34 | 0.008197 |
def stream_hashtag(self, tag, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Stream for all public statuses for the hashtag 'tag' seen by the connected
instance.
"""
if tag.sta... | [
"def",
"stream_hashtag",
"(",
"self",
",",
"tag",
",",
"listener",
",",
"run_async",
"=",
"False",
",",
"timeout",
"=",
"__DEFAULT_STREAM_TIMEOUT",
",",
"reconnect_async",
"=",
"False",
",",
"reconnect_async_wait_sec",
"=",
"__DEFAULT_STREAM_RECONNECT_WAIT_SEC",
")",
... | 77.625 | 0.009554 |
def syntax_check():
"""Runs flake8 against the codebase."""
with fab_settings(warn_only=True):
for file_type in settings.SYNTAX_CHECK:
needs_to_abort = False
# because egrep fails with exit code 1, we need to allow this as
# a successful exit code in our env
... | [
"def",
"syntax_check",
"(",
")",
":",
"with",
"fab_settings",
"(",
"warn_only",
"=",
"True",
")",
":",
"for",
"file_type",
"in",
"settings",
".",
"SYNTAX_CHECK",
":",
"needs_to_abort",
"=",
"False",
"# because egrep fails with exit code 1, we need to allow this as",
"... | 44.071429 | 0.000793 |
def _get_solver(self, **kwargs):
"""Return a new :class:`psamm.lpsolver.lp.Solver` instance"""
solver_args = dict(kwargs)
solver_args.update(self._solver_args)
return generic.Solver(**solver_args) | [
"def",
"_get_solver",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"solver_args",
"=",
"dict",
"(",
"kwargs",
")",
"solver_args",
".",
"update",
"(",
"self",
".",
"_solver_args",
")",
"return",
"generic",
".",
"Solver",
"(",
"*",
"*",
"solver_args",
... | 44.8 | 0.008772 |
def posterior_to_xarray(self):
"""Convert the posterior to an xarray dataset."""
data = {}
for i, var_name in enumerate(self.var_names):
data[var_name] = np.expand_dims(self.posterior[i], axis=0)
return dict_to_dataset(data, library=self.tfp, coords=self.coords, dims=sel... | [
"def",
"posterior_to_xarray",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"for",
"i",
",",
"var_name",
"in",
"enumerate",
"(",
"self",
".",
"var_names",
")",
":",
"data",
"[",
"var_name",
"]",
"=",
"np",
".",
"expand_dims",
"(",
"self",
".",
"poste... | 53.666667 | 0.009174 |
def parse_pakattr(self,pakattr):
""" parse package-iterable pairs from a property or boundary condition
argument
Parameters
----------
pakattr : iterable len 2
Returns
-------
pak : flopy.PakBase
the flopy package from the model instance
... | [
"def",
"parse_pakattr",
"(",
"self",
",",
"pakattr",
")",
":",
"raw",
"=",
"pakattr",
".",
"lower",
"(",
")",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"raw",
")",
"!=",
"2",
":",
"self",
".",
"logger",
".",
"lraise",
"(",
"\"pakattr is wron... | 39.581818 | 0.010309 |
def doaniscorr(PmagSpecRec, AniSpec):
"""
takes the 6 element 's' vector and the Dec,Inc, Int 'Dir' data,
performs simple anisotropy correction. returns corrected Dec, Inc, Int
"""
AniSpecRec = {}
for key in list(PmagSpecRec.keys()):
AniSpecRec[key] = PmagSpecRec[key]
Dir = np.zeros(... | [
"def",
"doaniscorr",
"(",
"PmagSpecRec",
",",
"AniSpec",
")",
":",
"AniSpecRec",
"=",
"{",
"}",
"for",
"key",
"in",
"list",
"(",
"PmagSpecRec",
".",
"keys",
"(",
")",
")",
":",
"AniSpecRec",
"[",
"key",
"]",
"=",
"PmagSpecRec",
"[",
"key",
"]",
"Dir"... | 41.942308 | 0.000448 |
def list_contrib(name=None, ret=False, _debug=False):
"""Show the list of all existing contribs.
Params:
- name: filter to search the contribs
- ret: whether the function should return a dict instead of printing it
"""
# _debug: checks that all contrib modules have correctly defined:
# # s... | [
"def",
"list_contrib",
"(",
"name",
"=",
"None",
",",
"ret",
"=",
"False",
",",
"_debug",
"=",
"False",
")",
":",
"# _debug: checks that all contrib modules have correctly defined:",
"# # scapy.contrib.description = [...]",
"# # scapy.contrib.status = [...]",
"# # scapy.contrib... | 36.677966 | 0.0009 |
def build_jsonld(self, url=None, code_url=None, ci_url=None,
readme_url=None, license_id=None):
"""Create a JSON-LD representation of this LSST LaTeX document.
Parameters
----------
url : `str`, optional
URL where this document is published to the web. P... | [
"def",
"build_jsonld",
"(",
"self",
",",
"url",
"=",
"None",
",",
"code_url",
"=",
"None",
",",
"ci_url",
"=",
"None",
",",
"readme_url",
"=",
"None",
",",
"license_id",
"=",
"None",
")",
":",
"jsonld",
"=",
"{",
"'@context'",
":",
"[",
"\"https://raw.... | 40.192308 | 0.000934 |
def split_by_proportions(total, proportions, mininum_values):
"""splits the given total by the given proportions but ensures that each value in
the result has at least the given minimum value"""
assert(len(proportions) == len(mininum_values))
assert(total >= sum(mininum_values))
assert(min(proportio... | [
"def",
"split_by_proportions",
"(",
"total",
",",
"proportions",
",",
"mininum_values",
")",
":",
"assert",
"(",
"len",
"(",
"proportions",
")",
"==",
"len",
"(",
"mininum_values",
")",
")",
"assert",
"(",
"total",
">=",
"sum",
"(",
"mininum_values",
")",
... | 37.863636 | 0.002342 |
def accept(self, title, titleAlignments):
"""
Return C{True} if the read id set in C{titleAlignments} is sufficiently
different from all previously seen read sets.
@param title: A C{str} sequence title.
@param titleAlignments: An instance of L{TitleAlignment}.
@return: A... | [
"def",
"accept",
"(",
"self",
",",
"title",
",",
"titleAlignments",
")",
":",
"# Sanity check: titles can only be passed once.",
"assert",
"title",
"not",
"in",
"self",
".",
"_titles",
",",
"(",
"'Title %r seen multiple times.'",
"%",
"title",
")",
"readIds",
"=",
... | 38.413793 | 0.001751 |
def parse_list_objects_v2(data, bucket_name):
"""
Parser for list objects version 2 response.
:param data: Response data for list objects.
:param bucket_name: Response for the bucket.
:return: Returns three distinct components:
- List of :class:`Object <Object>`
- True if list is trun... | [
"def",
"parse_list_objects_v2",
"(",
"data",
",",
"bucket_name",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'ListObjectV2Result'",
",",
"data",
")",
"is_truncated",
"=",
"root",
".",
"get_child_text",
"(",
"'IsTruncated'",
")",
".",
"lower",
... | 38.041667 | 0.001068 |
def circTOcutout(wcs,ra,dec,rad):
"""Convert an RA/DEC/RADIUS to an imcopy cutout"""
(x1,y1)=wcs.rd2xy((ra+rad/2.0,dec-rad/2.0))
(x2,y2)=wcs.rd2xy((ra-rad/2.0,dec+rad/2.0))
xl=min(x1,x2)
xr=max(x1,x2)
yl=min(y1,y2)
yu=max(y1,y2)
### constrain the cutout to be inside the image
x1... | [
"def",
"circTOcutout",
"(",
"wcs",
",",
"ra",
",",
"dec",
",",
"rad",
")",
":",
"(",
"x1",
",",
"y1",
")",
"=",
"wcs",
".",
"rd2xy",
"(",
"(",
"ra",
"+",
"rad",
"/",
"2.0",
",",
"dec",
"-",
"rad",
"/",
"2.0",
")",
")",
"(",
"x2",
",",
"y2... | 24.461538 | 0.075643 |
def plot_losses(self, skip_start:int=0, skip_end:int=0, return_fig:bool=None)->Optional[plt.Figure]:
"Plot training and validation losses."
fig, ax = plt.subplots(1,1)
losses = self._split_list(self.losses, skip_start, skip_end)
iterations = self._split_list(range_of(self.losses), skip_s... | [
"def",
"plot_losses",
"(",
"self",
",",
"skip_start",
":",
"int",
"=",
"0",
",",
"skip_end",
":",
"int",
"=",
"0",
",",
"return_fig",
":",
"bool",
"=",
"None",
")",
"->",
"Optional",
"[",
"plt",
".",
"Figure",
"]",
":",
"fig",
",",
"ax",
"=",
"pl... | 57.285714 | 0.023313 |
def boards(hwpack='arduino'):
"""read boards from boards.txt.
:param core_package: 'all,'arduino',..
"""
bunch = read_properties(boards_txt(hwpack))
bunch_items = list(bunch.items())
# remove invalid boards
for bid, board in bunch_items:
if 'build' not in board.keys() or 'name' n... | [
"def",
"boards",
"(",
"hwpack",
"=",
"'arduino'",
")",
":",
"bunch",
"=",
"read_properties",
"(",
"boards_txt",
"(",
"hwpack",
")",
")",
"bunch_items",
"=",
"list",
"(",
"bunch",
".",
"items",
"(",
")",
")",
"# remove invalid boards",
"for",
"bid",
",",
... | 24.823529 | 0.002283 |
def toggleswitch() -> AnnData:
"""Simulated toggleswitch.
Data obtained simulating a simple toggleswitch `Gardner *et al.*, Nature
(2000) <https://doi.org/10.1038/35002131>`__.
Simulate via :func:`~scanpy.api.sim`.
Returns
-------
Annotated data matrix.
"""
filename = os.path.dirn... | [
"def",
"toggleswitch",
"(",
")",
"->",
"AnnData",
":",
"filename",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"+",
"'/toggleswitch.txt'",
"adata",
"=",
"sc",
".",
"read",
"(",
"filename",
",",
"first_column_names",
"=",
"True",
")",
"a... | 27.4375 | 0.002203 |
def mui(x, y):
"""MUtial Information"""
assert len(x) == len(y)
l = len(x)
p_x = Counter(x)
p_y = Counter(y)
p_xy = Counter(zip(x, y))
return sum(p_xy[(x, y)] * math.log((p_xy[(x, y)] * l) / float(p_x[x] * p_y[y]), 2) / l
for x, y in p_xy) | [
"def",
"mui",
"(",
"x",
",",
"y",
")",
":",
"assert",
"len",
"(",
"x",
")",
"==",
"len",
"(",
"y",
")",
"l",
"=",
"len",
"(",
"x",
")",
"p_x",
"=",
"Counter",
"(",
"x",
")",
"p_y",
"=",
"Counter",
"(",
"y",
")",
"p_xy",
"=",
"Counter",
"(... | 30.444444 | 0.010638 |
def child_sequence(self, child):
"""Search for the sequence that contains this child.
:param child: The child node to search sequences for.
:type child: NodeNG
:returns: The sequence containing the given child node.
:rtype: iterable(NodeNG)
:raises AstroidError: If no ... | [
"def",
"child_sequence",
"(",
"self",
",",
"child",
")",
":",
"for",
"field",
"in",
"self",
".",
"_astroid_fields",
":",
"node_or_sequence",
"=",
"getattr",
"(",
"self",
",",
"field",
")",
"if",
"node_or_sequence",
"is",
"child",
":",
"return",
"[",
"node_... | 37.32 | 0.00209 |
def adjoint(self):
"""Adjoint of this operator.
The adjoint is given by the negative `Divergence` with corrections for
the method and padding.
The Divergence is constructed from a ``space`` as a product space
operator ``space^n --> space``, hence we need to provide the domain o... | [
"def",
"adjoint",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_linear",
":",
"raise",
"ValueError",
"(",
"'operator with nonzero pad_const ({}) is not'",
"' linear and has no adjoint'",
"''",
".",
"format",
"(",
"self",
".",
"pad_const",
")",
")",
"return"... | 42.421053 | 0.002427 |
def write(self, rootdir):
"""
Write the metadata to a JSON file in the rootdir.
Values contained in the metadata are:
version : int
The value of FORMAT_VERSION of this class.
ohlc_ratio : int
The default ratio by which to multiply the pricing data to
... | [
"def",
"write",
"(",
"self",
",",
"rootdir",
")",
":",
"calendar",
"=",
"self",
".",
"calendar",
"slicer",
"=",
"calendar",
".",
"schedule",
".",
"index",
".",
"slice_indexer",
"(",
"self",
".",
"start_session",
",",
"self",
".",
"end_session",
",",
")",... | 40.371429 | 0.000691 |
def collect_dirs(path, max_depth=1, followlinks=True):
"""Recursively find directories under the given path."""
if not os.path.isdir(path):
return []
o = [path]
if max_depth == 0:
return o
for subdir in os.listdir(path):
subdir = os.path.join(path, subdir)
if no... | [
"def",
"collect_dirs",
"(",
"path",
",",
"max_depth",
"=",
"1",
",",
"followlinks",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"[",
"]",
"o",
"=",
"[",
"path",
"]",
"if",
"max_depth",
"==... | 20.518519 | 0.001724 |
def X_less(self):
"""Zoom out on the x-axis."""
self.parent.value('window_length',
self.parent.value('window_length') / 2)
self.parent.overview.update_position() | [
"def",
"X_less",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
",",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
"/",
"2",
")",
"self",
".",
"parent",
".",
"overview",
".",
"update_position",
"... | 41.4 | 0.009479 |
def item_exist(self, campaign_id, item_id, nick=None):
'''xxxxx.xxxxx.adgroups.item.exist
===================================
判断在一个推广计划中是否已经推广了一个商品'''
request = TOPRequest('xxxxx.xxxxx.adgroups.item.exist')
request['campaign_id'] = campaign_id
request['item_id'] = item_id... | [
"def",
"item_exist",
"(",
"self",
",",
"campaign_id",
",",
"item_id",
",",
"nick",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'xxxxx.xxxxx.adgroups.item.exist'",
")",
"request",
"[",
"'campaign_id'",
"]",
"=",
"campaign_id",
"request",
"[",
"'i... | 42.7 | 0.011468 |
def get_edge_by_index(self, source_index: int, target_index: int) -> Optional[Edge]:
"""
Returns the edge connecting the nodes with the specified indices if such an edge exists.
Arguments:
source_index (int): The index of one of the endpoints of queried edge.
targe... | [
"def",
"get_edge_by_index",
"(",
"self",
",",
"source_index",
":",
"int",
",",
"target_index",
":",
"int",
")",
"->",
"Optional",
"[",
"Edge",
"]",
":",
"edge",
"=",
"self",
".",
"_edges",
".",
"get",
"(",
"(",
"source_index",
",",
"target_index",
")",
... | 43.8125 | 0.00838 |
def send(self, request_body):
''' Sends request body. '''
if not request_body:
self._httprequest.send()
else:
self._httprequest.send(request_body) | [
"def",
"send",
"(",
"self",
",",
"request_body",
")",
":",
"if",
"not",
"request_body",
":",
"self",
".",
"_httprequest",
".",
"send",
"(",
")",
"else",
":",
"self",
".",
"_httprequest",
".",
"send",
"(",
"request_body",
")"
] | 31.5 | 0.010309 |
def is_readable(self):
"""
:Return: `True` when the I/O channel can be read
"""
return self._socket is not None and not self._eof and (
self._state in ("connected", "closing")
or self._state == "tls-handshake"
... | [
"def",
"is_readable",
"(",
"self",
")",
":",
"return",
"self",
".",
"_socket",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"_eof",
"and",
"(",
"self",
".",
"_state",
"in",
"(",
"\"connected\"",
",",
"\"closing\"",
")",
"or",
"self",
".",
"_state",
... | 44.25 | 0.01108 |
def _next_merge(merge_node):
"""
Gets a node that has only leaf nodes below it. This table and
the ones below are ready to be merged to make a new leaf node.
"""
if all(_is_leaf_node(d) for d in _dict_value_to_pairs(merge_node)):
return merge_node
else:
for d in tz.remove(_is_le... | [
"def",
"_next_merge",
"(",
"merge_node",
")",
":",
"if",
"all",
"(",
"_is_leaf_node",
"(",
"d",
")",
"for",
"d",
"in",
"_dict_value_to_pairs",
"(",
"merge_node",
")",
")",
":",
"return",
"merge_node",
"else",
":",
"for",
"d",
"in",
"tz",
".",
"remove",
... | 35.384615 | 0.002119 |
def serialize(self):
"""
Serializes the Peer data as a simple JSON map string.
"""
return json.dumps({
"name": self.name,
"ip": self.ip,
"port": self.port
}, sort_keys=True) | [
"def",
"serialize",
"(",
"self",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"\"name\"",
":",
"self",
".",
"name",
",",
"\"ip\"",
":",
"self",
".",
"ip",
",",
"\"port\"",
":",
"self",
".",
"port",
"}",
",",
"sort_keys",
"=",
"True",
")"
] | 26.777778 | 0.008032 |
def tag(self, path, name):
'''
Change name associated with path
'''
if not path[len(path) - 1] == '/':
path += '/'
config = self.get_config()
folder = self.find_folder({
'path' : path
}, config)
if not folder:
raise custom_errors.FileNotInConfig(path)
old_name... | [
"def",
"tag",
"(",
"self",
",",
"path",
",",
"name",
")",
":",
"if",
"not",
"path",
"[",
"len",
"(",
"path",
")",
"-",
"1",
"]",
"==",
"'/'",
":",
"path",
"+=",
"'/'",
"config",
"=",
"self",
".",
"get_config",
"(",
")",
"folder",
"=",
"self",
... | 19.962963 | 0.00885 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.