text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _bnd(self, xloc, left, right, cache):
"""
Distribution bounds.
Example:
>>> print(chaospy.Uniform().range([-2, 0, 2, 4]))
[[0. 0. 0. 0.]
[1. 1. 1. 1.]]
>>> print(chaospy.Add(chaospy.Uniform(), 2).range([-2, 0, 2, 4]))
[[2. 2. 2. 2... | [
"def",
"_bnd",
"(",
"self",
",",
"xloc",
",",
"left",
",",
"right",
",",
"cache",
")",
":",
"left",
"=",
"evaluation",
".",
"get_forward_cache",
"(",
"left",
",",
"cache",
")",
"right",
"=",
"evaluation",
".",
"get_forward_cache",
"(",
"right",
",",
"c... | 37.568627 | 0.002035 |
def get_email_context(self,**kwargs):
''' Overrides EmailRecipientMixin '''
context = super(TemporaryRegistration,self).get_email_context(**kwargs)
context.update({
'first_name': self.firstName,
'last_name': self.lastName,
'registrationComments': self.comments... | [
"def",
"get_email_context",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"TemporaryRegistration",
",",
"self",
")",
".",
"get_email_context",
"(",
"*",
"*",
"kwargs",
")",
"context",
".",
"update",
"(",
"{",
"'first_name'",... | 40.117647 | 0.008596 |
def set_verbosity_level(verbosity_level=3, logger=None):
"""
Defines logging verbosity level.
Available verbosity levels::
0: Critical.
1: Error.
2: Warning.
3: Info.
4: Debug.
:param verbosity_level: Verbosity level.
:type verbosity_level: int
:param l... | [
"def",
"set_verbosity_level",
"(",
"verbosity_level",
"=",
"3",
",",
"logger",
"=",
"None",
")",
":",
"logger",
"=",
"LOGGER",
"if",
"logger",
"is",
"None",
"else",
"logger",
"if",
"verbosity_level",
"==",
"0",
":",
"logger",
".",
"setLevel",
"(",
"logging... | 27.756757 | 0.000941 |
def reset_less_significant(self, significant_version):
"""
Reset to zero all version info less significant than the
indicated version.
>>> ver = SummableVersion('3.1.2')
>>> ver.reset_less_significant(SummableVersion('0.1'))
>>> str(ver)
'3.1'
"""
def nonzero(x):
return x != 0
version_len = 3 #... | [
"def",
"reset_less_significant",
"(",
"self",
",",
"significant_version",
")",
":",
"def",
"nonzero",
"(",
"x",
")",
":",
"return",
"x",
"!=",
"0",
"version_len",
"=",
"3",
"# strict versions are always a tuple of 3",
"significant_pos",
"=",
"rfind",
"(",
"nonzero... | 31.055556 | 0.03125 |
def fetch_entries(self):
"""Fetch data and parse it to build a list of cable entries."""
data = []
for row in self.get_rows():
# Stop fetching data if limit has been met
if exceeded_limit(self.limit, len(data)):
break
entry = row.find_all('td'... | [
"def",
"fetch_entries",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"for",
"row",
"in",
"self",
".",
"get_rows",
"(",
")",
":",
"# Stop fetching data if limit has been met",
"if",
"exceeded_limit",
"(",
"self",
".",
"limit",
",",
"len",
"(",
"data",
")",... | 31.533333 | 0.002051 |
def _is_auto_field(self, cursor, table_name, column_name):
"""
Checks whether column is Identity
"""
# COLUMNPROPERTY: http://msdn2.microsoft.com/en-us/library/ms174968.aspx
#from django.db import connection
#cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsId... | [
"def",
"_is_auto_field",
"(",
"self",
",",
"cursor",
",",
"table_name",
",",
"column_name",
")",
":",
"# COLUMNPROPERTY: http://msdn2.microsoft.com/en-us/library/ms174968.aspx",
"#from django.db import connection",
"#cursor.execute(\"SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsIdentity')... | 50.25 | 0.014658 |
def create_new_output_file(sampler, filename, force=False, injection_file=None,
**kwargs):
"""Creates a new output file.
If the output file already exists, an ``OSError`` will be raised. This can
be overridden by setting ``force`` to ``True``.
Parameters
----------
s... | [
"def",
"create_new_output_file",
"(",
"sampler",
",",
"filename",
",",
"force",
"=",
"False",
",",
"injection_file",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"if",
"force",
":",
... | 37.717949 | 0.001325 |
def main() -> None:
""""Execute the main routine."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--module", help="name of the module to import",
choices=[
"functions_100_with_no_contract",
"functi... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"\"--module\"",
",",
"help",
"=",
"\"name of the module to import\"",
",",
"choices",
"="... | 35.862745 | 0.000532 |
def create_dirs(path):
"""
Creates all directories mentioned in the given path.
Useful to write a new file with the specified path.
It carefully skips the file-name in the given path.
:param path: Path of a file or directory
"""
fname = os.path.basename(path)
# if file name exi... | [
"def",
"create_dirs",
"(",
"path",
")",
":",
"fname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"# if file name exists in path, skip the filename",
"if",
"fname",
".",
"__contains__",
"(",
"'.'",
")",
":",
"path",
"=",
"os",
".",
"path",
"... | 29 | 0.002088 |
def _modifyItemTag(self, item_id, action, tag):
""" wrapper around actual HTTP POST string for modify tags """
return self.httpPost(ReaderUrl.EDIT_TAG_URL,
{'i': item_id, action: tag, 'ac': 'edit-tags'}) | [
"def",
"_modifyItemTag",
"(",
"self",
",",
"item_id",
",",
"action",
",",
"tag",
")",
":",
"return",
"self",
".",
"httpPost",
"(",
"ReaderUrl",
".",
"EDIT_TAG_URL",
",",
"{",
"'i'",
":",
"item_id",
",",
"action",
":",
"tag",
",",
"'ac'",
":",
"'edit-ta... | 61.25 | 0.008065 |
def link_directories(root_dir, package_doc_dirs):
"""Create symlinks to package/module documentation directories from the
root documentation project.
Parameters
----------
root_dir : `str`
Directory in the main documentation project where links will be
created. For example, this cou... | [
"def",
"link_directories",
"(",
"root_dir",
",",
"package_doc_dirs",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"for",
"dirname",
",",
"source_dirname",
"in",
"package_doc_dirs",
".",
"items",
"(",
")",
":",
"link_name",
"=",
... | 35.068966 | 0.000957 |
def ds_format(ds, input_format, output_format):
"""
Takes an input string and outputs another string
as specified in the output format
:param ds: input string which contains a date
:type ds: str
:param input_format: input string format. E.g. %Y-%m-%d
:type input_format: str
:param outpu... | [
"def",
"ds_format",
"(",
"ds",
",",
"input_format",
",",
"output_format",
")",
":",
"return",
"datetime",
".",
"strptime",
"(",
"ds",
",",
"input_format",
")",
".",
"strftime",
"(",
"output_format",
")"
] | 33.333333 | 0.001621 |
def uiFile(modulefile, inst, theme='', className=None):
"""
Returns the ui file for the given instance and module file.
:param moduleFile | <str>
inst | <QWidget>
:return <str>
"""
if className is None:
className = inst.__class__.__name_... | [
"def",
"uiFile",
"(",
"modulefile",
",",
"inst",
",",
"theme",
"=",
"''",
",",
"className",
"=",
"None",
")",
":",
"if",
"className",
"is",
"None",
":",
"className",
"=",
"inst",
".",
"__class__",
".",
"__name__",
"# use a module's name vs. filepath\r",
"if"... | 31 | 0.016618 |
def pause(self):
""" Pauses playback. """
if self.decoder.status == mediadecoder.PAUSED:
self.decoder.pause()
self.paused = False
elif self.decoder.status == mediadecoder.PLAYING:
self.decoder.pause()
self.paused = True
else:
print("Player not in pausable state") | [
"def",
"pause",
"(",
"self",
")",
":",
"if",
"self",
".",
"decoder",
".",
"status",
"==",
"mediadecoder",
".",
"PAUSED",
":",
"self",
".",
"decoder",
".",
"pause",
"(",
")",
"self",
".",
"paused",
"=",
"False",
"elif",
"self",
".",
"decoder",
".",
... | 27.7 | 0.038462 |
def result(self, *, claim_draw: bool = False) -> str:
"""
Gets the game result.
``1-0``, ``0-1`` or ``1/2-1/2`` if the
:func:`game is over <chess.Board.is_game_over()>`. Otherwise, the
result is undetermined: ``*``.
"""
# Chess variant support.
if self.is... | [
"def",
"result",
"(",
"self",
",",
"*",
",",
"claim_draw",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"# Chess variant support.",
"if",
"self",
".",
"is_variant_loss",
"(",
")",
":",
"return",
"\"0-1\"",
"if",
"self",
".",
"turn",
"==",
"WHITE",
... | 30.052632 | 0.001696 |
def make_geohash_tables(table,listofprecisions,**kwargs):
'''
sort_by - field to sort by for each group
return_squares - boolean arg if true returns a list of squares instead of writing out to table
'''
return_squares = False
sort_by = 'COUNT'
# logic for accepting kwarg inputs
for key,value in kwargs.iteritems... | [
"def",
"make_geohash_tables",
"(",
"table",
",",
"listofprecisions",
",",
"*",
"*",
"kwargs",
")",
":",
"return_squares",
"=",
"False",
"sort_by",
"=",
"'COUNT'",
"# logic for accepting kwarg inputs",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
... | 25.313433 | 0.042565 |
def generate_event_set(ucerf, background_sids, src_filter, ses_idx, seed):
"""
Generates the event set corresponding to a particular branch
"""
serial = seed + ses_idx * TWO16
# get rates from file
with h5py.File(ucerf.source_file, 'r') as hdf5:
occurrences = ucerf.tom.sample_number_of_o... | [
"def",
"generate_event_set",
"(",
"ucerf",
",",
"background_sids",
",",
"src_filter",
",",
"ses_idx",
",",
"seed",
")",
":",
"serial",
"=",
"seed",
"+",
"ses_idx",
"*",
"TWO16",
"# get rates from file",
"with",
"h5py",
".",
"File",
"(",
"ucerf",
".",
"source... | 41.083333 | 0.000661 |
def _initialize(cls, port, secret):
"""
Initialize BarrierTaskContext, other methods within BarrierTaskContext can only be called
after BarrierTaskContext is initialized.
"""
cls._port = port
cls._secret = secret | [
"def",
"_initialize",
"(",
"cls",
",",
"port",
",",
"secret",
")",
":",
"cls",
".",
"_port",
"=",
"port",
"cls",
".",
"_secret",
"=",
"secret"
] | 36.285714 | 0.011538 |
def normalize_index(index):
"""normalize numpy index"""
index = np.asarray(index)
if len(index) == 0:
return index.astype('int')
if index.dtype == 'bool':
index = index.nonzero()[0]
elif index.dtype == 'int':
pass
else:
raise ValueError('Index should be ... | [
"def",
"normalize_index",
"(",
"index",
")",
":",
"index",
"=",
"np",
".",
"asarray",
"(",
"index",
")",
"if",
"len",
"(",
"index",
")",
"==",
"0",
":",
"return",
"index",
".",
"astype",
"(",
"'int'",
")",
"if",
"index",
".",
"dtype",
"==",
"'bool'... | 24.857143 | 0.00831 |
def mark_quality(self, start_time, length, qual_name):
"""Mark signal quality, only add the new ones.
Parameters
----------
start_time : int
start time in s of the epoch being scored.
length : int
duration in s of the epoch being scored.
qual_name ... | [
"def",
"mark_quality",
"(",
"self",
",",
"start_time",
",",
"length",
",",
"qual_name",
")",
":",
"y_pos",
"=",
"BARS",
"[",
"'quality'",
"]",
"[",
"'pos0'",
"]",
"height",
"=",
"10",
"# the -1 is really important, otherwise we stay on the edge of the rect",
"old_sc... | 37.625 | 0.001619 |
def eval(self, keys):
"""
Examples:
Specify type literal for key.
>>> env.eval({MAIL_PORT: int})
"""
for k, v in keys.items(): # pylint: disable=invalid-name
if k in self.app.config:
try:
val = ast.literal_eval(sel... | [
"def",
"eval",
"(",
"self",
",",
"keys",
")",
":",
"for",
"k",
",",
"v",
"in",
"keys",
".",
"items",
"(",
")",
":",
"# pylint: disable=invalid-name",
"if",
"k",
"in",
"self",
".",
"app",
".",
"config",
":",
"try",
":",
"val",
"=",
"ast",
".",
"li... | 40 | 0.001953 |
def _lastColumn(self, block):
"""Returns the last non-whitespace column in the given line.
If there are only whitespaces in the line, the return value is -1.
"""
text = block.text()
index = len(block.text()) - 1
while index >= 0 and \
(text[index].isspace() ... | [
"def",
"_lastColumn",
"(",
"self",
",",
"block",
")",
":",
"text",
"=",
"block",
".",
"text",
"(",
")",
"index",
"=",
"len",
"(",
"block",
".",
"text",
"(",
")",
")",
"-",
"1",
"while",
"index",
">=",
"0",
"and",
"(",
"text",
"[",
"index",
"]",... | 35.416667 | 0.009174 |
def run(input, conf, filepath=None):
"""Lints a YAML source.
Returns a generator of LintProblem objects.
:param input: buffer, string or stream to read from
:param conf: yamllint configuration object
"""
if conf.is_file_ignored(filepath):
return ()
if isinstance(input, (type(b''),... | [
"def",
"run",
"(",
"input",
",",
"conf",
",",
"filepath",
"=",
"None",
")",
":",
"if",
"conf",
".",
"is_file_ignored",
"(",
"filepath",
")",
":",
"return",
"(",
")",
"if",
"isinstance",
"(",
"input",
",",
"(",
"type",
"(",
"b''",
")",
",",
"type",
... | 35.684211 | 0.001437 |
def clear_memoized_methods(obj, *method_names):
"""
Clear the memoized method or @memoizedproperty results for the given
method names from the given object.
>>> v = [0]
>>> def inc():
... v[0] += 1
... return v[0]
...
>>> class Foo(object):
... @memoizemethod
... ... | [
"def",
"clear_memoized_methods",
"(",
"obj",
",",
"*",
"method_names",
")",
":",
"for",
"key",
"in",
"list",
"(",
"getattr",
"(",
"obj",
",",
"'_memoized_results'",
",",
"{",
"}",
")",
".",
"keys",
"(",
")",
")",
":",
"# key[0] is the method name",
"if",
... | 26.065217 | 0.000804 |
def dependency_graph(self):
r"""
Returns a NetworkX graph object of the dependencies
See Also
--------
dependency_list
dependency_map
Notes
-----
To visualize the dependencies, the following NetworkX function and
settings is helpful:
... | [
"def",
"dependency_graph",
"(",
"self",
")",
":",
"dtree",
"=",
"nx",
".",
"DiGraph",
"(",
")",
"for",
"propname",
"in",
"self",
".",
"keys",
"(",
")",
":",
"dtree",
".",
"add_node",
"(",
"propname",
")",
"for",
"dependency",
"in",
"self",
"[",
"prop... | 30.269231 | 0.002463 |
def __insert_frond_RF(d_w, d_u, dfs_data):
"""Encapsulates the process of inserting a frond uw into the right side frond group."""
# --Add the frond to the right side
dfs_data['RF'].append( (d_w, d_u) )
dfs_data['FG']['r'] += 1
dfs_data['last_inserted_side'] = 'RF' | [
"def",
"__insert_frond_RF",
"(",
"d_w",
",",
"d_u",
",",
"dfs_data",
")",
":",
"# --Add the frond to the right side",
"dfs_data",
"[",
"'RF'",
"]",
".",
"append",
"(",
"(",
"d_w",
",",
"d_u",
")",
")",
"dfs_data",
"[",
"'FG'",
"]",
"[",
"'r'",
"]",
"+=",... | 40 | 0.013986 |
def prog(self, s=None):
""" Prints the progress indicator """
s = s or self.prog_msg
self.printer(s, end='') | [
"def",
"prog",
"(",
"self",
",",
"s",
"=",
"None",
")",
":",
"s",
"=",
"s",
"or",
"self",
".",
"prog_msg",
"self",
".",
"printer",
"(",
"s",
",",
"end",
"=",
"''",
")"
] | 32.25 | 0.015152 |
def split_by_idx(self, valid_idx:Collection[int])->'ItemLists':
"Split the data according to the indexes in `valid_idx`."
#train_idx = [i for i in range_of(self.items) if i not in valid_idx]
train_idx = np.setdiff1d(arange_of(self.items), valid_idx)
return self.split_by_idxs(train_idx, v... | [
"def",
"split_by_idx",
"(",
"self",
",",
"valid_idx",
":",
"Collection",
"[",
"int",
"]",
")",
"->",
"'ItemLists'",
":",
"#train_idx = [i for i in range_of(self.items) if i not in valid_idx]",
"train_idx",
"=",
"np",
".",
"setdiff1d",
"(",
"arange_of",
"(",
"self",
... | 65 | 0.015198 |
def file_modify(filename, settings):
"""
Modifies file access
Args:
filename (str): Filename.
settings (dict): Can be "mode" or "owners"
"""
for k, v in settings.items():
if k == "mode":
os.chmod(filename,v)
if k ==... | [
"def",
"file_modify",
"(",
"filename",
",",
"settings",
")",
":",
"for",
"k",
",",
"v",
"in",
"settings",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"\"mode\"",
":",
"os",
".",
"chmod",
"(",
"filename",
",",
"v",
")",
"if",
"k",
"==",
"\"owner... | 27.307692 | 0.010899 |
def run(self):
'''
Main loop of the ConCache, starts updates in intervals and
answers requests from the MWorkers
'''
context = zmq.Context()
# the socket for incoming cache requests
creq_in = context.socket(zmq.REP)
creq_in.setsockopt(zmq.LINGER, 100)
... | [
"def",
"run",
"(",
"self",
")",
":",
"context",
"=",
"zmq",
".",
"Context",
"(",
")",
"# the socket for incoming cache requests",
"creq_in",
"=",
"context",
".",
"socket",
"(",
"zmq",
".",
"REP",
")",
"creq_in",
".",
"setsockopt",
"(",
"zmq",
".",
"LINGER"... | 36.391667 | 0.001115 |
def nekmin(omega_in,q,x0=0.5,z0=0.5):
'''Computes the position of the neck (minimal radius) in an contact_binary star1'''
def Omega_xz(q,x,z):
return 1./np.sqrt(x**2+z**2)+q/np.sqrt((1-x)**2+z**2)+(q+1)*x**2/2.-q*x
def Omega_xy(q,x,y):
return 1./np.sqrt(x**2+y**2)+q/np.sqrt((1-x)**2+y**2)... | [
"def",
"nekmin",
"(",
"omega_in",
",",
"q",
",",
"x0",
"=",
"0.5",
",",
"z0",
"=",
"0.5",
")",
":",
"def",
"Omega_xz",
"(",
"q",
",",
"x",
",",
"z",
")",
":",
"return",
"1.",
"/",
"np",
".",
"sqrt",
"(",
"x",
"**",
"2",
"+",
"z",
"**",
"2... | 30.58209 | 0.034988 |
def profile_edit(request, username, edit_profile_form=EditProfileForm,
template_name='userena/profile_form.html', success_url=None,
extra_context=None, **kwargs):
"""
Edit profile.
Edits a profile selected by the supplied username. First checks
permissions if the user ... | [
"def",
"profile_edit",
"(",
"request",
",",
"username",
",",
"edit_profile_form",
"=",
"EditProfileForm",
",",
"template_name",
"=",
"'userena/profile_form.html'",
",",
"success_url",
"=",
"None",
",",
"extra_context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
... | 37.337662 | 0.002033 |
def to_yamlf(self, fpath: str, encoding: str='utf8', ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to yaml file
:param ignore_none: Properties which is None are excluded if True
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:return... | [
"def",
"to_yamlf",
"(",
"self",
",",
"fpath",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"'utf8'",
",",
"ignore_none",
":",
"bool",
"=",
"True",
",",
"ignore_empty",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"return",
"util",
".",
"save_ya... | 51.333333 | 0.021277 |
def delete_track_at_index(self, href=None, index=None):
"""Delete a track, or all the tracks.
'href' the relative href to the track list. May not be None.
'index' the index of the track to delete. If none is given,
all tracks are deleted.
Returns nothing.
If the respon... | [
"def",
"delete_track_at_index",
"(",
"self",
",",
"href",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"# Argument error checking.",
"assert",
"href",
"is",
"not",
"None",
"# Deal with any parameters that need to be passed in.",
"data",
"=",
"None",
"fields",
"... | 28.035714 | 0.002463 |
def load_soil_sample_data(sp):
"""
Sample data for the Soil object
:param sp: Soil Object
:return:
"""
# soil
sp.g_mod = 60.0e6 # [Pa]
sp.phi = 30 # [degrees]
sp.relative_density = .40 # [decimal]
sp.gwl = 2. # [m], ground water level
sp.unit_dry_weight = 17000 # [N/m3]
... | [
"def",
"load_soil_sample_data",
"(",
"sp",
")",
":",
"# soil",
"sp",
".",
"g_mod",
"=",
"60.0e6",
"# [Pa]",
"sp",
".",
"phi",
"=",
"30",
"# [degrees]",
"sp",
".",
"relative_density",
"=",
".40",
"# [decimal]",
"sp",
".",
"gwl",
"=",
"2.",
"# [m], ground wa... | 28.333333 | 0.001626 |
def appendArgs(url, args):
"""Append query arguments to a HTTP(s) URL. If the URL already has
query arguemtns, these arguments will be added, and the existing
arguments will be preserved. Duplicate arguments will not be
detected or collapsed (both will appear in the output).
@param url: The url to ... | [
"def",
"appendArgs",
"(",
"url",
",",
"args",
")",
":",
"if",
"hasattr",
"(",
"args",
",",
"'items'",
")",
":",
"args",
"=",
"sorted",
"(",
"args",
".",
"items",
"(",
")",
")",
"else",
":",
"args",
"=",
"list",
"(",
"args",
")",
"if",
"not",
"i... | 28.673469 | 0.000688 |
def noise_get_turbulence(
n: tcod.noise.Noise,
f: Sequence[float],
oc: float,
typ: int = NOISE_DEFAULT,
) -> float:
"""Return the turbulence noise sampled from the ``f`` coordinate.
Args:
n (Noise): A Noise instance.
f (Sequence[float]): The point to sample the noise from.
... | [
"def",
"noise_get_turbulence",
"(",
"n",
":",
"tcod",
".",
"noise",
".",
"Noise",
",",
"f",
":",
"Sequence",
"[",
"float",
"]",
",",
"oc",
":",
"float",
",",
"typ",
":",
"int",
"=",
"NOISE_DEFAULT",
",",
")",
"->",
"float",
":",
"return",
"float",
... | 27.363636 | 0.001605 |
def lscsum0(lx):
"""
Accepts log-values as input, exponentiates them, sums down the rows
(first dimension), then converts the sum back to log-space and returns the result.
Handles underflow by rescaling so that the largest values is exactly 1.0.
"""
# rows = lx.shape[0]
# columns = numpy.prod(lx.shape[1:]... | [
"def",
"lscsum0",
"(",
"lx",
")",
":",
"# rows = lx.shape[0]",
"# columns = numpy.prod(lx.shape[1:])",
"# lx = lx.reshape(rows, columns)",
"# bases = lx.max(1).reshape(rows, 1)",
"# bases = lx.max(0).reshape((1,) + lx.shape[1:])",
"lx",
"=",
"numpy",
".",
"asarray",
"(",
"lx",
")... | 34.162162 | 0.016154 |
def delete(self, delete_subdomains=False):
"""
Deletes this domain and all of its resource records. If this domain has
subdomains, each subdomain will now become a root domain. If you wish to
also delete any subdomains, pass True to 'delete_subdomains'.
"""
self.manager.d... | [
"def",
"delete",
"(",
"self",
",",
"delete_subdomains",
"=",
"False",
")",
":",
"self",
".",
"manager",
".",
"delete",
"(",
"self",
",",
"delete_subdomains",
"=",
"delete_subdomains",
")"
] | 51.714286 | 0.008152 |
def _attribute_is_magic(node, attrs, parents):
"""Checks that node is an attribute used inside one of allowed parents"""
if node.attrname not in attrs:
return False
if not node.last_child():
return False
try:
for cls in node.last_child().inferred():
if isinstance(cls... | [
"def",
"_attribute_is_magic",
"(",
"node",
",",
"attrs",
",",
"parents",
")",
":",
"if",
"node",
".",
"attrname",
"not",
"in",
"attrs",
":",
"return",
"False",
"if",
"not",
"node",
".",
"last_child",
"(",
")",
":",
"return",
"False",
"try",
":",
"for",... | 34.1875 | 0.001779 |
def _check_generation(self):
"""Check that the generation on the BIG-IP® matches the object
This will do a get to the objects URI and check that the generation
returned in the JSON matches the one the object currently has. If it
does not it will raise the `GenerationMismatch` exception... | [
"def",
"_check_generation",
"(",
"self",
")",
":",
"session",
"=",
"self",
".",
"_meta_data",
"[",
"'bigip'",
"]",
".",
"_meta_data",
"[",
"'icr_session'",
"]",
"response",
"=",
"session",
".",
"get",
"(",
"self",
".",
"_meta_data",
"[",
"'uri'",
"]",
")... | 55.875 | 0.0022 |
def freeze_from_checkpoint(input_checkpoint, output_file_path, output_node_names):
"""Freeze and shrink the graph based on a checkpoint and the output node names."""
check_input_checkpoint(input_checkpoint)
output_node_names = output_node_names_string_as_list(output_node_names)
with tf.Session() as se... | [
"def",
"freeze_from_checkpoint",
"(",
"input_checkpoint",
",",
"output_file_path",
",",
"output_node_names",
")",
":",
"check_input_checkpoint",
"(",
"input_checkpoint",
")",
"output_node_names",
"=",
"output_node_names_string_as_list",
"(",
"output_node_names",
")",
"with",
... | 67.714286 | 0.009365 |
def make_acro(past, prefix, s): # pragma: no cover
"""Create a three letter acronym from the input string s.
Args:
past: A set object, for storing acronyms that have already been created
prefix: A prefix added to the acronym before storing in the set
s: The string to create the acronym... | [
"def",
"make_acro",
"(",
"past",
",",
"prefix",
",",
"s",
")",
":",
"# pragma: no cover",
"def",
"_make_acro",
"(",
"s",
",",
"t",
"=",
"0",
")",
":",
"\"\"\"Make an acronym of s for trial t\"\"\"",
"# Really should cache these ...",
"v",
"=",
"[",
"'a'",
",",
... | 26.280488 | 0.001789 |
def tips(args):
"""
%prog tips patchers.bed complements.bed original.fasta backbone.fasta
Append telomeric sequences based on patchers and complements.
"""
p = OptionParser(tips.__doc__)
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
pbedfile, ... | [
"def",
"tips",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"tips",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"4",
":",
"sys",
".",
"exit",
"(",
"not",... | 28.647059 | 0.001985 |
def set_mac_addr_adv_interval(self, name, vrid, value=None, disable=False,
default=False, run=True):
"""Set the mac_addr_adv_interval property of the vrrp
Args:
name (string): The interface to configure.
vrid (integer): The vrid number for the v... | [
"def",
"set_mac_addr_adv_interval",
"(",
"self",
",",
"name",
",",
"vrid",
",",
"value",
"=",
"None",
",",
"disable",
"=",
"False",
",",
"default",
"=",
"False",
",",
"run",
"=",
"True",
")",
":",
"if",
"not",
"default",
"and",
"not",
"disable",
":",
... | 40.136364 | 0.001658 |
def set_clock_type(type):
"""
Sets the internal clock type for timing. Profiler shall not have any previous stats.
Otherwise an exception is thrown.
"""
type = type.upper()
if type not in CLOCK_TYPES:
raise YappiError("Invalid clock type:%s" % (type))
_yappi.set_clock_type(C... | [
"def",
"set_clock_type",
"(",
"type",
")",
":",
"type",
"=",
"type",
".",
"upper",
"(",
")",
"if",
"type",
"not",
"in",
"CLOCK_TYPES",
":",
"raise",
"YappiError",
"(",
"\"Invalid clock type:%s\"",
"%",
"(",
"type",
")",
")",
"_yappi",
".",
"set_clock_type"... | 32.8 | 0.008902 |
def _parse_status(data, cast_type):
"""
Parses a STATUS message and returns a CastStatus object.
:type data: dict
:param cast_type: Type of Chromecast.
:rtype: CastStatus
"""
data = data.get('status', {})
volume_data = data.get('volume', {})
try... | [
"def",
"_parse_status",
"(",
"data",
",",
"cast_type",
")",
":",
"data",
"=",
"data",
".",
"get",
"(",
"'status'",
",",
"{",
"}",
")",
"volume_data",
"=",
"data",
".",
"get",
"(",
"'volume'",
",",
"{",
"}",
")",
"try",
":",
"app_data",
"=",
"data",... | 31.40625 | 0.001931 |
def get_alerts_summary(self, **kwargs): # noqa: E501
"""Count alerts of various statuses for a customer # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_al... | [
"def",
"get_alerts_summary",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"get_alerts_summary_with_... | 42.35 | 0.002309 |
def CryptProtectData(
data, description=None, optional_entropy=None,
prompt_struct=None, flags=0,
):
"""
Encrypt data
"""
data_in = DATA_BLOB(data)
entropy = DATA_BLOB(optional_entropy) if optional_entropy else None
data_out = DATA_BLOB()
res = _CryptProtectData(
data_in,
description,
entropy,
None, ... | [
"def",
"CryptProtectData",
"(",
"data",
",",
"description",
"=",
"None",
",",
"optional_entropy",
"=",
"None",
",",
"prompt_struct",
"=",
"None",
",",
"flags",
"=",
"0",
",",
")",
":",
"data_in",
"=",
"DATA_BLOB",
"(",
"data",
")",
"entropy",
"=",
"DATA_... | 18.041667 | 0.048246 |
def _check_age(self, pub, min_interval=timedelta(seconds=0)):
"""Check the age of the receiver.
"""
now = datetime.utcnow()
if (now - self._last_age_check) <= min_interval:
return
LOGGER.debug("%s - checking addresses", str(datetime.utcnow()))
self._last_age_... | [
"def",
"_check_age",
"(",
"self",
",",
"pub",
",",
"min_interval",
"=",
"timedelta",
"(",
"seconds",
"=",
"0",
")",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"(",
"now",
"-",
"self",
".",
"_last_age_check",
")",
"<=",
"min_inte... | 41.826087 | 0.002033 |
def fit_from_image(self, data, voxelsize, seeds, unique_cls):
"""
This Method allows computes feature vector and train model.
:cls: list of index number of requested classes in seeds
"""
fvs, clsselected = self.features_from_image(data, voxelsize, seeds, unique_cls)
self... | [
"def",
"fit_from_image",
"(",
"self",
",",
"data",
",",
"voxelsize",
",",
"seeds",
",",
"unique_cls",
")",
":",
"fvs",
",",
"clsselected",
"=",
"self",
".",
"features_from_image",
"(",
"data",
",",
"voxelsize",
",",
"seeds",
",",
"unique_cls",
")",
"self",... | 41.875 | 0.008772 |
def merge_mhc_peptide_calls(job, antigen_predictions, transgened_files):
"""
This module will merge all the calls from nodes 18 and 19, and will filter for the top X%% of
binders of each allele. The module will then call the rank boosting script to finish off the
pipeline.
This module corresponds ... | [
"def",
"merge_mhc_peptide_calls",
"(",
"job",
",",
"antigen_predictions",
",",
"transgened_files",
")",
":",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Merging MHC calls'",
")",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
... | 50.042017 | 0.002141 |
def mock(config_or_spec=None, spec=None, strict=OMITTED):
"""Create 'empty' objects ('Mocks').
Will create an empty unconfigured object, that you can pass
around. All interactions (method calls) will be recorded and can be
verified using :func:`verify` et.al.
A plain `mock()` will be not `strict`,... | [
"def",
"mock",
"(",
"config_or_spec",
"=",
"None",
",",
"spec",
"=",
"None",
",",
"strict",
"=",
"OMITTED",
")",
":",
"if",
"type",
"(",
"config_or_spec",
")",
"is",
"dict",
":",
"config",
"=",
"config_or_spec",
"else",
":",
"config",
"=",
"{",
"}",
... | 32.931034 | 0.001017 |
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the ActivateRequestPayload object to a stream.
Args:
ostream (Stream): A data stream in which to encode object data,
supporting a write method; usually a BytearrayStream obj... | [
"def",
"write",
"(",
"self",
",",
"ostream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"tstream",
"=",
"BytearrayStream",
"(",
")",
"# Write the contents of the request payload",
"if",
"self",
".",
"unique_identifier",
"is",... | 42.130435 | 0.002018 |
def _get_header(self, header):
"""
Gets the html header
"""
if header is None:
html = self.header()
else:
html = header
return html | [
"def",
"_get_header",
"(",
"self",
",",
"header",
")",
":",
"if",
"header",
"is",
"None",
":",
"html",
"=",
"self",
".",
"header",
"(",
")",
"else",
":",
"html",
"=",
"header",
"return",
"html"
] | 21.666667 | 0.009852 |
def format_signed(feature, # type: Dict[str, Any]
formatter=None, # type: Callable[..., str]
**kwargs
):
# type: (...) -> str
"""
Format unhashed feature with sign.
>>> format_signed({'name': 'foo', 'sign': 1})
'foo'
>>> format_signed({'na... | [
"def",
"format_signed",
"(",
"feature",
",",
"# type: Dict[str, Any]",
"formatter",
"=",
"None",
",",
"# type: Callable[..., str]",
"*",
"*",
"kwargs",
")",
":",
"# type: (...) -> str",
"txt",
"=",
"''",
"if",
"feature",
"[",
"'sign'",
"]",
">",
"0",
"else",
"... | 31.8 | 0.001527 |
def update_arc_indexes(geometry, merged_arcs, old_arcs):
""" Updated geometry arc indexes, and add arcs to merged_arcs along the way.
Arguments are modified in-place, and nothing is returned.
"""
if geometry['type'] in ('Point', 'MultiPoint'):
return
elif geometry['type'] == 'LineStrin... | [
"def",
"update_arc_indexes",
"(",
"geometry",
",",
"merged_arcs",
",",
"old_arcs",
")",
":",
"if",
"geometry",
"[",
"'type'",
"]",
"in",
"(",
"'Point'",
",",
"'MultiPoint'",
")",
":",
"return",
"elif",
"geometry",
"[",
"'type'",
"]",
"==",
"'LineString'",
... | 38.941176 | 0.001474 |
def ceiling_height(self, value=99999.0):
"""Corresponds to IDD Field `ceiling_height` This is the value for
ceiling height in m. (77777 is unlimited ceiling height. 88888 is
cirroform ceiling.) It is not currently used in EnergyPlus
calculations.
Args:
value (float):... | [
"def",
"ceiling_height",
"(",
"self",
",",
"value",
"=",
"99999.0",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of t... | 36.76 | 0.002121 |
def initial_dir(self):
"""The initial directory defined for the job.
All input files, and log files are relative to this directory. Output files will be copied into this
directory by default. This directory will be created if it doesn't already exist when the job is submitted.
Note:
... | [
"def",
"initial_dir",
"(",
"self",
")",
":",
"initial_dir",
"=",
"self",
".",
"get",
"(",
"'initialdir'",
")",
"if",
"not",
"initial_dir",
":",
"initial_dir",
"=",
"os",
".",
"curdir",
"#TODO does this conflict with the working directory?",
"if",
"self",
".",
"_... | 50.470588 | 0.010297 |
def _iupac_ambiguous_equal(ambig_base, unambig_base):
"""
Tests two bases for equality, accounting for IUPAC ambiguous DNA
ambiguous base may be IUPAC ambiguous, unambiguous must be one of ACGT
"""
iupac_translation = {
'A': 'A',
'C': 'C',
'G': 'G',
'T': 'T',
... | [
"def",
"_iupac_ambiguous_equal",
"(",
"ambig_base",
",",
"unambig_base",
")",
":",
"iupac_translation",
"=",
"{",
"'A'",
":",
"'A'",
",",
"'C'",
":",
"'C'",
",",
"'G'",
":",
"'G'",
",",
"'T'",
":",
"'T'",
",",
"'U'",
":",
"'U'",
",",
"'R'",
":",
"'AG... | 24.766667 | 0.001295 |
def _make_before_request(self):
"""
Generate the before_request function to be added to the app.
Currently this function is static, however it is very likely we will
need to programmatically generate this function in the future.
"""
def before_request():
"""
... | [
"def",
"_make_before_request",
"(",
"self",
")",
":",
"def",
"before_request",
"(",
")",
":",
"\"\"\"\n Process invalid identity statuses and attach user to request.\n\n :raises: :exception:`exceptions.FlaskKeystoneUnauthorized`\n\n This function guarantees tha... | 40.976744 | 0.001109 |
def p_information_speed_duration(self, p):
'information : speed FOR duration'
logger.debug('information = speed %s for duration %s', p[1], p[3])
p[0] = p[1].for_duration(p[3]) | [
"def",
"p_information_speed_duration",
"(",
"self",
",",
"p",
")",
":",
"logger",
".",
"debug",
"(",
"'information = speed %s for duration %s'",
",",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
".",
... | 49 | 0.01005 |
def part(self, channels, message=""):
"""Send a PART command."""
self.send_items('PART', ','.join(always_iterable(channels)), message) | [
"def",
"part",
"(",
"self",
",",
"channels",
",",
"message",
"=",
"\"\"",
")",
":",
"self",
".",
"send_items",
"(",
"'PART'",
",",
"','",
".",
"join",
"(",
"always_iterable",
"(",
"channels",
")",
")",
",",
"message",
")"
] | 49.333333 | 0.013333 |
def showMessage(self,
title,
message,
icon=QtGui.QSystemTrayIcon.Information,
timeout=10000):
"""
Displays a message to the user via the tray icon.
:param title | <str>
me... | [
"def",
"showMessage",
"(",
"self",
",",
"title",
",",
"message",
",",
"icon",
"=",
"QtGui",
".",
"QSystemTrayIcon",
".",
"Information",
",",
"timeout",
"=",
"10000",
")",
":",
"tray",
"=",
"self",
".",
"trayIcon",
"(",
")",
"if",
"tray",
":",
"tray",
... | 34.125 | 0.012478 |
def sync_path_to_host(path, host, user, verbose=False, cmd=None, gid=None,
fatal=False):
"""Sync path to an specific peer host
Propagates exception if operation fails and fatal=True.
"""
cmd = cmd or copy(BASE_CMD)
if not verbose:
cmd.append('-silent')
# removing ... | [
"def",
"sync_path_to_host",
"(",
"path",
",",
"host",
",",
"user",
",",
"verbose",
"=",
"False",
",",
"cmd",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"fatal",
"=",
"False",
")",
":",
"cmd",
"=",
"cmd",
"or",
"copy",
"(",
"BASE_CMD",
")",
"if",
... | 29.833333 | 0.001353 |
def forward_char_extend_selection(self, e): #
u"""Move forward a character. """
self.l_buffer.forward_char_extend_selection(self.argument_reset)
self.finalize() | [
"def",
"forward_char_extend_selection",
"(",
"self",
",",
"e",
")",
":",
"# \r",
"self",
".",
"l_buffer",
".",
"forward_char_extend_selection",
"(",
"self",
".",
"argument_reset",
")",
"self",
".",
"finalize",
"(",
")"
] | 46.25 | 0.021277 |
def reject(self):
"""
Rejects the snapshot and closes the widget.
"""
if self.hideWindow():
self.hideWindow().show()
self.close()
self.deleteLater() | [
"def",
"reject",
"(",
"self",
")",
":",
"if",
"self",
".",
"hideWindow",
"(",
")",
":",
"self",
".",
"hideWindow",
"(",
")",
".",
"show",
"(",
")",
"self",
".",
"close",
"(",
")",
"self",
".",
"deleteLater",
"(",
")"
] | 24.555556 | 0.0131 |
def margin(self):
"""
[float] 总保证金
"""
return sum(position.margin for position in six.itervalues(self._positions)) | [
"def",
"margin",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"position",
".",
"margin",
"for",
"position",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"_positions",
")",
")"
] | 28.4 | 0.020548 |
def get_all_regions(self):
'''
Request a list of regions from Datapoint. Returns each Region
as a Site object. Regions rarely change, so we cache the response
for one hour to minimise requests to API.
'''
if (time() - self.regions_last_update) < self.regions_update_time:
... | [
"def",
"get_all_regions",
"(",
"self",
")",
":",
"if",
"(",
"time",
"(",
")",
"-",
"self",
".",
"regions_last_update",
")",
"<",
"self",
".",
"regions_update_time",
":",
"return",
"self",
".",
"regions_last_request",
"response",
"=",
"self",
".",
"call_api",... | 38 | 0.002445 |
def delete_model_genes(cobra_model, gene_list,
cumulative_deletions=True, disable_orphans=False):
"""delete_model_genes will set the upper and lower bounds for reactions
catalysed by the genes in gene_list if deleting the genes means that
the reaction cannot proceed according to
c... | [
"def",
"delete_model_genes",
"(",
"cobra_model",
",",
"gene_list",
",",
"cumulative_deletions",
"=",
"True",
",",
"disable_orphans",
"=",
"False",
")",
":",
"if",
"disable_orphans",
":",
"raise",
"NotImplementedError",
"(",
"\"disable_orphans not implemented\"",
")",
... | 42.254237 | 0.000784 |
def Struct(fields): # pylint: disable=invalid-name
"""Construct a struct parameter type description protobuf.
:type fields: list of :class:`type_pb2.StructType.Field`
:param fields: the fields of the struct
:rtype: :class:`type_pb2.Type`
:returns: the appropriate struct-type protobuf
"""
... | [
"def",
"Struct",
"(",
"fields",
")",
":",
"# pylint: disable=invalid-name",
"return",
"type_pb2",
".",
"Type",
"(",
"code",
"=",
"type_pb2",
".",
"STRUCT",
",",
"struct_type",
"=",
"type_pb2",
".",
"StructType",
"(",
"fields",
"=",
"fields",
")",
")"
] | 34.416667 | 0.002358 |
def from_txt(filename, length, delta_f, low_freq_cutoff, is_asd_file=True):
"""Read an ASCII file containing one-sided ASD or PSD data and generate
a frequency series with the corresponding PSD. The ASD or PSD data is
interpolated in order to match the desired resolution of the
generated frequency seri... | [
"def",
"from_txt",
"(",
"filename",
",",
"length",
",",
"delta_f",
",",
"low_freq_cutoff",
",",
"is_asd_file",
"=",
"True",
")",
":",
"file_data",
"=",
"numpy",
".",
"loadtxt",
"(",
"filename",
")",
"if",
"(",
"file_data",
"<",
"0",
")",
".",
"any",
"(... | 36.347826 | 0.001165 |
def carmichael_of_ppower( pp ):
"""Carmichael function of the given power of the given prime.
"""
p, a = pp
if p == 2 and a > 2: return 2**(a-2)
else: return (p-1) * p**(a-1) | [
"def",
"carmichael_of_ppower",
"(",
"pp",
")",
":",
"p",
",",
"a",
"=",
"pp",
"if",
"p",
"==",
"2",
"and",
"a",
">",
"2",
":",
"return",
"2",
"**",
"(",
"a",
"-",
"2",
")",
"else",
":",
"return",
"(",
"p",
"-",
"1",
")",
"*",
"p",
"**",
"... | 25.571429 | 0.048649 |
def sma(array, window_size, axis=-1, mode='reflect', **kwargs):
"""
Computes a 1D simple moving average along the given axis.
Parameters
----------
array : ndarray
Array on which to perform the convolution.
window_size: int
Width of the simple moving average window in indices.
axis : int, optional
Axis... | [
"def",
"sma",
"(",
"array",
",",
"window_size",
",",
"axis",
"=",
"-",
"1",
",",
"mode",
"=",
"'reflect'",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'axis'",
"]",
"=",
"axis",
"kwargs",
"[",
"'mode'",
"]",
"=",
"mode",
"if",
"not",
"isin... | 32.666667 | 0.000826 |
def remove_asn(self, auth, asn):
""" Remove an AS number.
* `auth` [BaseAuth]
AAA options.
* `spec` [asn]
An ASN specification.
Remove ASNs matching the `asn` argument.
This is the documentation of the internal backend function. ... | [
"def",
"remove_asn",
"(",
"self",
",",
"auth",
",",
"asn",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"remove_asn called; asn: %s\"",
"%",
"unicode",
"(",
"asn",
")",
")",
"# get list of ASNs to remove before removing them",
"asns",
"=",
"self",
".",... | 35.621622 | 0.001477 |
def init_optimizer(self, optimizer):
"""Init the optimizer.
Args:
optimizer (dict or :obj:`~torch.optim.Optimizer`): Either an
optimizer object or a dict used for constructing the optimizer.
Returns:
:obj:`~torch.optim.Optimizer`: An optimizer object.
... | [
"def",
"init_optimizer",
"(",
"self",
",",
"optimizer",
")",
":",
"if",
"isinstance",
"(",
"optimizer",
",",
"dict",
")",
":",
"optimizer",
"=",
"obj_from_dict",
"(",
"optimizer",
",",
"torch",
".",
"optim",
",",
"dict",
"(",
"params",
"=",
"self",
".",
... | 38.869565 | 0.002183 |
def multiglob_compile(globs, prefix=False):
"""Generate a single "A or B or C" regex from a list of shell globs.
:param globs: Patterns to be processed by :mod:`fnmatch`.
:type globs: iterable of :class:`~__builtins__.str`
:param prefix: If ``True``, then :meth:`~re.RegexObject.match` will
per... | [
"def",
"multiglob_compile",
"(",
"globs",
",",
"prefix",
"=",
"False",
")",
":",
"if",
"not",
"globs",
":",
"# An empty globs list should only match empty strings",
"return",
"re",
".",
"compile",
"(",
"'^$'",
")",
"elif",
"prefix",
":",
"globs",
"=",
"[",
"x"... | 38.222222 | 0.001418 |
def get_bounding_box(points):
"""Get the bounding box of a list of points.
Parameters
----------
points : list of points
Returns
-------
BoundingBox
"""
assert len(points) > 0, "At least one point has to be given."
min_x, max_x = points[0]['x'], points[0]['x']
min_y, max_y ... | [
"def",
"get_bounding_box",
"(",
"points",
")",
":",
"assert",
"len",
"(",
"points",
")",
">",
"0",
",",
"\"At least one point has to be given.\"",
"min_x",
",",
"max_x",
"=",
"points",
"[",
"0",
"]",
"[",
"'x'",
"]",
",",
"points",
"[",
"0",
"]",
"[",
... | 29.35 | 0.00165 |
def add_commands(cmds):
"""
Adds one or more commands to the module namespace.
Commands must end in "Command" to be added.
Example (see tests/parser.py):
sievelib.commands.add_commands(MytestCommand)
:param cmds: a single Command Object or list of Command Objects
"""
if not isinstance(c... | [
"def",
"add_commands",
"(",
"cmds",
")",
":",
"if",
"not",
"isinstance",
"(",
"cmds",
",",
"Iterable",
")",
":",
"cmds",
"=",
"[",
"cmds",
"]",
"for",
"command",
"in",
"cmds",
":",
"if",
"command",
".",
"__name__",
".",
"endswith",
"(",
"\"Command\"",
... | 31.2 | 0.002075 |
def _get_rs_id(variant, rs_map, variant_type):
"""
Given a variant dict, return unambiguous RS ID
TODO
Some sequence alterations appear to have mappings to dbsnp's notation
for example,
reference allele: TTTTTTTTTTTTTT
variant allele: TTTTTTTTTTTTTTT
Is ... | [
"def",
"_get_rs_id",
"(",
"variant",
",",
"rs_map",
",",
"variant_type",
")",
":",
"rs_id",
"=",
"None",
"if",
"variant_type",
"==",
"'snp'",
":",
"variant_key",
"=",
"\"{0}-{1}\"",
".",
"format",
"(",
"variant",
"[",
"'chromosome'",
"]",
",",
"variant",
"... | 42.557692 | 0.002208 |
def postproc(self):
"""
Obfuscate sensitive keys.
"""
self.do_file_sub(
"/etc/ovirt-engine/engine-config/engine-config.properties",
r"Password.type=(.*)",
r"Password.type=********"
)
self.do_file_sub(
"/etc/rhevm/rhevm-confi... | [
"def",
"postproc",
"(",
"self",
")",
":",
"self",
".",
"do_file_sub",
"(",
"\"/etc/ovirt-engine/engine-config/engine-config.properties\"",
",",
"r\"Password.type=(.*)\"",
",",
"r\"Password.type=********\"",
")",
"self",
".",
"do_file_sub",
"(",
"\"/etc/rhevm/rhevm-config/rhev... | 33.793478 | 0.000625 |
def axial_to_cartesian(q, r, size, orientation, aspect_scale=1):
''' Map axial *(q,r)* coordinates to cartesian *(x,y)* coordinates of
tiles centers.
This function can be useful for positioning other Bokeh glyphs with
cartesian coordinates in relation to a hex tiling.
This function was adapted fro... | [
"def",
"axial_to_cartesian",
"(",
"q",
",",
"r",
",",
"size",
",",
"orientation",
",",
"aspect_scale",
"=",
"1",
")",
":",
"if",
"orientation",
"==",
"\"pointytop\"",
":",
"x",
"=",
"size",
"*",
"np",
".",
"sqrt",
"(",
"3",
")",
"*",
"(",
"q",
"+",... | 32.14 | 0.000604 |
def render_to_response(self, context, indent=None):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context, indent=indent)) | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"indent",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_json_response",
"(",
"self",
".",
"convert_context_to_json",
"(",
"context",
",",
"indent",
"=",
"indent",
")",
")"
] | 69 | 0.014354 |
def cd(path_to): # pylint: disable=invalid-name
"""cd to the given path
If the path is a file, then cd to its parent directory
Remember current directory before the cd
so that we can cd back there with cd('-')
"""
if path_to == '-':
if not cd.previous:
raise PathError(... | [
"def",
"cd",
"(",
"path_to",
")",
":",
"# pylint: disable=invalid-name",
"if",
"path_to",
"==",
"'-'",
":",
"if",
"not",
"cd",
".",
"previous",
":",
"raise",
"PathError",
"(",
"'No previous directory to return to'",
")",
"return",
"cd",
"(",
"cd",
".",
"previo... | 28.633333 | 0.001126 |
def add_request_init_listener(self, fn, *args, **kwargs):
"""
Adds a callback with arguments to be called when any request is created.
It will be invoked as `fn(response_future, *args, **kwargs)` after each client request is created,
and before the request is sent\*. This can be used to... | [
"def",
"add_request_init_listener",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_request_init_callbacks",
".",
"append",
"(",
"(",
"fn",
",",
"args",
",",
"kwargs",
")",
")"
] | 57.842105 | 0.010743 |
def default_vrf_unicast_address_family(self, **kwargs):
"""Create default address family (ipv4/ipv6) under router bgp.
Args:
afi (str): Address family to configure. (ipv4, ipv6)
rbridge_id (str): The rbridge ID of the device on which BGP will be
con... | [
"def",
"default_vrf_unicast_address_family",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"afi",
"=",
"kwargs",
".",
"pop",
"(",
"'afi'",
",",
"'ipv4'",
")",
"rbridge_id",
"=",
"kwargs",
".",
"pop",
"(",
"'rbridge_id'",
",",
"'1'",
")",
"delete",
"=",... | 42.793103 | 0.000788 |
def add_zfs_apt_repository():
""" adds the ZFS repository """
with settings(hide('warnings', 'running', 'stdout'),
warn_only=False, capture=True):
sudo('DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get update')
install_ubuntu_development_tools()
apt_install(packages=['so... | [
"def",
"add_zfs_apt_repository",
"(",
")",
":",
"with",
"settings",
"(",
"hide",
"(",
"'warnings'",
",",
"'running'",
",",
"'stdout'",
")",
",",
"warn_only",
"=",
"False",
",",
"capture",
"=",
"True",
")",
":",
"sudo",
"(",
"'DEBIAN_FRONTEND=noninteractive /us... | 48.615385 | 0.001553 |
def generate(fn):
'''Parser generator. (combinator syntax).'''
if isinstance(fn, str):
return lambda f: generate(f).desc(fn)
@wraps(fn)
@Parser
def generated(text, index):
iterator, value = fn(), None
try:
while True:
parser = iterator.send(value)... | [
"def",
"generate",
"(",
"fn",
")",
":",
"if",
"isinstance",
"(",
"fn",
",",
"str",
")",
":",
"return",
"lambda",
"f",
":",
"generate",
"(",
"f",
")",
".",
"desc",
"(",
"fn",
")",
"@",
"wraps",
"(",
"fn",
")",
"@",
"Parser",
"def",
"generated",
... | 32.913043 | 0.001284 |
def makeBenchmarkRunner(path, args):
"""
Make a function that will run two Python processes serially: first one
which calls the setup function from the given file, then one which calls
the execute function from the given file.
"""
def runner():
return BenchmarkProcess.spawn(
... | [
"def",
"makeBenchmarkRunner",
"(",
"path",
",",
"args",
")",
":",
"def",
"runner",
"(",
")",
":",
"return",
"BenchmarkProcess",
".",
"spawn",
"(",
"executable",
"=",
"sys",
".",
"executable",
",",
"args",
"=",
"[",
"'-Wignore'",
"]",
"+",
"args",
",",
... | 34.307692 | 0.002183 |
def _win32_dir(path, star=''):
"""
Using the windows cmd shell to get information about a directory
"""
from ubelt import util_cmd
import re
wrapper = 'cmd /S /C "{}"' # the /S will preserve all inner quotes
command = 'dir /-C "{}"{}'.format(path, star)
wrapped = wrapper.format(command)... | [
"def",
"_win32_dir",
"(",
"path",
",",
"star",
"=",
"''",
")",
":",
"from",
"ubelt",
"import",
"util_cmd",
"import",
"re",
"wrapper",
"=",
"'cmd /S /C \"{}\"'",
"# the /S will preserve all inner quotes",
"command",
"=",
"'dir /-C \"{}\"{}'",
".",
"format",
"(",
"p... | 38.135135 | 0.000691 |
def _get_update_fn(strategy):
"""
Select dict-like class based on merge strategy and orderness of keys.
:param merge: Specify strategy from MERGE_STRATEGIES of how to merge dicts.
:return: Callable to update objects
"""
if strategy is None:
strategy = MS_DICTS
try:
return _M... | [
"def",
"_get_update_fn",
"(",
"strategy",
")",
":",
"if",
"strategy",
"is",
"None",
":",
"strategy",
"=",
"MS_DICTS",
"try",
":",
"return",
"_MERGE_FNS",
"[",
"strategy",
"]",
"except",
"KeyError",
":",
"if",
"callable",
"(",
"strategy",
")",
":",
"return"... | 29.25 | 0.00207 |
def get(self, node, path):
"""
Return instance at `path`.
An example module tree:
>>> from anytree import Node
>>> top = Node("top", parent=None)
>>> sub0 = Node("sub0", parent=top)
>>> sub0sub0 = Node("sub0sub0", parent=sub0)
>>> sub0sub1 = Node("sub0su... | [
"def",
"get",
"(",
"self",
",",
"node",
",",
"path",
")",
":",
"node",
",",
"parts",
"=",
"self",
".",
"__start",
"(",
"node",
",",
"path",
")",
"for",
"part",
"in",
"parts",
":",
"if",
"part",
"==",
"\"..\"",
":",
"node",
"=",
"node",
".",
"pa... | 29.689655 | 0.002248 |
def pot_dict_from_string(pot_data):
"""
Creates atomic symbol/potential number dictionary
forward and reverse
Arg:
pot_data: potential data in string format
Returns:
forward and reverse atom symbol and potential number dictionaries.
"""
... | [
"def",
"pot_dict_from_string",
"(",
"pot_data",
")",
":",
"pot_dict",
"=",
"{",
"}",
"pot_dict_reverse",
"=",
"{",
"}",
"begin",
"=",
"0",
"ln",
"=",
"-",
"1",
"for",
"line",
"in",
"pot_data",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"try",
":",
"if",... | 28.8125 | 0.002099 |
def construct_1d_arraylike_from_scalar(value, length, dtype):
"""
create a np.ndarray / pandas type of specified shape and dtype
filled with values
Parameters
----------
value : scalar value
length : int
dtype : pandas_dtype / np.dtype
Returns
-------
np.ndarray / pandas ty... | [
"def",
"construct_1d_arraylike_from_scalar",
"(",
"value",
",",
"length",
",",
"dtype",
")",
":",
"if",
"is_datetime64tz_dtype",
"(",
"dtype",
")",
":",
"from",
"pandas",
"import",
"DatetimeIndex",
"subarr",
"=",
"DatetimeIndex",
"(",
"[",
"value",
"]",
"*",
"... | 31.2 | 0.000777 |
def start(self, discord_token, discord_client_id):
"""Start Modis and log it into Discord."""
self.button_toggle_text.set("Stop Modis")
self.state = "on"
self.status_bar.set_status(1)
logger.info("----------------STARTING DISCORD MODIS----------------")
# Clear the mod... | [
"def",
"start",
"(",
"self",
",",
"discord_token",
",",
"discord_client_id",
")",
":",
"self",
".",
"button_toggle_text",
".",
"set",
"(",
"\"Stop Modis\"",
")",
"self",
".",
"state",
"=",
"\"on\"",
"self",
".",
"status_bar",
".",
"set_status",
"(",
"1",
"... | 40.302326 | 0.00169 |
def t_COLON(self, t):
r":"
t.endlexpos = t.lexpos + len(t.value)
return t | [
"def",
"t_COLON",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"endlexpos",
"=",
"t",
".",
"lexpos",
"+",
"len",
"(",
"t",
".",
"value",
")",
"return",
"t"
] | 23.5 | 0.020619 |
def calculate_base_sequence(base_offsets):
"""
Return a sequence of characters corresponding to the specified base.
Example::
>>> calculate_base_sequence([ ('0', '9'), ('A', 'F') ])
'0123456789ABCDEF'
@param base_offsets: a list of character offsets in the form of tuples
``... | [
"def",
"calculate_base_sequence",
"(",
"base_offsets",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"chr",
"(",
"c",
")",
"for",
"c",
"in",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"[",
"range",
"(",
"ord",
"(",
"x",
")"... | 39 | 0.008345 |
def subpool_imap(pool_size, func, iterable, flatten=False, unordered=False, buffer_size=None):
""" Generator version of subpool_map. Should be used with unordered=True for optimal performance """
from .context import get_current_job, set_current_job, log
if not pool_size:
for args in iterable:
yield f... | [
"def",
"subpool_imap",
"(",
"pool_size",
",",
"func",
",",
"iterable",
",",
"flatten",
"=",
"False",
",",
"unordered",
"=",
"False",
",",
"buffer_size",
"=",
"None",
")",
":",
"from",
".",
"context",
"import",
"get_current_job",
",",
"set_current_job",
",",
... | 25.777778 | 0.020166 |
def add_results(self, *rvs, **kwargs):
"""
Changes the state to reflect the mutation which yielded the given
result.
In order to use the result, the `fetch_mutation_tokens` option must
have been specified in the connection string, _and_ the result
must have been successf... | [
"def",
"add_results",
"(",
"self",
",",
"*",
"rvs",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"rvs",
":",
"raise",
"MissingTokenError",
".",
"pyexc",
"(",
"message",
"=",
"'No results passed'",
")",
"for",
"rv",
"in",
"rvs",
":",
"mi",
"=",
"rv... | 39.551724 | 0.001702 |
def pack_header_extensions(extensions: List[Tuple[int, bytes]]) -> Tuple[int, bytes]:
"""
Serialize header extensions according to RFC 5285.
"""
extension_profile = 0
extension_value = b''
if not extensions:
return extension_profile, extension_value
one_byte = True
for x_id, x_... | [
"def",
"pack_header_extensions",
"(",
"extensions",
":",
"List",
"[",
"Tuple",
"[",
"int",
",",
"bytes",
"]",
"]",
")",
"->",
"Tuple",
"[",
"int",
",",
"bytes",
"]",
":",
"extension_profile",
"=",
"0",
"extension_value",
"=",
"b''",
"if",
"not",
"extensi... | 32.108108 | 0.001634 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.