text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def search(self):
"""Returns the list of brains that match with the request criteria
"""
brains = []
# TODO Legacy
for name, adapter in getAdapters((self.context, self.request),
IReferenceWidgetVocabulary):
brains.extend(adapte... | [
"def",
"search",
"(",
"self",
")",
":",
"brains",
"=",
"[",
"]",
"# TODO Legacy",
"for",
"name",
",",
"adapter",
"in",
"getAdapters",
"(",
"(",
"self",
".",
"context",
",",
"self",
".",
"request",
")",
",",
"IReferenceWidgetVocabulary",
")",
":",
"brains... | 37.555556 | 16.111111 |
def delete(self, comment_id, issue_id=None, repo_slug=None):
""" Delete an issue from one of your repositories.
"""
issue_id = issue_id or self.issue_id
repo_slug = repo_slug or self.bitbucket.repo_slug or ''
url = self.bitbucket.url('DELETE_COMMENT',
... | [
"def",
"delete",
"(",
"self",
",",
"comment_id",
",",
"issue_id",
"=",
"None",
",",
"repo_slug",
"=",
"None",
")",
":",
"issue_id",
"=",
"issue_id",
"or",
"self",
".",
"issue_id",
"repo_slug",
"=",
"repo_slug",
"or",
"self",
".",
"bitbucket",
".",
"repo_... | 53.636364 | 14.636364 |
def missing_intervals(startdate, enddate, start, end,
dateconverter=None,
parseinterval=None,
intervals=None):
'''Given a ``startdate`` and an ``enddate`` dates, evaluate the
date intervals from which data is not available. It return a list of
... | [
"def",
"missing_intervals",
"(",
"startdate",
",",
"enddate",
",",
"start",
",",
"end",
",",
"dateconverter",
"=",
"None",
",",
"parseinterval",
"=",
"None",
",",
"intervals",
"=",
"None",
")",
":",
"parseinterval",
"=",
"parseinterval",
"or",
"default_parse_i... | 38.619048 | 16.428571 |
def split_trailing_whitespace(word):
"""
This function takes a word, such as 'test\n\n' and returns ('test','\n\n')
"""
stripped_length = len(word.rstrip())
return word[0:stripped_length], word[stripped_length:] | [
"def",
"split_trailing_whitespace",
"(",
"word",
")",
":",
"stripped_length",
"=",
"len",
"(",
"word",
".",
"rstrip",
"(",
")",
")",
"return",
"word",
"[",
"0",
":",
"stripped_length",
"]",
",",
"word",
"[",
"stripped_length",
":",
"]"
] | 37.666667 | 10 |
def proximal_arg_scaling(prox_factory, scaling):
r"""Calculate the proximal of function F(x * scaling).
Parameters
----------
prox_factory : callable
A factory function that, when called with a step size, returns the
proximal operator of ``F``
scaling : float or sequence of floats o... | [
"def",
"proximal_arg_scaling",
"(",
"prox_factory",
",",
"scaling",
")",
":",
"# To begin, we could check for two things:",
"# * Currently, we do not support complex scaling. We could therefore catch",
"# nonempty imaginary parts.",
"# * If some components of scaling are zero, then the follo... | 36.297619 | 22.630952 |
def rename(self):
"""
rename_expr ::= rename param_start rename_parameters param_stop
expression
rename_parameters ::= relation_name |
paren_left attribute_list paren_right |
relation_name paren_left attribute_list paren_right
"""
params = sel... | [
"def",
"rename",
"(",
"self",
")",
":",
"params",
"=",
"self",
".",
"relation_name",
"^",
"(",
"Optional",
"(",
"self",
".",
"relation_name",
")",
"+",
"self",
".",
"parenthesize",
"(",
"self",
".",
"attribute_list",
")",
")",
"return",
"self",
".",
"p... | 41.666667 | 20 |
def spectra(self, alpha=None, nmax=None, convention='power', unit='per_l',
base=10.):
"""
Return the spectra of one or more Slepian functions.
Usage
-----
spectra = x.spectra([alpha, nmax, convention, unit, base])
Returns
-------
spectra ... | [
"def",
"spectra",
"(",
"self",
",",
"alpha",
"=",
"None",
",",
"nmax",
"=",
"None",
",",
"convention",
"=",
"'power'",
",",
"unit",
"=",
"'per_l'",
",",
"base",
"=",
"10.",
")",
":",
"if",
"alpha",
"is",
"None",
":",
"if",
"nmax",
"is",
"None",
"... | 47.192308 | 25.384615 |
def positions(self, reverse=False):
"""returns a generator that walks the positions of this tree in DFO"""
def Posgen(reverse):
if reverse:
lastrootsib = self.last_sibling_position(self.root)
current = self.last_decendant(lastrootsib)
while cur... | [
"def",
"positions",
"(",
"self",
",",
"reverse",
"=",
"False",
")",
":",
"def",
"Posgen",
"(",
"reverse",
")",
":",
"if",
"reverse",
":",
"lastrootsib",
"=",
"self",
".",
"last_sibling_position",
"(",
"self",
".",
"root",
")",
"current",
"=",
"self",
"... | 42.333333 | 11.266667 |
def add_url_rule(self, rule, endpoint=None, view_func=None,
provide_automatic_options=None, register_with_babel=False,
**options):
"""
Like :meth:`~flask.Flask.add_url_rule`, but if ``register_with_babel`` is True,
then we also allow the Babel Bundle an ... | [
"def",
"add_url_rule",
"(",
"self",
",",
"rule",
",",
"endpoint",
"=",
"None",
",",
"view_func",
"=",
"None",
",",
"provide_automatic_options",
"=",
"None",
",",
"register_with_babel",
"=",
"False",
",",
"*",
"*",
"options",
")",
":",
"if",
"self",
".",
... | 55.928571 | 23.928571 |
def activate(locale):
"""
Override django's utils.translation.activate(). Django forces files
to be named django.mo (http://code.djangoproject.com/ticket/6376). Since
that's dumb and we want to be able to load different files depending on
what part of the site the user is in, we'll make our own fu... | [
"def",
"activate",
"(",
"locale",
")",
":",
"if",
"INSTALL_JINJA_TRANSLATIONS",
":",
"install_jinja_translations",
"(",
")",
"if",
"django",
".",
"VERSION",
">=",
"(",
"1",
",",
"3",
")",
":",
"django_trans",
".",
"_active",
".",
"value",
"=",
"_activate",
... | 41.666667 | 20.466667 |
def set_key_color(self, color: Tuple[int, int, int]) -> None:
"""Set a color to be transparent during blitting functions.
Args:
color (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
"""
lib.TCOD_image_set_key_color(self.... | [
"def",
"set_key_color",
"(",
"self",
",",
"color",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_image_set_key_color",
"(",
"self",
".",
"image_c",
",",
"color",
")"
] | 41 | 18 |
def get_hypervisor():
'''
Returns the name of the hypervisor running on this node or ``None``.
Detected hypervisors:
- kvm
- xen
- bhyve
CLI Example:
.. code-block:: bash
salt '*' virt.get_hypervisor
.. versionadded:: 2019.2.0
the function and the ``kvm``, ``xen... | [
"def",
"get_hypervisor",
"(",
")",
":",
"# To add a new 'foo' hypervisor, add the _is_foo_hyper function,",
"# add 'foo' to the list below and add it to the docstring with a .. versionadded::",
"hypervisors",
"=",
"[",
"'kvm'",
",",
"'xen'",
",",
"'bhyve'",
"]",
"result",
"=",
"[... | 28.833333 | 29.25 |
def requires_authentication(fn):
"""
Requires that the calling Subject be authenticated before allowing access.
:raises UnauthenticatedException: indicating that the decorated method is
not allowed to be executed because the
... | [
"def",
"requires_authentication",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"subject",
"=",
"Yosai",
".",
"get_current_subject",
"(",
")",
"if",
"not",
"su... | 37.368421 | 22.421053 |
def fetchEC2InstanceDict(regionNickname=None):
"""
Fetches EC2 instances types by region programmatically using the AWS pricing API.
See: https://aws.amazon.com/blogs/aws/new-aws-price-list-api/
:return: A dict of InstanceType objects, where the key is the string:
aws instance name (examp... | [
"def",
"fetchEC2InstanceDict",
"(",
"regionNickname",
"=",
"None",
")",
":",
"ec2Source",
"=",
"'https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/index.json'",
"if",
"regionNickname",
"is",
"None",
":",
"regionNickname",
"=",
"'us-west-2'",
"region",
... | 42.296296 | 27.037037 |
def get_csv_from_metadata(dsn, d):
"""
Two goals. Get all csv from metadata, and return new metadata with generated filenames to match files.
:param str dsn: Dataset name
:param dict d: Metadata
:return dict _csvs: Csv
"""
logger_csvs.info("enter get_csv_from_metadata")
_csvs = OrderedD... | [
"def",
"get_csv_from_metadata",
"(",
"dsn",
",",
"d",
")",
":",
"logger_csvs",
".",
"info",
"(",
"\"enter get_csv_from_metadata\"",
")",
"_csvs",
"=",
"OrderedDict",
"(",
")",
"_d",
"=",
"copy",
".",
"deepcopy",
"(",
"d",
")",
"try",
":",
"if",
"\"paleoDat... | 34.423077 | 24.576923 |
def execute(self, arg_str='', **kwargs):
"""runs the passed in arguments and returns an iterator on the output of
running command"""
cmd = "{} {} {}".format(self.cmd_prefix, self.script, arg_str)
expected_ret_code = kwargs.pop('code', 0)
# any kwargs with all capital letters sho... | [
"def",
"execute",
"(",
"self",
",",
"arg_str",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"\"{} {} {}\"",
".",
"format",
"(",
"self",
".",
"cmd_prefix",
",",
"self",
".",
"script",
",",
"arg_str",
")",
"expected_ret_code",
"=",
"kwargs",... | 33.915254 | 17.474576 |
def filter(self, source_file, encoding): # noqa A001
"""Parse XML file."""
sources = []
for content, filename, enc in self.get_content(source_file):
self.additional_context = self.get_context(filename)
sources.extend(self._filter(content, source_file, enc))
retu... | [
"def",
"filter",
"(",
"self",
",",
"source_file",
",",
"encoding",
")",
":",
"# noqa A001",
"sources",
"=",
"[",
"]",
"for",
"content",
",",
"filename",
",",
"enc",
"in",
"self",
".",
"get_content",
"(",
"source_file",
")",
":",
"self",
".",
"additional_... | 40.375 | 21.25 |
def process_user_input(self):
"""
This overrides the method in ConsoleMenu to allow for comma-delimited and range inputs.
Examples:
All of the following inputs would have the same result:
* 1,2,3,4
* 1-4
* 1-2,3-4
* 1 -... | [
"def",
"process_user_input",
"(",
"self",
")",
":",
"user_input",
"=",
"self",
".",
"screen",
".",
"input",
"(",
")",
"try",
":",
"indexes",
"=",
"self",
".",
"__parse_range_list",
"(",
"user_input",
")",
"# Subtract 1 from each number for its actual index number",
... | 33.68 | 19.6 |
def stop(state, host, ctid):
'''
Stop OpenVZ containers.
+ ctid: CTID of the container to stop
'''
args = ['{0}'.format(ctid)]
yield 'vzctl stop {0}'.format(' '.join(args)) | [
"def",
"stop",
"(",
"state",
",",
"host",
",",
"ctid",
")",
":",
"args",
"=",
"[",
"'{0}'",
".",
"format",
"(",
"ctid",
")",
"]",
"yield",
"'vzctl stop {0}'",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"args",
")",
")"
] | 19 | 23 |
def parse_cfg(self):
""" parses the given config file for experiments. """
self.cfgparser = ConfigParser()
if not self.cfgparser.read(self.options.config):
raise SystemExit('config file %s not found.'%self.options.config)
# Change the current working directory to be relativ... | [
"def",
"parse_cfg",
"(",
"self",
")",
":",
"self",
".",
"cfgparser",
"=",
"ConfigParser",
"(",
")",
"if",
"not",
"self",
".",
"cfgparser",
".",
"read",
"(",
"self",
".",
"options",
".",
"config",
")",
":",
"raise",
"SystemExit",
"(",
"'config file %s not... | 46.9 | 19.4 |
def load_pickle(file_path):
"""
Unpickle some data from a given path.
Input: - file_path: Target file path.
Output: - data: The python object that was serialized and stored in disk.
"""
pkl_file = open(file_path, 'rb')
data = pickle.load(pkl_file)
pkl_file.close()
return data | [
"def",
"load_pickle",
"(",
"file_path",
")",
":",
"pkl_file",
"=",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"data",
"=",
"pickle",
".",
"load",
"(",
"pkl_file",
")",
"pkl_file",
".",
"close",
"(",
")",
"return",
"data"
] | 25.333333 | 15.833333 |
def advance_to_checkpoint(self, checkpoint):
"""
Advance to the specified checkpoint, passing all preceding checkpoints including the specified checkpoint.
"""
if checkpoint in self._checkpoints:
for cp in self._checkpoints:
self.insert(cp)
if ... | [
"def",
"advance_to_checkpoint",
"(",
"self",
",",
"checkpoint",
")",
":",
"if",
"checkpoint",
"in",
"self",
".",
"_checkpoints",
":",
"for",
"cp",
"in",
"self",
".",
"_checkpoints",
":",
"self",
".",
"insert",
"(",
"cp",
")",
"if",
"cp",
"==",
"checkpoin... | 38.545455 | 13.090909 |
def want_release(self):
"""Does the user normally want to release this package.
Some colleagues find it irritating to have to remember to
answer the question "Check out the tag (for tweaks or
pypi/distutils server upload)" with the non-default 'no' when
in 99 percent of the case... | [
"def",
"want_release",
"(",
"self",
")",
":",
"default",
"=",
"True",
"if",
"self",
".",
"config",
"is",
"None",
":",
"return",
"default",
"try",
":",
"result",
"=",
"self",
".",
"config",
".",
"getboolean",
"(",
"'zest.releaser'",
",",
"'release'",
")",... | 39.727273 | 22.818182 |
def gaussian1d_moments(data, mask=None):
"""
Estimate 1D Gaussian parameters from the moments of 1D data.
This function can be useful for providing initial parameter values
when fitting a 1D Gaussian to the ``data``.
Parameters
----------
data : array_like (1D)
The 1D array.
m... | [
"def",
"gaussian1d_moments",
"(",
"data",
",",
"mask",
"=",
"None",
")",
":",
"if",
"np",
".",
"any",
"(",
"~",
"np",
".",
"isfinite",
"(",
"data",
")",
")",
":",
"data",
"=",
"np",
".",
"ma",
".",
"masked_invalid",
"(",
"data",
")",
"warnings",
... | 30.704545 | 21.113636 |
def find(self, s):
"""Locates the leader of the set to which the element ``s`` belongs.
Parameters
----------
s : object
An object that the ``UnionFind`` contains.
Returns
-------
object
The leader of the set that contains ``s``.
... | [
"def",
"find",
"(",
"self",
",",
"s",
")",
":",
"pSet",
"=",
"[",
"s",
"]",
"parent",
"=",
"self",
".",
"_leader",
"[",
"s",
"]",
"while",
"parent",
"!=",
"self",
".",
"_leader",
"[",
"parent",
"]",
":",
"pSet",
".",
"append",
"(",
"parent",
")... | 23.68 | 19.32 |
def instruction_to_svg_dict(self, instruction_or_id, copy_result=True):
"""Return the SVG dict for the SVGBuilder.
:param instruction_or_id: the instruction or id, see
:meth:`get_instruction_id`
:param bool copy_result: whether to copy the result
:rtype: dict
The resu... | [
"def",
"instruction_to_svg_dict",
"(",
"self",
",",
"instruction_or_id",
",",
"copy_result",
"=",
"True",
")",
":",
"instruction_id",
"=",
"self",
".",
"get_instruction_id",
"(",
"instruction_or_id",
")",
"if",
"instruction_id",
"in",
"self",
".",
"_cache",
":",
... | 36.842105 | 16.894737 |
def visit(cls, value, value_type=None, **kwargs):
"""A value visitor, which visits instances (typically), applies
:py:meth:`normalize.visitor.VisitorPattern.apply` to every attribute
slot, and returns the reduced result.
Like :py:func:`normalize.diff.diff`, this function accepts a serie... | [
"def",
"visit",
"(",
"cls",
",",
"value",
",",
"value_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"visitor",
"=",
"cls",
".",
"Visitor",
"(",
"cls",
".",
"unpack",
",",
"cls",
".",
"apply",
",",
"cls",
".",
"aggregate",
",",
"cls",
"."... | 40.973684 | 21.026316 |
def _is_target_region(self, stat, game_region):
"""Returns if the stat matches target game region.
:param stat: Json of gameplay stat.
:type stat: dict
:param game_region: Target game region.
:type game_region: str
:return: return does the stat... | [
"def",
"_is_target_region",
"(",
"self",
",",
"stat",
",",
"game_region",
")",
":",
"if",
"game_region",
"==",
"constants",
".",
"GAME_REGION_WILDCARD",
":",
"return",
"True",
"return",
"stat",
"[",
"'Region'",
"]",
"==",
"game_region"
] | 38.846154 | 12.769231 |
def string_to_34_array(sou=None, pin=None, man=None, honors=None):
"""
Method to convert one line string tiles format to the 34 array
We need it to increase readability of our tests
"""
results = TilesConverter.string_to_136_array(sou, pin, man, honors)
results = TilesCon... | [
"def",
"string_to_34_array",
"(",
"sou",
"=",
"None",
",",
"pin",
"=",
"None",
",",
"man",
"=",
"None",
",",
"honors",
"=",
"None",
")",
":",
"results",
"=",
"TilesConverter",
".",
"string_to_136_array",
"(",
"sou",
",",
"pin",
",",
"man",
",",
"honors... | 45.375 | 17.125 |
def getSamplingStrategy(self, serviceName):
"""
Parameters:
- serviceName
"""
self._seqid += 1
future = self._reqs[self._seqid] = concurrent.Future()
self.send_getSamplingStrategy(serviceName)
return future | [
"def",
"getSamplingStrategy",
"(",
"self",
",",
"serviceName",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"future",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"concurrent",
".",
"Future",
"(",
")",
"self",
".",
"send_getSamplingStr... | 25.666667 | 13 |
def iterfiles(service, name=None, mimeType=SHEET, order=FILEORDER):
"""Fetch and yield ``(id, name)`` pairs for Google drive files."""
params = {'orderBy': order, 'pageToken': None}
q = []
if name is not None:
q.append("name='%s'" % name)
if mimeType is not None:
q.append("mimeType='... | [
"def",
"iterfiles",
"(",
"service",
",",
"name",
"=",
"None",
",",
"mimeType",
"=",
"SHEET",
",",
"order",
"=",
"FILEORDER",
")",
":",
"params",
"=",
"{",
"'orderBy'",
":",
"order",
",",
"'pageToken'",
":",
"None",
"}",
"q",
"=",
"[",
"]",
"if",
"n... | 33.315789 | 16.578947 |
def format_ubuntu_dialog(df):
""" Print statements paired with replies, formatted for easy review """
s = ''
for i, record in df.iterrows():
statement = list(split_turns(record.Context))[-1] # <1>
reply = list(split_turns(record.Utterance))[-1] # <2>
s += 'Statement: {}\n'.format(s... | [
"def",
"format_ubuntu_dialog",
"(",
"df",
")",
":",
"s",
"=",
"''",
"for",
"i",
",",
"record",
"in",
"df",
".",
"iterrows",
"(",
")",
":",
"statement",
"=",
"list",
"(",
"split_turns",
"(",
"record",
".",
"Context",
")",
")",
"[",
"-",
"1",
"]",
... | 41.888889 | 14.444444 |
def is_time_valid(self, timestamp):
"""Check if time is valid for this Timerange
If sec_from_morning is not provided, get the value.
:param timestamp: time to check
:type timestamp: int
:return: True if time is valid (in interval), False otherwise
:rtype: bool
"... | [
"def",
"is_time_valid",
"(",
"self",
",",
"timestamp",
")",
":",
"sec_from_morning",
"=",
"get_sec_from_morning",
"(",
"timestamp",
")",
"return",
"(",
"self",
".",
"is_valid",
"and",
"self",
".",
"hstart",
"*",
"3600",
"+",
"self",
".",
"mstart",
"*",
"60... | 36.333333 | 14.8 |
def set_baseline(self, version):
"""Set the baseline into the creation information table
version: str
The version of the current database to set in the information
table. The baseline must be in the format x.x.x where x are numbers.
"""
pattern = re.compile(r"^\d... | [
"def",
"set_baseline",
"(",
"self",
",",
"version",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"^\\d+\\.\\d+\\.\\d+$\"",
")",
"if",
"not",
"re",
".",
"match",
"(",
"pattern",
",",
"version",
")",
":",
"raise",
"ValueError",
"(",
"'Wrong versio... | 33.029412 | 13.735294 |
def _synthesize(self):
"""
Assigns all placeholder labels to actual values and implicitly declares the ``ro``
register for backwards compatibility.
Changed in 1.9: Either all qubits must be defined or all undefined. If qubits are
undefined, this method will not help you. You mus... | [
"def",
"_synthesize",
"(",
"self",
")",
":",
"self",
".",
"_synthesized_instructions",
"=",
"instantiate_labels",
"(",
"self",
".",
"_instructions",
")",
"self",
".",
"_synthesized_instructions",
"=",
"implicitly_declare_ro",
"(",
"self",
".",
"_synthesized_instructio... | 47.190476 | 29.285714 |
def bootstrap_isc(iscs, pairwise=False, summary_statistic='median',
n_bootstraps=1000, ci_percentile=95, random_state=None):
"""One-sample group-level bootstrap hypothesis test for ISCs
For ISCs from one more voxels or ROIs, resample subjects with replacement
to construct a bootstrap dis... | [
"def",
"bootstrap_isc",
"(",
"iscs",
",",
"pairwise",
"=",
"False",
",",
"summary_statistic",
"=",
"'median'",
",",
"n_bootstraps",
"=",
"1000",
",",
"ci_percentile",
"=",
"95",
",",
"random_state",
"=",
"None",
")",
":",
"# Standardize structure of input data",
... | 39.763158 | 24.322368 |
def parse_yes_no_str(bool_str):
"""Parse a string serialization of boolean data as yes (Y) or no (N).
Prase a string serialization of boolean data where True is "Y" and False is
"N" case-insensitive.
@param bool_str: The string to parse.
@type bool_str: str
@return: The interpreted string.
... | [
"def",
"parse_yes_no_str",
"(",
"bool_str",
")",
":",
"lower_bool_str",
"=",
"bool_str",
".",
"lower",
"(",
")",
"if",
"lower_bool_str",
"==",
"'n'",
":",
"return",
"False",
"elif",
"lower_bool_str",
"==",
"'y'",
":",
"return",
"True",
"else",
":",
"raise",
... | 32.35 | 18.25 |
def write_groovy_script_and_configs(
filename, content, job_configs, view_configs=None):
"""Write out the groovy script and configs to file.
This writes the reconfigure script to the file location
and places the expanded configs in subdirectories 'view_configs' /
'job_configs' that the script c... | [
"def",
"write_groovy_script_and_configs",
"(",
"filename",
",",
"content",
",",
"job_configs",
",",
"view_configs",
"=",
"None",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"h",
":",
"h",
".",
"write",
"(",
"content",
")",
"if",
"vi... | 42.090909 | 17.30303 |
def graph(
model, format='raw', prog='dot', path=None, name=None, consts=False, legend=False,
collapse_deterministics=False, collapse_potentials=False, label_edges=True):
"""
graph( model,
format='raw',
prog='dot',
path=None,
name=None,
co... | [
"def",
"graph",
"(",
"model",
",",
"format",
"=",
"'raw'",
",",
"prog",
"=",
"'dot'",
",",
"path",
"=",
"None",
",",
"name",
"=",
"None",
",",
"consts",
"=",
"False",
",",
"legend",
"=",
"False",
",",
"collapse_deterministics",
"=",
"False",
",",
"co... | 36.229787 | 17.293617 |
def iteritems(self, multi=False):
"""Like :meth:`items` but returns an iterator."""
for key, values in dict.iteritems(self):
if multi:
for value in values:
yield key, value
else:
yield key, values[0] | [
"def",
"iteritems",
"(",
"self",
",",
"multi",
"=",
"False",
")",
":",
"for",
"key",
",",
"values",
"in",
"dict",
".",
"iteritems",
"(",
"self",
")",
":",
"if",
"multi",
":",
"for",
"value",
"in",
"values",
":",
"yield",
"key",
",",
"value",
"else"... | 35.5 | 8.625 |
def _post_connect(self):
"""Initialize authentication when the connection is established
and we are the initiator."""
if not self.initiator:
if "plain" in self.auth_methods or "digest" in self.auth_methods:
self.set_iq_get_handler("query","jabber:iq:auth",
... | [
"def",
"_post_connect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"initiator",
":",
"if",
"\"plain\"",
"in",
"self",
".",
"auth_methods",
"or",
"\"digest\"",
"in",
"self",
".",
"auth_methods",
":",
"self",
".",
"set_iq_get_handler",
"(",
"\"query\"",
... | 47.8125 | 14.25 |
def init_logs():
"""Initiate log file."""
start_time = dt.fromtimestamp(time.time()).strftime('%Y%m%d_%H%M')
logname = os.path.join(os.path.expanduser("~") + "/nanoGUI_" + start_time + ".log")
handlers = [logging.FileHandler(logname)]
logging.basicConfig(
format='%(asctime)s %(message)s',
... | [
"def",
"init_logs",
"(",
")",
":",
"start_time",
"=",
"dt",
".",
"fromtimestamp",
"(",
"time",
".",
"time",
"(",
")",
")",
".",
"strftime",
"(",
"'%Y%m%d_%H%M'",
")",
"logname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"exp... | 46.583333 | 22.416667 |
def session(self):
""" Creates a context with an open SQLAlchemy session.
"""
engine = self.engine
connection = engine.connect()
db_session = scoped_session(
sessionmaker(autocommit=False, autoflush=True, bind=engine))
yield db_session
db_session.close... | [
"def",
"session",
"(",
"self",
")",
":",
"engine",
"=",
"self",
".",
"engine",
"connection",
"=",
"engine",
".",
"connect",
"(",
")",
"db_session",
"=",
"scoped_session",
"(",
"sessionmaker",
"(",
"autocommit",
"=",
"False",
",",
"autoflush",
"=",
"True",
... | 34 | 11.7 |
def domain_create(self, domain, master=True, **kwargs):
"""
Registers a new Domain on the acting user's account. Make sure to point
your registrar to Linode's nameservers so that Linode's DNS manager will
correctly serve your domain.
:param domain: The domain to register to Lin... | [
"def",
"domain_create",
"(",
"self",
",",
"domain",
",",
"master",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'domain'",
":",
"domain",
",",
"'type'",
":",
"'master'",
"if",
"master",
"else",
"'slave'",
",",
"}",
"params",
"... | 33.37037 | 22.185185 |
def GetParent(self):
"""Constructs a path info corresponding to the parent of current path.
The root path (represented by an empty list of components, corresponds to
`/` on Unix-like systems) does not have a parent.
Returns:
Instance of `rdf_objects.PathInfo` or `None` if parent does not exist.
... | [
"def",
"GetParent",
"(",
"self",
")",
":",
"if",
"self",
".",
"root",
":",
"return",
"None",
"return",
"PathInfo",
"(",
"components",
"=",
"self",
".",
"components",
"[",
":",
"-",
"1",
"]",
",",
"path_type",
"=",
"self",
".",
"path_type",
",",
"dire... | 29.3125 | 21.5 |
def create(dataset, target,
features=None, max_iterations=10,
validation_set='auto',
class_weights = None,
max_depth=6, step_size=0.3,
min_loss_reduction=0.0, min_child_weight=0.1,
row_subsample=1.0, column_subsample=1.0,
verbose=True,
... | [
"def",
"create",
"(",
"dataset",
",",
"target",
",",
"features",
"=",
"None",
",",
"max_iterations",
"=",
"10",
",",
"validation_set",
"=",
"'auto'",
",",
"class_weights",
"=",
"None",
",",
"max_depth",
"=",
"6",
",",
"step_size",
"=",
"0.3",
",",
"min_l... | 46.322751 | 25.634921 |
def to_json(content, indent=None):
"""
Serializes a python object as JSON
This method uses the DJangoJSONEncoder to to ensure that python objects
such as Decimal objects are properly serialized. It can also serialize
Django QuerySet objects.
"""
if isinstance(content, QuerySet):
jso... | [
"def",
"to_json",
"(",
"content",
",",
"indent",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"content",
",",
"QuerySet",
")",
":",
"json_serializer",
"=",
"serializers",
".",
"get_serializer",
"(",
"'json'",
")",
"(",
")",
"serialized_content",
"=",
"j... | 42.277778 | 23.277778 |
def health_check(self):
""" Pull health and alarm information from the device.
Purpose: Grab the cpu/mem usage, system/chassis alarms, top 5
| processes, and states if the primary/backup partitions are on
| different versions.
@returns: The output that should be s... | [
"def",
"health_check",
"(",
"self",
")",
":",
"output",
"=",
"'Chassis Alarms:\\n\\t'",
"# Grab chassis alarms, system alarms, show chassis routing-engine,",
"# 'show system processes extensive', and also xpath to the",
"# relevant nodes on each.",
"chassis_alarms",
"=",
"self",
".",
... | 50.382979 | 20.446809 |
def fun_as_arg(self, x, *args):
"""``fun_as_arg(x, fun, *more_args)`` calls ``fun(x, *more_args)``.
Use case::
fmin(cma.fun_as_arg, args=(fun,), gradf=grad_numerical)
calls fun_as_args(x, args) and grad_numerical(x, fun, args=args)
"""
fun = args[0]
more_a... | [
"def",
"fun_as_arg",
"(",
"self",
",",
"x",
",",
"*",
"args",
")",
":",
"fun",
"=",
"args",
"[",
"0",
"]",
"more_args",
"=",
"args",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"args",
")",
">",
"1",
"else",
"(",
")",
"return",
"fun",
"(",
"x",
"... | 29.307692 | 22.230769 |
def run_process(cwd, args):
"""Executes an external process via subprocess.Popen"""
try:
process = check_output(args, cwd=cwd, stderr=STDOUT)
return process
except CalledProcessError as e:
log('Uh oh, the teapot broke again! Error:', e, type(e), lvl=verbose, pretty=True)
log... | [
"def",
"run_process",
"(",
"cwd",
",",
"args",
")",
":",
"try",
":",
"process",
"=",
"check_output",
"(",
"args",
",",
"cwd",
"=",
"cwd",
",",
"stderr",
"=",
"STDOUT",
")",
"return",
"process",
"except",
"CalledProcessError",
"as",
"e",
":",
"log",
"("... | 37.9 | 21 |
def new_kitchen():
"""Create LittleChef directory structure (Kitchen)"""
def _mkdir(d, content=""):
if not os.path.exists(d):
os.mkdir(d)
# Add a README so that it can be added to version control
readme_path = os.path.join(d, 'README')
if not os.path.exist... | [
"def",
"new_kitchen",
"(",
")",
":",
"def",
"_mkdir",
"(",
"d",
",",
"content",
"=",
"\"\"",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"d",
")",
":",
"os",
".",
"mkdir",
"(",
"d",
")",
"# Add a README so that it can be added to vers... | 41.230769 | 13.769231 |
def bear(a1, b1, a2, b2):
"""Find bearing/position angle between two points on a unit sphere.
Parameters
----------
a1, b1 : float
Longitude-like and latitude-like angles defining the first
point. Both are in radians.
a2, b2 : float
Longitude-like and latitude-like angles d... | [
"def",
"bear",
"(",
"a1",
",",
"b1",
",",
"a2",
",",
"b2",
")",
":",
"# Find perpendicular to the plane containing the base and",
"# z-axis. Then find the perpendicular to the plane containing",
"# the base and the target. The angle between these two is the",
"# position angle or beari... | 30 | 24.215054 |
def _create_auth(team, timeout=None):
"""
Reads the credentials, updates the access token if necessary, and returns it.
"""
url = get_registry_url(team)
contents = _load_auth()
auth = contents.get(url)
if auth is not None:
# If the access token expires within a minute, update it.
... | [
"def",
"_create_auth",
"(",
"team",
",",
"timeout",
"=",
"None",
")",
":",
"url",
"=",
"get_registry_url",
"(",
"team",
")",
"contents",
"=",
"_load_auth",
"(",
")",
"auth",
"=",
"contents",
".",
"get",
"(",
"url",
")",
"if",
"auth",
"is",
"not",
"No... | 34.772727 | 17.863636 |
def get_base_info(self, obj):
"""Returns the base info of an object
"""
if obj is None:
return {}
info = {
"id": obj.getId(),
"uid": obj.UID(),
"title": obj.Title(),
"description": obj.Description(),
"url": obj.abso... | [
"def",
"get_base_info",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"{",
"}",
"info",
"=",
"{",
"\"id\"",
":",
"obj",
".",
"getId",
"(",
")",
",",
"\"uid\"",
":",
"obj",
".",
"UID",
"(",
")",
",",
"\"title\"",
"... | 23.2 | 15.866667 |
def _process_neg_flux(self, x, y):
"""Remove negative flux."""
if self._keep_neg: # Nothing to do
return y
old_y = None
if np.isscalar(y): # pragma: no cover
if y < 0:
n_neg = 1
old_x = x
old_y = y
... | [
"def",
"_process_neg_flux",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"self",
".",
"_keep_neg",
":",
"# Nothing to do",
"return",
"y",
"old_y",
"=",
"None",
"if",
"np",
".",
"isscalar",
"(",
"y",
")",
":",
"# pragma: no cover",
"if",
"y",
"<",
... | 30.666667 | 19.727273 |
def scoped_format(txt, **objects):
"""Format a string with respect to a set of objects' attributes.
Example:
>>> Class Foo(object):
>>> def __init__(self):
>>> self.name = "Dave"
>>> print scoped_format("hello {foo.name}", foo=Foo())
hello Dave
Args:
... | [
"def",
"scoped_format",
"(",
"txt",
",",
"*",
"*",
"objects",
")",
":",
"pretty",
"=",
"objects",
".",
"pop",
"(",
"\"pretty\"",
",",
"RecursiveAttribute",
".",
"format_pretty",
")",
"expand",
"=",
"objects",
".",
"pop",
"(",
"\"expand\"",
",",
"RecursiveA... | 38.521739 | 19.869565 |
def reconnect(self, conn_retries=None):
''' Connects to Redis with a exponential waiting (3**n) '''
if conn_retries is None:
conn_retries = self.conn_retries
count = 0
if self.logger:
self.logger.info('Connecting to Redis..')
while count < conn_re... | [
"def",
"reconnect",
"(",
"self",
",",
"conn_retries",
"=",
"None",
")",
":",
"if",
"conn_retries",
"is",
"None",
":",
"conn_retries",
"=",
"self",
".",
"conn_retries",
"count",
"=",
"0",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",
"in... | 37.818182 | 18 |
def all(self, query=None, **kwargs):
"""
Gets all organizations.
"""
return super(OrganizationsProxy, self).all(query=query) | [
"def",
"all",
"(",
"self",
",",
"query",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"OrganizationsProxy",
",",
"self",
")",
".",
"all",
"(",
"query",
"=",
"query",
")"
] | 25.333333 | 12.666667 |
def user(self):
""" Return a (deferred) cached Koji user name for this change. """
# Note, do any tasks really have an "owner_id", or are they all
# "owner"?
owner_id = getattr(self.task, 'owner_id', self.task.owner)
return self.task.connection.cache.user_name(owner_id) | [
"def",
"user",
"(",
"self",
")",
":",
"# Note, do any tasks really have an \"owner_id\", or are they all",
"# \"owner\"?",
"owner_id",
"=",
"getattr",
"(",
"self",
".",
"task",
",",
"'owner_id'",
",",
"self",
".",
"task",
".",
"owner",
")",
"return",
"self",
".",
... | 50.833333 | 20.833333 |
def split_path_and_file(s):
"""
Given a full path to a file, split and return a path and filename
:param str s: Path
:return str _path: Directory Path
:return str _filename: Filename
"""
_path = s
_filename = ""
try:
x = os.path.split(s)
_path = x[0]
_filenam... | [
"def",
"split_path_and_file",
"(",
"s",
")",
":",
"_path",
"=",
"s",
"_filename",
"=",
"\"\"",
"try",
":",
"x",
"=",
"os",
".",
"path",
".",
"split",
"(",
"s",
")",
"_path",
"=",
"x",
"[",
"0",
"]",
"_filename",
"=",
"x",
"[",
"1",
"]",
"except... | 22.611111 | 17.388889 |
def arrow_head(document, x0, y0, x1, y1, arrowshape):
"make arrow head at (x1,y1), arrowshape is tuple (d1, d2, d3)"
import math
dx = x1 - x0
dy = y1 - y0
poly = document.createElement('polygon')
d = math.sqrt(dx*dx + dy*dy)
if d == 0.0: # XXX: equal, no "close enough"
return poly
try:
d1, d2, d3 = l... | [
"def",
"arrow_head",
"(",
"document",
",",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
",",
"arrowshape",
")",
":",
"import",
"math",
"dx",
"=",
"x1",
"-",
"x0",
"dy",
"=",
"y1",
"-",
"y0",
"poly",
"=",
"document",
".",
"createElement",
"(",
"'polygon'"... | 19.058824 | 24.823529 |
def handleEvent(self, event):
"""This method should be called every time through the main loop.
It handles all of the keyboard key actions
Parameters:
| eventObj - the event object obtained by calling pygame.event.get()
Returns:
| False most of the tim... | [
"def",
"handleEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"isEnabled",
":",
"return",
"False",
"if",
"(",
"event",
".",
"type",
"==",
"pygame",
".",
"MOUSEBUTTONDOWN",
")",
"and",
"(",
"event",
".",
"button",
"==",
"1",
")"... | 41.666667 | 25 |
def _construct_end_index( spansStartingFrom ):
''' Creates an index which stores all annotations (from spansStartingFrom)
by their end position in text (annotation[END]).
Each start position (in the index) is associated with a list of
annotation objects (annotations ending at that... | [
"def",
"_construct_end_index",
"(",
"spansStartingFrom",
")",
":",
"endIndex",
"=",
"{",
"}",
"for",
"i",
"in",
"spansStartingFrom",
":",
"for",
"span1",
"in",
"spansStartingFrom",
"[",
"i",
"]",
":",
"# keep the record of endTags, start positions (for determining the l... | 48.711111 | 20.444444 |
def CopyToPath(self):
"""Copies the shell items to a path.
Returns:
str: converted shell item list path or None.
"""
number_of_path_segments = len(self._path_segments)
if number_of_path_segments == 0:
return None
strings = [self._path_segments[0]]
number_of_path_segments -= 1
... | [
"def",
"CopyToPath",
"(",
"self",
")",
":",
"number_of_path_segments",
"=",
"len",
"(",
"self",
".",
"_path_segments",
")",
"if",
"number_of_path_segments",
"==",
"0",
":",
"return",
"None",
"strings",
"=",
"[",
"self",
".",
"_path_segments",
"[",
"0",
"]",
... | 33.333333 | 17 |
def analyze_modules(project, task_handle=taskhandle.NullTaskHandle()):
"""Perform static object analysis on all python files in the project
Note that this might be really time consuming.
"""
resources = project.get_python_files()
job_set = task_handle.create_jobset('Analyzing Modules', len(resource... | [
"def",
"analyze_modules",
"(",
"project",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"resources",
"=",
"project",
".",
"get_python_files",
"(",
")",
"job_set",
"=",
"task_handle",
".",
"create_jobset",
"(",
"'Analyzing Modu... | 41.818182 | 12.818182 |
def cli(env):
"""Print environment variables."""
filtered_vars = dict([(k, v)
for k, v in env.vars.items()
if not k.startswith('_')])
env.fout(formatting.iter_to_table(filtered_vars)) | [
"def",
"cli",
"(",
"env",
")",
":",
"filtered_vars",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"env",
".",
"vars",
".",
"items",
"(",
")",
"if",
"not",
"k",
".",
"startswith",
"(",
"'_'",
")",
"]",
")",
"en... | 40.333333 | 12.333333 |
def metal_complexation(metals, metal_binding_lig, metal_binding_bs):
"""Find all metal complexes between metals and appropriate groups in both protein and ligand, as well as water"""
data = namedtuple('metal_complex', 'metal metal_orig_idx metal_type target target_orig_idx target_type '
... | [
"def",
"metal_complexation",
"(",
"metals",
",",
"metal_binding_lig",
",",
"metal_binding_bs",
")",
":",
"data",
"=",
"namedtuple",
"(",
"'metal_complex'",
",",
"'metal metal_orig_idx metal_type target target_orig_idx target_type '",
"'coordination_num distance resnr restype '",
... | 60.738562 | 30.026144 |
def do_workers(self, args):
'''list all known workers'''
workers = self.task_master.workers(alive=not args.all)
for k in sorted(workers.iterkeys()):
self.stdout.write('{0} ({1})\n'.format(k, workers[k]))
if args.details:
heartbeat = self.task_master.get_he... | [
"def",
"do_workers",
"(",
"self",
",",
"args",
")",
":",
"workers",
"=",
"self",
".",
"task_master",
".",
"workers",
"(",
"alive",
"=",
"not",
"args",
".",
"all",
")",
"for",
"k",
"in",
"sorted",
"(",
"workers",
".",
"iterkeys",
"(",
")",
")",
":",... | 49.333333 | 15.777778 |
def add_lb_secgroup(self, lb_name, hosts, port):
"""
Used by the load balancer deployer to register a hostname
for a load balancer, in order that security group rules can be
applied later. This is multiprocess-safe, but since keys are
accessed only be a single load balancer deplo... | [
"def",
"add_lb_secgroup",
"(",
"self",
",",
"lb_name",
",",
"hosts",
",",
"port",
")",
":",
"self",
".",
"lb_sec_groups",
".",
"merge",
"(",
"lb_name",
",",
"{",
"'hosts'",
":",
"hosts",
",",
"'port'",
":",
"port",
"}",
")"
] | 43.6 | 26 |
def get_commit(self, sha):
"""
:calls: `GET /repos/:owner/:repo/commits/:sha <http://developer.github.com/v3/repos/commits>`_
:param sha: string
:rtype: :class:`github.Commit.Commit`
"""
assert isinstance(sha, (str, unicode)), sha
headers, data = self._requester.r... | [
"def",
"get_commit",
"(",
"self",
",",
"sha",
")",
":",
"assert",
"isinstance",
"(",
"sha",
",",
"(",
"str",
",",
"unicode",
")",
")",
",",
"sha",
"headers",
",",
"data",
"=",
"self",
".",
"_requester",
".",
"requestJsonAndCheck",
"(",
"\"GET\"",
",",
... | 40.166667 | 18.5 |
def length(self):
"""Gets length
:return: How many items in linked list of linked list
"""
item = self.head
counter = 0
while item is not None:
counter += 1
item = item.next_node
return counter | [
"def",
"length",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"head",
"counter",
"=",
"0",
"while",
"item",
"is",
"not",
"None",
":",
"counter",
"+=",
"1",
"item",
"=",
"item",
".",
"next_node",
"return",
"counter"
] | 20.307692 | 19.307692 |
def get_current_roles():
"""
Determines the list of roles, that the current host is assigned to. If ``env.roledefs`` is not set, an empty list
is returned.
:return: List of roles of the current host.
:rtype: list
"""
current_host = env.host_string
roledefs = env.get('roledefs')
if r... | [
"def",
"get_current_roles",
"(",
")",
":",
"current_host",
"=",
"env",
".",
"host_string",
"roledefs",
"=",
"env",
".",
"get",
"(",
"'roledefs'",
")",
"if",
"roledefs",
":",
"return",
"[",
"role",
"for",
"role",
",",
"hosts",
"in",
"six",
".",
"iteritems... | 32.307692 | 23.076923 |
def write_zip(
src_fs, # type: FS
file, # type: Union[Text, BinaryIO]
compression=zipfile.ZIP_DEFLATED, # type: int
encoding="utf-8", # type: Text
walker=None, # type: Optional[Walker]
):
# type: (...) -> None
"""Write the contents of a filesystem to a zip file.
Arguments:
... | [
"def",
"write_zip",
"(",
"src_fs",
",",
"# type: FS",
"file",
",",
"# type: Union[Text, BinaryIO]",
"compression",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
",",
"# type: int",
"encoding",
"=",
"\"utf-8\"",
",",
"# type: Text",
"walker",
"=",
"None",
",",
"# type: Option... | 42.297297 | 19.472973 |
def schema(self, schema):
"""Specifies the input schema.
Some data sources (e.g. JSON) can infer the input schema automatically from data.
By specifying the schema here, the underlying data source can skip the schema
inference step, and thus speed up data loading.
:param schema... | [
"def",
"schema",
"(",
"self",
",",
"schema",
")",
":",
"from",
"pyspark",
".",
"sql",
"import",
"SparkSession",
"spark",
"=",
"SparkSession",
".",
"builder",
".",
"getOrCreate",
"(",
")",
"if",
"isinstance",
"(",
"schema",
",",
"StructType",
")",
":",
"j... | 44.681818 | 22.727273 |
def from_file(cls, fmt, filename=None,
structure_file=None, are_coops=False):
"""
Creates a CompleteCohp object from an output file of a COHP
calculation. Valid formats are either LMTO (for the Stuttgart
LMTO-ASA code) or LOBSTER (for the LOBSTER code).
Args:
... | [
"def",
"from_file",
"(",
"cls",
",",
"fmt",
",",
"filename",
"=",
"None",
",",
"structure_file",
"=",
"None",
",",
"are_coops",
"=",
"False",
")",
":",
"fmt",
"=",
"fmt",
".",
"upper",
"(",
")",
"if",
"fmt",
"==",
"\"LMTO\"",
":",
"# LMTO COOPs and orb... | 45.29661 | 20.398305 |
def _init_valid_functions(action_dimensions):
"""Initialize ValidFunctions and set up the callbacks."""
sizes = {
"screen": tuple(int(i) for i in action_dimensions.screen),
"screen2": tuple(int(i) for i in action_dimensions.screen),
"minimap": tuple(int(i) for i in action_dimensions.minimap),
}
... | [
"def",
"_init_valid_functions",
"(",
"action_dimensions",
")",
":",
"sizes",
"=",
"{",
"\"screen\"",
":",
"tuple",
"(",
"int",
"(",
"i",
")",
"for",
"i",
"in",
"action_dimensions",
".",
"screen",
")",
",",
"\"screen2\"",
":",
"tuple",
"(",
"int",
"(",
"i... | 37.470588 | 22.117647 |
def process_response(self, req, resp, resource):
"""
Serializes ``req.context['result']`` to resp.body as JSON.
If :attr:`~zengine.settings.DEBUG` is True,
``sys._debug_db_queries`` (set by pyoko) added to response.
"""
if 'result' not in req.context:
return... | [
"def",
"process_response",
"(",
"self",
",",
"req",
",",
"resp",
",",
"resource",
")",
":",
"if",
"'result'",
"not",
"in",
"req",
".",
"context",
":",
"return",
"req",
".",
"context",
"[",
"'result'",
"]",
"[",
"'is_login'",
"]",
"=",
"'user_id'",
"in"... | 36.714286 | 19.666667 |
def get_by_name(self, name):
"""
Gets a SAN Manager by name.
Args:
name: Name of the SAN Manager
Returns:
dict: SAN Manager.
"""
san_managers = self._client.get_all()
result = [x for x in san_managers if x['name'] == name]
return ... | [
"def",
"get_by_name",
"(",
"self",
",",
"name",
")",
":",
"san_managers",
"=",
"self",
".",
"_client",
".",
"get_all",
"(",
")",
"result",
"=",
"[",
"x",
"for",
"x",
"in",
"san_managers",
"if",
"x",
"[",
"'name'",
"]",
"==",
"name",
"]",
"return",
... | 25.923077 | 14.692308 |
def metadata(func):
"""Add metadata to an item.
Decorator that adds metadata to a given item such as
the gelk revision used.
"""
@functools.wraps(func)
def decorator(self, *args, **kwargs):
eitem = func(self, *args, **kwargs)
metadata = {
'metadata__gelk_version': s... | [
"def",
"metadata",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"decorator",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"eitem",
"=",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*"... | 29.888889 | 17.666667 |
def wrapper__ignore(self, type_):
"""
Selectively ignore certain types when wrapping attributes.
:param class type: The class/type definition to ignore.
:rtype list(type): The current list of ignored types
"""
if type_ not in self.__exclusion_list:
self.__ex... | [
"def",
"wrapper__ignore",
"(",
"self",
",",
"type_",
")",
":",
"if",
"type_",
"not",
"in",
"self",
".",
"__exclusion_list",
":",
"self",
".",
"__exclusion_list",
".",
"append",
"(",
"type_",
")",
"return",
"self",
".",
"__exclusion_list"
] | 33.909091 | 15.727273 |
def is_data_value(searchpath, searchtree, dtype = None, empty_is_false = False):
"""
Follow searchpath through the datatree in searchtree
and report if there exists a value of type dtype
searchpath is a list of keys/indices
If dtype is None check for any value
you can also supply a tuple to dty... | [
"def",
"is_data_value",
"(",
"searchpath",
",",
"searchtree",
",",
"dtype",
"=",
"None",
",",
"empty_is_false",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"searchpath",
",",
"(",
"str",
",",
"unicode",
",",
"int",
")",
")",
":",
"searchpath",
"=",
... | 29.310345 | 19.068966 |
def save_institute(self, institute):
""" Called when institute is created/updated. """
name = institute.name
logger.debug("save_institute '%s'" % name)
# institute created
# institute updated
if institute.is_active:
# date_deleted is not set, user should exi... | [
"def",
"save_institute",
"(",
"self",
",",
"institute",
")",
":",
"name",
"=",
"institute",
".",
"name",
"logger",
".",
"debug",
"(",
"\"save_institute '%s'\"",
"%",
"name",
")",
"# institute created",
"# institute updated",
"if",
"institute",
".",
"is_active",
... | 35.130435 | 19.695652 |
def obj2bunch(data, commdct, obj):
"""make a new bunch object using the data object"""
dtls = data.dtls
key = obj[0].upper()
key_i = dtls.index(key)
abunch = makeabunch(commdct, obj, key_i)
return abunch | [
"def",
"obj2bunch",
"(",
"data",
",",
"commdct",
",",
"obj",
")",
":",
"dtls",
"=",
"data",
".",
"dtls",
"key",
"=",
"obj",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"key_i",
"=",
"dtls",
".",
"index",
"(",
"key",
")",
"abunch",
"=",
"makeabunch",
... | 31.571429 | 11.714286 |
def is_bad_chunk(self, chunk_meta, grp, pug, chk):
"""Check the chunk is offline or not"""
meta = self.get_chunk_meta_item(chunk_meta, grp, pug, chk)
if meta.CS & 0x8 != 0:
return True
return False | [
"def",
"is_bad_chunk",
"(",
"self",
",",
"chunk_meta",
",",
"grp",
",",
"pug",
",",
"chk",
")",
":",
"meta",
"=",
"self",
".",
"get_chunk_meta_item",
"(",
"chunk_meta",
",",
"grp",
",",
"pug",
",",
"chk",
")",
"if",
"meta",
".",
"CS",
"&",
"0x8",
"... | 39.333333 | 13.833333 |
def send_request(self, message):
"""Send message request to HANA db and return reply message
:param message: Instance of Message object containing segments and parts of a HANA db request
:returns: Instance of reply Message object
"""
payload = message.pack() # obtain BytesIO ins... | [
"def",
"send_request",
"(",
"self",
",",
"message",
")",
":",
"payload",
"=",
"message",
".",
"pack",
"(",
")",
"# obtain BytesIO instance",
"return",
"self",
".",
"__send_message_recv_reply",
"(",
"payload",
".",
"getvalue",
"(",
")",
")"
] | 55 | 17.571429 |
def arrange_plots_on_one_canvas(FigureAxTupleArray, title='', SubtitleArray = [], show_fig=True):
"""
Arranges plots, given in an array of tuples consisting of fig and axs,
onto a subplot-figure consisting of 2 horizontal times the lenght of the
passed (fig,axs)-array divided by 2 vertical subplots
... | [
"def",
"arrange_plots_on_one_canvas",
"(",
"FigureAxTupleArray",
",",
"title",
"=",
"''",
",",
"SubtitleArray",
"=",
"[",
"]",
",",
"show_fig",
"=",
"True",
")",
":",
"if",
"SubtitleArray",
"==",
"[",
"]",
":",
"SubtitleArray",
"=",
"[",
"\"Plot {}\"",
".",
... | 42.333333 | 19.166667 |
def _competition(self, x):
"""!
@brief Calculates neuron winner (distance, neuron index).
@param[in] x (list): Input pattern from the input data set, for example it can be coordinates of point.
@return (uint) Returns index of neuron that is winner.
... | [
"def",
"_competition",
"(",
"self",
",",
"x",
")",
":",
"index",
"=",
"0",
"minimum",
"=",
"euclidean_distance_square",
"(",
"self",
".",
"_weights",
"[",
"0",
"]",
",",
"x",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"self",
".",
"_size",
",",... | 33.05 | 22.1 |
def rpcexec(self, payload):
""" Manual execute a command on API (internally used)
param str payload: The payload containing the request
return: Servers answer to the query
rtype: json
raises RPCConnection: if no connction can be made
raises Unauthoriz... | [
"def",
"rpcexec",
"(",
"self",
",",
"payload",
")",
":",
"try",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"\"http://{}:{}/rpc\"",
".",
"format",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
",",
"data",
"=",
"json",
".",
"dumps"... | 41.682927 | 17.731707 |
def download_image(self, handle, dest):
"""
Downloads the image from the http server
Args:
handle (str): url from the `self.baseurl` to the remote template
dest (str): Path to store the downloaded url to, must be a file
path
Returns:
... | [
"def",
"download_image",
"(",
"self",
",",
"handle",
",",
"dest",
")",
":",
"with",
"log_utils",
".",
"LogTask",
"(",
"'Download image %s'",
"%",
"handle",
",",
"logger",
"=",
"LOGGER",
")",
":",
"self",
".",
"open_url",
"(",
"url",
"=",
"handle",
",",
... | 30.25 | 21.5 |
def start(self, show_exit_option=None):
"""
Start the menu in a new thread and allow the user to interact with it.
The thread is a daemon, so :meth:`join()<consolemenu.ConsoleMenu.join>` should be called if there's a
possibility that the main thread will exit before the menu is done
... | [
"def",
"start",
"(",
"self",
",",
"show_exit_option",
"=",
"None",
")",
":",
"self",
".",
"previous_active_menu",
"=",
"ConsoleMenu",
".",
"currently_active_menu",
"ConsoleMenu",
".",
"currently_active_menu",
"=",
"None",
"self",
".",
"should_exit",
"=",
"False",
... | 35 | 24.870968 |
def _pop_indent_stack(self, node, node_type=None, action=None):
"""Get callable full name."""
indent = self._get_indent(node)
indent_stack = copy.deepcopy(self._indent_stack)
# Find enclosing scope
while (len(indent_stack) > 1) and (
(
(indent <= inden... | [
"def",
"_pop_indent_stack",
"(",
"self",
",",
"node",
",",
"node_type",
"=",
"None",
",",
"action",
"=",
"None",
")",
":",
"indent",
"=",
"self",
".",
"_get_indent",
"(",
"node",
")",
"indent_stack",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_in... | 33.022222 | 13.577778 |
def main():
"""Main entry point."""
# Build default paths for files.
dirs = appdirs.AppDirs('hangups', 'hangups')
default_log_path = os.path.join(dirs.user_log_dir, 'hangups.log')
default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt')
default_config_path = 'hangups.conf'
... | [
"def",
"main",
"(",
")",
":",
"# Build default paths for files.",
"dirs",
"=",
"appdirs",
".",
"AppDirs",
"(",
"'hangups'",
",",
"'hangups'",
")",
"default_log_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirs",
".",
"user_log_dir",
",",
"'hangups.log'",
... | 45.204545 | 19 |
def synchronise(func):
""" If task already queued, running, or finished, don't restart. """
def inner(request, *args):
lock_id = '%s-%s-built-%s' % (
datetime.date.today(), func.__name__,
",".join([str(a) for a in args]))
if cache.add(lock_id, 'true', LOCK_EXPIRE):
... | [
"def",
"synchronise",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"request",
",",
"*",
"args",
")",
":",
"lock_id",
"=",
"'%s-%s-built-%s'",
"%",
"(",
"datetime",
".",
"date",
".",
"today",
"(",
")",
",",
"func",
".",
"__name__",
",",
"\",\"",
".",
... | 32.090909 | 12.818182 |
def normalize_arxiv_category(category):
"""Normalize arXiv category to be schema compliant.
This properly capitalizes the category and replaces the dash by a dot if
needed. If the category is obsolete, it also gets converted it to its
current equivalent.
Example:
>>> from inspire_schemas.u... | [
"def",
"normalize_arxiv_category",
"(",
"category",
")",
":",
"category",
"=",
"_NEW_CATEGORIES",
".",
"get",
"(",
"category",
".",
"lower",
"(",
")",
",",
"category",
")",
"for",
"valid_category",
"in",
"valid_arxiv_categories",
"(",
")",
":",
"if",
"(",
"c... | 38.894737 | 22.578947 |
def installFS(rh, vaddr, mode, fileSystem, diskType):
"""
Install a filesystem on a virtual machine's dasd.
Input:
Request Handle:
userid - Userid that owns the disk
Virtual address as known to the owning system.
Access mode to use to get the disk.
Disk Type - 3390 or ... | [
"def",
"installFS",
"(",
"rh",
",",
"vaddr",
",",
"mode",
",",
"fileSystem",
",",
"diskType",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter vmUtils.installFS, userid: \"",
"+",
"rh",
".",
"userid",
"+",
"\", vaddr: \"",
"+",
"str",
"(",
"vaddr",
")",
"... | 37.759197 | 12.280936 |
def Unlock(fd, path):
"""Release the lock on the file.
Args:
fd: int, the file descriptor of the file to unlock.
path: string, the name of the file to lock.
Raises:
IOError, raised from flock while attempting to release a file lock.
"""
try:
fcntl.flock(fd, fcntl.LOCK_UN | fcntl.LOCK_NB)
e... | [
"def",
"Unlock",
"(",
"fd",
",",
"path",
")",
":",
"try",
":",
"fcntl",
".",
"flock",
"(",
"fd",
",",
"fcntl",
".",
"LOCK_UN",
"|",
"fcntl",
".",
"LOCK_NB",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
... | 30.529412 | 22.352941 |
def fit(self, X, y):
"""Fit the model using X as training data and y as target values"""
self._data = X
self._classes = np.unique(y)
self._labels = y
self._is_fitted = True | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"self",
".",
"_data",
"=",
"X",
"self",
".",
"_classes",
"=",
"np",
".",
"unique",
"(",
"y",
")",
"self",
".",
"_labels",
"=",
"y",
"self",
".",
"_is_fitted",
"=",
"True"
] | 29.571429 | 15.428571 |
def local(args: arg(container=list),
cd=None,
environ: arg(type=dict) = None,
replace_env=False,
paths=(),
shell: arg(type=bool) = None,
stdout: arg(type=StreamOptions) = None,
stderr: arg(type=StreamOptions) = None,
echo=False,
r... | [
"def",
"local",
"(",
"args",
":",
"arg",
"(",
"container",
"=",
"list",
")",
",",
"cd",
"=",
"None",
",",
"environ",
":",
"arg",
"(",
"type",
"=",
"dict",
")",
"=",
"None",
",",
"replace_env",
"=",
"False",
",",
"paths",
"=",
"(",
")",
",",
"sh... | 30.429907 | 20.682243 |
def validate_signature(self, filename):
"""Returns True if a valid signature is present for filename"""
if not GPG_PRESENT:
return False
sigfilename = filename + '.sig'
try:
with open(sigfilename):
pass
except IOError:
# Sig... | [
"def",
"validate_signature",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"GPG_PRESENT",
":",
"return",
"False",
"sigfilename",
"=",
"filename",
"+",
"'.sig'",
"try",
":",
"with",
"open",
"(",
"sigfilename",
")",
":",
"pass",
"except",
"IOError",
"... | 26.368421 | 18.105263 |
def parse_line(self, line: str):
"""
Parse a line from database
:param line: line to parse
"""
for i in KEYPAIR_RE.finditer(line):
key = i.group(1)
value = urllib.parse.unquote(i.group(2))
self[key] = value | [
"def",
"parse_line",
"(",
"self",
",",
"line",
":",
"str",
")",
":",
"for",
"i",
"in",
"KEYPAIR_RE",
".",
"finditer",
"(",
"line",
")",
":",
"key",
"=",
"i",
".",
"group",
"(",
"1",
")",
"value",
"=",
"urllib",
".",
"parse",
".",
"unquote",
"(",
... | 30.444444 | 6.444444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.