text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_project_by_network_id(network_id,**kwargs):
"""
get a project complexmodel by a network_id
"""
user_id = kwargs.get('user_id')
projects_i = db.DBSession.query(Project).join(ProjectOwner).join(Network, Project.id==Network.project_id).filter(
... | [
"def",
"get_project_by_network_id",
"(",
"network_id",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"projects_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Project",
")",
".",
"join",
"(",
"Projec... | 41.833333 | 0.011688 |
def load_json_dct(
dct,
record_store=None,
schema=None,
loader=from_json_compatible
):
""" Create a Record instance from a json-compatible dictionary
The dictionary values should have types that are json compatible,
as if just loaded from a json serialized record string.
... | [
"def",
"load_json_dct",
"(",
"dct",
",",
"record_store",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"loader",
"=",
"from_json_compatible",
")",
":",
"if",
"schema",
"is",
"None",
":",
"if",
"record_store",
"is",
"None",
":",
"record_store",
"=",
"auto_s... | 30.26087 | 0.000696 |
def dict_intersection(dict1, dict2, combine=False, combine_op=op.add):
r"""
Args:
dict1 (dict):
dict2 (dict):
combine (bool): Combines keys only if the values are equal if False else
values are combined using combine_op (default = False)
combine_op (func): (default = ... | [
"def",
"dict_intersection",
"(",
"dict1",
",",
"dict2",
",",
"combine",
"=",
"False",
",",
"combine_op",
"=",
"op",
".",
"add",
")",
":",
"isect_keys",
"=",
"set",
"(",
"dict1",
".",
"keys",
"(",
")",
")",
".",
"intersection",
"(",
"set",
"(",
"dict2... | 34.581395 | 0.000654 |
def expr_stmt(self, lhs, rhs):
"""
(2.6, 2.7, 3.0, 3.1)
expr_stmt: testlist (augassign (yield_expr|testlist) |
('=' (yield_expr|testlist))*)
(3.2-)
expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) |
('=' (yie... | [
"def",
"expr_stmt",
"(",
"self",
",",
"lhs",
",",
"rhs",
")",
":",
"if",
"isinstance",
"(",
"rhs",
",",
"ast",
".",
"AugAssign",
")",
":",
"if",
"isinstance",
"(",
"lhs",
",",
"ast",
".",
"Tuple",
")",
"or",
"isinstance",
"(",
"lhs",
",",
"ast",
... | 43.12 | 0.001815 |
def cluster_elongate():
"Not so applicable for this sample"
start_centers = [[1.0, 4.5], [3.1, 2.7]]
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_ELONGATE, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_ELONGATE, criter... | [
"def",
"cluster_elongate",
"(",
")",
":",
"start_centers",
"=",
"[",
"[",
"1.0",
",",
"4.5",
"]",
",",
"[",
"3.1",
",",
"2.7",
"]",
"]",
"template_clustering",
"(",
"start_centers",
",",
"SIMPLE_SAMPLES",
".",
"SAMPLE_ELONGATE",
",",
"criterion",
"=",
"spl... | 74.8 | 0.018519 |
def _match_filter_plot(stream, cccsum, template_names, rawthresh, plotdir,
plot_format, i): # pragma: no cover
"""
Plotting function for match_filter.
:param stream: Stream to plot
:param cccsum: Cross-correlation sum to plot
:param template_names: Template names used
:p... | [
"def",
"_match_filter_plot",
"(",
"stream",
",",
"cccsum",
",",
"template_names",
",",
"rawthresh",
",",
"plotdir",
",",
"plot_format",
",",
"i",
")",
":",
"# pragma: no cover",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"plt",
".",
"ioff",
"(",
")"... | 45.371429 | 0.000617 |
def display_console(self, request):
"""Display a standalone shell."""
if 0 not in self.frames:
self.frames[0] = _ConsoleFrame(self.console_init_func())
return Response(render_console_html(secret=self.secret),
content_type='text/html') | [
"def",
"display_console",
"(",
"self",
",",
"request",
")",
":",
"if",
"0",
"not",
"in",
"self",
".",
"frames",
":",
"self",
".",
"frames",
"[",
"0",
"]",
"=",
"_ConsoleFrame",
"(",
"self",
".",
"console_init_func",
"(",
")",
")",
"return",
"Response",... | 46.166667 | 0.010638 |
def get_config_load_path(conf_path=None):
"""
Return config file load path
Priority:
1. conf_path
2. current directory
3. home directory
Parameters
----------
conf_path
Returns
-------
"""
if conf_path is None:
# test ./andes.conf
if o... | [
"def",
"get_config_load_path",
"(",
"conf_path",
"=",
"None",
")",
":",
"if",
"conf_path",
"is",
"None",
":",
"# test ./andes.conf",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"'andes.conf'",
")",
":",
"conf_path",
"=",
"'andes.conf'",
"# test ~/andes.conf",
... | 22.322581 | 0.001385 |
def statement(self) -> Statement:
"""Parse YANG statement.
Raises:
EndOfInput: If past the end of input.
UnexpectedInput: If no syntactically correct statement is found.
"""
pref, kw = self.keyword()
pres = self.opt_separator()
next = self.peek()
... | [
"def",
"statement",
"(",
"self",
")",
"->",
"Statement",
":",
"pref",
",",
"kw",
"=",
"self",
".",
"keyword",
"(",
")",
"pres",
"=",
"self",
".",
"opt_separator",
"(",
")",
"next",
"=",
"self",
".",
"peek",
"(",
")",
"if",
"next",
"==",
"\";\"",
... | 29.724138 | 0.002247 |
def _initialize_memory(self, policy_params):
"""Initialize temporary and permanent memory.
Args:
policy_params: Nested tuple of policy parameters with all dimensions set.
Initializes the attributes `self._current_episodes`,
`self._finished_episodes`, and `self._num_finished_episodes`. The episod... | [
"def",
"_initialize_memory",
"(",
"self",
",",
"policy_params",
")",
":",
"# We store observation, action, policy parameters, and reward.",
"template",
"=",
"(",
"self",
".",
"_batch_env",
".",
"observ",
"[",
"0",
"]",
",",
"self",
".",
"_batch_env",
".",
"action",
... | 46.208333 | 0.001767 |
def nearest_neighbors(
X, n_neighbors, metric, metric_kwds, angular, random_state, verbose=False
):
"""Compute the ``n_neighbors`` nearest points for each data point in ``X``
under ``metric``. This may be exact, but more likely is approximated via
nearest neighbor descent.
Parameters
----------... | [
"def",
"nearest_neighbors",
"(",
"X",
",",
"n_neighbors",
",",
"metric",
",",
"metric_kwds",
",",
"angular",
",",
"random_state",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"ts",
"(",
")",
",",
"\"Finding Nearest Neighbors\""... | 36.350746 | 0.001199 |
def ensure_crossplat_path(path, winroot='C:'):
r"""
ensure_crossplat_path
Args:
path (str):
Returns:
str: crossplat_path
Example(DOCTEST):
>>> # ENABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> path = r'C:\somedir'
>>> cplat_path = ensur... | [
"def",
"ensure_crossplat_path",
"(",
"path",
",",
"winroot",
"=",
"'C:'",
")",
":",
"cplat_path",
"=",
"path",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"if",
"cplat_path",
"==",
"winroot",
":",
"cplat_path",
"+=",
"'/'",
"return",
"cplat_path"
] | 22.782609 | 0.001832 |
def run_cmd(cmd, echo=False, fail_silently=False, **kwargs):
r"""Call given command with ``subprocess.call`` function.
:param cmd: Command to run.
:type cmd: tuple or str
:param echo:
If enabled show command to call and its output in STDOUT, otherwise
hide all output. By default: False
... | [
"def",
"run_cmd",
"(",
"cmd",
",",
"echo",
"=",
"False",
",",
"fail_silently",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
",",
"err",
"=",
"None",
",",
"None",
"if",
"echo",
":",
"cmd_str",
"=",
"cmd",
"if",
"isinstance",
"(",
"cmd",
... | 35.195122 | 0.000674 |
def previous(self):
"""
fetch the chart identified by this chart's previous_id attribute
if the previous_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.previous_id:
return Ch... | [
"def",
"previous",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"previous_id",
":",
"return",
"Chart",
"(",
"self",
".",
"previous_id",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'attempted to get previous chart, but none was found'",
")",
"return",... | 43.6 | 0.010479 |
def create(host, port, result_converter=None, testcase_converter=None, args=None):
"""
Function which is called by Icetea to create an instance of the cloud client. This function
must exists.
This function myust not return None. Either return an instance of Client or raise.
"""
return SampleClie... | [
"def",
"create",
"(",
"host",
",",
"port",
",",
"result_converter",
"=",
"None",
",",
"testcase_converter",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"return",
"SampleClient",
"(",
"host",
",",
"port",
",",
"result_converter",
",",
"testcase_converter... | 53.142857 | 0.010582 |
def users_getPresence(self, *, user: str, **kwargs) -> SlackResponse:
"""Gets user presence information.
Args:
user (str): User to get presence info on. Defaults to the authed user.
e.g. 'W1234567890'
"""
kwargs.update({"user": user})
return self.api_... | [
"def",
"users_getPresence",
"(",
"self",
",",
"*",
",",
"user",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"SlackResponse",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"user\"",
":",
"user",
"}",
")",
"return",
"self",
".",
"api_call",
"(",
"\"use... | 41 | 0.01061 |
def _tls_P_hash(secret, seed, req_len, hm):
"""
Provides the implementation of P_hash function defined in
section 5 of RFC 4346 (and section 5 of RFC 5246). Two
parameters have been added (hm and req_len):
- secret : the key to be used. If RFC 4868 is to be believed,
the length must ... | [
"def",
"_tls_P_hash",
"(",
"secret",
",",
"seed",
",",
"req_len",
",",
"hm",
")",
":",
"hash_len",
"=",
"hm",
".",
"hash_alg",
".",
"hash_len",
"n",
"=",
"(",
"req_len",
"+",
"hash_len",
"-",
"1",
")",
"//",
"hash_len",
"seed",
"=",
"bytes_encode",
"... | 35.366667 | 0.000917 |
def cli(env, crt, csr, icc, key, notes):
"""Add and upload SSL certificate details."""
template = {
'intermediateCertificate': '',
'certificateSigningRequest': '',
'notes': notes,
}
template['certificate'] = open(crt).read()
template['privateKey'] = open(key).read()
if c... | [
"def",
"cli",
"(",
"env",
",",
"crt",
",",
"csr",
",",
"icc",
",",
"key",
",",
"notes",
")",
":",
"template",
"=",
"{",
"'intermediateCertificate'",
":",
"''",
",",
"'certificateSigningRequest'",
":",
"''",
",",
"'notes'",
":",
"notes",
",",
"}",
"temp... | 28.55 | 0.001695 |
def print_help(self, session, command=None):
"""
Prints the available methods and their documentation, or the
documentation of the given command.
"""
if command:
# Single command mode
if command in self._commands:
# Argument is a name space... | [
"def",
"print_help",
"(",
"self",
",",
"session",
",",
"command",
"=",
"None",
")",
":",
"if",
"command",
":",
"# Single command mode",
"if",
"command",
"in",
"self",
".",
"_commands",
":",
"# Argument is a name space",
"self",
".",
"__print_namespace_help",
"("... | 35.9 | 0.001085 |
def timeout_process_add_queue(self, module, cache_time):
"""
Add a module to the timeout_queue if it is scheduled in the future or
if it is due for an update immediately just trigger that.
the timeout_queue is a dict with the scheduled time as the key and the
value is a list of ... | [
"def",
"timeout_process_add_queue",
"(",
"self",
",",
"module",
",",
"cache_time",
")",
":",
"# If already set to update do nothing",
"if",
"module",
"in",
"self",
".",
"timeout_update_due",
":",
"return",
"# remove if already in the queue",
"key",
"=",
"self",
".",
"... | 42.688889 | 0.001018 |
def read(self, nml_fname, nml_patch_in=None, patch_fname=None):
"""Parse a Fortran namelist file and store the contents.
>>> parser = f90nml.Parser()
>>> data_nml = parser.read('data.nml')
"""
# For switching based on files versus paths
nml_is_path = not hasattr(nml_fnam... | [
"def",
"read",
"(",
"self",
",",
"nml_fname",
",",
"nml_patch_in",
"=",
"None",
",",
"patch_fname",
"=",
"None",
")",
":",
"# For switching based on files versus paths",
"nml_is_path",
"=",
"not",
"hasattr",
"(",
"nml_fname",
",",
"'read'",
")",
"patch_is_path",
... | 38.139535 | 0.001189 |
def _open(self):
"""
Open the file; get sheets
:return:
"""
if not hasattr(self, '_file'):
self._file = self.gc.open(self.name)
self.sheet_names = self._file.worksheets() | [
"def",
"_open",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_file'",
")",
":",
"self",
".",
"_file",
"=",
"self",
".",
"gc",
".",
"open",
"(",
"self",
".",
"name",
")",
"self",
".",
"sheet_names",
"=",
"self",
".",
"_file",... | 28.375 | 0.008547 |
def encode(msg, strict=False, logger=None, timezone_offset=None):
"""
Encodes and returns the L{msg<Envelope>} as an AMF stream.
@param strict: Enforce strict encoding. Default is C{False}. Specifically
header/body lengths will be written correctly, instead of the default 0.
Default is `Fal... | [
"def",
"encode",
"(",
"msg",
",",
"strict",
"=",
"False",
",",
"logger",
"=",
"None",
",",
"timezone_offset",
"=",
"None",
")",
":",
"stream",
"=",
"util",
".",
"BufferedByteStream",
"(",
")",
"encoder",
"=",
"pyamf",
".",
"get_encoder",
"(",
"pyamf",
... | 36.418605 | 0.002488 |
def posterior_predictive_to_xarray(self):
"""Convert posterior_predictive samples to xarray."""
posterior = self.posterior
posterior_predictive = self.posterior_predictive
data = get_draws(posterior, variables=posterior_predictive)
return dict_to_dataset(data, library=self.p... | [
"def",
"posterior_predictive_to_xarray",
"(",
"self",
")",
":",
"posterior",
"=",
"self",
".",
"posterior",
"posterior_predictive",
"=",
"self",
".",
"posterior_predictive",
"data",
"=",
"get_draws",
"(",
"posterior",
",",
"variables",
"=",
"posterior_predictive",
"... | 59.5 | 0.008287 |
def rm_op(l, name, op):
"""Remove an opcode. This is used when basing a new Python release off
of another one, and there is an opcode that is in the old release
that was removed in the new release.
We are pretty aggressive about removing traces of the op.
"""
# opname is an array, so we need to... | [
"def",
"rm_op",
"(",
"l",
",",
"name",
",",
"op",
")",
":",
"# opname is an array, so we need to keep the position in there.",
"l",
"[",
"'opname'",
"]",
"[",
"op",
"]",
"=",
"'<%s>'",
"%",
"op",
"if",
"op",
"in",
"l",
"[",
"'hasconst'",
"]",
":",
"l",
"... | 30.513514 | 0.012017 |
def inherit_docstrings(cls):
"""Class decorator for inheriting docstrings.
Automatically inherits base class doc-strings if not present in the
derived class.
"""
@functools.wraps(cls)
def _inherit_docstrings(cls):
if not isinstance(cls, (type, colorise.compat.ClassType)):
r... | [
"def",
"inherit_docstrings",
"(",
"cls",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"cls",
")",
"def",
"_inherit_docstrings",
"(",
"cls",
")",
":",
"if",
"not",
"isinstance",
"(",
"cls",
",",
"(",
"type",
",",
"colorise",
".",
"compat",
".",
"Class... | 34.541667 | 0.001174 |
def _suggest_semantic_version(s):
"""
Try to suggest a semantic form for a version for which
_suggest_normalized_version couldn't come up with anything.
"""
result = s.strip().lower()
for pat, repl in _REPLACEMENTS:
result = pat.sub(repl, result)
if not result:
result = '0.0.... | [
"def",
"_suggest_semantic_version",
"(",
"s",
")",
":",
"result",
"=",
"s",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"for",
"pat",
",",
"repl",
"in",
"_REPLACEMENTS",
":",
"result",
"=",
"pat",
".",
"sub",
"(",
"repl",
",",
"result",
")",
"i... | 29.568182 | 0.002232 |
def si_format(value, precision=1, format_str=u'{value} {prefix}',
exp_format_str=u'{value}e{expof10}'):
'''
Format value to string with SI prefix, using the specified precision.
Parameters
----------
value : int, float
Input value.
precision : int
Number of digits ... | [
"def",
"si_format",
"(",
"value",
",",
"precision",
"=",
"1",
",",
"format_str",
"=",
"u'{value} {prefix}'",
",",
"exp_format_str",
"=",
"u'{value}e{expof10}'",
")",
":",
"svalue",
",",
"expof10",
"=",
"split",
"(",
"value",
",",
"precision",
")",
"value_forma... | 31.414894 | 0.000328 |
def eig_one_step(current_vector, learning_rate, vector_prod_fn):
"""Function that performs one step of gd (variant) for min eigen value.
Args:
current_vector: current estimate of the eigen vector with minimum eigen
value.
learning_rate: learning rate.
vector_prod_fn: function which returns produc... | [
"def",
"eig_one_step",
"(",
"current_vector",
",",
"learning_rate",
",",
"vector_prod_fn",
")",
":",
"grad",
"=",
"2",
"*",
"vector_prod_fn",
"(",
"current_vector",
")",
"# Current objective = (1/2)*v^T (2*M*v); v = current_vector",
"# grad = 2*M*v",
"current_objective",
"=... | 38.923077 | 0.013878 |
def find_linked_dynamic_libraries():
"""
This function attempts to locate the required link libraries, and returns
them as a list of absolute paths.
"""
with TaskContext("Find the required dynamic libraries") as log:
llvm = get_llvm()
libs = required_link_libraries()
resolved... | [
"def",
"find_linked_dynamic_libraries",
"(",
")",
":",
"with",
"TaskContext",
"(",
"\"Find the required dynamic libraries\"",
")",
"as",
"log",
":",
"llvm",
"=",
"get_llvm",
"(",
")",
"libs",
"=",
"required_link_libraries",
"(",
")",
"resolved",
"=",
"[",
"]",
"... | 45.263158 | 0.001707 |
def wait_for_instance(
vm_=None,
data=None,
ip_address=None,
display_ssh_output=True,
call=None,
):
'''
Wait for an instance upon creation from the EC2 API, to become available
'''
if call == 'function':
# Technically this function may be called other ... | [
"def",
"wait_for_instance",
"(",
"vm_",
"=",
"None",
",",
"data",
"=",
"None",
",",
"ip_address",
"=",
"None",
",",
"display_ssh_output",
"=",
"True",
",",
"call",
"=",
"None",
",",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"# Technically this funct... | 38.533937 | 0.001374 |
def getParent(self, returned_properties=None):
"""Get the parent workitem of this workitem
If no parent, None will be returned.
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:return: a :... | [
"def",
"getParent",
"(",
"self",
",",
"returned_properties",
"=",
"None",
")",
":",
"parent_tag",
"=",
"(",
"\"rtc_cm:com.ibm.team.workitem.linktype.\"",
"\"parentworkitem.parent\"",
")",
"rp",
"=",
"returned_properties",
"parent",
"=",
"(",
"self",
".",
"rtc_obj",
... | 39.576923 | 0.001898 |
async def movies(self):
'''list of movies in the collection
|force|
|coro|
Returns
-------
list
of type :class:`embypy.objects.Movie`
'''
items = []
for i in await self.items:
if i.type == 'Movie':
items.append(i)
elif hasattr(i, 'movies'):
items.... | [
"async",
"def",
"movies",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"for",
"i",
"in",
"await",
"self",
".",
"items",
":",
"if",
"i",
".",
"type",
"==",
"'Movie'",
":",
"items",
".",
"append",
"(",
"i",
")",
"elif",
"hasattr",
"(",
"i",
","... | 17.947368 | 0.008357 |
def add_all_database_reactions(model, compartments):
"""Add all reactions from database that occur in given compartments.
Args:
model: :class:`psamm.metabolicmodel.MetabolicModel`.
"""
added = set()
for rxnid in model.database.reactions:
reaction = model.database.get_reaction(rxnid... | [
"def",
"add_all_database_reactions",
"(",
"model",
",",
"compartments",
")",
":",
"added",
"=",
"set",
"(",
")",
"for",
"rxnid",
"in",
"model",
".",
"database",
".",
"reactions",
":",
"reaction",
"=",
"model",
".",
"database",
".",
"get_reaction",
"(",
"rx... | 32.176471 | 0.001776 |
def schedule_to_array(schedule, events, slots):
"""Convert a schedule from schedule to array form
Parameters
----------
schedule : list or tuple
of instances of :py:class:`resources.ScheduledItem`
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tu... | [
"def",
"schedule_to_array",
"(",
"schedule",
",",
"events",
",",
"slots",
")",
":",
"array",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"events",
")",
",",
"len",
"(",
"slots",
")",
")",
",",
"dtype",
"=",
"np",
".",
"int8",
")",
"for",
"item... | 31.913043 | 0.001323 |
def remove_from_role(server_context, role, user_id=None, email=None, container_path=None):
"""
Remove user/group from security role
:param server_context: A LabKey server context. See utils.create_server_context.
:param role: (from get_roles) to remove user from
:param user_id: to remove permissions... | [
"def",
"remove_from_role",
"(",
"server_context",
",",
"role",
",",
"user_id",
"=",
"None",
",",
"email",
"=",
"None",
",",
"container_path",
"=",
"None",
")",
":",
"return",
"__make_security_role_api_request",
"(",
"server_context",
",",
"'removeAssignment.api'",
... | 59 | 0.008345 |
def validate_groupby_func(name, args, kwargs, allowed=None):
"""
'args' and 'kwargs' should be empty, except for allowed
kwargs because all of
their necessary parameters are explicitly listed in
the function signature
"""
if allowed is None:
allowed = []
kwargs = set(kwargs) - s... | [
"def",
"validate_groupby_func",
"(",
"name",
",",
"args",
",",
"kwargs",
",",
"allowed",
"=",
"None",
")",
":",
"if",
"allowed",
"is",
"None",
":",
"allowed",
"=",
"[",
"]",
"kwargs",
"=",
"set",
"(",
"kwargs",
")",
"-",
"set",
"(",
"allowed",
")",
... | 31.529412 | 0.001812 |
def update_package_files(srcdir, extensions, package_data, packagenames,
package_dirs):
"""
This function is deprecated and maintained for backward compatibility
with affiliated packages. Affiliated packages should update their
setup.py to use `get_package_info` instead.
""... | [
"def",
"update_package_files",
"(",
"srcdir",
",",
"extensions",
",",
"package_data",
",",
"packagenames",
",",
"package_dirs",
")",
":",
"info",
"=",
"get_package_info",
"(",
"srcdir",
")",
"extensions",
".",
"extend",
"(",
"info",
"[",
"'ext_modules'",
"]",
... | 41.692308 | 0.001805 |
def calc(self, x:Image, *args:Any, **kwargs:Any)->Image:
"Apply to image `x`, wrapping it if necessary."
if self._wrap: return getattr(x, self._wrap)(self.func, *args, **kwargs)
else: return self.func(x, *args, **kwargs) | [
"def",
"calc",
"(",
"self",
",",
"x",
":",
"Image",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Image",
":",
"if",
"self",
".",
"_wrap",
":",
"return",
"getattr",
"(",
"x",
",",
"self",
".",
"_wrap",
")",
"(... | 62.5 | 0.039526 |
def hl_table2canvas(self, w, res_dict):
"""Highlight mask on canvas when user click on table."""
objlist = []
# Remove existing highlight
if self.maskhltag:
try:
self.canvas.delete_object_by_tag(self.maskhltag, redraw=False)
except Exception:
... | [
"def",
"hl_table2canvas",
"(",
"self",
",",
"w",
",",
"res_dict",
")",
":",
"objlist",
"=",
"[",
"]",
"# Remove existing highlight",
"if",
"self",
".",
"maskhltag",
":",
"try",
":",
"self",
".",
"canvas",
".",
"delete_object_by_tag",
"(",
"self",
".",
"mas... | 33.833333 | 0.002395 |
def getBucketValues(self):
""" See the function description in base.py """
# Need to re-create?
if self._bucketValues is None:
topDownMappingM = self._getTopDownMapping()
numBuckets = topDownMappingM.nRows()
self._bucketValues = []
for bucketIdx in range(numBuckets):
self._b... | [
"def",
"getBucketValues",
"(",
"self",
")",
":",
"# Need to re-create?",
"if",
"self",
".",
"_bucketValues",
"is",
"None",
":",
"topDownMappingM",
"=",
"self",
".",
"_getTopDownMapping",
"(",
")",
"numBuckets",
"=",
"topDownMappingM",
".",
"nRows",
"(",
")",
"... | 33.333333 | 0.012165 |
def get_overlapping_ranges(self, collection_link, sorted_ranges):
'''
Given the sorted ranges and a collection,
Returns the list of overlapping partition key ranges
:param str collection_link:
The collection link.
:param (list of routing_range._Range) sorted_... | [
"def",
"get_overlapping_ranges",
"(",
"self",
",",
"collection_link",
",",
"sorted_ranges",
")",
":",
"# validate if the list is non-overlapping and sorted",
"if",
"not",
"self",
".",
"_is_sorted_and_non_overlapping",
"(",
"sorted_ranges",
")",
":",
"raise",
"ValueError",
... | 49.314815 | 0.0081 |
def _build_layers(self, inputs, num_outputs, options):
"""Process the flattened inputs.
Note that dict inputs will be flattened into a vector. To define a
model that processes the components separately, use _build_layers_v2().
"""
hiddens = options.get("fcnet_hiddens")
... | [
"def",
"_build_layers",
"(",
"self",
",",
"inputs",
",",
"num_outputs",
",",
"options",
")",
":",
"hiddens",
"=",
"options",
".",
"get",
"(",
"\"fcnet_hiddens\"",
")",
"activation",
"=",
"get_activation_fn",
"(",
"options",
".",
"get",
"(",
"\"fcnet_activation... | 36.166667 | 0.001795 |
def genfsms(self,meter=None):
"""Generate FSM images. Requires networkx and GraphViz."""
if (hasattr(self,'allParses')):
name=self.getName()
import networkx as nx
m2int={'w':'0','s':'1'}
gs={}
gs['weight']=['str_weight']
gs['stress']=['str_stress']
gs['stressweight']=['str_stress','str_weigh... | [
"def",
"genfsms",
"(",
"self",
",",
"meter",
"=",
"None",
")",
":",
"if",
"(",
"hasattr",
"(",
"self",
",",
"'allParses'",
")",
")",
":",
"name",
"=",
"self",
".",
"getName",
"(",
")",
"import",
"networkx",
"as",
"nx",
"m2int",
"=",
"{",
"'w'",
"... | 26.375 | 0.056585 |
def isEnabled(self):
"""
Return whether or not this layer is enabled and can be set as the \
current layer.
:sa linkEnabledToCurrent
:return <bool>
"""
if self._linkEnabledToCurrent:
addtl = self.isCurrent()
e... | [
"def",
"isEnabled",
"(",
"self",
")",
":",
"if",
"self",
".",
"_linkEnabledToCurrent",
":",
"addtl",
"=",
"self",
".",
"isCurrent",
"(",
")",
"else",
":",
"addtl",
"=",
"True",
"return",
"self",
".",
"_enabled",
"and",
"addtl"
] | 23.875 | 0.015113 |
def get(self, url, params=None, headers=None, content=None, form_content=None):
# type: (str, Optional[Dict[str, str]], Optional[Dict[str, str]], Any, Optional[Dict[str, Any]]) -> ClientRequest
"""Create a GET request object.
:param str url: The request URL.
:param dict params: Request ... | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"content",
"=",
"None",
",",
"form_content",
"=",
"None",
")",
":",
"# type: (str, Optional[Dict[str, str]], Optional[Dict[str, str]], Any, Optional[Dict[str, Any]]) -... | 46.5 | 0.008787 |
def summary(self, key, column="C1", timeoutSecs=10, **kwargs):
'''
Return the summary for a single column for a single Frame in the h2o cluster.
'''
params_dict = {
# 'offset': 0,
# 'len': 100
}
h2o_methods.check_params_update_kwargs(params_dict, kwargs, 'summary', True)
... | [
"def",
"summary",
"(",
"self",
",",
"key",
",",
"column",
"=",
"\"C1\"",
",",
"timeoutSecs",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"params_dict",
"=",
"{",
"# 'offset': 0,",
"# 'len': 100",
"}",
"h2o_methods",
".",
"check_params_update_kwargs",
"(",
... | 38.307692 | 0.013725 |
def render(self, content = None, **settings):
"""
Perform widget rendering, but do not print anything.
"""
(content, settings) = self.get_setup(content, **settings)
return self._render(content, **settings) | [
"def",
"render",
"(",
"self",
",",
"content",
"=",
"None",
",",
"*",
"*",
"settings",
")",
":",
"(",
"content",
",",
"settings",
")",
"=",
"self",
".",
"get_setup",
"(",
"content",
",",
"*",
"*",
"settings",
")",
"return",
"self",
".",
"_render",
"... | 40 | 0.016327 |
def oneup(self, window_name, object_name, iterations):
"""
Press scrollbar up with number of iterations
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type... | [
"def",
"oneup",
"(",
"self",
",",
"window_name",
",",
"object_name",
",",
"iterations",
")",
":",
"if",
"not",
"self",
".",
"verifyscrollbarvertical",
"(",
"window_name",
",",
"object_name",
")",
":",
"raise",
"LdtpServerException",
"(",
"'Object not vertical scro... | 37.151515 | 0.00159 |
def sens_batmon_encode(self, temperature, voltage, current, SoC, batterystatus, serialnumber, hostfetcontrol, cellvoltage1, cellvoltage2, cellvoltage3, cellvoltage4, cellvoltage5, cellvoltage6):
'''
Battery pack monitoring data for Li-Ion batteries
temperature ... | [
"def",
"sens_batmon_encode",
"(",
"self",
",",
"temperature",
",",
"voltage",
",",
"current",
",",
"SoC",
",",
"batterystatus",
",",
"serialnumber",
",",
"hostfetcontrol",
",",
"cellvoltage1",
",",
"cellvoltage2",
",",
"cellvoltage3",
",",
"cellvoltage4",
",",
"... | 83.7 | 0.010041 |
def setup_temp_logger(log_level='error'):
'''
Setup the temporary console logger
'''
if is_temp_logging_configured():
logging.getLogger(__name__).warning(
'Temporary logging is already configured'
)
return
if log_level is None:
log_level = 'warning'
... | [
"def",
"setup_temp_logger",
"(",
"log_level",
"=",
"'error'",
")",
":",
"if",
"is_temp_logging_configured",
"(",
")",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"warning",
"(",
"'Temporary logging is already configured'",
")",
"return",
"if",
"lo... | 29.25 | 0.000636 |
def run_drop_tables(_):
'''
Running the script.
'''
print('--')
drop_the_table(TabPost)
drop_the_table(TabTag)
drop_the_table(TabMember)
drop_the_table(TabWiki)
drop_the_table(TabLink)
drop_the_table(TabEntity)
drop_the_table(TabPostHist)
drop_the_table(TabWikiHist)
... | [
"def",
"run_drop_tables",
"(",
"_",
")",
":",
"print",
"(",
"'--'",
")",
"drop_the_table",
"(",
"TabPost",
")",
"drop_the_table",
"(",
"TabTag",
")",
"drop_the_table",
"(",
"TabMember",
")",
"drop_the_table",
"(",
"TabWiki",
")",
"drop_the_table",
"(",
"TabLin... | 24.545455 | 0.001783 |
def miller_rabin(n, k):
"""Run the Miller-Rabin test on n with at most k iterations
Arguments:
n (int): number whose primality is to be tested
k (int): maximum number of iterations to run
Returns:
bool: If n is prime, then True is returned. Otherwise, False is
returned, exc... | [
"def",
"miller_rabin",
"(",
"n",
",",
"k",
")",
":",
"assert",
"n",
">",
"3",
"# find r and d such that n-1 = 2^r × d",
"d",
"=",
"n",
"-",
"1",
"r",
"=",
"0",
"while",
"d",
"%",
"2",
"==",
"0",
":",
"d",
"//=",
"2",
"r",
"+=",
"1",
"assert",
"n"... | 26.5 | 0.000958 |
def set_static_ip(iface, addr, gateway=None, append=False):
'''
Set static IP configuration on a Windows NIC
iface
The name of the interface to manage
addr
IP address with subnet length (ex. ``10.1.2.3/24``). The
:mod:`ip.get_subnet_length <salt.modules.win_ip.get_subnet_length... | [
"def",
"set_static_ip",
"(",
"iface",
",",
"addr",
",",
"gateway",
"=",
"None",
",",
"append",
"=",
"False",
")",
":",
"def",
"_find_addr",
"(",
"iface",
",",
"addr",
",",
"timeout",
"=",
"1",
")",
":",
"ip",
",",
"cidr",
"=",
"addr",
".",
"rsplit"... | 32.555556 | 0.001104 |
def _get_quantiles(self, X, width, quantiles, modelmat=None, lp=None,
prediction=False, xform=True, term=-1):
"""
estimate prediction intervals for LinearGAM
Parameters
----------
X : array
input data of shape (n_samples, m_features)
wi... | [
"def",
"_get_quantiles",
"(",
"self",
",",
"X",
",",
"width",
",",
"quantiles",
",",
"modelmat",
"=",
"None",
",",
"lp",
"=",
"None",
",",
"prediction",
"=",
"False",
",",
"xform",
"=",
"True",
",",
"term",
"=",
"-",
"1",
")",
":",
"if",
"quantiles... | 38.402597 | 0.001978 |
def owner_type(self, value):
"""Set ``owner_type`` to the given value.
In addition:
* Update the internal type of the ``owner`` field.
* Update the value of the ``owner`` field if a value is already set.
"""
self._owner_type = value
if value == 'User':
... | [
"def",
"owner_type",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_owner_type",
"=",
"value",
"if",
"value",
"==",
"'User'",
":",
"self",
".",
"_fields",
"[",
"'owner'",
"]",
"=",
"entity_fields",
".",
"OneToOneField",
"(",
"User",
")",
"if",
"ha... | 38.333333 | 0.001885 |
def get_objects(self):
"""
Return a list of all content objects in this distribution.
:rtype: list of :class:`boto.cloudfront.object.Object`
:return: The content objects
"""
bucket = self._get_bucket()
objs = []
for key in bucket:
objs... | [
"def",
"get_objects",
"(",
"self",
")",
":",
"bucket",
"=",
"self",
".",
"_get_bucket",
"(",
")",
"objs",
"=",
"[",
"]",
"for",
"key",
"in",
"bucket",
":",
"objs",
".",
"append",
"(",
"key",
")",
"return",
"objs"
] | 28.416667 | 0.008523 |
def ensure_traj(traj):
r"""Makes sure that traj is a trajectory (array of float)
"""
if is_float_matrix(traj) or is_bool_matrix(traj):
return traj
elif is_float_vector(traj):
return traj[:,None]
else:
try:
arr = np.array(traj)
arr = ensure_dtype_float... | [
"def",
"ensure_traj",
"(",
"traj",
")",
":",
"if",
"is_float_matrix",
"(",
"traj",
")",
"or",
"is_bool_matrix",
"(",
"traj",
")",
":",
"return",
"traj",
"elif",
"is_float_vector",
"(",
"traj",
")",
":",
"return",
"traj",
"[",
":",
",",
"None",
"]",
"el... | 36.45 | 0.008021 |
def EMetaclass(cls):
"""Class decorator for creating PyEcore metaclass."""
superclass = cls.__bases__
if not issubclass(cls, EObject):
sclasslist = list(superclass)
if object in superclass:
index = sclasslist.index(object)
sclasslist.insert(index, EObject)
... | [
"def",
"EMetaclass",
"(",
"cls",
")",
":",
"superclass",
"=",
"cls",
".",
"__bases__",
"if",
"not",
"issubclass",
"(",
"cls",
",",
"EObject",
")",
":",
"sclasslist",
"=",
"list",
"(",
"superclass",
")",
"if",
"object",
"in",
"superclass",
":",
"index",
... | 35.772727 | 0.001238 |
def del_edges(self, edges, *args, **kwargs):
"""
Removes edges from the graph. Takes optional arguments for
``DictGraph.del_edge``.
Arguments:
- edges(iterable) Sequence of edges to be removed from the
``DictGraph``.
"""
... | [
"def",
"del_edges",
"(",
"self",
",",
"edges",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"edge",
"in",
"edges",
":",
"self",
".",
"del_edge",
"(",
"edge",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 29.153846 | 0.017903 |
def _stderr_raw(self, s):
"""Writes the string to stdout"""
print(s, end='', file=sys.stderr)
sys.stderr.flush() | [
"def",
"_stderr_raw",
"(",
"self",
",",
"s",
")",
":",
"print",
"(",
"s",
",",
"end",
"=",
"''",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")"
] | 33.25 | 0.014706 |
def deserialize_dataframe(reader, data_type_id):
"""
Deserialize a dataframe.
Parameters
----------
reader : file
File-like object to read from. Must be opened in binary mode.
data_type_id : dict
Serialization format of the raw data.
See the azureml.DataTypeIds class for... | [
"def",
"deserialize_dataframe",
"(",
"reader",
",",
"data_type_id",
")",
":",
"_not_none",
"(",
"'reader'",
",",
"reader",
")",
"_not_none_or_empty",
"(",
"'data_type_id'",
",",
"data_type_id",
")",
"serializer",
"=",
"_SERIALIZERS",
".",
"get",
"(",
"data_type_id... | 26.875 | 0.001497 |
def deposit_fetcher(record_uuid, data):
"""Fetch a deposit identifier.
:param record_uuid: Record UUID.
:param data: Record content.
:returns: A :class:`invenio_pidstore.fetchers.FetchedPID` that contains
data['_deposit']['id'] as pid_value.
"""
return FetchedPID(
provider=Depos... | [
"def",
"deposit_fetcher",
"(",
"record_uuid",
",",
"data",
")",
":",
"return",
"FetchedPID",
"(",
"provider",
"=",
"DepositProvider",
",",
"pid_type",
"=",
"DepositProvider",
".",
"pid_type",
",",
"pid_value",
"=",
"str",
"(",
"data",
"[",
"'_deposit'",
"]",
... | 31.923077 | 0.002342 |
def get_info(self):
"""
Get info for all filters.
"""
out = ''
for k in sorted(self.components.keys()):
out += '{:s}: {:s}'.format(k, self.info[k]) + '\n'
return(out) | [
"def",
"get_info",
"(",
"self",
")",
":",
"out",
"=",
"''",
"for",
"k",
"in",
"sorted",
"(",
"self",
".",
"components",
".",
"keys",
"(",
")",
")",
":",
"out",
"+=",
"'{:s}: {:s}'",
".",
"format",
"(",
"k",
",",
"self",
".",
"info",
"[",
"k",
"... | 27.375 | 0.00885 |
def undo(self):
"""Undo the last cluster assignment operation.
Returns
-------
up : UpdateInfo instance of the changes done by this operation.
"""
_, _, undo_state = self._undo_stack.back()
# Retrieve the initial spike_cluster structure.
spike_clusters... | [
"def",
"undo",
"(",
"self",
")",
":",
"_",
",",
"_",
",",
"undo_state",
"=",
"self",
".",
"_undo_stack",
".",
"back",
"(",
")",
"# Retrieve the initial spike_cluster structure.",
"spike_clusters_new",
"=",
"self",
".",
"_spike_clusters_base",
".",
"copy",
"(",
... | 33.34375 | 0.001821 |
def print_tree(editor, file=sys.stdout, print_blocks=False, return_list=False):
"""
Prints the editor fold tree to stdout, for debugging purpose.
:param editor: CodeEditor instance.
:param file: file handle where the tree will be printed. Default is stdout.
:param print_blocks: True to print all bl... | [
"def",
"print_tree",
"(",
"editor",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"print_blocks",
"=",
"False",
",",
"return_list",
"=",
"False",
")",
":",
"output_list",
"=",
"[",
"]",
"block",
"=",
"editor",
".",
"document",
"(",
")",
".",
"firstBlock... | 38.428571 | 0.000725 |
def gather(params, indices, dtype=tf.float32):
"""Version of tf.gather that works faster on tpu."""
if not is_xla_compiled():
return tf.gather(params, indices)
vocab_size = params.get_shape().as_list()[0]
indices_flat = tf.reshape(indices, [-1])
out = tf.matmul(tf.one_hot(indices_flat, vocab_size, dtype=d... | [
"def",
"gather",
"(",
"params",
",",
"indices",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"if",
"not",
"is_xla_compiled",
"(",
")",
":",
"return",
"tf",
".",
"gather",
"(",
"params",
",",
"indices",
")",
"vocab_size",
"=",
"params",
".",
"ge... | 43.777778 | 0.0199 |
def physical_pins(self, function):
"""
Return the physical pins supporting the specified *function* as tuples
of ``(header, pin_number)`` where *header* is a string specifying the
header containing the *pin_number*. Note that the return value is a
:class:`set` which is not indexa... | [
"def",
"physical_pins",
"(",
"self",
",",
"function",
")",
":",
"return",
"{",
"(",
"header",
",",
"pin",
".",
"number",
")",
"for",
"(",
"header",
",",
"info",
")",
"in",
"self",
".",
"headers",
".",
"items",
"(",
")",
"for",
"pin",
"in",
"info",
... | 43.473684 | 0.00237 |
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding pac... | [
"def",
"get_submodules",
"(",
"app",
",",
"module",
")",
":",
"submodules",
"=",
"_get_submodules",
"(",
"app",
",",
"module",
")",
"return",
"[",
"name",
"for",
"name",
",",
"ispkg",
"in",
"submodules",
"if",
"not",
"ispkg",
"]"
] | 36 | 0.002083 |
def create(cls, service=None, endpoint=None, data=None, *args, **kwargs):
"""
Create an integration within the scope of an service.
Make sure that they should reasonably be able to query with an
service or endpoint that knows about an service.
"""
cls.validate(data)
... | [
"def",
"create",
"(",
"cls",
",",
"service",
"=",
"None",
",",
"endpoint",
"=",
"None",
",",
"data",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cls",
".",
"validate",
"(",
"data",
")",
"if",
"service",
"is",
"None",
"and",... | 43.777778 | 0.002484 |
def label_to_latex(text):
# pylint: disable=anomalous-backslash-in-string
r"""Convert text into a latex-passable representation.
This method just escapes the following reserved LaTeX characters:
% \ _ ~ &, whilst trying to avoid doubly-escaping already escaped
characters
Parameters
-------... | [
"def",
"label_to_latex",
"(",
"text",
")",
":",
"# pylint: disable=anomalous-backslash-in-string",
"if",
"text",
"is",
"None",
":",
"return",
"''",
"out",
"=",
"[",
"]",
"x",
"=",
"None",
"# loop over matches in reverse order and replace",
"for",
"m",
"in",
"re_late... | 26.255319 | 0.000781 |
def init_app(self, app):
"""Initialize the `app` for use with this
:class:`~flask_mysqldb.MySQL` class.
This is called automatically if `app` is passed to
:meth:`~MySQL.__init__`.
:param flask.Flask app: the application to configure for use with
this :class:`~flask_m... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"app",
".",
"config",
".",
"setdefault",
"(",
"'MYSQL_HOST'",
",",
"'localhost'",
")",
"app",
".",
"config",
".",
"setdefault",
"(",
"'MYSQL_USER'",
",",
"None",
")",
"app",
".",
"config",
".",
"set... | 43.6 | 0.001795 |
def handle_import(self, options):
"""
Gets the posts from either the provided URL or the path if it
is local.
"""
url = options.get("url")
if url is None:
raise CommandError("Usage is import_wordpress %s" % self.args)
try:
import feedparse... | [
"def",
"handle_import",
"(",
"self",
",",
"options",
")",
":",
"url",
"=",
"options",
".",
"get",
"(",
"\"url\"",
")",
"if",
"url",
"is",
"None",
":",
"raise",
"CommandError",
"(",
"\"Usage is import_wordpress %s\"",
"%",
"self",
".",
"args",
")",
"try",
... | 45.261538 | 0.000665 |
def fix_objective_as_constraint(model, fraction=1, bound=None,
name='fixed_objective_{}'):
"""Fix current objective as an additional constraint.
When adding constraints to a model, such as done in pFBA which
minimizes total flux, these constraints can become too powerful,
... | [
"def",
"fix_objective_as_constraint",
"(",
"model",
",",
"fraction",
"=",
"1",
",",
"bound",
"=",
"None",
",",
"name",
"=",
"'fixed_objective_{}'",
")",
":",
"fix_objective_name",
"=",
"name",
".",
"format",
"(",
"model",
".",
"objective",
".",
"name",
")",
... | 39.73913 | 0.000534 |
def exit_if_path_exists(self):
"""
Exit early if the path cannot be found.
"""
if os.path.exists(self.output_path):
ui.error(c.MESSAGES["path_exists"], self.output_path)
sys.exit(1) | [
"def",
"exit_if_path_exists",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"output_path",
")",
":",
"ui",
".",
"error",
"(",
"c",
".",
"MESSAGES",
"[",
"\"path_exists\"",
"]",
",",
"self",
".",
"output_path",
")",
... | 33 | 0.008439 |
def searchNs(self, doc, nameSpace):
"""Search a Ns registered under a given name space for a
document. recurse on the parents until it finds the defined
namespace or return None otherwise. @nameSpace can be None,
this is a search for the default namespace. We don't allow
... | [
"def",
"searchNs",
"(",
"self",
",",
"doc",
",",
"nameSpace",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlSearchNs",
"(",
"doc__o",
",",
"self",
"... | 52.071429 | 0.008086 |
def propose(self, current, r):
"""Generates a random sample from the discrete probability distribution and
returns its value, the log of the probability of sampling that value and the
log of the probability of sampling the current value (passed in).
"""
stay = (r.uniform(0, 1) < self.kernel)
if ... | [
"def",
"propose",
"(",
"self",
",",
"current",
",",
"r",
")",
":",
"stay",
"=",
"(",
"r",
".",
"uniform",
"(",
"0",
",",
"1",
")",
"<",
"self",
".",
"kernel",
")",
"if",
"stay",
":",
"logKernel",
"=",
"numpy",
".",
"log",
"(",
"self",
".",
"k... | 43.875 | 0.018131 |
def shrink(self, index, target, body=None, params=None):
"""
The shrink index API allows you to shrink an existing index into a new
index with fewer primary shards. The number of primary shards in the
target index must be a factor of the shards in the source index. For
example an... | [
"def",
"shrink",
"(",
"self",
",",
"index",
",",
"target",
",",
"body",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"for",
"param",
"in",
"(",
"index",
",",
"target",
")",
":",
"if",
"param",
"in",
"SKIP_IN_PATH",
":",
"raise",
"ValueError",
... | 56.678571 | 0.002478 |
def namedb_preorder_insert( cur, preorder_rec ):
"""
Add a name or namespace preorder record, if it doesn't exist already.
DO NOT CALL THIS DIRECTLY.
"""
preorder_row = copy.deepcopy( preorder_rec )
assert 'preorder_hash' in preorder_row, "BUG: missing preorder_hash"
try:
pre... | [
"def",
"namedb_preorder_insert",
"(",
"cur",
",",
"preorder_rec",
")",
":",
"preorder_row",
"=",
"copy",
".",
"deepcopy",
"(",
"preorder_rec",
")",
"assert",
"'preorder_hash'",
"in",
"preorder_row",
",",
"\"BUG: missing preorder_hash\"",
"try",
":",
"preorder_query",
... | 31.75 | 0.019878 |
def get_base_url(self, request):
""" Creates base url string.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:return: base string for url to Sentinel Hub's OGC service for this product.
... | [
"def",
"get_base_url",
"(",
"self",
",",
"request",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"request",
".",
"service_type",
".",
"value",
"# These 2 lines are temporal and will be removed after the use of uswest url wont be required anymore:",
"if",
"hasattr",
... | 61.470588 | 0.009425 |
def str_variants(store, institute_obj, case_obj, variants_query, page=1, per_page=50):
"""Pre-process list of STR variants."""
# Nothing unique to STRs on this level. Inheritance?
return variants(store, institute_obj, case_obj, variants_query, page, per_page) | [
"def",
"str_variants",
"(",
"store",
",",
"institute_obj",
",",
"case_obj",
",",
"variants_query",
",",
"page",
"=",
"1",
",",
"per_page",
"=",
"50",
")",
":",
"# Nothing unique to STRs on this level. Inheritance?",
"return",
"variants",
"(",
"store",
",",
"instit... | 67 | 0.01107 |
def get_recent_comments(number=5, template='zinnia/tags/comments_recent.html'):
"""
Return the most recent comments.
"""
# Using map(smart_text... fix bug related to issue #8554
entry_published_pks = map(smart_text,
Entry.published.values_list('id', flat=True))
cont... | [
"def",
"get_recent_comments",
"(",
"number",
"=",
"5",
",",
"template",
"=",
"'zinnia/tags/comments_recent.html'",
")",
":",
"# Using map(smart_text... fix bug related to issue #8554",
"entry_published_pks",
"=",
"map",
"(",
"smart_text",
",",
"Entry",
".",
"published",
"... | 40.277778 | 0.001348 |
def escape(s, quote=False):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences. If
the optional flag `quote` is `True`, the quotation mark character (") is
also translated.
There is a special handling for `None` which escapes to an empty string.
:param s: the string to escape.
... | [
"def",
"escape",
"(",
"s",
",",
"quote",
"=",
"False",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"''",
"elif",
"hasattr",
"(",
"s",
",",
"'__html__'",
")",
":",
"return",
"s",
".",
"__html__",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"... | 33.3 | 0.00146 |
def CacheStorage_deleteEntry(self, cacheId, request):
"""
Function path: CacheStorage.deleteEntry
Domain: CacheStorage
Method name: deleteEntry
Parameters:
Required arguments:
'cacheId' (type: CacheId) -> Id of cache where the entry will be deleted.
'request' (type: string) -> URL spec of ... | [
"def",
"CacheStorage_deleteEntry",
"(",
"self",
",",
"cacheId",
",",
"request",
")",
":",
"assert",
"isinstance",
"(",
"request",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'request' must be of type '['str']'. Received type: '%s'\"",
"%",
"type",
"(",
"request... | 32.45 | 0.043413 |
def inverse_transform(self, maps):
""" This function transforms from component masses and cartesian spins to
mass-weighted spin parameters perpendicular with the angular momentum.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
... | [
"def",
"inverse_transform",
"(",
"self",
",",
"maps",
")",
":",
"# convert",
"out",
"=",
"{",
"}",
"xi1",
"=",
"conversions",
".",
"primary_xi",
"(",
"maps",
"[",
"parameters",
".",
"mass1",
"]",
",",
"maps",
"[",
"parameters",
".",
"mass2",
"]",
",",
... | 44.754717 | 0.001238 |
def get_ft_names(mod, include_inner=False)->List[str]:
"Return all the functions of module `mod`."
# If the module has an attribute __all__, it picks those.
# Otherwise, it returns all the functions defined inside a module.
fn_names = []
for elt_name in get_exports(mod):
elt = getattr(mod,el... | [
"def",
"get_ft_names",
"(",
"mod",
",",
"include_inner",
"=",
"False",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# If the module has an attribute __all__, it picks those.",
"# Otherwise, it returns all the functions defined inside a module.",
"fn_names",
"=",
"[",
"]",
"for... | 45.2 | 0.015168 |
def upsert_acl(cursor, uuid_, permissions):
"""Given a ``uuid`` and a set of permissions given as a
tuple of ``uid`` and ``permission``, upsert them into the database.
"""
if not isinstance(permissions, (list, set, tuple,)):
raise TypeError("``permissions`` is an invalid type: {}"
... | [
"def",
"upsert_acl",
"(",
"cursor",
",",
"uuid_",
",",
"permissions",
")",
":",
"if",
"not",
"isinstance",
"(",
"permissions",
",",
"(",
"list",
",",
"set",
",",
"tuple",
",",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"``permissions`` is an invalid type: {... | 33.192308 | 0.001126 |
def times_to_ms(h=0, m=0, s=0, ms=0):
"""
Convert hours, minutes, seconds to milliseconds.
Arguments may be positive or negative, int or float,
need not be normalized (``s=120`` is okay).
Returns:
Number of milliseconds (rounded to int).
"""
ms += s * 1000
ms += m ... | [
"def",
"times_to_ms",
"(",
"h",
"=",
"0",
",",
"m",
"=",
"0",
",",
"s",
"=",
"0",
",",
"ms",
"=",
"0",
")",
":",
"ms",
"+=",
"s",
"*",
"1000",
"ms",
"+=",
"m",
"*",
"60000",
"ms",
"+=",
"h",
"*",
"3600000",
"return",
"int",
"(",
"round",
... | 24.066667 | 0.010667 |
def _antenna_uvw(uvw, antenna1, antenna2, chunks, nr_of_antenna):
""" numba implementation of antenna_uvw """
if antenna1.ndim != 1:
raise ValueError("antenna1 shape should be (row,)")
if antenna2.ndim != 1:
raise ValueError("antenna2 shape should be (row,)")
if uvw.ndim != 2 or uvw.s... | [
"def",
"_antenna_uvw",
"(",
"uvw",
",",
"antenna1",
",",
"antenna2",
",",
"chunks",
",",
"nr_of_antenna",
")",
":",
"if",
"antenna1",
".",
"ndim",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"antenna1 shape should be (row,)\"",
")",
"if",
"antenna2",
".",
... | 29.694444 | 0.000906 |
def opt_pagesize(self, pagesize):
""" Get or set the page size of the query output """
if pagesize != "auto":
pagesize = int(pagesize)
self.conf["pagesize"] = pagesize | [
"def",
"opt_pagesize",
"(",
"self",
",",
"pagesize",
")",
":",
"if",
"pagesize",
"!=",
"\"auto\"",
":",
"pagesize",
"=",
"int",
"(",
"pagesize",
")",
"self",
".",
"conf",
"[",
"\"pagesize\"",
"]",
"=",
"pagesize"
] | 39.8 | 0.009852 |
def request_id(self, request_id):
"""
Sets the request_id of this ErrorResponse.
Request ID.
:param request_id: The request_id of this ErrorResponse.
:type: str
"""
if request_id is not None and not re.search('^[A-Za-z0-9]{32}', request_id):
raise Val... | [
"def",
"request_id",
"(",
"self",
",",
"request_id",
")",
":",
"if",
"request_id",
"is",
"not",
"None",
"and",
"not",
"re",
".",
"search",
"(",
"'^[A-Za-z0-9]{32}'",
",",
"request_id",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `request_id`, must... | 37.333333 | 0.008715 |
def find_mutant_amino_acid_interval(
cdna_sequence,
cdna_first_codon_offset,
cdna_variant_start_offset,
cdna_variant_end_offset,
n_ref,
n_amino_acids):
"""
Parameters
----------
cdna_sequence : skbio.DNA or str
cDNA sequence found in RNAseq data
... | [
"def",
"find_mutant_amino_acid_interval",
"(",
"cdna_sequence",
",",
"cdna_first_codon_offset",
",",
"cdna_variant_start_offset",
",",
"cdna_variant_end_offset",
",",
"n_ref",
",",
"n_amino_acids",
")",
":",
"cdna_alt_nucleotides",
"=",
"cdna_sequence",
"[",
"cdna_variant_sta... | 38.586957 | 0.001099 |
def accession(auth, label, project=None):
'''
Get the Accession ID for any Experiment label.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.accession(auth, 'AB1234C')
u'XNAT_E00001'
:param auth: XNAT authenticati... | [
"def",
"accession",
"(",
"auth",
",",
"label",
",",
"project",
"=",
"None",
")",
":",
"return",
"list",
"(",
"experiments",
"(",
"auth",
",",
"label",
",",
"project",
")",
")",
"[",
"0",
"]",
".",
"id"
] | 28.85 | 0.001678 |
def _evaluate(self,x,y):
'''
Returns the level of the interpolated function at each value in x,y.
Only called internally by HARKinterpolator2D.__call__ (etc).
'''
x_pos, y_pos = self.findSector(x,y)
alpha, beta = self.findCoords(x,y,x_pos,y_pos)
# Calculate the f... | [
"def",
"_evaluate",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"x_pos",
",",
"y_pos",
"=",
"self",
".",
"findSector",
"(",
"x",
",",
"y",
")",
"alpha",
",",
"beta",
"=",
"self",
".",
"findCoords",
"(",
"x",
",",
"y",
",",
"x_pos",
",",
"y_pos",... | 41.066667 | 0.028571 |
def delete_object(self, id):
"""Deletes the object with the given ID from the graph."""
return self.request(
"{0}/{1}".format(self.version, id), method="DELETE"
) | [
"def",
"delete_object",
"(",
"self",
",",
"id",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"{0}/{1}\"",
".",
"format",
"(",
"self",
".",
"version",
",",
"id",
")",
",",
"method",
"=",
"\"DELETE\"",
")"
] | 38.8 | 0.010101 |
def gpg_download_key( key_id, key_server, config_dir=None ):
"""
Download a GPG key from a key server.
Do not import it into any keyrings.
Return the ASCII-armored key
"""
config_dir = get_config_dir( config_dir )
tmpdir = make_gpg_tmphome( prefix="download", config_dir=config_dir )
gpg... | [
"def",
"gpg_download_key",
"(",
"key_id",
",",
"key_server",
",",
"config_dir",
"=",
"None",
")",
":",
"config_dir",
"=",
"get_config_dir",
"(",
"config_dir",
")",
"tmpdir",
"=",
"make_gpg_tmphome",
"(",
"prefix",
"=",
"\"download\"",
",",
"config_dir",
"=",
"... | 30.333333 | 0.021302 |
def list_tar (archive, compression, cmd, verbosity, interactive):
"""List a TAR archive."""
cmdlist = [cmd, '-n']
add_star_opts(cmdlist, compression, verbosity)
cmdlist.append("file=%s" % archive)
return cmdlist | [
"def",
"list_tar",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"cmdlist",
"=",
"[",
"cmd",
",",
"'-n'",
"]",
"add_star_opts",
"(",
"cmdlist",
",",
"compression",
",",
"verbosity",
")",
"cmdlist",
".",
"... | 37.666667 | 0.008658 |
def modify_number_pattern(number_pattern, **kwargs):
"""Modifies a number pattern by specified keyword arguments."""
params = ['pattern', 'prefix', 'suffix', 'grouping',
'int_prec', 'frac_prec', 'exp_prec', 'exp_plus']
for param in params:
if param in kwargs:
continue
... | [
"def",
"modify_number_pattern",
"(",
"number_pattern",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"[",
"'pattern'",
",",
"'prefix'",
",",
"'suffix'",
",",
"'grouping'",
",",
"'int_prec'",
",",
"'frac_prec'",
",",
"'exp_prec'",
",",
"'exp_plus'",
"]",
... | 44 | 0.002475 |
def saveDirectory(alias):
"""save a directory to a certain alias/nickname"""
if not settings.platformCompatible():
return False
dataFile = open(settings.getDataFile(), "wb")
currentDirectory = os.path.abspath(".")
directory = {alias : currentDirectory}
pickle.dump(directory, dataFile)
speech.success(alias + " ... | [
"def",
"saveDirectory",
"(",
"alias",
")",
":",
"if",
"not",
"settings",
".",
"platformCompatible",
"(",
")",
":",
"return",
"False",
"dataFile",
"=",
"open",
"(",
"settings",
".",
"getDataFile",
"(",
")",
",",
"\"wb\"",
")",
"currentDirectory",
"=",
"os",... | 44.1 | 0.026667 |
def calculate_fuzzy_chi(alpha, square_map, right_eigenvectors):
"""Calculate the membership matrix (chi) from parameters alpha.
Parameters
----------
alpha : ndarray
Parameters of objective function (e.g. flattened A)
square_map : ndarray
Mapping from square indices (i,j) to flat in... | [
"def",
"calculate_fuzzy_chi",
"(",
"alpha",
",",
"square_map",
",",
"right_eigenvectors",
")",
":",
"# Convert parameter vector into matrix A",
"A",
"=",
"to_square",
"(",
"alpha",
",",
"square_map",
")",
"# Make A feasible.",
"A",
"=",
"fill_A",
"(",
"A",
",",
"r... | 31.1 | 0.00104 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.