text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def read_metadata(self): # type: () ->Dict[str,str]
"""
Get version out of a .ini file (or .cfg)
:return:
"""
config = configparser.ConfigParser()
config.read(self.file_inventory.config_files[0])
try:
return {"setup.cfg": config["metadata"]["version"]... | [
"def",
"read_metadata",
"(",
"self",
")",
":",
"# type: () ->Dict[str,str]",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"self",
".",
"file_inventory",
".",
"config_files",
"[",
"0",
"]",
")",
"try",
":",
"return... | 32.545455 | 13.636364 |
def log_analytics(self):
"""Instance depends on the API version:
* 2017-12-01: :class:`LogAnalyticsOperations<azure.mgmt.compute.v2017_12_01.operations.LogAnalyticsOperations>`
* 2018-04-01: :class:`LogAnalyticsOperations<azure.mgmt.compute.v2018_04_01.operations.LogAnalyticsOperations>`
... | [
"def",
"log_analytics",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'log_analytics'",
")",
"if",
"api_version",
"==",
"'2017-12-01'",
":",
"from",
".",
"v2017_12_01",
".",
"operations",
"import",
"LogAnalyticsOperations",
"as"... | 71.521739 | 39.782609 |
def right_click(self, x, y, n=1, pre_dl=None, post_dl=None):
"""Right click at ``(x, y)`` on screen for ``n`` times.
at begin.
**中文文档**
在屏幕的 ``(x, y)`` 坐标处右键单击 ``n`` 次。
"""
self.delay(pre_dl)
self.m.click(x, y, 2, n)
self.delay(post_dl) | [
"def",
"right_click",
"(",
"self",
",",
"x",
",",
"y",
",",
"n",
"=",
"1",
",",
"pre_dl",
"=",
"None",
",",
"post_dl",
"=",
"None",
")",
":",
"self",
".",
"delay",
"(",
"pre_dl",
")",
"self",
".",
"m",
".",
"click",
"(",
"x",
",",
"y",
",",
... | 26.545455 | 16.545455 |
def find_a_system_python(line):
"""Find a Python installation from a given line.
This tries to parse the line in various of ways:
* Looks like an absolute path? Use it directly.
* Looks like a py.exe call? Use py.exe to get the executable.
* Starts with "py" something? Looks like a python command.... | [
"def",
"find_a_system_python",
"(",
"line",
")",
":",
"from",
".",
"vendor",
".",
"pythonfinder",
"import",
"Finder",
"finder",
"=",
"Finder",
"(",
"system",
"=",
"False",
",",
"global_search",
"=",
"True",
")",
"if",
"not",
"line",
":",
"return",
"next",
... | 40.636364 | 18.318182 |
def anomalyProbability(self, value, anomalyScore, timestamp=None):
"""
Compute the probability that the current value plus anomaly score represents
an anomaly given the historical distribution of anomaly scores. The closer
the number is to 1, the higher the chance it is an anomaly.
:param value: th... | [
"def",
"anomalyProbability",
"(",
"self",
",",
"value",
",",
"anomalyScore",
",",
"timestamp",
"=",
"None",
")",
":",
"if",
"timestamp",
"is",
"None",
":",
"timestamp",
"=",
"self",
".",
"_iteration",
"dataPoint",
"=",
"(",
"timestamp",
",",
"value",
",",
... | 37.2 | 19.644444 |
def validate_format(self, obj, pointer=None):
"""
================= ============
Expected draft04 Alias of
----------------- ------------
date-time rfc3339.datetime
email email
hostname hostname
ipv4 ipv4
... | [
"def",
"validate_format",
"(",
"self",
",",
"obj",
",",
"pointer",
"=",
"None",
")",
":",
"if",
"'format'",
"in",
"self",
".",
"attrs",
":",
"substituted",
"=",
"{",
"'date-time'",
":",
"'rfc3339.datetime'",
",",
"'email'",
":",
"'email'",
",",
"'hostname'... | 33.833333 | 9.433333 |
def clean_text(self, domain, **kwargs):
"""Try to extract only the domain bit from the """
try:
# handle URLs by extracting the domain name
domain = urlparse(domain).hostname or domain
domain = domain.lower()
# get rid of port specs
domain = do... | [
"def",
"clean_text",
"(",
"self",
",",
"domain",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# handle URLs by extracting the domain name",
"domain",
"=",
"urlparse",
"(",
"domain",
")",
".",
"hostname",
"or",
"domain",
"domain",
"=",
"domain",
".",
"lowe... | 37.8 | 10.6 |
def determine_elected_candidates_in_order(self, candidate_votes):
"""
determine all candidates with at least a quota of votes in `candidate_votes'. returns results in
order of decreasing vote count. Any ties are resolved within this method.
"""
eligible_by_vote = defaultdict(list... | [
"def",
"determine_elected_candidates_in_order",
"(",
"self",
",",
"candidate_votes",
")",
":",
"eligible_by_vote",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"candidate_id",
",",
"votes",
"in",
"candidate_votes",
".",
"candidate_votes_iter",
"(",
")",
":",
"if",
... | 54.472222 | 24.972222 |
def set(cls, **kwargs):
"""
Sets a configuration value for the Scout agent. Values set here will
not override values set in ENV.
"""
global SCOUT_PYTHON_VALUES
for key, value in kwargs.items():
SCOUT_PYTHON_VALUES[key] = value | [
"def",
"set",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"SCOUT_PYTHON_VALUES",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"SCOUT_PYTHON_VALUES",
"[",
"key",
"]",
"=",
"value"
] | 34.875 | 8.125 |
def cylinder(script, up='z', height=1.0, radius=None, radius1=None,
radius2=None, diameter=None, diameter1=None, diameter2=None,
center=False, cir_segments=32, color=None):
"""Create a cylinder or cone primitive. Usage is based on OpenSCAD.
# height = height of the cylinder
# radiu... | [
"def",
"cylinder",
"(",
"script",
",",
"up",
"=",
"'z'",
",",
"height",
"=",
"1.0",
",",
"radius",
"=",
"None",
",",
"radius1",
"=",
"None",
",",
"radius2",
"=",
"None",
",",
"diameter",
"=",
"None",
",",
"diameter1",
"=",
"None",
",",
"diameter2",
... | 35.434783 | 14.275362 |
def flotify(result, num=50):
"""
Return a list of (timestamp, duration) sets for test result.
"""
results = list(TestResult.objects.filter(test=result.test, site=result.site)[:num])
results.reverse()
return [[get_timestamp(result.run_date), result.duration/1000] for result in results] | [
"def",
"flotify",
"(",
"result",
",",
"num",
"=",
"50",
")",
":",
"results",
"=",
"list",
"(",
"TestResult",
".",
"objects",
".",
"filter",
"(",
"test",
"=",
"result",
".",
"test",
",",
"site",
"=",
"result",
".",
"site",
")",
"[",
":",
"num",
"]... | 43.285714 | 21.571429 |
def spellchecker(word):
"""
Looks for possible typos, i.e., deletion, insertion, transposition and
alteration. If the target is 'audreyr': deletion is 'adreyr', insertion is
'audreeyr', transposition is 'aurdeyr' and alteration is 'audriyr'.
Returns a list of possible words sorted by matching the s... | [
"def",
"spellchecker",
"(",
"word",
")",
":",
"splits",
"=",
"[",
"(",
"word",
"[",
":",
"i",
"]",
",",
"word",
"[",
"i",
":",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"word",
")",
"+",
"1",
")",
"]",
"deletes",
"=",
"[",
"a",
... | 50.117647 | 22.470588 |
def delete(name, remove=False, force=False):
'''
Remove a user from the minion
CLI Example:
.. code-block:: bash
salt '*' user.delete name remove=True force=True
'''
if salt.utils.stringutils.contains_whitespace(name):
raise SaltInvocationError('Username cannot contain whitesp... | [
"def",
"delete",
"(",
"name",
",",
"remove",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"salt",
".",
"utils",
".",
"stringutils",
".",
"contains_whitespace",
"(",
"name",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'Username cannot contain... | 32.928571 | 26 |
def search(self, query, indices=None, doc_types=None, model=None, scan=False, headers=None, **query_params):
"""Execute a search against one or more indices to get the resultset.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to ... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"indices",
"=",
"None",
",",
"doc_types",
"=",
"None",
",",
"model",
"=",
"None",
",",
"scan",
"=",
"False",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"query_params",
")",
":",
"if",
"isinstance",
... | 44.6 | 25.9 |
def read_cdf(self, infile):
"""Return a cdf handle created by the available cdf library.
python-netcdf4 and scipy supported (default:scipy)"""
if not self.return_cdf:
self.load_cdf_module()
if self.cdf_module == "scipy":
# making it compatible to older scipy vers... | [
"def",
"read_cdf",
"(",
"self",
",",
"infile",
")",
":",
"if",
"not",
"self",
".",
"return_cdf",
":",
"self",
".",
"load_cdf_module",
"(",
")",
"if",
"self",
".",
"cdf_module",
"==",
"\"scipy\"",
":",
"# making it compatible to older scipy versions",
"file_obj",... | 35.842105 | 13.052632 |
def on_serial_port_change(self, serial_port):
"""Triggered when settings of a serial port of the
associated virtual machine have changed.
in serial_port of type :class:`ISerialPort`
raises :class:`VBoxErrorInvalidVmState`
Session state prevents operation.
r... | [
"def",
"on_serial_port_change",
"(",
"self",
",",
"serial_port",
")",
":",
"if",
"not",
"isinstance",
"(",
"serial_port",
",",
"ISerialPort",
")",
":",
"raise",
"TypeError",
"(",
"\"serial_port can only be an instance of type ISerialPort\"",
")",
"self",
".",
"_call",... | 37.294118 | 14.882353 |
def RandomGraph(nodes=range(10), min_links=2, width=400, height=300,
curvature=lambda: random.uniform(1.1, 1.5)):
"""Construct a random graph, with the specified nodes, and random links.
The nodes are laid out randomly on a (width x height) rectangle.
Then each node is connec... | [
"def",
"RandomGraph",
"(",
"nodes",
"=",
"range",
"(",
"10",
")",
",",
"min_links",
"=",
"2",
",",
"width",
"=",
"400",
",",
"height",
"=",
"300",
",",
"curvature",
"=",
"lambda",
":",
"random",
".",
"uniform",
"(",
"1.1",
",",
"1.5",
")",
")",
"... | 52.24 | 19.24 |
def get_splicejunction_file(out_dir, data):
"""
locate the splicejunction file starting from the alignment directory
"""
samplename = dd.get_sample_name(data)
sjfile = os.path.join(out_dir, os.pardir, "{0}SJ.out.tab").format(samplename)
if file_exists(sjfile):
return sjfile
else:
... | [
"def",
"get_splicejunction_file",
"(",
"out_dir",
",",
"data",
")",
":",
"samplename",
"=",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"sjfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"os",
".",
"pardir",
",",
"\"{0}SJ.out.tab\"",
... | 32.7 | 16.1 |
def GetMessages(self, formatter_mediator, event):
"""Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
eve... | [
"def",
"GetMessages",
"(",
"self",
",",
"formatter_mediator",
",",
"event",
")",
":",
"if",
"self",
".",
"DATA_TYPE",
"!=",
"event",
".",
"data_type",
":",
"raise",
"errors",
".",
"WrongFormatter",
"(",
"'Unsupported data type: {0:s}.'",
".",
"format",
"(",
"e... | 36.181818 | 22.772727 |
def pclass_for_definition(self, name):
"""
Get a ``pyrsistent.PClass`` subclass representing the Swagger definition
in this specification which corresponds to the given name.
:param unicode name: The name of the definition to use.
:return: A Python class which can be used to re... | [
"def",
"pclass_for_definition",
"(",
"self",
",",
"name",
")",
":",
"while",
"True",
":",
"try",
":",
"cls",
"=",
"self",
".",
"_pclasses",
"[",
"name",
"]",
"except",
"KeyError",
":",
"try",
":",
"original_definition",
"=",
"self",
".",
"definitions",
"... | 43.425 | 19.425 |
def get_total_distance_traveled(latlon_track):
'''
Returns the total distance traveled of a GPS track. Used to calculate whether or not the entire sequence was just stationary video
Takes a sequence of points as input
'''
latlon_list = []
# Remove timestamps from list
for idx, point in enume... | [
"def",
"get_total_distance_traveled",
"(",
"latlon_track",
")",
":",
"latlon_list",
"=",
"[",
"]",
"# Remove timestamps from list",
"for",
"idx",
",",
"point",
"in",
"enumerate",
"(",
"latlon_track",
")",
":",
"lat",
"=",
"latlon_track",
"[",
"idx",
"]",
"[",
... | 36.052632 | 17.842105 |
def _send_features(self, features):
"""
Send a query to the backend api with a list of observed features in this log file
:param features: Features found in the log file
:return: Response text from ThreshingFloor API
"""
# Hit the auth endpoint with a list of features
... | [
"def",
"_send_features",
"(",
"self",
",",
"features",
")",
":",
"# Hit the auth endpoint with a list of features",
"try",
":",
"r",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"base_uri",
"+",
"self",
".",
"api_endpoint",
",",
"json",
"=",
"features",
","... | 42.35 | 26.05 |
def getComics(options):
"""Retrieve comics."""
if options.handler:
for name in set(options.handler):
events.addHandler(name, options.basepath, options.baseurl, options.allowdownscale)
events.getHandler().start()
errors = 0
try:
for scraperobj in getScrapers(options.comic,... | [
"def",
"getComics",
"(",
"options",
")",
":",
"if",
"options",
".",
"handler",
":",
"for",
"name",
"in",
"set",
"(",
"options",
".",
"handler",
")",
":",
"events",
".",
"addHandler",
"(",
"name",
",",
"options",
".",
"basepath",
",",
"options",
".",
... | 31.857143 | 17.5 |
def to_utf8(text):
""" Enforce UTF8 encoding.
"""
# return empty/false stuff unaltered
if not text:
if isinstance(text, string_types):
text = ""
return text
try:
# Is it a unicode string, or pure ascii?
return text.encode("utf8")
except UnicodeDecodeE... | [
"def",
"to_utf8",
"(",
"text",
")",
":",
"# return empty/false stuff unaltered",
"if",
"not",
"text",
":",
"if",
"isinstance",
"(",
"text",
",",
"string_types",
")",
":",
"text",
"=",
"\"\"",
"return",
"text",
"try",
":",
"# Is it a unicode string, or pure ascii?"... | 35.05 | 14.725 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
# pylint: disable=too-many-arguments
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for specification of input and result values.
Implements the following eq... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# pylint: disable=too-many-arguments",
"# obtain coefficients for required intensity measure type (IMT)",
"coeffs",
"=",
"self",
".",
"COEFFS_BA... | 35.34375 | 23.96875 |
def string_get(self, ypos, xpos, length):
"""
Get a string of `length` at screen co-ordinates `ypos`/`xpos`
Co-ordinates are 1 based, as listed in the status area of the
terminal.
"""
# the screen's co-ordinates are 1 based, but the command is 0 based
... | [
"def",
"string_get",
"(",
"self",
",",
"ypos",
",",
"xpos",
",",
"length",
")",
":",
"# the screen's co-ordinates are 1 based, but the command is 0 based",
"xpos",
"-=",
"1",
"ypos",
"-=",
"1",
"cmd",
"=",
"self",
".",
"exec_command",
"(",
"\"Ascii({0},{1},{2})\"",
... | 38.125 | 19.75 |
def delete_event(self, client, check):
"""
Resolves an event for a given check on a given client. (delayed action)
"""
self._request('DELETE', '/events/{}/{}'.format(client, check))
return True | [
"def",
"delete_event",
"(",
"self",
",",
"client",
",",
"check",
")",
":",
"self",
".",
"_request",
"(",
"'DELETE'",
",",
"'/events/{}/{}'",
".",
"format",
"(",
"client",
",",
"check",
")",
")",
"return",
"True"
] | 38 | 15.333333 |
def get_status(self, response, finished=False):
"""Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status`, or
None if the status cannot be determined"""
lines = [line.strip() for line in response.split("\n")
... | [
"def",
"get_status",
"(",
"self",
",",
"response",
",",
"finished",
"=",
"False",
")",
":",
"lines",
"=",
"[",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"response",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"line",
".",
"strip",
"(",
")",... | 43.6 | 12.4 |
def get_max_id(self, object_type, role):
"""Get the highest used ID."""
if object_type == 'user':
objectclass = 'posixAccount'
ldap_attr = 'uidNumber'
elif object_type == 'group': # pragma: no cover
objectclass = 'posixGroup'
ldap_attr = 'gidNumbe... | [
"def",
"get_max_id",
"(",
"self",
",",
"object_type",
",",
"role",
")",
":",
"if",
"object_type",
"==",
"'user'",
":",
"objectclass",
"=",
"'posixAccount'",
"ldap_attr",
"=",
"'uidNumber'",
"elif",
"object_type",
"==",
"'group'",
":",
"# pragma: no cover",
"obje... | 33.030303 | 20.909091 |
def copy(self, new_id=None, attribute_overrides={}):
"""
Copies the DatabaseObject under the ID_KEY new_id.
@param new_id: the value for ID_KEY of the copy; if this is none,
creates the new object with a random ID_KEY
@param attribute_overrides: dictionary of attribu... | [
"def",
"copy",
"(",
"self",
",",
"new_id",
"=",
"None",
",",
"attribute_overrides",
"=",
"{",
"}",
")",
":",
"data",
"=",
"dict",
"(",
"self",
")",
"data",
".",
"update",
"(",
"attribute_overrides",
")",
"if",
"new_id",
"is",
"not",
"None",
":",
"dat... | 41.875 | 18.375 |
def terms(self):
"""Iterator over the terms of the sum
Yield from the (possibly) infinite list of terms of the indexed sum, if
the sum was written out explicitly. Each yielded term in an instance of
:class:`.Expression`
"""
from qnet.algebra.core.scalar_algebra import Sc... | [
"def",
"terms",
"(",
"self",
")",
":",
"from",
"qnet",
".",
"algebra",
".",
"core",
".",
"scalar_algebra",
"import",
"ScalarValue",
"for",
"mapping",
"in",
"yield_from_ranges",
"(",
"self",
".",
"ranges",
")",
":",
"term",
"=",
"self",
".",
"term",
".",
... | 42.571429 | 17.714286 |
def parse_delay_import_directory(self, rva, size):
"""Walk and parse the delay import directory."""
import_descs = []
while True:
try:
# If the RVA is invalid all would blow up. Some PEs seem to be
# specially nasty and have an invalid RVA.
... | [
"def",
"parse_delay_import_directory",
"(",
"self",
",",
"rva",
",",
"size",
")",
":",
"import_descs",
"=",
"[",
"]",
"while",
"True",
":",
"try",
":",
"# If the RVA is invalid all would blow up. Some PEs seem to be",
"# specially nasty and have an invalid RVA.",
"data",
... | 36.264151 | 18.90566 |
def get_value(data, name, field, allow_many_nested=False):
"""Get a value from a dictionary. Handles ``MultiDict`` types when
``multiple=True``. If the value is not found, return `missing`.
:param object data: Mapping (e.g. `dict`) or list-like instance to
pull the value from.
:param str name: ... | [
"def",
"get_value",
"(",
"data",
",",
"name",
",",
"field",
",",
"allow_many_nested",
"=",
"False",
")",
":",
"missing_value",
"=",
"missing",
"if",
"allow_many_nested",
"and",
"isinstance",
"(",
"field",
",",
"ma",
".",
"fields",
".",
"Nested",
")",
"and"... | 35.647059 | 16.970588 |
def format_v2_score_response(request, response):
"""
{
"scores": {
"<context>": {
"<model_name>": {
"scores": {
"<rev_id>": <score>,
"<rev_id>": <score>
},
"features": ... | [
"def",
"format_v2_score_response",
"(",
"request",
",",
"response",
")",
":",
"return",
"util",
".",
"jsonify",
"(",
"{",
"\"scores\"",
":",
"{",
"response",
".",
"context",
".",
"name",
":",
"{",
"model_name",
":",
"format_v2_model",
"(",
"request",
",",
... | 32.243243 | 12.351351 |
def prune_loop_for_kic(self, loops_segments, search_radius, expected_min_loop_length = None, expected_max_loop_length = None, generate_pymol_session = False):
'''A wrapper for prune_structure_according_to_loop_definitions suitable for the Rosetta kinematic closure (KIC) loop modeling method.'''
return s... | [
"def",
"prune_loop_for_kic",
"(",
"self",
",",
"loops_segments",
",",
"search_radius",
",",
"expected_min_loop_length",
"=",
"None",
",",
"expected_max_loop_length",
"=",
"None",
",",
"generate_pymol_session",
"=",
"False",
")",
":",
"return",
"self",
".",
"prune_st... | 202.333333 | 162.333333 |
def phonix(word, max_length=4, zero_pad=True):
"""Return the Phonix code for a word.
This is a wrapper for :py:meth:`Phonix.encode`.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 4)
zero_pad : bool
... | [
"def",
"phonix",
"(",
"word",
",",
"max_length",
"=",
"4",
",",
"zero_pad",
"=",
"True",
")",
":",
"return",
"Phonix",
"(",
")",
".",
"encode",
"(",
"word",
",",
"max_length",
",",
"zero_pad",
")"
] | 20.59375 | 23.65625 |
def _draw(self, data):
"""
Draw text
"""
self._cursor.clearSelection()
self._cursor.setPosition(self._last_cursor_pos)
if '\x07' in data.txt:
print('\a')
txt = data.txt.replace('\x07', '')
if '\x08' in txt:
parts = txt.split('\x08... | [
"def",
"_draw",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_cursor",
".",
"clearSelection",
"(",
")",
"self",
".",
"_cursor",
".",
"setPosition",
"(",
"self",
".",
"_last_cursor_pos",
")",
"if",
"'\\x07'",
"in",
"data",
".",
"txt",
":",
"print",... | 38.02 | 13.54 |
def can_publish(self):
"""
Return True if there is a draft version of the document that's ready to
be published.
"""
with self.published_context():
published = self.one(
Q._uid == self._uid,
projection={'revision': True}
... | [
"def",
"can_publish",
"(",
"self",
")",
":",
"with",
"self",
".",
"published_context",
"(",
")",
":",
"published",
"=",
"self",
".",
"one",
"(",
"Q",
".",
"_uid",
"==",
"self",
".",
"_uid",
",",
"projection",
"=",
"{",
"'revision'",
":",
"True",
"}",... | 29.166667 | 18.055556 |
def register_opts(conf):
"""Configure options within configuration library."""
conf.register_cli_opts(CLI_OPTS)
conf.register_opts(EPISODE_OPTS)
conf.register_opts(FORMAT_OPTS)
conf.register_opts(CACHE_OPTS, 'cache') | [
"def",
"register_opts",
"(",
"conf",
")",
":",
"conf",
".",
"register_cli_opts",
"(",
"CLI_OPTS",
")",
"conf",
".",
"register_opts",
"(",
"EPISODE_OPTS",
")",
"conf",
".",
"register_opts",
"(",
"FORMAT_OPTS",
")",
"conf",
".",
"register_opts",
"(",
"CACHE_OPTS... | 38.5 | 5.333333 |
def get_string_resources(self, package_name, locale='\x00\x00'):
"""
Get the XML (as string) of all resources of type 'string'.
Read more about string resources:
https://developer.android.com/guide/topics/resources/string-resource.html
:param package_name: the package name to g... | [
"def",
"get_string_resources",
"(",
"self",
",",
"package_name",
",",
"locale",
"=",
"'\\x00\\x00'",
")",
":",
"self",
".",
"_analyse",
"(",
")",
"buff",
"=",
"'<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n'",
"buff",
"+=",
"'<resources>\\n'",
"try",
":",
"for",
"... | 34.071429 | 22.857143 |
def plus_dora(tile, dora_indicators):
"""
:param tile: int 136 tiles format
:param dora_indicators: array of 136 tiles format
:return: int count of dora
"""
tile_index = tile // 4
dora_count = 0
for dora in dora_indicators:
dora //= 4
# sou, pin, man
if tile_ind... | [
"def",
"plus_dora",
"(",
"tile",
",",
"dora_indicators",
")",
":",
"tile_index",
"=",
"tile",
"//",
"4",
"dora_count",
"=",
"0",
"for",
"dora",
"in",
"dora_indicators",
":",
"dora",
"//=",
"4",
"# sou, pin, man",
"if",
"tile_index",
"<",
"EAST",
":",
"# wi... | 22.545455 | 17.318182 |
def forwards(self, orm):
"Write your forwards methods here."
orm['avocado.DataField'].objects.get_or_create(app_name='samples', model_name='batch', field_name='id',
defaults=dict(published=True, name='Batch', name_plural='Batches')) | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"orm",
"[",
"'avocado.DataField'",
"]",
".",
"objects",
".",
"get_or_create",
"(",
"app_name",
"=",
"'samples'",
",",
"model_name",
"=",
"'batch'",
",",
"field_name",
"=",
"'id'",
",",
"defaults",
"=",
... | 65.25 | 33.25 |
def iter_items(self, start_key=None, end_key=None, reverse=False):
"""Iterates over the (key, value) items of the associated tree,
in ascending order if reverse is True, iterate in descending order,
reverse defaults to False"""
# optimized iterator (reduced method calls) - faster on CPy... | [
"def",
"iter_items",
"(",
"self",
",",
"start_key",
"=",
"None",
",",
"end_key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"# optimized iterator (reduced method calls) - faster on CPython but slower on pypy",
"if",
"self",
".",
"is_empty",
"(",
")",
":",
... | 45.5 | 23.25 |
def get_datetime(timestamp):
"""
Turn a string timestamp into a date time. First tries to use dateutil.
Failing that it tries to guess the time format and converts it manually
using stfptime.
@returns: A timezone unaware timestamp.
"""
timestamp_is_float = False
try:
... | [
"def",
"get_datetime",
"(",
"timestamp",
")",
":",
"timestamp_is_float",
"=",
"False",
"try",
":",
"float",
"(",
"timestamp",
")",
"timestamp_is_float",
"=",
"True",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"if",
"timestamp_is_float",
"... | 28.519231 | 20.596154 |
def restriction_dist_chart (self):
""" Make the petagRestrictionDistribution plot """
pconfig = {
'id': 'petagRestrictionDistribution',
'title': 'Restriction Distribution',
'ylab': 'Reads',
'xlab': 'Distance from cut site (bp)',
'data_labels'... | [
"def",
"restriction_dist_chart",
"(",
"self",
")",
":",
"pconfig",
"=",
"{",
"'id'",
":",
"'petagRestrictionDistribution'",
",",
"'title'",
":",
"'Restriction Distribution'",
",",
"'ylab'",
":",
"'Reads'",
",",
"'xlab'",
":",
"'Distance from cut site (bp)'",
",",
"'... | 30.85 | 16.45 |
def on_message(self, message):
"""
Handle an incoming message.
message -- message to handle
"""
try:
message = json.loads(message)
except ValueError:
try:
self.write_message(json.dumps({
'messageType': 'error',
... | [
"def",
"on_message",
"(",
"self",
",",
"message",
")",
":",
"try",
":",
"message",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"except",
"ValueError",
":",
"try",
":",
"self",
".",
"write_message",
"(",
"json",
".",
"dumps",
"(",
"{",
"'messageType... | 35.917647 | 16.035294 |
def _get_deleted_fs(name, blade):
'''
Private function to check
if a file systeem has already been deleted
'''
try:
_fs = _get_fs(name, blade)
if _fs and _fs.destroyed:
return _fs
except rest.ApiException:
return None | [
"def",
"_get_deleted_fs",
"(",
"name",
",",
"blade",
")",
":",
"try",
":",
"_fs",
"=",
"_get_fs",
"(",
"name",
",",
"blade",
")",
"if",
"_fs",
"and",
"_fs",
".",
"destroyed",
":",
"return",
"_fs",
"except",
"rest",
".",
"ApiException",
":",
"return",
... | 24.272727 | 16.818182 |
def _format_data(data):
# type: (Union[str, IO]) -> Union[Tuple[None, str], Tuple[Optional[str], IO, str]]
"""Format field data according to whether it is a stream or
a string for a form-data request.
:param data: The request field data.
:type data: str or file-like object.
... | [
"def",
"_format_data",
"(",
"data",
")",
":",
"# type: (Union[str, IO]) -> Union[Tuple[None, str], Tuple[Optional[str], IO, str]]",
"if",
"hasattr",
"(",
"data",
",",
"'read'",
")",
":",
"data",
"=",
"cast",
"(",
"IO",
",",
"data",
")",
"data_name",
"=",
"None",
"... | 40.111111 | 14.555556 |
def needs_low_priority(self, priority):
"""
:return: None
"""
assert isinstance(priority, int)
if priority != velbus.LOW_PRIORITY:
self.parser_error("needs low priority set") | [
"def",
"needs_low_priority",
"(",
"self",
",",
"priority",
")",
":",
"assert",
"isinstance",
"(",
"priority",
",",
"int",
")",
"if",
"priority",
"!=",
"velbus",
".",
"LOW_PRIORITY",
":",
"self",
".",
"parser_error",
"(",
"\"needs low priority set\"",
")"
] | 32.285714 | 5.428571 |
def mutation(self, strength = 0.1):
'''
Single gene mutation
'''
mutStrengthReal = strength
mutMaxSizeReal = self.gLength/2
mutSizeReal = int(numpy.random.random_integers(1,mutMaxSizeReal))
mutationPosReal = int(numpy.random.random_integers(0+mutSizeReal-1,self.y.shape[0]-1-mutSizeReal))
mutationSignRea... | [
"def",
"mutation",
"(",
"self",
",",
"strength",
"=",
"0.1",
")",
":",
"mutStrengthReal",
"=",
"strength",
"mutMaxSizeReal",
"=",
"self",
".",
"gLength",
"/",
"2",
"mutSizeReal",
"=",
"int",
"(",
"numpy",
".",
"random",
".",
"random_integers",
"(",
"1",
... | 39.789474 | 30 |
def IsDatabaseLink(link):
"""Finds whether the link is a database Self Link or a database ID based link
:param str link:
Link to analyze
:return:
True or False.
:rtype: boolean
"""
if not link:
return False
# trimming the leading and trailing "/" from the input str... | [
"def",
"IsDatabaseLink",
"(",
"link",
")",
":",
"if",
"not",
"link",
":",
"return",
"False",
"# trimming the leading and trailing \"/\" from the input string",
"link",
"=",
"TrimBeginningAndEndingSlashes",
"(",
"link",
")",
"# Splitting the link(separated by \"/\") into parts "... | 23.064516 | 23.516129 |
def get_term_category_frequencies(self, scatterchartdata):
'''
Parameters
----------
scatterchartdata : ScatterChartData
Returns
-------
pd.DataFrame
'''
df = self.term_category_freq_df.rename(
columns={c: c + ' freq' for c in self.term_category_freq_df}
)
df.index.name = 'term'
return df | [
"def",
"get_term_category_frequencies",
"(",
"self",
",",
"scatterchartdata",
")",
":",
"df",
"=",
"self",
".",
"term_category_freq_df",
".",
"rename",
"(",
"columns",
"=",
"{",
"c",
":",
"c",
"+",
"' freq'",
"for",
"c",
"in",
"self",
".",
"term_category_fre... | 18.9375 | 26.3125 |
def certclone(chain, copy_extensions=False):
for i in range(len(chain)):
chain[i] = chain[i].to_cryptography()
newchain = []
'''
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
pubkey = key.public_key()
... | [
"def",
"certclone",
"(",
"chain",
",",
"copy_extensions",
"=",
"False",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"chain",
")",
")",
":",
"chain",
"[",
"i",
"]",
"=",
"chain",
"[",
"i",
"]",
".",
"to_cryptography",
"(",
")",
"newchain",... | 28.983607 | 22.098361 |
def clear( self ):
"""
Clears the current settings for the current action.
"""
item = self.uiActionTREE.currentItem()
if ( not item ):
return
self.uiShortcutTXT.setText('')
item.setText(1, '') | [
"def",
"clear",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"uiActionTREE",
".",
"currentItem",
"(",
")",
"if",
"(",
"not",
"item",
")",
":",
"return",
"self",
".",
"uiShortcutTXT",
".",
"setText",
"(",
"''",
")",
"item",
".",
"setText",
"(",
... | 26 | 13.2 |
def git_working_dir(func):
"""Decorator which changes the current working dir to the one of the git
repository in order to assure relative paths are handled correctly"""
@wraps(func)
def set_git_working_dir(self, *args, **kwargs):
cur_wd = os.getcwd()
os.chdir(self.repo.working_tree_dir... | [
"def",
"git_working_dir",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"set_git_working_dir",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cur_wd",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
... | 30.9375 | 16 |
def match(self, filename, line, codes):
"""Match rule."""
if ((not self.file_selectors or self.file_match_any(filename)) and
(not self.environment_marker_selector or
self.environment_marker_evaluate()) and
(not self.code_selectors or self.codes_match_any(... | [
"def",
"match",
"(",
"self",
",",
"filename",
",",
"line",
",",
"codes",
")",
":",
"if",
"(",
"(",
"not",
"self",
".",
"file_selectors",
"or",
"self",
".",
"file_match_any",
"(",
"filename",
")",
")",
"and",
"(",
"not",
"self",
".",
"environment_marker... | 41.083333 | 19.166667 |
def vector_analysis(vector, coordinates, elements_vdw, increment=1.0):
"""Analyse a sampling vector's path for window analysis purpose."""
# Calculate number of chunks if vector length is divided by increment.
chunks = int(np.linalg.norm(vector) // increment)
# Create a single chunk.
chunk = vector ... | [
"def",
"vector_analysis",
"(",
"vector",
",",
"coordinates",
",",
"elements_vdw",
",",
"increment",
"=",
"1.0",
")",
":",
"# Calculate number of chunks if vector length is divided by increment.",
"chunks",
"=",
"int",
"(",
"np",
".",
"linalg",
".",
"norm",
"(",
"vec... | 47.789474 | 18.368421 |
def generate_func_code(self):
"""
Creates base code of validation function and calls helper
for creating code by definition.
"""
self.l('NoneType = type(None)')
# Generate parts that are referenced and not yet generated
while self._needed_validation_functions:
... | [
"def",
"generate_func_code",
"(",
"self",
")",
":",
"self",
".",
"l",
"(",
"'NoneType = type(None)'",
")",
"# Generate parts that are referenced and not yet generated",
"while",
"self",
".",
"_needed_validation_functions",
":",
"# During generation of validation function, could b... | 50 | 16.307692 |
def date_time_between_dates(
self,
datetime_start=None,
datetime_end=None,
tzinfo=None):
"""
Takes two DateTime objects and returns a random datetime between the two
given datetimes.
Accepts DateTime objects.
:param datetime_start:... | [
"def",
"date_time_between_dates",
"(",
"self",
",",
"datetime_start",
"=",
"None",
",",
"datetime_end",
"=",
"None",
",",
"tzinfo",
"=",
"None",
")",
":",
"if",
"datetime_start",
"is",
"None",
":",
"datetime_start",
"=",
"datetime",
".",
"now",
"(",
"tzinfo"... | 35.184211 | 17.973684 |
def contains_point( self, x, y ):
"""Is the point (x,y) on this curve?"""
return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0 | [
"def",
"contains_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"(",
"y",
"*",
"y",
"-",
"(",
"x",
"*",
"x",
"*",
"x",
"+",
"self",
".",
"__a",
"*",
"x",
"+",
"self",
".",
"__b",
")",
")",
"%",
"self",
".",
"__p",
"==",
"0"
... | 51.333333 | 15 |
def _split_keys(mapping, separator='.', colliding=None):
"""
Recursively walks *mapping* to split keys that contain the separator into
nested mappings.
.. note::
Keys not of type `str` are not supported and will raise errors.
:param mapping: the mapping to process
:param separator: th... | [
"def",
"_split_keys",
"(",
"mapping",
",",
"separator",
"=",
"'.'",
",",
"colliding",
"=",
"None",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"... | 39.093023 | 25.418605 |
def main():
"""Command line interface for the ``qpass`` program."""
# Initialize logging to the terminal.
coloredlogs.install()
# Prepare for command line argument parsing.
action = show_matching_entry
program_opts = dict(exclude_list=[])
show_opts = dict(filters=[], use_clipboard=is_clipboa... | [
"def",
"main",
"(",
")",
":",
"# Initialize logging to the terminal.",
"coloredlogs",
".",
"install",
"(",
")",
"# Prepare for command line argument parsing.",
"action",
"=",
"show_matching_entry",
"program_opts",
"=",
"dict",
"(",
"exclude_list",
"=",
"[",
"]",
")",
... | 41 | 14.916667 |
def _equal_values(self, val1, val2):
"""Matrices are equal if they hash to the same value."""
if self._is_supported_matrix(val1):
if self._is_supported_matrix(val2):
_, _, hash_tuple_1 = self._serialize_matrix(val1)
_, _, hash_tuple_2 = self._serialize_matrix... | [
"def",
"_equal_values",
"(",
"self",
",",
"val1",
",",
"val2",
")",
":",
"if",
"self",
".",
"_is_supported_matrix",
"(",
"val1",
")",
":",
"if",
"self",
".",
"_is_supported_matrix",
"(",
"val2",
")",
":",
"_",
",",
"_",
",",
"hash_tuple_1",
"=",
"self"... | 39.538462 | 20.153846 |
def check_ascii_256(string):
"""Check that `string` is printable ASCII and at most 256 chars.
Raise a `ValueError` if this check fails. Note that `string` itself doesn't
have to be ASCII-encoded.
:type string: str
:param string: The string to check.
"""
if string is None:
return
... | [
"def",
"check_ascii_256",
"(",
"string",
")",
":",
"if",
"string",
"is",
"None",
":",
"return",
"if",
"len",
"(",
"string",
")",
">",
"256",
":",
"raise",
"ValueError",
"(",
"\"Value is longer than 256 characters\"",
")",
"bad_char",
"=",
"_NON_PRINTABLE_ASCII",... | 35.85 | 18.2 |
def getCol(self, column, numberColumns=None):
""" Returns the specified column of the region (if the raster is set)
If numberColumns is provided, uses that instead of the raster
"""
column = int(column)
if self._raster[0] == 0 or self._raster[1] == 0:
return self
... | [
"def",
"getCol",
"(",
"self",
",",
"column",
",",
"numberColumns",
"=",
"None",
")",
":",
"column",
"=",
"int",
"(",
"column",
")",
"if",
"self",
".",
"_raster",
"[",
"0",
"]",
"==",
"0",
"or",
"self",
".",
"_raster",
"[",
"1",
"]",
"==",
"0",
... | 47.52381 | 17.142857 |
def prt_hier_all(self, prt=sys.stdout):
"""Write hierarchy for all GO Terms in obo file."""
# Print: [biological_process, molecular_function, and cellular_component]
items_list = set()
for goid in ['GO:0008150', 'GO:0003674', 'GO:0005575']:
items_list.update(self.prt_hier_dow... | [
"def",
"prt_hier_all",
"(",
"self",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"# Print: [biological_process, molecular_function, and cellular_component]",
"items_list",
"=",
"set",
"(",
")",
"for",
"goid",
"in",
"[",
"'GO:0008150'",
",",
"'GO:0003674'",
",",
... | 50.428571 | 16.285714 |
def get_name(self):
"""Accessor to service_description attribute or name if first not defined
:return: service name
:rtype: str
"""
if hasattr(self, 'service_description'):
return self.service_description
if hasattr(self, 'name'):
return self.name... | [
"def",
"get_name",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'service_description'",
")",
":",
"return",
"self",
".",
"service_description",
"if",
"hasattr",
"(",
"self",
",",
"'name'",
")",
":",
"return",
"self",
".",
"name",
"return",
... | 32.272727 | 11.545455 |
def to_geojson(products):
"""Return the products from a query response as a GeoJSON with the values in their
appropriate Python types.
"""
feature_list = []
for i, (product_id, props) in enumerate(products.items()):
props = props.copy()
props['id'] = produ... | [
"def",
"to_geojson",
"(",
"products",
")",
":",
"feature_list",
"=",
"[",
"]",
"for",
"i",
",",
"(",
"product_id",
",",
"props",
")",
"in",
"enumerate",
"(",
"products",
".",
"items",
"(",
")",
")",
":",
"props",
"=",
"props",
".",
"copy",
"(",
")"... | 43.315789 | 12.210526 |
def _crc(plaintext):
"""Generates crc32. Modulo keep the value within int range."""
if not isinstance(plaintext, six.binary_type):
plaintext = six.b(plaintext)
return (zlib.crc32(plaintext) % 2147483647) & 0xffffffff | [
"def",
"_crc",
"(",
"plaintext",
")",
":",
"if",
"not",
"isinstance",
"(",
"plaintext",
",",
"six",
".",
"binary_type",
")",
":",
"plaintext",
"=",
"six",
".",
"b",
"(",
"plaintext",
")",
"return",
"(",
"zlib",
".",
"crc32",
"(",
"plaintext",
")",
"%... | 46.4 | 10.8 |
async def CreatePool(self, attrs, name, provider):
'''
attrs : typing.Mapping[str, typing.Any]
name : str
provider : str
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Storage',
request='Create... | [
"async",
"def",
"CreatePool",
"(",
"self",
",",
"attrs",
",",
"name",
",",
"provider",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Storage'",
",",
"request",
"=",
"'CreatePool'",
",",
... | 29.666667 | 12.222222 |
def reinterpret_cast(self, sigOrVal, toType):
"""
Cast value or signal of this type to another type of same size.
:param sigOrVal: instance of signal or value to cast
:param toType: instance of HdlType to cast into
"""
try:
return self.auto_cast(sigOrVal, toT... | [
"def",
"reinterpret_cast",
"(",
"self",
",",
"sigOrVal",
",",
"toType",
")",
":",
"try",
":",
"return",
"self",
".",
"auto_cast",
"(",
"sigOrVal",
",",
"toType",
")",
"except",
"TypeConversionErr",
":",
"pass",
"try",
":",
"r",
"=",
"self",
".",
"_reinte... | 30.263158 | 16.157895 |
def next(self, length):
"""Return a new segment starting right after self in the same buffer."""
return Segment(self.strip, length, self.offset + self.length) | [
"def",
"next",
"(",
"self",
",",
"length",
")",
":",
"return",
"Segment",
"(",
"self",
".",
"strip",
",",
"length",
",",
"self",
".",
"offset",
"+",
"self",
".",
"length",
")"
] | 57.333333 | 15.333333 |
def signed_session(self, session=None):
# type: (Optional[requests.Session]) -> requests.Session
"""Create requests session with any required auth headers
applied.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:pa... | [
"def",
"signed_session",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"# type: (Optional[requests.Session]) -> requests.Session",
"session",
"=",
"super",
"(",
"BasicAuthentication",
",",
"self",
")",
".",
"signed_session",
"(",
"session",
")",
"session",
"."... | 40.8 | 18.666667 |
def verify_certs(*args):
'''
Sanity checking for the specified SSL certificates
'''
msg = ("Could not find a certificate: {0}\n"
"If you want to quickly generate a self-signed certificate, "
"use the tls.create_self_signed_cert function in Salt")
for arg in args:
if ... | [
"def",
"verify_certs",
"(",
"*",
"args",
")",
":",
"msg",
"=",
"(",
"\"Could not find a certificate: {0}\\n\"",
"\"If you want to quickly generate a self-signed certificate, \"",
"\"use the tls.create_self_signed_cert function in Salt\"",
")",
"for",
"arg",
"in",
"args",
":",
"... | 34.454545 | 21.181818 |
def _validate_type(cls, typeobj):
"""
Validate that all required type methods are implemented.
At minimum a type must have:
- a convert() or convert_binary() function
- a default_formatter() function
Raises an ArgumentError if the type is not valid
"""
... | [
"def",
"_validate_type",
"(",
"cls",
",",
"typeobj",
")",
":",
"if",
"not",
"(",
"hasattr",
"(",
"typeobj",
",",
"\"convert\"",
")",
"or",
"hasattr",
"(",
"typeobj",
",",
"\"convert_binary\"",
")",
")",
":",
"raise",
"ArgumentError",
"(",
"\"type is invalid,... | 43.8125 | 28.8125 |
def get_course_enrollments(self, enterprise_customer, days):
"""
Get course enrollments for all the learners of given enterprise customer.
Arguments:
enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners
of this enterprise customer.
... | [
"def",
"get_course_enrollments",
"(",
"self",
",",
"enterprise_customer",
",",
"days",
")",
":",
"return",
"CourseEnrollment",
".",
"objects",
".",
"filter",
"(",
"created__gt",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"datetime",
".",
"t... | 42.176471 | 26.764706 |
def from_web_element(self, web_element):
"""
Store reference to a WebElement instance representing the element on the DOM.
Use it when an instance of WebElement has already been created (e.g. as the result of find_element) and
you want to create a UIComponent out of it withou... | [
"def",
"from_web_element",
"(",
"self",
",",
"web_element",
")",
":",
"if",
"isinstance",
"(",
"web_element",
",",
"WebElement",
")",
"is",
"not",
"True",
":",
"raise",
"TypeError",
"(",
"\"web_element parameter is not of type WebElement.\"",
")",
"self",
".",
"_w... | 55.181818 | 24.454545 |
def get_order(self, order_id):
"""
See more:
http://developer.oanda.com/rest-live/orders/#getInformationForAnOrder
"""
url = "{0}/{1}/accounts/{2}/orders/{3}".format(
self.domain,
self.API_VERSION,
self.account_id,
order_id
... | [
"def",
"get_order",
"(",
"self",
",",
"order_id",
")",
":",
"url",
"=",
"\"{0}/{1}/accounts/{2}/orders/{3}\"",
".",
"format",
"(",
"self",
".",
"domain",
",",
"self",
".",
"API_VERSION",
",",
"self",
".",
"account_id",
",",
"order_id",
")",
"try",
":",
"re... | 29.470588 | 16.058824 |
def _GetArchiveTypes(self, mediator, path_spec):
"""Determines if a data stream contains an archive such as: TAR or ZIP.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
path_spec (dfvfs.PathSpec): path spe... | [
"def",
"_GetArchiveTypes",
"(",
"self",
",",
"mediator",
",",
"path_spec",
")",
":",
"try",
":",
"type_indicators",
"=",
"analyzer",
".",
"Analyzer",
".",
"GetArchiveTypeIndicators",
"(",
"path_spec",
",",
"resolver_context",
"=",
"mediator",
".",
"resolver_contex... | 37.956522 | 24.130435 |
def ingest(self):
"""*Perform conesearches of the online NED database and import the results into a the sherlock-database*
The code:
1. uses the list of transient coordinates and queries NED for the results within the given search radius
2. Creates the `tcs_cat_ned_stream` tabl... | [
"def",
"ingest",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``ingest`` method'",
")",
"if",
"not",
"self",
".",
"radiusArcsec",
":",
"self",
".",
"log",
".",
"error",
"(",
"'please give a radius in arcsec with which to preform the... | 36.494382 | 19.011236 |
def replace_namespaced_lease(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_lease # noqa: E501
replace the specified Lease # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=Tru... | [
"def",
"replace_namespaced_lease",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
... | 59.6 | 33.04 |
def _reorder_via_klist(d,nkl,**kwargs):
'''
d = {'scheme': 'http', 'path': '/index.php', 'params': 'params', 'query': 'username=query', 'fragment': 'frag', 'username': '', 'password': '', 'hostname': 'www.baidu.com', 'port': ''}
pobj(d)
nkl = ['scheme', 'username', 'password', 'hostname', 'p... | [
"def",
"_reorder_via_klist",
"(",
"d",
",",
"nkl",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"'deepcopy'",
"in",
"kwargs",
")",
":",
"deepcopy",
"=",
"kwargs",
"[",
"'deepcopy'",
"]",
"else",
":",
"deepcopy",
"=",
"True",
"if",
"(",
"deepcopy",
"... | 32.666667 | 28.190476 |
def clog(color):
"""Same to ``log``, but this one centralizes the message first."""
logger = log(color)
return lambda msg: logger(centralize(msg).rstrip()) | [
"def",
"clog",
"(",
"color",
")",
":",
"logger",
"=",
"log",
"(",
"color",
")",
"return",
"lambda",
"msg",
":",
"logger",
"(",
"centralize",
"(",
"msg",
")",
".",
"rstrip",
"(",
")",
")"
] | 41 | 14 |
def sinkhorn(inputs, n_iters=20):
"""Performs incomplete Sinkhorn normalization to inputs.
By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix
with positive entries can be turned into a doubly-stochastic matrix
(i.e. its rows and columns add up to one) via the succesive row and column
... | [
"def",
"sinkhorn",
"(",
"inputs",
",",
"n_iters",
"=",
"20",
")",
":",
"vocab_size",
"=",
"tf",
".",
"shape",
"(",
"inputs",
")",
"[",
"-",
"1",
"]",
"log_alpha",
"=",
"tf",
".",
"reshape",
"(",
"inputs",
",",
"[",
"-",
"1",
",",
"vocab_size",
",... | 41.425 | 24.1 |
def balancer_absent(name, profile, **libcloud_kwargs):
'''
Ensures a load balancer is absent.
:param name: Load Balancer name
:type name: ``str``
:param profile: The profile key
:type profile: ``str``
'''
balancers = __salt__['libcloud_loadbalancer.list_balancers'](profile)
match... | [
"def",
"balancer_absent",
"(",
"name",
",",
"profile",
",",
"*",
"*",
"libcloud_kwargs",
")",
":",
"balancers",
"=",
"__salt__",
"[",
"'libcloud_loadbalancer.list_balancers'",
"]",
"(",
"profile",
")",
"match",
"=",
"[",
"z",
"for",
"z",
"in",
"balancers",
"... | 36.705882 | 25.058824 |
def configure(cls, host_name: str = '', service_name: str = '', service_version='',
http_host: str = '127.0.0.1', http_port: int = 8000,
tcp_host: str = '127.0.0.1', tcp_port: int = 8001, ssl_context=None,
registry_host: str = "0.0.0.0", registry_port: int = 4500,
... | [
"def",
"configure",
"(",
"cls",
",",
"host_name",
":",
"str",
"=",
"''",
",",
"service_name",
":",
"str",
"=",
"''",
",",
"service_version",
"=",
"''",
",",
"http_host",
":",
"str",
"=",
"'127.0.0.1'",
",",
"http_port",
":",
"int",
"=",
"8000",
",",
... | 50.518519 | 18.37037 |
def result_or_error(response):
"""Get `result` field from Betfair response or raise exception if not
found.
:param Response response:
:raises: ApiError if no results passed
"""
data = response.json()
result = data.get('result')
if result is not None:
return result
raise exce... | [
"def",
"result_or_error",
"(",
"response",
")",
":",
"data",
"=",
"response",
".",
"json",
"(",
")",
"result",
"=",
"data",
".",
"get",
"(",
"'result'",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"raise",
"exceptions",
".",
"Api... | 28.333333 | 12.833333 |
def publish(self, json_msg):
'''
json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}'
'''
pyobj = json.loads(json_msg)
for topic, value in pyobj.items():
msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value))
self._pub.publish(msg) | [
"def",
"publish",
"(",
"self",
",",
"json_msg",
")",
":",
"pyobj",
"=",
"json",
".",
"loads",
"(",
"json_msg",
")",
"for",
"topic",
",",
"value",
"in",
"pyobj",
".",
"items",
"(",
")",
":",
"msg",
"=",
"'{topic} {data}'",
".",
"format",
"(",
"topic",... | 37.25 | 17.25 |
def stop_daemon(self, payload=None):
"""Kill current processes and initiate daemon shutdown.
The daemon will shut down after a last check on all killed processes.
"""
kill_signal = signals['9']
self.process_handler.kill_all(kill_signal, True)
self.running = False
... | [
"def",
"stop_daemon",
"(",
"self",
",",
"payload",
"=",
"None",
")",
":",
"kill_signal",
"=",
"signals",
"[",
"'9'",
"]",
"self",
".",
"process_handler",
".",
"kill_all",
"(",
"kill_signal",
",",
"True",
")",
"self",
".",
"running",
"=",
"False",
"return... | 36.090909 | 15.909091 |
def send_command(self, command):
"""Send a command for FastAGI request:
:param command: Command to launch on FastAGI request. Ex: 'EXEC StartMusicOnHolds'
:type command: String
:Example:
::
@asyncio.coroutine
def call_waiting(request):
... | [
"def",
"send_command",
"(",
"self",
",",
"command",
")",
":",
"command",
"+=",
"'\\n'",
"self",
".",
"writer",
".",
"write",
"(",
"command",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
")",
"yield",
"from",
"self",
".",
"writer",
".",
"drain",
... | 36.848485 | 24.090909 |
def pipe(self, target):
"""
Pipes this Recver to *target*. *target* can either be `Sender`_ (or
`Pair`_) or a callable.
If *target* is a Sender, the two pairs are rewired so that sending on
this Recver's Sender will now be directed to the target's Recver::
sender1, ... | [
"def",
"pipe",
"(",
"self",
",",
"target",
")",
":",
"if",
"callable",
"(",
"target",
")",
":",
"sender",
",",
"recver",
"=",
"self",
".",
"hub",
".",
"pipe",
"(",
")",
"# link the two ends in the closure with a strong reference to",
"# prevent them from being gar... | 31.810345 | 20.293103 |
def handle_config(args):
"""usage: cosmic-ray config <session-file>
Show the configuration for in a session.
"""
session_file = get_db_name(args['<session-file>'])
with use_db(session_file) as database:
config = database.get_config()
print(serialize_config(config))
return ExitC... | [
"def",
"handle_config",
"(",
"args",
")",
":",
"session_file",
"=",
"get_db_name",
"(",
"args",
"[",
"'<session-file>'",
"]",
")",
"with",
"use_db",
"(",
"session_file",
")",
"as",
"database",
":",
"config",
"=",
"database",
".",
"get_config",
"(",
")",
"p... | 28.727273 | 12.454545 |
def save(self, inplace=True):
"""Save all modification to the dataset on the server.
:param inplace: Apply edits on the current instance or get a new one.
:return: Dataset instance.
"""
modified_data = self._modified_data()
if bool(modified_data):
dataset_requ... | [
"def",
"save",
"(",
"self",
",",
"inplace",
"=",
"True",
")",
":",
"modified_data",
"=",
"self",
".",
"_modified_data",
"(",
")",
"if",
"bool",
"(",
"modified_data",
")",
":",
"dataset_request_data",
"=",
"{",
"}",
"name",
"=",
"modified_data",
".",
"pop... | 34 | 17.222222 |
def find(self, pattern):
"""
:param pattern: REGULAR EXPRESSION TO MATCH NAME (NOT INCLUDING PATH)
:return: LIST OF File OBJECTS THAT HAVE MATCHING NAME
"""
output = []
def _find(dir):
if re.match(pattern, dir._filename.split("/")[-1]):
output... | [
"def",
"find",
"(",
"self",
",",
"pattern",
")",
":",
"output",
"=",
"[",
"]",
"def",
"_find",
"(",
"dir",
")",
":",
"if",
"re",
".",
"match",
"(",
"pattern",
",",
"dir",
".",
"_filename",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
... | 30.866667 | 16.066667 |
def wrap(cls, root, refobjinter, refobjects):
"""Wrap the given refobjects in a :class:`Reftrack` instance
and set the right parents
This is the preferred method for creating refobjects. Because you cannot set
the parent of a :class:`Reftrack` before the parent has been wrapped itselfed... | [
"def",
"wrap",
"(",
"cls",
",",
"root",
",",
"refobjinter",
",",
"refobjects",
")",
":",
"tracks",
"=",
"[",
"]",
"for",
"r",
"in",
"refobjects",
":",
"track",
"=",
"cls",
"(",
"root",
"=",
"root",
",",
"refobjinter",
"=",
"refobjinter",
",",
"refobj... | 39.848485 | 18.545455 |
def Weibull(lamda, k, tag=None):
"""
A Weibull random variate
Parameters
----------
lamda : scalar
The scale parameter
k : scalar
The shape parameter
"""
assert (
lamda > 0 and k > 0
), 'Weibull "lamda" and "k" parameters must be greater than zero'
re... | [
"def",
"Weibull",
"(",
"lamda",
",",
"k",
",",
"tag",
"=",
"None",
")",
":",
"assert",
"(",
"lamda",
">",
"0",
"and",
"k",
">",
"0",
")",
",",
"'Weibull \"lamda\" and \"k\" parameters must be greater than zero'",
"return",
"uv",
"(",
"ss",
".",
"exponweib",
... | 23.066667 | 17.2 |
def handle_PoisonPillFrame(self, frame):
""" Is sent in case protocol lost connection to server."""
# Will be delivered after Close or CloseOK handlers. It's for channels,
# so ignore it.
if self.connection.closed.done():
return
# If connection was not closed already ... | [
"def",
"handle_PoisonPillFrame",
"(",
"self",
",",
"frame",
")",
":",
"# Will be delivered after Close or CloseOK handlers. It's for channels,",
"# so ignore it.",
"if",
"self",
".",
"connection",
".",
"closed",
".",
"done",
"(",
")",
":",
"return",
"# If connection was n... | 46.444444 | 12.222222 |
def get_query_context_error_report(self):
"""Get a report on context-specific errors relative to what is expected on the query strand.
:returns: Object with a 'header' and a 'data' where data describes context: before,after ,reference, query. A total is kept for each reference base, and individual errors are ... | [
"def",
"get_query_context_error_report",
"(",
"self",
")",
":",
"report",
"=",
"{",
"}",
"report",
"[",
"'header'",
"]",
"=",
"[",
"'before'",
",",
"'after'",
",",
"'reference'",
",",
"'query'",
",",
"'fraction'",
"]",
"report",
"[",
"'data'",
"]",
"=",
... | 41.6 | 22.35 |
def pretty_plot_two_axis(x, y1, y2, xlabel=None, y1label=None, y2label=None,
width=8, height=None, dpi=300):
"""
Variant of pretty_plot that does a dual axis plot. Adapted from matplotlib
examples. Makes it easier to create plots with different axes.
Args:
x (np.ndarray... | [
"def",
"pretty_plot_two_axis",
"(",
"x",
",",
"y1",
",",
"y2",
",",
"xlabel",
"=",
"None",
",",
"y1label",
"=",
"None",
",",
"y2label",
"=",
"None",
",",
"width",
"=",
"8",
",",
"height",
"=",
"None",
",",
"dpi",
"=",
"300",
")",
":",
"import",
"... | 34.358974 | 22.512821 |
def fishqq(lon=None, lat=None, di_block=None):
"""
Test whether a distribution is Fisherian and make a corresponding Q-Q plot.
The Q-Q plot shows the data plotted against the value expected from a
Fisher distribution. The first plot is the uniform plot which is the
Fisher model distribution in terms... | [
"def",
"fishqq",
"(",
"lon",
"=",
"None",
",",
"lat",
"=",
"None",
",",
"di_block",
"=",
"None",
")",
":",
"if",
"di_block",
"is",
"None",
":",
"all_dirs",
"=",
"make_di_block",
"(",
"lon",
",",
"lat",
")",
"else",
":",
"all_dirs",
"=",
"di_block",
... | 35.607955 | 17.255682 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.