text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def b(self):
'''
Positive antipodal point on the minor axis, Point class.
'''
b = Point(self.center)
if self.xAxisIsMinor:
b.x += self.minorRadius
else:
b.y += self.minorRadius
return b | [
"def",
"b",
"(",
"self",
")",
":",
"b",
"=",
"Point",
"(",
"self",
".",
"center",
")",
"if",
"self",
".",
"xAxisIsMinor",
":",
"b",
".",
"x",
"+=",
"self",
".",
"minorRadius",
"else",
":",
"b",
".",
"y",
"+=",
"self",
".",
"minorRadius",
"return"... | 21.333333 | 22.666667 |
def map(self, f):
"""
Maps this Pair with *f*'; see :meth:`vanilla.core.Recver.map`
Returns a new Pair of our current Sender and the mapped target's
Recver.
"""
return self._replace(recver=self.recver.map(f)) | [
"def",
"map",
"(",
"self",
",",
"f",
")",
":",
"return",
"self",
".",
"_replace",
"(",
"recver",
"=",
"self",
".",
"recver",
".",
"map",
"(",
"f",
")",
")"
] | 31.25 | 20.5 |
def must_be_same(self, klass):
"""Called to make sure a Node is a Dir. Since we're an
Entry, we can morph into one."""
if self.__class__ is not klass:
self.__class__ = klass
self._morph()
self.clear() | [
"def",
"must_be_same",
"(",
"self",
",",
"klass",
")",
":",
"if",
"self",
".",
"__class__",
"is",
"not",
"klass",
":",
"self",
".",
"__class__",
"=",
"klass",
"self",
".",
"_morph",
"(",
")",
"self",
".",
"clear",
"(",
")"
] | 36.428571 | 6.857143 |
def comparison_stats(df, els=None):
"""
Compute comparison stats for test and LAtools data.
Population-level similarity assessed by a Kolmogorov-Smirnov test.
Individual similarity assessed by a pairwise Wilcoxon signed rank test.
Trends in residuals assessed by regression analysis, w... | [
"def",
"comparison_stats",
"(",
"df",
",",
"els",
"=",
"None",
")",
":",
"if",
"els",
"is",
"None",
":",
"els",
"=",
"[",
"'Li'",
",",
"'Mg'",
",",
"'Al'",
",",
"'P'",
",",
"'Ti'",
",",
"'Y'",
",",
"'La'",
",",
"'Ce'",
",",
"'Pr'",
",",
"'Nd'",... | 28.825 | 23.575 |
def create_response(
self, data: dict = None, response: requests.Response = None, errors: list = None
) -> Response:
"""
Helper function to generate a :class:`~notifiers.core.Response` object
:param data: The data that was used to send the notification
:param response: :clas... | [
"def",
"create_response",
"(",
"self",
",",
"data",
":",
"dict",
"=",
"None",
",",
"response",
":",
"requests",
".",
"Response",
"=",
"None",
",",
"errors",
":",
"list",
"=",
"None",
")",
"->",
"Response",
":",
"status",
"=",
"FAILURE_STATUS",
"if",
"e... | 35.111111 | 19.888889 |
def row_to_dict(self, row, allele, alternate_alleles):
"""Return a parsed dictionary for JSON."""
def _variant_sbid(**kwargs):
"""Generates a SolveBio variant ID (SBID)."""
return '{build}-{chromosome}-{start}-{stop}-{allele}'\
.format(**kwargs).upper()
... | [
"def",
"row_to_dict",
"(",
"self",
",",
"row",
",",
"allele",
",",
"alternate_alleles",
")",
":",
"def",
"_variant_sbid",
"(",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Generates a SolveBio variant ID (SBID).\"\"\"",
"return",
"'{build}-{chromosome}-{start}-{stop}-{allele}'",
... | 33.617647 | 15 |
def _executemany(self, cursor, query, parameters):
"""The function is mostly useful for commands that update the database:
any result set returned by the query is discarded."""
try:
self._log(query)
cursor.executemany(query, parameters)
except OperationalError ... | [
"def",
"_executemany",
"(",
"self",
",",
"cursor",
",",
"query",
",",
"parameters",
")",
":",
"try",
":",
"self",
".",
"_log",
"(",
"query",
")",
"cursor",
".",
"executemany",
"(",
"query",
",",
"parameters",
")",
"except",
"OperationalError",
"as",
"e",... | 46.2 | 15.7 |
def ExpandGroups(path):
"""Performs group expansion on a given path.
For example, given path `foo/{bar,baz}/{quux,norf}` this method will yield
`foo/bar/quux`, `foo/bar/norf`, `foo/baz/quux`, `foo/baz/norf`.
Args:
path: A path to expand.
Yields:
Paths that can be obtained from given path by expandi... | [
"def",
"ExpandGroups",
"(",
"path",
")",
":",
"precondition",
".",
"AssertType",
"(",
"path",
",",
"Text",
")",
"chunks",
"=",
"[",
"]",
"offset",
"=",
"0",
"for",
"match",
"in",
"PATH_GROUP_REGEX",
".",
"finditer",
"(",
"path",
")",
":",
"chunks",
"."... | 25 | 22.5 |
def regular_generic_msg(hostname, result, oneline, caption):
''' output on the result of a module run that is not command '''
if not oneline:
return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(result,format=True))
else:
return "%s | %s >> %s\n" % (hostname, caption, utils.jsonify(... | [
"def",
"regular_generic_msg",
"(",
"hostname",
",",
"result",
",",
"oneline",
",",
"caption",
")",
":",
"if",
"not",
"oneline",
":",
"return",
"\"%s | %s >> %s\\n\"",
"%",
"(",
"hostname",
",",
"caption",
",",
"utils",
".",
"jsonify",
"(",
"result",
",",
"... | 46 | 32.285714 |
def set_headers(self, headers):
"""Set headers"""
for (header, value) in headers.iteritems():
self.set_header(header, value) | [
"def",
"set_headers",
"(",
"self",
",",
"headers",
")",
":",
"for",
"(",
"header",
",",
"value",
")",
"in",
"headers",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"set_header",
"(",
"header",
",",
"value",
")"
] | 37.25 | 5.5 |
def normalize_jr(jr, url=None):
""" normalize JSON reference, also fix
implicit reference of JSON pointer.
input:
- #/definitions/User
- http://test.com/swagger.json#/definitions/User
output:
- http://test.com/swagger.json#/definitions/User
input:
- some_folder/User.json
output:... | [
"def",
"normalize_jr",
"(",
"jr",
",",
"url",
"=",
"None",
")",
":",
"if",
"jr",
"==",
"None",
":",
"return",
"jr",
"idx",
"=",
"jr",
".",
"find",
"(",
"'#'",
")",
"path",
",",
"jp",
"=",
"(",
"jr",
"[",
":",
"idx",
"]",
",",
"jr",
"[",
"id... | 27.4 | 21.085714 |
def add_constraints(self):
"""
Set the base constraints of the relation query
"""
if self._constraints:
super(MorphOneOrMany, self).add_constraints()
self._query.where(self._morph_type, self._morph_name) | [
"def",
"add_constraints",
"(",
"self",
")",
":",
"if",
"self",
".",
"_constraints",
":",
"super",
"(",
"MorphOneOrMany",
",",
"self",
")",
".",
"add_constraints",
"(",
")",
"self",
".",
"_query",
".",
"where",
"(",
"self",
".",
"_morph_type",
",",
"self"... | 31.625 | 15.125 |
def set_xlimits_for_all(self, row_column_list=None, min=None, max=None):
"""Set x-axis limits of specified subplots.
:param row_column_list: a list containing (row, column) tuples to
specify the subplots, or None to indicate *all* subplots.
:type row_column_list: list or None
... | [
"def",
"set_xlimits_for_all",
"(",
"self",
",",
"row_column_list",
"=",
"None",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
")",
":",
"if",
"row_column_list",
"is",
"None",
":",
"self",
".",
"limits",
"[",
"'xmin'",
"]",
"=",
"min",
"self",
".",
... | 38.6875 | 15.0625 |
def time_calls_with_dims(**dims):
"""Decorator to time the execution of the function with dimensions."""
def time_wrapper(fn):
@functools.wraps(fn)
def fn_wrapper(*args, **kwargs):
_timer = timer("%s_calls" %
pyformance.registry.get_qualname(fn), **dims)
... | [
"def",
"time_calls_with_dims",
"(",
"*",
"*",
"dims",
")",
":",
"def",
"time_wrapper",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"fn_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_timer",
"=",
"ti... | 42.818182 | 11.909091 |
def _capitalize_first_letter(word):
"""Return a regex pattern with the first letter.
Accepts both lowercase and uppercase.
"""
if word[0].isalpha():
# These two cases are necessary in order to get a regex pattern
# starting with '[xX]' and not '[Xx]'. This allows to check for
# ... | [
"def",
"_capitalize_first_letter",
"(",
"word",
")",
":",
"if",
"word",
"[",
"0",
"]",
".",
"isalpha",
"(",
")",
":",
"# These two cases are necessary in order to get a regex pattern",
"# starting with '[xX]' and not '[Xx]'. This allows to check for",
"# colliding regex afterward... | 38.285714 | 17.785714 |
def get_all_for_project(self, name, **kwargs):
"""
Gets the Build Records produced from the BuildConfiguration by name.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when r... | [
"def",
"get_all_for_project",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_all_for_project_with_... | 42.344828 | 16.62069 |
def format_screen(strng):
"""Format a string for screen printing.
This removes some latex-type format codes."""
# Paragraph continue
par_re = re.compile(r'\\$',re.MULTILINE)
strng = par_re.sub('',strng)
return strng | [
"def",
"format_screen",
"(",
"strng",
")",
":",
"# Paragraph continue",
"par_re",
"=",
"re",
".",
"compile",
"(",
"r'\\\\$'",
",",
"re",
".",
"MULTILINE",
")",
"strng",
"=",
"par_re",
".",
"sub",
"(",
"''",
",",
"strng",
")",
"return",
"strng"
] | 29.125 | 13.375 |
def load_privatekey(type, buffer, passphrase=None):
"""
Load a private key (PKey) from the string *buffer* encoded with the type
*type*.
:param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
:param buffer: The buffer the key is stored in
:param passphrase: (optional) if encrypted PEM ... | [
"def",
"load_privatekey",
"(",
"type",
",",
"buffer",
",",
"passphrase",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"buffer",
",",
"_text_type",
")",
":",
"buffer",
"=",
"buffer",
".",
"encode",
"(",
"\"ascii\"",
")",
"bio",
"=",
"_new_mem_buf",
"("... | 33.794118 | 19.852941 |
def register_model(self, model, bundle):
"""
Registers a bundle as the main bundle for a
model. Used when we need to lookup urls by
a model.
"""
if model in self._model_registry:
raise AlreadyRegistered('The model %s is already registered' \
... | [
"def",
"register_model",
"(",
"self",
",",
"model",
",",
"bundle",
")",
":",
"if",
"model",
"in",
"self",
".",
"_model_registry",
":",
"raise",
"AlreadyRegistered",
"(",
"'The model %s is already registered'",
"%",
"model",
")",
"if",
"bundle",
".",
"url_params"... | 35.266667 | 14.466667 |
def _get_diff(self):
"""Get a diff between running config and a proposed file."""
diff = []
self._create_sot_file()
command = ('show diff rollback-patch file {0} file {1}'.format(
'sot_file', self.replace_file.split('/')[-1]))
diff_out = self.device.send_comman... | [
"def",
"_get_diff",
"(",
"self",
")",
":",
"diff",
"=",
"[",
"]",
"self",
".",
"_create_sot_file",
"(",
")",
"command",
"=",
"(",
"'show diff rollback-patch file {0} file {1}'",
".",
"format",
"(",
"'sot_file'",
",",
"self",
".",
"replace_file",
".",
"split",
... | 46.736842 | 16.631579 |
def guesser(types=GUESS_TYPES, strict=False):
"""Create a type guesser for multiple values."""
return TypeGuesser(types=types, strict=strict) | [
"def",
"guesser",
"(",
"types",
"=",
"GUESS_TYPES",
",",
"strict",
"=",
"False",
")",
":",
"return",
"TypeGuesser",
"(",
"types",
"=",
"types",
",",
"strict",
"=",
"strict",
")"
] | 49 | 5 |
def _expand_paths_itr(paths, marker='*'):
"""Iterator version of :func:`expand_paths`.
"""
for path in paths:
if is_path(path):
if marker in path: # glob path pattern
for ppath in sglob(path):
yield ppath
else:
yield path ... | [
"def",
"_expand_paths_itr",
"(",
"paths",
",",
"marker",
"=",
"'*'",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"is_path",
"(",
"path",
")",
":",
"if",
"marker",
"in",
"path",
":",
"# glob path pattern",
"for",
"ppath",
"in",
"sglob",
"(",
"pat... | 34.05 | 9.2 |
def failures():
"""Show any unexpected failures"""
if not HAVE_BIN_LIBS:
click.echo("missing required binary libs (lz4, msgpack)")
return
q = Queue('failed', connection=worker.connection)
for i in q.get_job_ids():
j = q.job_class.fetch(i, connection=q.connection)
click.e... | [
"def",
"failures",
"(",
")",
":",
"if",
"not",
"HAVE_BIN_LIBS",
":",
"click",
".",
"echo",
"(",
"\"missing required binary libs (lz4, msgpack)\"",
")",
"return",
"q",
"=",
"Queue",
"(",
"'failed'",
",",
"connection",
"=",
"worker",
".",
"connection",
")",
"for... | 38.230769 | 17.923077 |
def search(self, keyword, types=[], terr=KKBOXTerritory.TAIWAN):
'''
Searches within KKBOX's database.
:param keyword: the keyword.
:type keyword: str
:param types: the search types.
:return: list
:param terr: the current territory.
:return: API response.... | [
"def",
"search",
"(",
"self",
",",
"keyword",
",",
"types",
"=",
"[",
"]",
",",
"terr",
"=",
"KKBOXTerritory",
".",
"TAIWAN",
")",
":",
"url",
"=",
"'https://api.kkbox.com/v1.1/search'",
"url",
"+=",
"'?'",
"+",
"url_parse",
".",
"urlencode",
"(",
"{",
"... | 36.263158 | 19.421053 |
def sig_handler(self, sig, _):
""" Handle the signal sent to the process
:param sig: Signal set to the process
:param _: Frame is not being used
"""
import tornado.ioloop
from tornado.process import task_id
tid = task_id()
pid = os.getpid()
if tid... | [
"def",
"sig_handler",
"(",
"self",
",",
"sig",
",",
"_",
")",
":",
"import",
"tornado",
".",
"ioloop",
"from",
"tornado",
".",
"process",
"import",
"task_id",
"tid",
"=",
"task_id",
"(",
")",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"if",
"tid",
... | 38.5625 | 12.1875 |
def export(self, top=True):
"""Exports object to its string representation.
Args:
top (bool): if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are embedded in as fields inlist ... | [
"def",
"export",
"(",
"self",
",",
"top",
"=",
"True",
")",
":",
"out",
"=",
"[",
"]",
"if",
"top",
":",
"out",
".",
"append",
"(",
"self",
".",
"_internal_name",
")",
"out",
".",
"append",
"(",
"self",
".",
"_to_str",
"(",
"self",
".",
"title_of... | 44.752941 | 10.682353 |
def get_contents_as_string(self, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None,
response_headers=None):
"""
Retrieve an object from S3 using the name of the Key ... | [
"def",
"get_contents_as_string",
"(",
"self",
",",
"headers",
"=",
"None",
",",
"cb",
"=",
"None",
",",
"num_cb",
"=",
"10",
",",
"torrent",
"=",
"False",
",",
"version_id",
"=",
"None",
",",
"response_headers",
"=",
"None",
")",
":",
"fp",
"=",
"Strin... | 45.489362 | 22.297872 |
def _get_rnn_layer(mode, num_layers, input_size, hidden_size, dropout, weight_dropout):
"""create rnn layer given specs"""
if mode == 'rnn_relu':
rnn_block = functools.partial(rnn.RNN, activation='relu')
elif mode == 'rnn_tanh':
rnn_block = functools.partial(rnn.RNN, activation='tanh')
e... | [
"def",
"_get_rnn_layer",
"(",
"mode",
",",
"num_layers",
",",
"input_size",
",",
"hidden_size",
",",
"dropout",
",",
"weight_dropout",
")",
":",
"if",
"mode",
"==",
"'rnn_relu'",
":",
"rnn_block",
"=",
"functools",
".",
"partial",
"(",
"rnn",
".",
"RNN",
"... | 34.722222 | 22.166667 |
def show_firewall_policy(self, firewall_policy, **_params):
"""Fetches information of a certain firewall policy."""
return self.get(self.firewall_policy_path % (firewall_policy),
params=_params) | [
"def",
"show_firewall_policy",
"(",
"self",
",",
"firewall_policy",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"firewall_policy_path",
"%",
"(",
"firewall_policy",
")",
",",
"params",
"=",
"_params",
")"
] | 57.75 | 12.5 |
def Query(r, what, fields, qfilter=None):
"""
Retrieves information about resources.
@type what: string
@param what: Resource name, one of L{constants.QR_VIA_RAPI}
@type fields: list of string
@param fields: Requested fields
@type qfilter: None or list
@param qfilter: Query filter
... | [
"def",
"Query",
"(",
"r",
",",
"what",
",",
"fields",
",",
"qfilter",
"=",
"None",
")",
":",
"body",
"=",
"{",
"\"fields\"",
":",
"fields",
",",
"}",
"if",
"qfilter",
"is",
"not",
"None",
":",
"body",
"[",
"\"qfilter\"",
"]",
"=",
"body",
"[",
"\... | 23.086957 | 19.173913 |
def set_label(self, value,callb=None):
"""Convenience method to set the label of the device
This method will send a SetLabel message to the device, and request callb be executed
when an ACK is received. The default callback will simply cache the value.
:param value: The new label
... | [
"def",
"set_label",
"(",
"self",
",",
"value",
",",
"callb",
"=",
"None",
")",
":",
"if",
"len",
"(",
"value",
")",
">",
"32",
":",
"value",
"=",
"value",
"[",
":",
"32",
"]",
"mypartial",
"=",
"partial",
"(",
"self",
".",
"resp_set_label",
",",
... | 42.904762 | 22.857143 |
def check_ups_alarms_present(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.2.1.33.1.6.1.0
MIB excerpt
The present number of active alarm conditions.
"""
if the_snmp_value != '0':
the_helper.add_status(pynag.Plugins.critical)
else:
the_helper.add_status(pynag.Plug... | [
"def",
"check_ups_alarms_present",
"(",
"the_session",
",",
"the_helper",
",",
"the_snmp_value",
")",
":",
"if",
"the_snmp_value",
"!=",
"'0'",
":",
"the_helper",
".",
"add_status",
"(",
"pynag",
".",
"Plugins",
".",
"critical",
")",
"else",
":",
"the_helper",
... | 35.272727 | 15.090909 |
def init_duts(self, args): # pylint: disable=too-many-locals,too-many-branches
"""
Initializes duts of different types based on configuration provided by AllocationContext.
Able to do the initialization of duts in parallel, if --parallel_flash was provided.
:param args: Argument Namesp... | [
"def",
"init_duts",
"(",
"self",
",",
"args",
")",
":",
"# pylint: disable=too-many-locals,too-many-branches",
"# TODO: Split into smaller chunks to reduce complexity.",
"threads",
"=",
"[",
"]",
"abort_queue",
"=",
"Queue",
"(",
")",
"def",
"thread_wrapper",
"(",
"*",
... | 39.622222 | 20 |
def _decompress_data(self, data):
'''Decompress the given data and return the uncompressed data.'''
if self._decompressor:
try:
return self._decompressor.decompress(data)
except zlib.error as error:
raise ProtocolError(
'zlib er... | [
"def",
"_decompress_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"_decompressor",
":",
"try",
":",
"return",
"self",
".",
"_decompressor",
".",
"decompress",
"(",
"data",
")",
"except",
"zlib",
".",
"error",
"as",
"error",
":",
"raise",
... | 36.454545 | 15 |
def capture(self, instance_id, name, additional_disks=False, notes=None):
"""Capture one or all disks from a VS to a SoftLayer image.
Parameters set to None will be ignored and not attempted to be updated.
:param integer instance_id: the instance ID to edit
:param string name: name ass... | [
"def",
"capture",
"(",
"self",
",",
"instance_id",
",",
"name",
",",
"additional_disks",
"=",
"False",
",",
"notes",
"=",
"None",
")",
":",
"vsi",
"=",
"self",
".",
"client",
".",
"call",
"(",
"'Virtual_Guest'",
",",
"'getObject'",
",",
"id",
"=",
"ins... | 36.666667 | 21.843137 |
def pfeedback(self, msg: str) -> None:
"""For printing nonessential feedback. Can be silenced with `quiet`.
Inclusion in redirected output is controlled by `feedback_to_output`."""
if not self.quiet:
if self.feedback_to_output:
self.poutput(msg)
else:
... | [
"def",
"pfeedback",
"(",
"self",
",",
"msg",
":",
"str",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"quiet",
":",
"if",
"self",
".",
"feedback_to_output",
":",
"self",
".",
"poutput",
"(",
"msg",
")",
"else",
":",
"self",
".",
"decolorized_wri... | 47.875 | 9.625 |
def _patch(self, route, data, headers=None, failure_message=None):
"""
Execute a patch request and return the result
"""
headers = self._get_headers(headers)
response_lambda = (
lambda: requests.patch(
self._get_qualified_route(route), headers=headers,... | [
"def",
"_patch",
"(",
"self",
",",
"route",
",",
"data",
",",
"headers",
"=",
"None",
",",
"failure_message",
"=",
"None",
")",
":",
"headers",
"=",
"self",
".",
"_get_headers",
"(",
"headers",
")",
"response_lambda",
"=",
"(",
"lambda",
":",
"requests",... | 43.5 | 21 |
def _dfs_usb_info(obj, parents):
""" Find all of the usb info that we can from this particular IORegistry
tree with depth first search (and searching the parent stack....)
"""
output = {}
if (
"BSD Name" in obj
and obj["BSD Name"].startswith("disk")
and mbed_volume_name_m... | [
"def",
"_dfs_usb_info",
"(",
"obj",
",",
"parents",
")",
":",
"output",
"=",
"{",
"}",
"if",
"(",
"\"BSD Name\"",
"in",
"obj",
"and",
"obj",
"[",
"\"BSD Name\"",
"]",
".",
"startswith",
"(",
"\"disk\"",
")",
"and",
"mbed_volume_name_match",
".",
"search",
... | 38 | 15.45 |
def sample_vMF(mu, kappa, num_samples):
"""Generate num_samples N-dimensional samples from von Mises Fisher
distribution around center mu \in R^N with concentration kappa.
"""
dim = len(mu)
result = np.zeros((num_samples, dim))
for nn in range(num_samples):
# sample offset from center (o... | [
"def",
"sample_vMF",
"(",
"mu",
",",
"kappa",
",",
"num_samples",
")",
":",
"dim",
"=",
"len",
"(",
"mu",
")",
"result",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_samples",
",",
"dim",
")",
")",
"for",
"nn",
"in",
"range",
"(",
"num_samples",
")",
... | 34.470588 | 17.058824 |
def jacobian_s(nodes, degree, dimension):
r"""Compute :math:`\frac{\partial B}{\partial s}`.
.. note::
This is a helper for :func:`_jacobian_both`, which has an
equivalent Fortran implementation.
Args:
nodes (numpy.ndarray): Array of nodes in a surface.
degree (int): The deg... | [
"def",
"jacobian_s",
"(",
"nodes",
",",
"degree",
",",
"dimension",
")",
":",
"num_nodes",
"=",
"(",
"degree",
"*",
"(",
"degree",
"+",
"1",
")",
")",
"//",
"2",
"result",
"=",
"np",
".",
"empty",
"(",
"(",
"dimension",
",",
"num_nodes",
")",
",",
... | 31.7 | 18.733333 |
def apply(self, token, previous=(None, None), next=(None, None)):
""" Returns a (token, tag)-tuple for the given token,
in context of the given previous and next (token, tag)-tuples.
"""
return [token[0], self._classifier.classify(self._v(token[0], previous, next))] | [
"def",
"apply",
"(",
"self",
",",
"token",
",",
"previous",
"=",
"(",
"None",
",",
"None",
")",
",",
"next",
"=",
"(",
"None",
",",
"None",
")",
")",
":",
"return",
"[",
"token",
"[",
"0",
"]",
",",
"self",
".",
"_classifier",
".",
"classify",
... | 59.6 | 21.2 |
def add_filters(self, filterer, filters):
"""Add filters to a filterer from a list of names."""
for f in filters:
try:
filterer.addFilter(self.config['filters'][f])
except StandardError as e:
raise ValueError('Unable to add filter %r: %s' % (f, e)) | [
"def",
"add_filters",
"(",
"self",
",",
"filterer",
",",
"filters",
")",
":",
"for",
"f",
"in",
"filters",
":",
"try",
":",
"filterer",
".",
"addFilter",
"(",
"self",
".",
"config",
"[",
"'filters'",
"]",
"[",
"f",
"]",
")",
"except",
"StandardError",
... | 44.857143 | 13.571429 |
def save_matches(self, matches):
"""Save matches of a failed execution to the log.
:param matches: a list of matches in JSON format
"""
if not os.path.exists(os.path.dirname(self.location())):
os.makedirs(os.path.dirname(self.location()))
with open(self.location(), ... | [
"def",
"save_matches",
"(",
"self",
",",
"matches",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"location",
"(",
")",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"... | 38.307692 | 14.461538 |
def _perform_file_action(self, filename, action):
"""Perform action on specific file types.
Dynamic dispatch function for performing actions on
specific file types.
"""
ext = os.path.splitext(filename)[1]
try:
func = getattr(self, '_{}_{}'.format(action, ext[... | [
"def",
"_perform_file_action",
"(",
"self",
",",
"filename",
",",
"action",
")",
":",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
"try",
":",
"func",
"=",
"getattr",
"(",
"self",
",",
"'_{}_{}'",
".",
"format"... | 36.666667 | 16.333333 |
def retrieve(self, key):
"""Retrieves a cached array if possible."""
column_file = os.path.join(self._hash_dir, '%s.json' % key)
cache_file = os.path.join(self._hash_dir, '%s.npy' % key)
if os.path.exists(cache_file):
data = np.load(cache_file)
if os.path.exists(... | [
"def",
"retrieve",
"(",
"self",
",",
"key",
")",
":",
"column_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_hash_dir",
",",
"'%s.json'",
"%",
"key",
")",
"cache_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_hash_... | 36.4 | 17.666667 |
def play(self):
"""
Keep only times in ScienceSegments which are in the playground
"""
length = len(self)
# initialize list of output segments
ostart = -1
outlist = []
begin_s2 = 729273613
play_space = 6370
play_len = 600
for seg in self:
start = seg.start()
st... | [
"def",
"play",
"(",
"self",
")",
":",
"length",
"=",
"len",
"(",
"self",
")",
"# initialize list of output segments",
"ostart",
"=",
"-",
"1",
"outlist",
"=",
"[",
"]",
"begin_s2",
"=",
"729273613",
"play_space",
"=",
"6370",
"play_len",
"=",
"600",
"for",... | 22.217391 | 21.521739 |
def metricCompute(self, sensorToBody, bodyToSpecificObject):
"""
Compute the
"sensor's location relative to a specific object"
from the
"body's location relative to a specific object"
and the
"sensor's location relative to body"
@param sensorToBody (numpy array)
Active cells o... | [
"def",
"metricCompute",
"(",
"self",
",",
"sensorToBody",
",",
"bodyToSpecificObject",
")",
":",
"overlaps",
"=",
"self",
".",
"metricConnections",
".",
"computeActivity",
"(",
"{",
"\"bodyToSpecificObject\"",
":",
"bodyToSpecificObject",
",",
"\"sensorToBody\"",
":",... | 33.307692 | 18 |
def _assign_enterprise_role_to_users(self, _get_batch_method, options, is_feature_role=False):
"""
Assigns enterprise role to users.
"""
role_name = options['role']
batch_limit = options['batch_limit']
batch_sleep = options['batch_sleep']
batch_offset = options['b... | [
"def",
"_assign_enterprise_role_to_users",
"(",
"self",
",",
"_get_batch_method",
",",
"options",
",",
"is_feature_role",
"=",
"False",
")",
":",
"role_name",
"=",
"options",
"[",
"'role'",
"]",
"batch_limit",
"=",
"options",
"[",
"'batch_limit'",
"]",
"batch_slee... | 34.829268 | 16.585366 |
def _struct_or_lob_handler(c, ctx):
"""Handles tokens that begin with an open brace."""
assert c == _OPEN_BRACE
c, self = yield
yield ctx.immediate_transition(_STRUCT_OR_LOB_TABLE[c](c, ctx)) | [
"def",
"_struct_or_lob_handler",
"(",
"c",
",",
"ctx",
")",
":",
"assert",
"c",
"==",
"_OPEN_BRACE",
"c",
",",
"self",
"=",
"yield",
"yield",
"ctx",
".",
"immediate_transition",
"(",
"_STRUCT_OR_LOB_TABLE",
"[",
"c",
"]",
"(",
"c",
",",
"ctx",
")",
")"
] | 40.6 | 13.2 |
def deep_get(self, content, keys, traversed_path=None):
'''
Allow to retrieve content nested inside a several layers deep dict/list
Examples: -content: {
"key1": {
"key2" : [
{
... | [
"def",
"deep_get",
"(",
"self",
",",
"content",
",",
"keys",
",",
"traversed_path",
"=",
"None",
")",
":",
"if",
"traversed_path",
"is",
"None",
":",
"traversed_path",
"=",
"[",
"]",
"if",
"keys",
"==",
"[",
"]",
":",
"return",
"[",
"(",
"traversed_pat... | 39.875 | 19.625 |
def update(self, deviceUid, metadata=None, deviceInfo=None, status=None):
"""
Update an existing device
"""
if not isinstance(deviceUid, DeviceUid) and isinstance(deviceUid, dict):
deviceUid = DeviceUid(**deviceUid)
deviceUrl = "api/v0002/device/types/%s/devices/%s"... | [
"def",
"update",
"(",
"self",
",",
"deviceUid",
",",
"metadata",
"=",
"None",
",",
"deviceInfo",
"=",
"None",
",",
"status",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"deviceUid",
",",
"DeviceUid",
")",
"and",
"isinstance",
"(",
"deviceUid",... | 36.705882 | 24.705882 |
def _gradient_black_lines(
self, text, start, step=1,
fore=None, back=None, style=None, reverse=False,
movefactor=2, rgb_mode=False):
""" Yield colorized characters,
within the 24-length black gradient,
treating each line separately.
"""
... | [
"def",
"_gradient_black_lines",
"(",
"self",
",",
"text",
",",
"start",
",",
"step",
"=",
"1",
",",
"fore",
"=",
"None",
",",
"back",
"=",
"None",
",",
"style",
"=",
"None",
",",
"reverse",
"=",
"False",
",",
"movefactor",
"=",
"2",
",",
"rgb_mode",
... | 31.642857 | 11.642857 |
def add_simmanager_api(self, mock):
'''Add org.ofono.SimManager API to a mock'''
iface = 'org.ofono.SimManager'
mock.AddProperties(iface, {
'BarredDialing': _parameters.get('BarredDialing', False),
'CardIdentifier': _parameters.get('CardIdentifier', new_iccid(self)),
'FixedDialing':... | [
"def",
"add_simmanager_api",
"(",
"self",
",",
"mock",
")",
":",
"iface",
"=",
"'org.ofono.SimManager'",
"mock",
".",
"AddProperties",
"(",
"iface",
",",
"{",
"'BarredDialing'",
":",
"_parameters",
".",
"get",
"(",
"'BarredDialing'",
",",
"False",
")",
",",
... | 49.233333 | 25.033333 |
def get_location(self, ip, detailed=False):
"""Returns a dictionary with location data or False on failure.
Amount of information about IP contained in the dictionary depends
upon `detailed` flag state.
"""
seek = self._get_pos(ip)
if seek > 0:
return self.... | [
"def",
"get_location",
"(",
"self",
",",
"ip",
",",
"detailed",
"=",
"False",
")",
":",
"seek",
"=",
"self",
".",
"_get_pos",
"(",
"ip",
")",
"if",
"seek",
">",
"0",
":",
"return",
"self",
".",
"_parse_location",
"(",
"seek",
",",
"detailed",
"=",
... | 28.461538 | 21.076923 |
def parsedate(data):
"""Convert a time string to a time tuple."""
t = parsedate_tz(data)
if isinstance(t, tuple):
return t[:9]
else:
return t | [
"def",
"parsedate",
"(",
"data",
")",
":",
"t",
"=",
"parsedate_tz",
"(",
"data",
")",
"if",
"isinstance",
"(",
"t",
",",
"tuple",
")",
":",
"return",
"t",
"[",
":",
"9",
"]",
"else",
":",
"return",
"t"
] | 23.857143 | 17.285714 |
def get_rsa_props(
object_class,
exported_cfgs,
remote_intents=None,
ep_svc_id=None,
fw_id=None,
pkg_vers=None,
service_intents=None,
):
"""
Constructs a dictionary of RSA properties from the given arguments
:param object_class: Service specifications
:param exported_cfgs: E... | [
"def",
"get_rsa_props",
"(",
"object_class",
",",
"exported_cfgs",
",",
"remote_intents",
"=",
"None",
",",
"ep_svc_id",
"=",
"None",
",",
"fw_id",
"=",
"None",
",",
"pkg_vers",
"=",
"None",
",",
"service_intents",
"=",
"None",
",",
")",
":",
"results",
"=... | 32.566038 | 14.339623 |
def _futureExceptions(self, request):
"""
Returns all future extra info, cancellations and postponements created
for this recurring event
"""
retval = []
# We know all future exception dates are in the parent time zone
myToday = timezone.localdate(timezone=self.tz... | [
"def",
"_futureExceptions",
"(",
"self",
",",
"request",
")",
":",
"retval",
"=",
"[",
"]",
"# We know all future exception dates are in the parent time zone",
"myToday",
"=",
"timezone",
".",
"localdate",
"(",
"timezone",
"=",
"self",
".",
"tz",
")",
"for",
"extr... | 44.636364 | 19.090909 |
def get_filename(disposition):
"""Parse Content-Disposition header to pull out the filename bit.
See: http://tools.ietf.org/html/rfc2616#section-19.5.1
"""
if disposition:
params = [param.strip() for param in disposition.split(';')[1:]]
for param in params:
if '=' in param:... | [
"def",
"get_filename",
"(",
"disposition",
")",
":",
"if",
"disposition",
":",
"params",
"=",
"[",
"param",
".",
"strip",
"(",
")",
"for",
"param",
"in",
"disposition",
".",
"split",
"(",
"';'",
")",
"[",
"1",
":",
"]",
"]",
"for",
"param",
"in",
"... | 33.923077 | 15.307692 |
def copy(self, *args, **kwargs):
"""
Make a copy of this object.
See Also:
For arguments and description of behavior see `pandas docs`_.
.. _pandas docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.copy.html
"""
cls = self.__class__ ... | [
"def",
"copy",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"# Note that type conversion does not perform copy",
"return",
"cls",
"(",
"pd",
".",
"DataFrame",
"(",
"self",
")",
".",
"copy",
"(",
... | 38.363636 | 24.727273 |
def _set_shortcut_ownership(path, user):
'''
Set the ownership of a shortcut and return a boolean indicating
success/failure
'''
try:
__salt__['file.lchown'](path, user)
except OSError:
pass
return _check_shortcut_ownership(path, user) | [
"def",
"_set_shortcut_ownership",
"(",
"path",
",",
"user",
")",
":",
"try",
":",
"__salt__",
"[",
"'file.lchown'",
"]",
"(",
"path",
",",
"user",
")",
"except",
"OSError",
":",
"pass",
"return",
"_check_shortcut_ownership",
"(",
"path",
",",
"user",
")"
] | 27 | 20.6 |
def build_is_last_day_of_season(num_steps_per_season):
"""Build utility method to compute whether the season is changing."""
num_steps_per_cycle = np.sum(num_steps_per_season)
changepoints = np.cumsum(np.ravel(num_steps_per_season)) - 1
def is_last_day_of_season(t):
t_ = dist_util.maybe_get_static_value(t)
... | [
"def",
"build_is_last_day_of_season",
"(",
"num_steps_per_season",
")",
":",
"num_steps_per_cycle",
"=",
"np",
".",
"sum",
"(",
"num_steps_per_season",
")",
"changepoints",
"=",
"np",
".",
"cumsum",
"(",
"np",
".",
"ravel",
"(",
"num_steps_per_season",
")",
")",
... | 45.214286 | 12.428571 |
def printInvoice(self, REQUEST=None, RESPONSE=None):
"""Print invoice
"""
invoice = self.getInvoice()
invoice_url = invoice.absolute_url()
RESPONSE.redirect('{}/invoice_print'.format(invoice_url)) | [
"def",
"printInvoice",
"(",
"self",
",",
"REQUEST",
"=",
"None",
",",
"RESPONSE",
"=",
"None",
")",
":",
"invoice",
"=",
"self",
".",
"getInvoice",
"(",
")",
"invoice_url",
"=",
"invoice",
".",
"absolute_url",
"(",
")",
"RESPONSE",
".",
"redirect",
"(",
... | 38.5 | 7.666667 |
def set_character_set(self, charset):
"""Set the connection character set to charset. The character
set can only be changed in MySQL-4.1 and newer. If you try
to change the character set from the current value in an
older version, NotSupportedError will be raised."""
if charset i... | [
"def",
"set_character_set",
"(",
"self",
",",
"charset",
")",
":",
"if",
"charset",
"in",
"(",
"\"utf8mb4\"",
",",
"\"utf8mb3\"",
")",
":",
"py_charset",
"=",
"\"utf8\"",
"else",
":",
"py_charset",
"=",
"charset",
"if",
"self",
".",
"character_set_name",
"("... | 46.055556 | 13.166667 |
def get_dimension(data):
"""
Get dimension of the data passed by argument independently if it's an
arrays or dictionaries
"""
result = [0, 0]
if isinstance(data, list):
result = get_dimension_array(data)
elif isinstance(data, dict):
result = get_dimension_dict(data)
re... | [
"def",
"get_dimension",
"(",
"data",
")",
":",
"result",
"=",
"[",
"0",
",",
"0",
"]",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"result",
"=",
"get_dimension_array",
"(",
"data",
")",
"elif",
"isinstance",
"(",
"data",
",",
"dict",
")"... | 22.714286 | 17.714286 |
def map_to_subset(self, file, outfile=None, ontology=None, subset=None, class_map=None, relations=None):
"""
Map a file to a subset, writing out results
You can pass either a subset name (e.g. goslim_generic) or a dictionary with ready-made mappings
Arguments
---------
... | [
"def",
"map_to_subset",
"(",
"self",
",",
"file",
",",
"outfile",
"=",
"None",
",",
"ontology",
"=",
"None",
",",
"subset",
"=",
"None",
",",
"class_map",
"=",
"None",
",",
"relations",
"=",
"None",
")",
":",
"if",
"subset",
"is",
"not",
"None",
":",... | 40.104167 | 20.729167 |
def prune(t):
"""Returns the currently defining instance of t.
As a side effect, collapses the list of type instances. The function Prune
is used whenever a type expression has to be inspected: it will always
return a type expression which is either an uninstantiated type variable or
a type operato... | [
"def",
"prune",
"(",
"t",
")",
":",
"if",
"isinstance",
"(",
"t",
",",
"TypeVariable",
")",
":",
"if",
"t",
".",
"instance",
"is",
"not",
"None",
":",
"t",
".",
"instance",
"=",
"prune",
"(",
"t",
".",
"instance",
")",
"return",
"t",
".",
"instan... | 34.619048 | 23.238095 |
def input_fields(self, preamble, *args):
"""Get a set of fields from the user. Optionally a preamble may be
shown to the user secribing the fields to return. The fields are
specified as the remaining arguments with each field being a a
list with the following entries:
- a pr... | [
"def",
"input_fields",
"(",
"self",
",",
"preamble",
",",
"*",
"args",
")",
":",
"self",
".",
"new_section",
"(",
")",
"if",
"preamble",
"is",
"not",
"None",
":",
"self",
".",
"message",
"(",
"preamble",
")",
"if",
"any",
"(",
"[",
"True",
"for",
"... | 39.66 | 19.86 |
def DbGetClassAttributeList(self, argin):
""" Get attrilute list for a given Tango class with a specified filter
:param argin: Str[0] = Tango class name
Str[1] = Attribute name filter (eg: att*)
:type: tango.DevVarStringArray
:return: Str[0] = Class attribute name
Str[n]... | [
"def",
"DbGetClassAttributeList",
"(",
"self",
",",
"argin",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"In DbGetClassAttributeList()\"",
")",
"class_name",
"=",
"argin",
"[",
"0",
"]",
"wildcard",
"=",
"replace_wildcard",
"(",
"argin",
"[",
"1",
"]... | 44.384615 | 9.846154 |
def location_path(self, path):
"""
Set the Location-Path of the response.
:type path: String
:param path: the Location-Path as a string
"""
path = path.strip("/")
tmp = path.split("?")
path = tmp[0]
paths = path.split("/")
for p in paths:
... | [
"def",
"location_path",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"path",
".",
"strip",
"(",
"\"/\"",
")",
"tmp",
"=",
"path",
".",
"split",
"(",
"\"?\"",
")",
"path",
"=",
"tmp",
"[",
"0",
"]",
"paths",
"=",
"path",
".",
"split",
"(",
"... | 29.4375 | 12.8125 |
def _beaglebone_id(self):
"""Try to detect id of a Beaglebone."""
try:
with open("/sys/bus/nvmem/devices/0-00500/nvmem", "rb") as eeprom:
eeprom_bytes = eeprom.read(16)
except FileNotFoundError:
return None
if eeprom_bytes[:4] != b'\xaaU3\xee':
... | [
"def",
"_beaglebone_id",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"\"/sys/bus/nvmem/devices/0-00500/nvmem\"",
",",
"\"rb\"",
")",
"as",
"eeprom",
":",
"eeprom_bytes",
"=",
"eeprom",
".",
"read",
"(",
"16",
")",
"except",
"FileNotFoundError",
":"... | 31.5 | 17.888889 |
def label_image(
self,
parent,
basic_config,
feature,
image_classification_config=None,
bounding_poly_config=None,
polyline_config=None,
segmentation_config=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_... | [
"def",
"label_image",
"(",
"self",
",",
"parent",
",",
"basic_config",
",",
"feature",
",",
"image_classification_config",
"=",
"None",
",",
"bounding_poly_config",
"=",
"None",
",",
"polyline_config",
"=",
"None",
",",
"segmentation_config",
"=",
"None",
",",
"... | 48.236111 | 28 |
def send_root_file(self, filename):
"""
Function used to send static files from the root of the domain.
"""
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(self.config['ROOT_FOLDER'], filename,
cache_timeout=cache... | [
"def",
"send_root_file",
"(",
"self",
",",
"filename",
")",
":",
"cache_timeout",
"=",
"self",
".",
"get_send_file_max_age",
"(",
"filename",
")",
"return",
"send_from_directory",
"(",
"self",
".",
"config",
"[",
"'ROOT_FOLDER'",
"]",
",",
"filename",
",",
"ca... | 46.142857 | 15.857143 |
def GetTemplates(alias=None,location=None):
"""Gets the list of Templates available to the account and location.
https://t3n.zendesk.com/entries/23102683-List-Available-Server-Templates
:param alias: short code for a particular account. If none will use account's default alias
:param location: datacenter whe... | [
"def",
"GetTemplates",
"(",
"alias",
"=",
"None",
",",
"location",
"=",
"None",
")",
":",
"if",
"alias",
"is",
"None",
":",
"alias",
"=",
"clc",
".",
"v1",
".",
"Account",
".",
"GetAlias",
"(",
")",
"if",
"location",
"is",
"None",
":",
"location",
... | 45.615385 | 26.923077 |
def set_credentials(self, username, password=None, region=None,
tenant_id=None, authenticate=False):
"""
Sets the username and password directly. Because Rackspace auth uses
the api_key, make sure that any old values are cleared.
"""
self.api_key = None
super(... | [
"def",
"set_credentials",
"(",
"self",
",",
"username",
",",
"password",
"=",
"None",
",",
"region",
"=",
"None",
",",
"tenant_id",
"=",
"None",
",",
"authenticate",
"=",
"False",
")",
":",
"self",
".",
"api_key",
"=",
"None",
"super",
"(",
"RaxIdentity"... | 50.444444 | 19.777778 |
def write_wav(self, filename):
"""Write this sample to a WAV file.
:param filename: the file to which to write
"""
wave_output = None
try:
wave_output = wave.open(filename, 'w')
wave_output.setparams(WAVE_PARAMS)
frames = bytearray([x << 4 ... | [
"def",
"write_wav",
"(",
"self",
",",
"filename",
")",
":",
"wave_output",
"=",
"None",
"try",
":",
"wave_output",
"=",
"wave",
".",
"open",
"(",
"filename",
",",
"'w'",
")",
"wave_output",
".",
"setparams",
"(",
"WAVE_PARAMS",
")",
"frames",
"=",
"bytea... | 26 | 18.777778 |
def _parse_indices(self, indices):
r"""
This private method accepts a list of pores or throats and returns a
properly structured Numpy array of indices.
Parameters
----------
indices : multiple options
This argument can accept numerous different data types in... | [
"def",
"_parse_indices",
"(",
"self",
",",
"indices",
")",
":",
"if",
"indices",
"is",
"None",
":",
"indices",
"=",
"sp",
".",
"array",
"(",
"[",
"]",
",",
"ndmin",
"=",
"1",
",",
"dtype",
"=",
"int",
")",
"locs",
"=",
"sp",
".",
"array",
"(",
... | 33.676471 | 16.823529 |
def log_x_cb(self, w, val):
"""Toggle linear/log scale for X-axis."""
self.tab_plot.logx = val
self.plot_two_columns() | [
"def",
"log_x_cb",
"(",
"self",
",",
"w",
",",
"val",
")",
":",
"self",
".",
"tab_plot",
".",
"logx",
"=",
"val",
"self",
".",
"plot_two_columns",
"(",
")"
] | 34.75 | 7.5 |
def updateFile(cls, file_, url):
"""Check and update file compares with remote_url
Args:
file_: str. Local filename. Normally it's __file__
url: str. Remote url of raw file content. Normally it's https://raw.github.com/...
Returns:
bool: file updated or not
... | [
"def",
"updateFile",
"(",
"cls",
",",
"file_",
",",
"url",
")",
":",
"def",
"compare",
"(",
"s1",
",",
"s2",
")",
":",
"return",
"s1",
"==",
"s2",
",",
"len",
"(",
"s2",
")",
"-",
"len",
"(",
"s1",
")",
"if",
"not",
"url",
"or",
"not",
"file_... | 38.083333 | 16.527778 |
def skycoord_to_pixel_scale_angle(skycoord, wcs, small_offset=1 * u.arcsec):
"""
Convert a set of SkyCoord coordinates into pixel coordinates, pixel
scales, and position angles.
Parameters
----------
skycoord : `~astropy.coordinates.SkyCoord`
Sky coordinates
wcs : `~astropy.wcs.WCS`... | [
"def",
"skycoord_to_pixel_scale_angle",
"(",
"skycoord",
",",
"wcs",
",",
"small_offset",
"=",
"1",
"*",
"u",
".",
"arcsec",
")",
":",
"# Convert to pixel coordinates",
"x",
",",
"y",
"=",
"skycoord_to_pixel",
"(",
"skycoord",
",",
"wcs",
",",
"mode",
"=",
"... | 33.578947 | 21.894737 |
def exec_scratch_virtualenv(args):
"""
goals:
- get any random site-packages off of the pythonpath
- ensure we can import virtualenv
- ensure that we're not using the interpreter that we may need to delete
- idempotency: do nothing if the above goals are already met
"""
s... | [
"def",
"exec_scratch_virtualenv",
"(",
"args",
")",
":",
"scratch",
"=",
"Scratch",
"(",
")",
"if",
"not",
"exists",
"(",
"scratch",
".",
"python",
")",
":",
"run",
"(",
"(",
"'virtualenv'",
",",
"scratch",
".",
"venv",
")",
")",
"if",
"not",
"exists",... | 41.483871 | 22.258065 |
def set_entries(self, entries, user_scope):
"""SetEntries.
[Preview API] Set the specified setting entry values for the given user/all-users scope
:param {object} entries: The entries to set
:param str user_scope: User-Scope at which to set the values. Should be "me" for the current user... | [
"def",
"set_entries",
"(",
"self",
",",
"entries",
",",
"user_scope",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"user_scope",
"is",
"not",
"None",
":",
"route_values",
"[",
"'userScope'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'user_... | 52.933333 | 19.666667 |
def select_inputs(self, address: str, amount: int) -> dict:
'''finds apropriate utxo's to include in rawtx, while being careful
to never spend old transactions with a lot of coin age.
Argument is intiger, returns list of apropriate UTXO's'''
utxos = []
utxo_sum = Decimal(0)
... | [
"def",
"select_inputs",
"(",
"self",
",",
"address",
":",
"str",
",",
"amount",
":",
"int",
")",
"->",
"dict",
":",
"utxos",
"=",
"[",
"]",
"utxo_sum",
"=",
"Decimal",
"(",
"0",
")",
"for",
"tx",
"in",
"sorted",
"(",
"self",
".",
"listunspent",
"("... | 41.111111 | 24.148148 |
def runUAT(self, args):
"""
Runs the Unreal Automation Tool with the supplied arguments
"""
Utility.run([self.getRunUATScript()] + args, cwd=self.getEngineRoot(), raiseOnError=True) | [
"def",
"runUAT",
"(",
"self",
",",
"args",
")",
":",
"Utility",
".",
"run",
"(",
"[",
"self",
".",
"getRunUATScript",
"(",
")",
"]",
"+",
"args",
",",
"cwd",
"=",
"self",
".",
"getEngineRoot",
"(",
")",
",",
"raiseOnError",
"=",
"True",
")"
] | 37 | 17.8 |
def flower(port, address):
"""Runs a Celery Flower web server
Celery Flower is a UI to monitor the Celery operation on a given
broker"""
BROKER_URL = celery_app.conf.BROKER_URL
cmd = (
'celery flower '
f'--broker={BROKER_URL} '
f'--port={port} '
f'--address={address}... | [
"def",
"flower",
"(",
"port",
",",
"address",
")",
":",
"BROKER_URL",
"=",
"celery_app",
".",
"conf",
".",
"BROKER_URL",
"cmd",
"=",
"(",
"'celery flower '",
"f'--broker={BROKER_URL} '",
"f'--port={port} '",
"f'--address={address} '",
")",
"logging",
".",
"info",
... | 31.55 | 15.8 |
def create_convert_sbml_id_function(
compartment_prefix='C_', reaction_prefix='R_',
compound_prefix='M_', decode_id=entry_id_from_cobra_encoding):
"""Create function for converting SBML IDs.
The returned function will strip prefixes, decode the ID using the provided
function. These prefixes... | [
"def",
"create_convert_sbml_id_function",
"(",
"compartment_prefix",
"=",
"'C_'",
",",
"reaction_prefix",
"=",
"'R_'",
",",
"compound_prefix",
"=",
"'M_'",
",",
"decode_id",
"=",
"entry_id_from_cobra_encoding",
")",
":",
"def",
"convert_sbml_id",
"(",
"entry",
")",
... | 36.076923 | 16.153846 |
def export_configuration_generator(self, sql, sql_args):
"""
Generator for :class:`meteorpi_model.ExportConfiguration`
:param sql:
A SQL statement which must return rows describing export configurations
:param sql_args:
Any variables required to populate the quer... | [
"def",
"export_configuration_generator",
"(",
"self",
",",
"sql",
",",
"sql_args",
")",
":",
"self",
".",
"con",
".",
"execute",
"(",
"sql",
",",
"sql_args",
")",
"results",
"=",
"self",
".",
"con",
".",
"fetchall",
"(",
")",
"output",
"=",
"[",
"]",
... | 50.066667 | 29.8 |
def _ordered_struct_start_handler(handler, ctx):
"""Handles the special case of ordered structs, specified by the type ID 0xD1.
This coroutine's only purpose is to ensure that the struct in question declares at least one field name/value pair,
as required by the spec.
"""
_, self = yield
self_h... | [
"def",
"_ordered_struct_start_handler",
"(",
"handler",
",",
"ctx",
")",
":",
"_",
",",
"self",
"=",
"yield",
"self_handler",
"=",
"_create_delegate_handler",
"(",
"self",
")",
"(",
"length",
",",
"_",
")",
",",
"_",
"=",
"yield",
"ctx",
".",
"immediate_tr... | 50.133333 | 26.866667 |
def format(self, model: AssetAllocationModel, full: bool = False):
""" Returns the view-friendly output of the aa model """
self.full = full
# Header
output = f"Asset Allocation model, total: {model.currency} {model.total_amount:,.2f}\n"
# Column Headers
for column in s... | [
"def",
"format",
"(",
"self",
",",
"model",
":",
"AssetAllocationModel",
",",
"full",
":",
"bool",
"=",
"False",
")",
":",
"self",
".",
"full",
"=",
"full",
"# Header",
"output",
"=",
"f\"Asset Allocation model, total: {model.currency} {model.total_amount:,.2f}\\n\"",... | 35.36 | 22.64 |
def get(self, request, bot_id, id, format=None):
"""
Get list of header parameters of a handler
---
serializer: AbsParamSerializer
responseMessages:
- code: 401
message: Not authenticated
"""
return super(HeaderParameterList, self).get(re... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
"=",
"None",
")",
":",
"return",
"super",
"(",
"HeaderParameterList",
",",
"self",
")",
".",
"get",
"(",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
")"
] | 33.7 | 12.1 |
def tcp_traceflow(packet, timestamp, *, data_link, count=NotImplemented):
"""Trace packet flow for TCP."""
if getattr(packet, 'ip', None):
ip = packet['ip']
elif getattr(packet, 'ip6', None):
ip = packet['ip6']
else:
return False, None
tcp = getattr(ip, 'tcp', None)
if tc... | [
"def",
"tcp_traceflow",
"(",
"packet",
",",
"timestamp",
",",
"*",
",",
"data_link",
",",
"count",
"=",
"NotImplemented",
")",
":",
"if",
"getattr",
"(",
"packet",
",",
"'ip'",
",",
"None",
")",
":",
"ip",
"=",
"packet",
"[",
"'ip'",
"]",
"elif",
"ge... | 54.36 | 29.56 |
def update_ip_address(context, id, ip_address):
"""Due to NCP-1592 ensure that address_type cannot change after update."""
LOG.info("update_ip_address %s for tenant %s" % (id, context.tenant_id))
ports = []
if 'ip_address' not in ip_address:
raise n_exc.BadRequest(resource="ip_addresses",
... | [
"def",
"update_ip_address",
"(",
"context",
",",
"id",
",",
"ip_address",
")",
":",
"LOG",
".",
"info",
"(",
"\"update_ip_address %s for tenant %s\"",
"%",
"(",
"id",
",",
"context",
".",
"tenant_id",
")",
")",
"ports",
"=",
"[",
"]",
"if",
"'ip_address'",
... | 49.640449 | 21.977528 |
def rem2ics():
"""Command line tool to convert from Remind to iCalendar"""
# pylint: disable=maybe-no-member
from argparse import ArgumentParser, FileType
from dateutil.parser import parse
from sys import stdin, stdout
parser = ArgumentParser(description='Converter from Remind to iCalendar synt... | [
"def",
"rem2ics",
"(",
")",
":",
"# pylint: disable=maybe-no-member",
"from",
"argparse",
"import",
"ArgumentParser",
",",
"FileType",
"from",
"dateutil",
".",
"parser",
"import",
"parse",
"from",
"sys",
"import",
"stdin",
",",
"stdout",
"parser",
"=",
"ArgumentPa... | 54.909091 | 28.515152 |
def end_of_directory(self, succeeded=True, update_listing=False,
cache_to_disc=True):
'''Wrapper for xbmcplugin.endOfDirectory. Records state in
self._end_of_directory.
Typically it is not necessary to call this method directly, as
calling :meth:`~xbmcswift2.Plu... | [
"def",
"end_of_directory",
"(",
"self",
",",
"succeeded",
"=",
"True",
",",
"update_listing",
"=",
"False",
",",
"cache_to_disc",
"=",
"True",
")",
":",
"self",
".",
"_update_listing",
"=",
"update_listing",
"if",
"not",
"self",
".",
"_end_of_directory",
":",
... | 48.133333 | 18.8 |
def relative_probability( self, l1, l2, c1, c2 ):
"""
The relative probability for a jump between two sites with specific site types and coordination numbers.
Args:
l1 (Str): Site label for the initial site.
l2 (Str): Site label for the final site.
c1 (Int): ... | [
"def",
"relative_probability",
"(",
"self",
",",
"l1",
",",
"l2",
",",
"c1",
",",
"c2",
")",
":",
"if",
"self",
".",
"site_energies",
":",
"site_delta_E",
"=",
"self",
".",
"site_energies",
"[",
"l2",
"]",
"-",
"self",
".",
"site_energies",
"[",
"l1",
... | 42.809524 | 23.571429 |
def _normalize_images(self):
"""
normalizes image filenames by prepending 'File:' if needed
"""
if 'image' not in self.data:
return
for img in self.data['image']:
fname = img['file'].replace('_', ' ')
fstart = fname.startswith('File:')
... | [
"def",
"_normalize_images",
"(",
"self",
")",
":",
"if",
"'image'",
"not",
"in",
"self",
".",
"data",
":",
"return",
"for",
"img",
"in",
"self",
".",
"data",
"[",
"'image'",
"]",
":",
"fname",
"=",
"img",
"[",
"'file'",
"]",
".",
"replace",
"(",
"'... | 36.142857 | 6.857143 |
def update_recommender(ctx, weeks, processes):
"""
Download and build the recommendations.
- Fetch new statistics from the current week.
- Generate recommendations.
- Update the recommendations.
"""
weeks = get_last_weeks(weeks)
recommender = RecordRecommender(config)
# Redownload i... | [
"def",
"update_recommender",
"(",
"ctx",
",",
"weeks",
",",
"processes",
")",
":",
"weeks",
"=",
"get_last_weeks",
"(",
"weeks",
")",
"recommender",
"=",
"RecordRecommender",
"(",
"config",
")",
"# Redownload incomplete weeks",
"first_weeks",
"=",
"weeks",
"[",
... | 30 | 11.619048 |
def _read_configuration(config_filename):
"""
Checks the supplement file.
:param str config_filename: The name of the configuration file.
:rtype: (configparser.ConfigParser,configparser.ConfigParser)
"""
config = ConfigParser()
config.read(config_filename)
... | [
"def",
"_read_configuration",
"(",
"config_filename",
")",
":",
"config",
"=",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"config_filename",
")",
"if",
"'supplement'",
"in",
"config",
"[",
"'database'",
"]",
":",
"path",
"=",
"os",
".",
"path",
... | 32.736842 | 17.789474 |
def regenerate(location='http://www.iana.org/assignments/language-subtag-registry',
filename=None, default_encoding='utf-8'):
"""
Generate the languages Python module.
"""
paren = re.compile('\([^)]*\)')
# Get the language list.
data = urllib2.urlopen(location)
if ('content-t... | [
"def",
"regenerate",
"(",
"location",
"=",
"'http://www.iana.org/assignments/language-subtag-registry'",
",",
"filename",
"=",
"None",
",",
"default_encoding",
"=",
"'utf-8'",
")",
":",
"paren",
"=",
"re",
".",
"compile",
"(",
"'\\([^)]*\\)'",
")",
"# Get the language... | 36.780488 | 19.609756 |
def create_colormap(palette):
"""Create colormap of the given numpy file, color vector or colormap."""
from trollimage.colormap import Colormap
fname = palette.get('filename', None)
if fname:
data = np.load(fname)
cmap = []
num = 1.0 * data.shape[0]
for i in range(int(num... | [
"def",
"create_colormap",
"(",
"palette",
")",
":",
"from",
"trollimage",
".",
"colormap",
"import",
"Colormap",
"fname",
"=",
"palette",
".",
"get",
"(",
"'filename'",
",",
"None",
")",
"if",
"fname",
":",
"data",
"=",
"np",
".",
"load",
"(",
"fname",
... | 32.451613 | 14.451613 |
def fuzzy_search(self, *filters):
"""
Perform a "fuzzy" search that matches the given characters in the given order.
:param filters: The pattern(s) to search for.
:returns: The matched password names (a list of strings).
"""
matches = []
logger.verbose(
... | [
"def",
"fuzzy_search",
"(",
"self",
",",
"*",
"filters",
")",
":",
"matches",
"=",
"[",
"]",
"logger",
".",
"verbose",
"(",
"\"Performing fuzzy search on %s (%s) ..\"",
",",
"pluralize",
"(",
"len",
"(",
"filters",
")",
",",
"\"pattern\"",
")",
",",
"concate... | 39.47619 | 20.142857 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.