text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
async def start_polling(self,
timeout=20,
relax=0.1,
limit=None,
reset_webhook=None,
fast: typing.Optional[bool] = True,
error_sleep: int = 5):
... | [
"async",
"def",
"start_polling",
"(",
"self",
",",
"timeout",
"=",
"20",
",",
"relax",
"=",
"0.1",
",",
"limit",
"=",
"None",
",",
"reset_webhook",
"=",
"None",
",",
"fast",
":",
"typing",
".",
"Optional",
"[",
"bool",
"]",
"=",
"True",
",",
"error_s... | 33.491803 | 20.213115 |
def _qname(self) -> Optional[QualName]:
"""Parse XML QName."""
if self.test_string("*"):
self.skip_ws()
return False
ident = self.yang_identifier()
ws = self.skip_ws()
try:
next = self.peek()
except EndOfInput:
return ident,... | [
"def",
"_qname",
"(",
"self",
")",
"->",
"Optional",
"[",
"QualName",
"]",
":",
"if",
"self",
".",
"test_string",
"(",
"\"*\"",
")",
":",
"self",
".",
"skip_ws",
"(",
")",
"return",
"False",
"ident",
"=",
"self",
".",
"yang_identifier",
"(",
")",
"ws... | 30.47619 | 12.857143 |
def attach_virtual_server(self, ticket_id=None, virtual_id=None):
"""Attach a virtual server to a ticket.
:param integer ticket_id: the id of the ticket to attach to
:param integer virtual_id: the id of the virtual server to attach
:returns: dict -- The new ticket attachment
""... | [
"def",
"attach_virtual_server",
"(",
"self",
",",
"ticket_id",
"=",
"None",
",",
"virtual_id",
"=",
"None",
")",
":",
"return",
"self",
".",
"ticket",
".",
"addAttachedVirtualGuest",
"(",
"virtual_id",
",",
"id",
"=",
"ticket_id",
")"
] | 43.333333 | 23.555556 |
def make_line_segments(x, y, ispath=True):
"""
Return an (n x 2 x 2) array of n line segments
Parameters
----------
x : array-like
x points
y : array-like
y points
ispath : bool
If True, the points represent a path from one point
to the next until the last. I... | [
"def",
"make_line_segments",
"(",
"x",
",",
"y",
",",
"ispath",
"=",
"True",
")",
":",
"if",
"ispath",
":",
"x",
"=",
"interleave",
"(",
"x",
"[",
":",
"-",
"1",
"]",
",",
"x",
"[",
"1",
":",
"]",
")",
"y",
"=",
"interleave",
"(",
"y",
"[",
... | 27.416667 | 18.583333 |
def run_netsh_command(netsh_args):
"""Execute a netsh command and return the output."""
devnull = open(os.devnull, 'w')
command_raw = 'netsh interface ipv4 ' + netsh_args
return int(subprocess.call(command_raw, stdout=devnull)) | [
"def",
"run_netsh_command",
"(",
"netsh_args",
")",
":",
"devnull",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"command_raw",
"=",
"'netsh interface ipv4 '",
"+",
"netsh_args",
"return",
"int",
"(",
"subprocess",
".",
"call",
"(",
"command_raw",
... | 47.8 | 9 |
def find_if_multibase(column, quality_cutoff, base_cutoff, base_fraction_cutoff):
"""
Finds if a position in a pileup has more than one base present.
:param column: A pileupColumn generated by pysam
:param quality_cutoff: Desired minimum phred quality for a base in order to be counted towards a multi-al... | [
"def",
"find_if_multibase",
"(",
"column",
",",
"quality_cutoff",
",",
"base_cutoff",
",",
"base_fraction_cutoff",
")",
":",
"# Sometimes the qualities come out to ridiculously high (>70) values. Looks to be because sometimes reads",
"# are overlapping and the qualities get summed for over... | 68.096774 | 40.322581 |
def _grow_trees(self):
"""
Adds new trees to the forest according to the specified growth method.
"""
if self.grow_method == GROW_AUTO_INCREMENTAL:
self.tree_kwargs['auto_grow'] = True
while len(self.trees) < self.size:
self.trees.append(Tree(data... | [
"def",
"_grow_trees",
"(",
"self",
")",
":",
"if",
"self",
".",
"grow_method",
"==",
"GROW_AUTO_INCREMENTAL",
":",
"self",
".",
"tree_kwargs",
"[",
"'auto_grow'",
"]",
"=",
"True",
"while",
"len",
"(",
"self",
".",
"trees",
")",
"<",
"self",
".",
"size",... | 38.222222 | 15.777778 |
def thumbnail(self, path, height, width, quality=100, **kwargs):
"""获取文件缩略图
:param path: 远程文件路径
:param height: 缩略图高
:param width: 缩略图宽
:param quality: 缩略图质量,默认100
:return: requests.Response
.. note::
如果返回 HTTP 404 说明该文件不存在缩略图形式
"""
... | [
"def",
"thumbnail",
"(",
"self",
",",
"path",
",",
"height",
",",
"width",
",",
"quality",
"=",
"100",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'ec'",
":",
"1",
",",
"'path'",
":",
"path",
",",
"'quality'",
":",
"quality",
",",
"'w... | 30.190476 | 18.142857 |
def _intersection_with_si(self, si):
"""
Intersection with another :class:`StridedInterval`.
:param si: The other operand
:return:
"""
new_si_set = set()
for si_ in self._si_set:
r = si_.intersection(si)
new_si_set.add(r)
if len(... | [
"def",
"_intersection_with_si",
"(",
"self",
",",
"si",
")",
":",
"new_si_set",
"=",
"set",
"(",
")",
"for",
"si_",
"in",
"self",
".",
"_si_set",
":",
"r",
"=",
"si_",
".",
"intersection",
"(",
"si",
")",
"new_si_set",
".",
"add",
"(",
"r",
")",
"i... | 27.636364 | 19.454545 |
def find_behind_subscriptions(self, request):
"""
Starts a celery task that looks through active subscriptions to find
and subscriptions that are behind where they should be, and adds a
BehindSubscription for them.
"""
task_id = find_behind_subscriptions.delay()
... | [
"def",
"find_behind_subscriptions",
"(",
"self",
",",
"request",
")",
":",
"task_id",
"=",
"find_behind_subscriptions",
".",
"delay",
"(",
")",
"return",
"Response",
"(",
"{",
"\"accepted\"",
":",
"True",
",",
"\"task_id\"",
":",
"str",
"(",
"task_id",
")",
... | 38.636364 | 20.454545 |
def _restore_backup(self):
"""Restore the specified database."""
input_filename, input_file = self._get_backup_file(database=self.database_name,
servername=self.servername)
self.logger.info("Restoring backup for database '%s' and server ... | [
"def",
"_restore_backup",
"(",
"self",
")",
":",
"input_filename",
",",
"input_file",
"=",
"self",
".",
"_get_backup_file",
"(",
"database",
"=",
"self",
".",
"database_name",
",",
"servername",
"=",
"self",
".",
"servername",
")",
"self",
".",
"logger",
"."... | 47.72 | 24.56 |
def parseParams(string):
"""
Parse parameters
"""
all = params_re.findall(string)
allParameters = []
for tup in all:
paramList = [tup[0]] # tup looks like (name, valuesString)
for pair in param_values_re.findall(tup[1]):
# pair looks like ('', value) or (value, '')
... | [
"def",
"parseParams",
"(",
"string",
")",
":",
"all",
"=",
"params_re",
".",
"findall",
"(",
"string",
")",
"allParameters",
"=",
"[",
"]",
"for",
"tup",
"in",
"all",
":",
"paramList",
"=",
"[",
"tup",
"[",
"0",
"]",
"]",
"# tup looks like (name, valuesS... | 31.25 | 11.75 |
def pop_to(source, dest, key, name=None):
"""
A convenience function which pops a key k from source to dest.
None values are not passed on. If k already exists in dest an
error is raised.
"""
value = source.pop(key, None)
if value is not None:
safe_setitem(dest, key, value, name=nam... | [
"def",
"pop_to",
"(",
"source",
",",
"dest",
",",
"key",
",",
"name",
"=",
"None",
")",
":",
"value",
"=",
"source",
".",
"pop",
"(",
"key",
",",
"None",
")",
"if",
"value",
"is",
"not",
"None",
":",
"safe_setitem",
"(",
"dest",
",",
"key",
",",
... | 33 | 12.8 |
def toMBI(self, getMemoryDump = False):
"""
Returns a L{win32.MemoryBasicInformation} object using the data
retrieved from the database.
@type getMemoryDump: bool
@param getMemoryDump: (Optional) If C{True} retrieve the memory dump.
Defaults to C{False} since this m... | [
"def",
"toMBI",
"(",
"self",
",",
"getMemoryDump",
"=",
"False",
")",
":",
"mbi",
"=",
"win32",
".",
"MemoryBasicInformation",
"(",
")",
"mbi",
".",
"BaseAddress",
"=",
"self",
".",
"address",
"mbi",
".",
"RegionSize",
"=",
"self",
".",
"size",
"mbi",
... | 39.709677 | 13.129032 |
def get_stdev(self, asset_type):
"""
Returns the standard deviation for a set of a certain asset type.
:param asset_type: ``str`` of the asset type to calculate standard
deviation for.
:returns: A ``int`` or ``float`` of standard deviation, depending on
the self.decimal_... | [
"def",
"get_stdev",
"(",
"self",
",",
"asset_type",
")",
":",
"load_times",
"=",
"[",
"]",
"# Handle edge cases like TTFB",
"if",
"asset_type",
"==",
"'ttfb'",
":",
"for",
"page",
"in",
"self",
".",
"pages",
":",
"if",
"page",
".",
"time_to_first_byte",
"is"... | 39.84 | 17.6 |
def verify_x509_cert_chain(cert_chain, ca_pem_file=None, ca_path=None):
"""
Look at certs in the cert chain and add them to the store one by one.
Return the cert at the end of the chain. That is the cert to be used by the caller for verifying.
From https://www.w3.org/TR/xmldsig-core2/#sec-X509Data:
... | [
"def",
"verify_x509_cert_chain",
"(",
"cert_chain",
",",
"ca_pem_file",
"=",
"None",
",",
"ca_path",
"=",
"None",
")",
":",
"from",
"OpenSSL",
"import",
"SSL",
"context",
"=",
"SSL",
".",
"Context",
"(",
"SSL",
".",
"TLSv1_METHOD",
")",
"if",
"ca_pem_file",
... | 42.588235 | 17.647059 |
def on_connected(self, headers, body):
"""
Once the connection is established, and 'heart-beat' is found in the headers, we calculate the real
heartbeat numbers (based on what the server sent and what was specified by the client) - if the heartbeats
are not 0, we start up the heartbeat l... | [
"def",
"on_connected",
"(",
"self",
",",
"headers",
",",
"body",
")",
":",
"if",
"'heart-beat'",
"in",
"headers",
":",
"self",
".",
"heartbeats",
"=",
"utils",
".",
"calculate_heartbeats",
"(",
"headers",
"[",
"'heart-beat'",
"]",
".",
"replace",
"(",
"' '... | 53.172414 | 27.241379 |
def account_info(remote, resp):
"""Retrieve remote account information used to find local user.
It returns a dictionary with the following structure:
.. code-block:: python
{
'user': {
'email': '...',
'profile': {
'username': '...',
... | [
"def",
"account_info",
"(",
"remote",
",",
"resp",
")",
":",
"gh",
"=",
"github3",
".",
"login",
"(",
"token",
"=",
"resp",
"[",
"'access_token'",
"]",
")",
"me",
"=",
"gh",
".",
"me",
"(",
")",
"return",
"dict",
"(",
"user",
"=",
"dict",
"(",
"e... | 27.65 | 18.5 |
def variables(self, value):
"""
Setter for **self.__variables** attribute.
:param value: Attribute value.
:type value: dict
"""
if value is not None:
assert type(value) is dict, "'{0}' attribute: '{1}' type is not 'dict'!".format("variables", value)
... | [
"def",
"variables",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"dict",
",",
"\"'{0}' attribute: '{1}' type is not 'dict'!\"",
".",
"format",
"(",
"\"variables\"",
",",
"value",
")"... | 41.625 | 21.75 |
def _make_request(self, url, **kwargs):
"""
Make a request to an OAuth2 endpoint
"""
response = requests.post(url, **kwargs)
try:
return response.json()
except ValueError:
pass
return parse_qs(response.content) | [
"def",
"_make_request",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"return",
"response",
".",
"json",
"(",
")",
"except",
"ValueError",
... | 28.1 | 8.5 |
def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | [
"def",
"relative_path",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"path",
")"
] | 28.4 | 8 |
def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query):
"""
Return the request params we would send to the api.
"""
url, params = self._prepare_request(command, query)
return {
"url": url, "params": params, "files": files, "stream": u... | [
"def",
"do",
"(",
"self",
",",
"command",
",",
"files",
"=",
"None",
",",
"use_long_polling",
"=",
"False",
",",
"request_timeout",
"=",
"None",
",",
"*",
"*",
"query",
")",
":",
"url",
",",
"params",
"=",
"self",
".",
"_prepare_request",
"(",
"command... | 47.7 | 24.9 |
def statement(self, days=60):
"""Download the :py:class:`ofxparse.Statement` given the time range
:param days: Number of days to look back at
:type days: integer
:rtype: :py:class:`ofxparser.Statement`
"""
parsed = self.download_parsed(days=days)
return parsed.ac... | [
"def",
"statement",
"(",
"self",
",",
"days",
"=",
"60",
")",
":",
"parsed",
"=",
"self",
".",
"download_parsed",
"(",
"days",
"=",
"days",
")",
"return",
"parsed",
".",
"account",
".",
"statement"
] | 36.333333 | 10.111111 |
def main():
"""
The single entry point to glim command line interface.Main method is called
from pypi console_scripts key or by glim.py on root.This function
initializes a new app given the glim commands and app commands if app
exists.
Usage
-----
$ python glim/cli.py start
$ py... | [
"def",
"main",
"(",
")",
":",
"# register the global parser",
"preparser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
",",
"add_help",
"=",
"False",
")",
"preparser",
".",
"add_argument",
"(",
"'--env'",
",",
"'-e'",
",",
"... | 29.709677 | 21.354839 |
def service_checks():
"""Validate all `service_checks.json` files."""
root = get_root()
echo_info("Validating all service_checks.json files...")
failed_checks = 0
ok_checks = 0
for check_name in sorted(os.listdir(root)):
service_checks_file = os.path.join(root, check_name, 'service_check... | [
"def",
"service_checks",
"(",
")",
":",
"root",
"=",
"get_root",
"(",
")",
"echo_info",
"(",
"\"Validating all service_checks.json files...\"",
")",
"failed_checks",
"=",
"0",
"ok_checks",
"=",
"0",
"for",
"check_name",
"in",
"sorted",
"(",
"os",
".",
"listdir",... | 43.454545 | 22.3 |
def Parse(self, stat, file_object, knowledge_base):
"""Parse the History file."""
_ = knowledge_base
# TODO(user): Convert this to use the far more intelligent plaso parser.
chrome = ChromeParser(file_object)
for timestamp, entry_type, url, data1, _, _ in chrome.Parse():
if entry_type == "CHRO... | [
"def",
"Parse",
"(",
"self",
",",
"stat",
",",
"file_object",
",",
"knowledge_base",
")",
":",
"_",
"=",
"knowledge_base",
"# TODO(user): Convert this to use the far more intelligent plaso parser.",
"chrome",
"=",
"ChromeParser",
"(",
"file_object",
")",
"for",
"timesta... | 39.954545 | 10.090909 |
def format_image(path, options):
'''Formats an image.
Args:
path (str): Path to the image file.
options (dict): Options to apply to the image.
Returns:
(list) A list of PIL images. The list will always be of length
1 unless resolutions for resizing are provided in the optio... | [
"def",
"format_image",
"(",
"path",
",",
"options",
")",
":",
"image",
"=",
"Image",
".",
"open",
"(",
"path",
")",
"image_pipeline_results",
"=",
"__pipeline_image",
"(",
"image",
",",
"options",
")",
"return",
"image_pipeline_results"
] | 31.714286 | 22.428571 |
def list_milestones(self, **queryparams):
"""
Get the list of :class:`Milestone` resources for the project.
"""
return Milestones(self.requester).list(project=self.id, **queryparams) | [
"def",
"list_milestones",
"(",
"self",
",",
"*",
"*",
"queryparams",
")",
":",
"return",
"Milestones",
"(",
"self",
".",
"requester",
")",
".",
"list",
"(",
"project",
"=",
"self",
".",
"id",
",",
"*",
"*",
"queryparams",
")"
] | 42 | 13.6 |
def unwrap(self, value):
"""Unpack a Value into an augmented python type (selected from the 'value' field)
"""
if value.changed('value.choices'):
self._choices = value['value.choices']
idx = value['value.index']
ret = ntenum(idx)._store(value)
try:
... | [
"def",
"unwrap",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
".",
"changed",
"(",
"'value.choices'",
")",
":",
"self",
".",
"_choices",
"=",
"value",
"[",
"'value.choices'",
"]",
"idx",
"=",
"value",
"[",
"'value.index'",
"]",
"ret",
"=",
"nten... | 32.538462 | 11.307692 |
def file_upload_dialog_timeout(self, value):
"""
Sets the options File Upload Dialog Timeout value
:Args:
- value: Timeout in milliseconds
"""
if not isinstance(value, int):
raise ValueError('File Upload Dialog Timeout must be an integer.')
self._op... | [
"def",
"file_upload_dialog_timeout",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"'File Upload Dialog Timeout must be an integer.'",
")",
"self",
".",
"_options",
"[",
"self",
".... | 32.363636 | 17.272727 |
def _is_base_matcher_class_definition(meta, classname, dict_):
"""Checks whether given class name and dictionary
define the :class:`BaseMatcher`.
"""
if classname != 'BaseMatcher':
return False
methods = list(filter(inspect.isfunction, dict_.values()))
return ... | [
"def",
"_is_base_matcher_class_definition",
"(",
"meta",
",",
"classname",
",",
"dict_",
")",
":",
"if",
"classname",
"!=",
"'BaseMatcher'",
":",
"return",
"False",
"methods",
"=",
"list",
"(",
"filter",
"(",
"inspect",
".",
"isfunction",
",",
"dict_",
".",
... | 46.375 | 12.375 |
def to_json_data(self, model_name=None):
"""
Parameters
----------
model_name: str, default None
if given, will be used as external file directory base name
Returns
-------
A dictionary of serialized data.
"""
return collections.Ordere... | [
"def",
"to_json_data",
"(",
"self",
",",
"model_name",
"=",
"None",
")",
":",
"return",
"collections",
".",
"OrderedDict",
"(",
"[",
"(",
"k",
",",
"self",
".",
"get_serialized_value",
"(",
"k",
",",
"model_name",
"=",
"model_name",
")",
")",
"for",
"k",... | 32.916667 | 20.583333 |
def domains(self):
"""
This method returns all of your current domains.
"""
json = self.request('/domains', method='GET')
status = json.get('status')
if status == 'OK':
domains_json = json.get('domains', [])
domains = [Domain.from_json(domain) for ... | [
"def",
"domains",
"(",
"self",
")",
":",
"json",
"=",
"self",
".",
"request",
"(",
"'/domains'",
",",
"method",
"=",
"'GET'",
")",
"status",
"=",
"json",
".",
"get",
"(",
"'status'",
")",
"if",
"status",
"==",
"'OK'",
":",
"domains_json",
"=",
"json"... | 36.692308 | 13.769231 |
def attach_photo(self, photo: String, caption: String = None):
"""
Attach photo
:param photo:
:param caption:
:return: self
"""
self.media.attach_photo(photo, caption)
return self | [
"def",
"attach_photo",
"(",
"self",
",",
"photo",
":",
"String",
",",
"caption",
":",
"String",
"=",
"None",
")",
":",
"self",
".",
"media",
".",
"attach_photo",
"(",
"photo",
",",
"caption",
")",
"return",
"self"
] | 23.5 | 16.5 |
def sample(self, fraction, seed=None, exact=False):
"""
Sample a fraction of the current SFrame's rows.
Parameters
----------
fraction : float
Fraction of the rows to fetch. Must be between 0 and 1.
if exact is False (default), the number of rows returned... | [
"def",
"sample",
"(",
"self",
",",
"fraction",
",",
"seed",
"=",
"None",
",",
"exact",
"=",
"False",
")",
":",
"if",
"seed",
"is",
"None",
":",
"seed",
"=",
"abs",
"(",
"hash",
"(",
"\"%0.20f\"",
"%",
"time",
".",
"time",
"(",
")",
")",
")",
"%... | 30.666667 | 23.541667 |
def by_key(self, style_key, style_value):
"""Return a processor for a "simple" style value.
Parameters
----------
style_key : str
A style key.
style_value : bool or str
A "simple" style value that is either a style attribute (str) and a
boolea... | [
"def",
"by_key",
"(",
"self",
",",
"style_key",
",",
"style_value",
")",
":",
"if",
"self",
".",
"style_types",
"[",
"style_key",
"]",
"is",
"bool",
":",
"style_attr",
"=",
"style_key",
"else",
":",
"style_attr",
"=",
"style_value",
"def",
"proc",
"(",
"... | 28.125 | 18.708333 |
def _get_correct_module(mod):
"""returns imported module
check if is ``leonardo_module_conf`` specified and then import them
"""
module_location = getattr(
mod, 'leonardo_module_conf',
getattr(mod, "LEONARDO_MODULE_CONF", None))
if module_location:
mod = import_module(module... | [
"def",
"_get_correct_module",
"(",
"mod",
")",
":",
"module_location",
"=",
"getattr",
"(",
"mod",
",",
"'leonardo_module_conf'",
",",
"getattr",
"(",
"mod",
",",
"\"LEONARDO_MODULE_CONF\"",
",",
"None",
")",
")",
"if",
"module_location",
":",
"mod",
"=",
"imp... | 32.571429 | 14.714286 |
def connect(self, url: str):
"""Connect to the database and set it as main database
:param url: path to the database, uses the Sqlalchemy format
:type url: str
:example: ``ds.connect("sqlite:///mydb.slqite")``
"""
try:
self.db = dataset.connect(url, row_type... | [
"def",
"connect",
"(",
"self",
",",
"url",
":",
"str",
")",
":",
"try",
":",
"self",
".",
"db",
"=",
"dataset",
".",
"connect",
"(",
"url",
",",
"row_type",
"=",
"stuf",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"err",
"(",
"e",
... | 33.235294 | 17.764706 |
def In(self, *values):
"""Sets the type of the WHERE clause as "in".
Args:
*values: The values to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to.
"""
self._awql = self._CreateMultipleValuesCondition(values, 'IN')
return self._query_build... | [
"def",
"In",
"(",
"self",
",",
"*",
"values",
")",
":",
"self",
".",
"_awql",
"=",
"self",
".",
"_CreateMultipleValuesCondition",
"(",
"values",
",",
"'IN'",
")",
"return",
"self",
".",
"_query_builder"
] | 28.363636 | 20.909091 |
def get_energy(self):
"""
Returns the consumed energy since the start of the statistics in Wh.
Attention: Returns None if the value can't be queried or is unknown.
"""
value = self.box.homeautoswitch("getswitchenergy", self.actor_id)
return int(value) if value.isdigit() e... | [
"def",
"get_energy",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"box",
".",
"homeautoswitch",
"(",
"\"getswitchenergy\"",
",",
"self",
".",
"actor_id",
")",
"return",
"int",
"(",
"value",
")",
"if",
"value",
".",
"isdigit",
"(",
")",
"else",
"No... | 46 | 19.714286 |
def should_break_here(self, frame):
"""Check wether there is a breakpoint at this frame."""
# Next line commented out for performance
#_logger.b_debug("should_break_here(filename=%s, lineno=%s) with breaks=%s",
# frame.f_code.co_filename,
# frame.f_l... | [
"def",
"should_break_here",
"(",
"self",
",",
"frame",
")",
":",
"# Next line commented out for performance",
"#_logger.b_debug(\"should_break_here(filename=%s, lineno=%s) with breaks=%s\",",
"# frame.f_code.co_filename,",
"# frame.f_lineno,",
"# ... | 51.133333 | 17.2 |
def given_i_am_logged_in(context, username):
"""
:type username: str
:type context: behave.runner.Context
"""
user = get_user_model().objects.get(username=username)
context.apiClient.force_authenticate(user=user) | [
"def",
"given_i_am_logged_in",
"(",
"context",
",",
"username",
")",
":",
"user",
"=",
"get_user_model",
"(",
")",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username",
")",
"context",
".",
"apiClient",
".",
"force_authenticate",
"(",
"user",
"=",
... | 33.714286 | 7.428571 |
def ASR(self, a):
"""
ASR (Arithmetic Shift Right) alias LSR (Logical Shift Right)
Shifts all bits of the register one place to the right. Bit seven is held
constant. Bit zero is shifted into the C (carry) bit.
source code forms: ASR Q; ASRA; ASRB
CC bits "HNZVC": uaa-... | [
"def",
"ASR",
"(",
"self",
",",
"a",
")",
":",
"r",
"=",
"(",
"a",
">>",
"1",
")",
"|",
"(",
"a",
"&",
"0x80",
")",
"self",
".",
"clear_NZC",
"(",
")",
"self",
".",
"C",
"=",
"get_bit",
"(",
"a",
",",
"bit",
"=",
"0",
")",
"# same as: self.... | 30.375 | 20.625 |
def create_role_config_group(resource_root, service_name, name, display_name,
role_type, cluster_name="default"):
"""
Create a role config group.
@param resource_root: The root Resource object.
@param service_name: Service name.
@param name: The name of the new group.
@param display_name: The display na... | [
"def",
"create_role_config_group",
"(",
"resource_root",
",",
"service_name",
",",
"name",
",",
"display_name",
",",
"role_type",
",",
"cluster_name",
"=",
"\"default\"",
")",
":",
"apigroup",
"=",
"ApiRoleConfigGroup",
"(",
"resource_root",
",",
"name",
",",
"dis... | 43 | 12.733333 |
def printFrequencyStatistics(counts, frequencies, numWords, size):
"""
Print interesting statistics regarding the counts and frequency matrices
"""
avgBits = float(counts.sum())/numWords
print "Retina width=128, height=128"
print "Total number of words processed=",numWords
print "Average number of bits pe... | [
"def",
"printFrequencyStatistics",
"(",
"counts",
",",
"frequencies",
",",
"numWords",
",",
"size",
")",
":",
"avgBits",
"=",
"float",
"(",
"counts",
".",
"sum",
"(",
")",
")",
"/",
"numWords",
"print",
"\"Retina width=128, height=128\"",
"print",
"\"Total numbe... | 44.8125 | 9.9375 |
def get_policy(self, name):
"""Get a single Policy by name.
Args:
name (str): The name of the Policy.
Returns:
(:obj:`Policy`) The Policy that matches the name.
"""
address = _create_policy_address(name)
policy_list_bytes = None
try:
... | [
"def",
"get_policy",
"(",
"self",
",",
"name",
")",
":",
"address",
"=",
"_create_policy_address",
"(",
"name",
")",
"policy_list_bytes",
"=",
"None",
"try",
":",
"policy_list_bytes",
"=",
"self",
".",
"_state_view",
".",
"get",
"(",
"address",
"=",
"address... | 29.24 | 19.4 |
def findall(self, string, *args, **kwargs):
"""Apply `findall`."""
return self._pattern.findall(string, *args, **kwargs) | [
"def",
"findall",
"(",
"self",
",",
"string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_pattern",
".",
"findall",
"(",
"string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 33.5 | 16 |
def evaluate_formula(formula, variables):
"""Very simple formula evaluator. Beware the security.
:param formula: A simple formula.
:type formula: str
:param variables: A collection of variable (key and value).
:type variables: dict
:returns: The result of the formula execution.
:rtype: fl... | [
"def",
"evaluate_formula",
"(",
"formula",
",",
"variables",
")",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"variables",
".",
"items",
"(",
")",
")",
":",
"if",
"value",
"is",
"None",
"or",
"(",
"hasattr",
"(",
"value",
",",
"'isNull'",
")"... | 32.263158 | 16.947368 |
def parse_path(root_dir):
"""Split path into head and last component for the completer.
Also return position where last component starts.
:param root_dir: str path
:return: tuple of (string, string, int)
"""
base_dir, last_dir, position = '', '', 0
if root_dir:
base_dir, last_dir = o... | [
"def",
"parse_path",
"(",
"root_dir",
")",
":",
"base_dir",
",",
"last_dir",
",",
"position",
"=",
"''",
",",
"''",
",",
"0",
"if",
"root_dir",
":",
"base_dir",
",",
"last_dir",
"=",
"os",
".",
"path",
".",
"split",
"(",
"root_dir",
")",
"position",
... | 38.636364 | 8.636364 |
def H(g,i):
"""recursively constructs H line for g; i = len(g)-1"""
g1 = g&(2**i)
if i:
n = Hwidth(i)
i=i-1
Hn = H(g,i)
if g1:
return Hn<<(2*n) | Hn<<n | Hn
else:
return int('1'*n,2)<<(2*n) | L(g,i)<<n | Hn
else:
if g1... | [
"def",
"H",
"(",
"g",
",",
"i",
")",
":",
"g1",
"=",
"g",
"&",
"(",
"2",
"**",
"i",
")",
"if",
"i",
":",
"n",
"=",
"Hwidth",
"(",
"i",
")",
"i",
"=",
"i",
"-",
"1",
"Hn",
"=",
"H",
"(",
"g",
",",
"i",
")",
"if",
"g1",
":",
"return",... | 24 | 20.9375 |
def validate_project(project_name):
"""
Check the defined project name against keywords, builtins and existing
modules to avoid name clashing
"""
if '-' in project_name:
return None
if keyword.iskeyword(project_name):
return None
if project_name in dir(__builtins__):
... | [
"def",
"validate_project",
"(",
"project_name",
")",
":",
"if",
"'-'",
"in",
"project_name",
":",
"return",
"None",
"if",
"keyword",
".",
"iskeyword",
"(",
"project_name",
")",
":",
"return",
"None",
"if",
"project_name",
"in",
"dir",
"(",
"__builtins__",
")... | 26.875 | 13.375 |
def _parse_port_ranges(pool_str):
"""Given a 'N-P,X-Y' description of port ranges, return a set of ints."""
ports = set()
for range_str in pool_str.split(','):
try:
a, b = range_str.split('-', 1)
start, end = int(a), int(b)
except ValueError:
log.error('Ig... | [
"def",
"_parse_port_ranges",
"(",
"pool_str",
")",
":",
"ports",
"=",
"set",
"(",
")",
"for",
"range_str",
"in",
"pool_str",
".",
"split",
"(",
"','",
")",
":",
"try",
":",
"a",
",",
"b",
"=",
"range_str",
".",
"split",
"(",
"'-'",
",",
"1",
")",
... | 38 | 14.333333 |
def nodes():
'''
List running nodes on all enabled cloud providers. Automatically flushes caches
'''
for name, provider in env.providers.items():
print name
provider.nodes()
print | [
"def",
"nodes",
"(",
")",
":",
"for",
"name",
",",
"provider",
"in",
"env",
".",
"providers",
".",
"items",
"(",
")",
":",
"print",
"name",
"provider",
".",
"nodes",
"(",
")",
"print"
] | 26.5 | 26.25 |
def _create_output_directories(self, analysis):
"""
Create the necessary output and resource directories for the specified analysis
:param: analysis: analysis associated with a given test_id
"""
try:
os.makedirs(analysis.output_directory)
except OSError as exception:
if exception.err... | [
"def",
"_create_output_directories",
"(",
"self",
",",
"analysis",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"analysis",
".",
"output_directory",
")",
"except",
"OSError",
"as",
"exception",
":",
"if",
"exception",
".",
"errno",
"!=",
"errno",
".",
... | 35.3125 | 16.5625 |
def handle_image_posts(function=None):
"""
Decorator for views that handles ajax image posts in base64 encoding, saving
the image and returning the url
"""
@wraps(function, assigned=available_attrs(function))
def _wrapped_view(request, *args, **kwargs):
if 'image' in request.META['CONTEN... | [
"def",
"handle_image_posts",
"(",
"function",
"=",
"None",
")",
":",
"@",
"wraps",
"(",
"function",
",",
"assigned",
"=",
"available_attrs",
"(",
"function",
")",
")",
"def",
"_wrapped_view",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"... | 51.928571 | 23.785714 |
def copy(value, **kwargs):
"""Return a copy of a **HasProperties** instance
A copy is produced by serializing the HasProperties instance then
deserializing it to a new instance. Therefore, if any properties
cannot be serialized/deserialized, :code:`copy` will fail. Any
keyword arguments will be pas... | [
"def",
"copy",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"HasProperties",
")",
":",
"raise",
"ValueError",
"(",
"'properties.copy may only be used to copy'",
"'HasProperties instances'",
")",
"kwargs",
".",
"u... | 47.0625 | 21.625 |
def save_to_name_list(dest, name_parts, value):
"""
Util to save some name sequence to a dict. For instance, `("location","query")` would save
to dest["location"]["query"].
"""
if len(name_parts) > 1:
for part in name_parts[:-1]:
if part not in dest:
dest[part] = ... | [
"def",
"save_to_name_list",
"(",
"dest",
",",
"name_parts",
",",
"value",
")",
":",
"if",
"len",
"(",
"name_parts",
")",
">",
"1",
":",
"for",
"part",
"in",
"name_parts",
"[",
":",
"-",
"1",
"]",
":",
"if",
"part",
"not",
"in",
"dest",
":",
"dest",... | 34.090909 | 11 |
def prepare(self, **kwargs):
""" Prepare for rendering """
for k, v in kwargs.items():
setattr(self, k, v)
if not self.is_initialized:
self.initialize()
if not self.proxy_is_active:
self.activate_proxy() | [
"def",
"prepare",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")",
"if",
"not",
"self",
".",
"is_initialized",
":",
"self",
".",
... | 33 | 6.625 |
def infer_bool(node, context=None):
"""Understand bool calls."""
if len(node.args) > 1:
# Invalid bool call.
raise UseInferenceDefault
if not node.args:
return nodes.Const(False)
argument = node.args[0]
try:
inferred = next(argument.infer(context=context))
excep... | [
"def",
"infer_bool",
"(",
"node",
",",
"context",
"=",
"None",
")",
":",
"if",
"len",
"(",
"node",
".",
"args",
")",
">",
"1",
":",
"# Invalid bool call.",
"raise",
"UseInferenceDefault",
"if",
"not",
"node",
".",
"args",
":",
"return",
"nodes",
".",
"... | 26.857143 | 14.285714 |
def DiffPrimitiveArrays(self, oldObj, newObj):
"""Diff two primitive arrays"""
if len(oldObj) != len(newObj):
__Log__.debug('DiffDoArrays: Array lengths do not match %d != %d'
% (len(oldObj), len(newObj)))
return False
match = True
if self._ignoreArrayOrder:
... | [
"def",
"DiffPrimitiveArrays",
"(",
"self",
",",
"oldObj",
",",
"newObj",
")",
":",
"if",
"len",
"(",
"oldObj",
")",
"!=",
"len",
"(",
"newObj",
")",
":",
"__Log__",
".",
"debug",
"(",
"'DiffDoArrays: Array lengths do not match %d != %d'",
"%",
"(",
"len",
"(... | 34.904762 | 15.714286 |
def set_salt_view():
'''
Helper function that sets the salt design
document. Uses get_valid_salt_views and some hardcoded values.
'''
options = _get_options(ret=None)
# Create the new object that we will shove in as the design doc.
new_doc = {}
new_doc['views'] = get_valid_salt_views()... | [
"def",
"set_salt_view",
"(",
")",
":",
"options",
"=",
"_get_options",
"(",
"ret",
"=",
"None",
")",
"# Create the new object that we will shove in as the design doc.",
"new_doc",
"=",
"{",
"}",
"new_doc",
"[",
"'views'",
"]",
"=",
"get_valid_salt_views",
"(",
")",
... | 34.52381 | 23.285714 |
def str_index(x, sub, start=0, end=None):
"""Returns the lowest indices in each string in a column, where the provided substring is fully contained between within a
sample. If the substring is not found, -1 is returned. It is the same as `str.find`.
:param str sub: A substring to be found in the samples
... | [
"def",
"str_index",
"(",
"x",
",",
"sub",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"return",
"str_find",
"(",
"x",
",",
"sub",
",",
"start",
",",
"end",
")"
] | 28.484848 | 22.515152 |
def removeChild(self, child):
"""
Remove a child from this element. The child element is
returned, and it's parentNode element is reset. If the
child will not be used any more, you should call its
unlink() method to promote garbage collection.
"""
for i, childNode in enumerate(self.childNodes):
if ch... | [
"def",
"removeChild",
"(",
"self",
",",
"child",
")",
":",
"for",
"i",
",",
"childNode",
"in",
"enumerate",
"(",
"self",
".",
"childNodes",
")",
":",
"if",
"childNode",
"is",
"child",
":",
"del",
"self",
".",
"childNodes",
"[",
"i",
"]",
"child",
"."... | 32.538462 | 12.076923 |
def report(times=None,
include_itrs=True,
include_stats=True,
delim_mode=False,
format_options=None):
"""
Produce a formatted report of the current timing data.
Notes:
When reporting a collection of parallel subdivisions, only the one with
the gre... | [
"def",
"report",
"(",
"times",
"=",
"None",
",",
"include_itrs",
"=",
"True",
",",
"include_stats",
"=",
"True",
",",
"delim_mode",
"=",
"False",
",",
"format_options",
"=",
"None",
")",
":",
"if",
"times",
"is",
"None",
":",
"if",
"f",
".",
"root",
... | 38.384615 | 17.246154 |
def start_head_processes(self):
"""Start head processes on the node."""
logger.info(
"Process STDOUT and STDERR is being redirected to {}.".format(
self._logs_dir))
assert self._redis_address is None
# If this is the head node, start the relevant head node pro... | [
"def",
"start_head_processes",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Process STDOUT and STDERR is being redirected to {}.\"",
".",
"format",
"(",
"self",
".",
"_logs_dir",
")",
")",
"assert",
"self",
".",
"_redis_address",
"is",
"None",
"# If this is... | 41.230769 | 12.076923 |
def filter_exclude_dicts(filter_dict=None, exclude_dict=None, name='acctno', values=[], swap=False):
"""Produces kwargs dicts for Django Queryset `filter` and `exclude` from a list of values
The last, critical step in generating Django ORM kwargs dicts from a natural language query.
Properly parses "NOT" u... | [
"def",
"filter_exclude_dicts",
"(",
"filter_dict",
"=",
"None",
",",
"exclude_dict",
"=",
"None",
",",
"name",
"=",
"'acctno'",
",",
"values",
"=",
"[",
"]",
",",
"swap",
"=",
"False",
")",
":",
"filter_dict",
"=",
"filter_dict",
"or",
"{",
"}",
"exclude... | 40.392857 | 24.035714 |
def add_leverage(self):
""" Adds leverage term to the model
Returns
----------
None (changes instance attributes)
"""
if self.leverage is True:
pass
else:
self.leverage = True
self.z_no += 1
self.laten... | [
"def",
"add_leverage",
"(",
"self",
")",
":",
"if",
"self",
".",
"leverage",
"is",
"True",
":",
"pass",
"else",
":",
"self",
".",
"leverage",
"=",
"True",
"self",
".",
"z_no",
"+=",
"1",
"self",
".",
"latent_variables",
".",
"z_list",
".",
"pop",
"("... | 44.304348 | 24.347826 |
def _dynamic_operation(self, map_obj):
"""
Generate function to dynamically apply the operation.
Wraps an existing HoloMap or DynamicMap.
"""
if not isinstance(map_obj, DynamicMap):
def dynamic_operation(*key, **kwargs):
kwargs = dict(self._eval_kwargs... | [
"def",
"_dynamic_operation",
"(",
"self",
",",
"map_obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"map_obj",
",",
"DynamicMap",
")",
":",
"def",
"dynamic_operation",
"(",
"*",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"dict",
"(",
"sel... | 49.380952 | 17.47619 |
def connect(
creator, maxusage=None, setsession=None,
failures=None, ping=1, closeable=True, *args, **kwargs):
"""A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 c... | [
"def",
"connect",
"(",
"creator",
",",
"maxusage",
"=",
"None",
",",
"setsession",
"=",
"None",
",",
"failures",
"=",
"None",
",",
"ping",
"=",
"1",
",",
"closeable",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Stea... | 57.310345 | 25.551724 |
def _get_predictions(self, data, break_ties="random", return_probs=False, **kwargs):
"""Computes predictions in batch, given a labeled dataset
Args:
data: a Pytorch DataLoader, Dataset, or tuple with Tensors (X,Y):
X: The input for the predict method
Y: An [n... | [
"def",
"_get_predictions",
"(",
"self",
",",
"data",
",",
"break_ties",
"=",
"\"random\"",
",",
"return_probs",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"data_loader",
"=",
"self",
".",
"_create_data_loader",
"(",
"data",
")",
"Y_p",
"=",
"[",
"]... | 37.756098 | 20.097561 |
def IMUL(cpu, *operands):
"""
Signed multiply.
Performs a signed multiplication of two operands. This instruction has
three forms, depending on the number of operands.
- One-operand form. This form is identical to that used by the MUL
instruction. Here, the sourc... | [
"def",
"IMUL",
"(",
"cpu",
",",
"*",
"operands",
")",
":",
"dest",
"=",
"operands",
"[",
"0",
"]",
"OperandSize",
"=",
"dest",
".",
"size",
"reg_name_h",
"=",
"{",
"8",
":",
"'AH'",
",",
"16",
":",
"'DX'",
",",
"32",
":",
"'EDX'",
",",
"64",
":... | 45.573427 | 21.755245 |
def jdbc(self, url, table, column=None, lowerBound=None, upperBound=None, numPartitions=None,
predicates=None, properties=None):
"""
Construct a :class:`DataFrame` representing the database table named ``table``
accessible via JDBC URL ``url`` and connection ``properties``.
... | [
"def",
"jdbc",
"(",
"self",
",",
"url",
",",
"table",
",",
"column",
"=",
"None",
",",
"lowerBound",
"=",
"None",
",",
"upperBound",
"=",
"None",
",",
"numPartitions",
"=",
"None",
",",
"predicates",
"=",
"None",
",",
"properties",
"=",
"None",
")",
... | 62.612245 | 32.734694 |
def stitch(images):
"""Stitch regular spaced images.
Parameters
----------
images : ImageCollection or list of tuple(path, row, column)
Each image-tuple should contain path, row and column. Row 0,
column 0 is top left image.
Example:
>>> images = [('1.png', 0, 0), ('2.p... | [
"def",
"stitch",
"(",
"images",
")",
":",
"if",
"type",
"(",
"images",
")",
"!=",
"ImageCollection",
":",
"images",
"=",
"ImageCollection",
"(",
"images",
")",
"calc_translations_parallel",
"(",
"images",
")",
"_translation_warn",
"(",
"images",
")",
"yoffset"... | 31.755556 | 19.2 |
def list_containers(active=True, defined=True,
as_object=False, config_path=None):
"""
List the containers on the system.
"""
if config_path:
if not os.path.exists(config_path):
return tuple()
try:
entries = _lxc.list_containers(active=act... | [
"def",
"list_containers",
"(",
"active",
"=",
"True",
",",
"defined",
"=",
"True",
",",
"as_object",
"=",
"False",
",",
"config_path",
"=",
"None",
")",
":",
"if",
"config_path",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_path",
"... | 29.875 | 20.125 |
def list_users(self, **kwargs):
"""List all users in organisation.
:param int limit: The number of users to retrieve
:param str order: The ordering direction, ascending (asc) or descending (desc)
:param str after: Get users after/starting at given user ID
:param dict filters: Di... | [
"def",
"list_users",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"self",
".",
"_verify_sort_options",
"(",
"kwargs",
")",
"kwargs",
"=",
"self",
".",
"_verify_filters",
"(",
"kwargs",
",",
"User",
")",
"api",
"=",
"self",
".",
"_get_... | 48.714286 | 18.642857 |
def check_if_alive(self):
"""Check if the content is available on the host server. Returns `True` if available, else `False`.
This method is `lazy`-evaluated or only executes when called.
:rtype: bool
"""
try:
from urllib2 import urlopen, URLError, HTTPError
... | [
"def",
"check_if_alive",
"(",
"self",
")",
":",
"try",
":",
"from",
"urllib2",
"import",
"urlopen",
",",
"URLError",
",",
"HTTPError",
"except",
"ImportError",
":",
"from",
"urllib",
".",
"request",
"import",
"urlopen",
",",
"URLError",
",",
"HTTPError",
"if... | 35.32 | 20.12 |
def as_proj4(self):
"""
Return the PROJ.4 string which corresponds to the CRS.
For example::
>>> print(get(21781).as_proj4())
+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 \
+k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel \
+towgs84=674.4,15.1,405.3,0,0,0,... | [
"def",
"as_proj4",
"(",
"self",
")",
":",
"url",
"=",
"'{prefix}{code}.proj4?download'",
".",
"format",
"(",
"prefix",
"=",
"EPSG_IO_URL",
",",
"code",
"=",
"self",
".",
"id",
")",
"return",
"requests",
".",
"get",
"(",
"url",
")",
".",
"text",
".",
"s... | 34.933333 | 20.133333 |
def do_clearqueue(self, line):
"""clearqueue Remove the operations in the queue of write operations without
performing them."""
self._split_args(line, 0, 0)
self._command_processor.get_operation_queue().clear()
self._print_info_if_verbose("All operations in the write queue were c... | [
"def",
"do_clearqueue",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"_split_args",
"(",
"line",
",",
"0",
",",
"0",
")",
"self",
".",
"_command_processor",
".",
"get_operation_queue",
"(",
")",
".",
"clear",
"(",
")",
"self",
".",
"_print_info_if_ve... | 53.833333 | 13.333333 |
def connect(self, timeout_sec=TIMEOUT_SEC):
"""Connect to the device. If not connected within the specified timeout
then an exception is thrown.
"""
self._central_manager.connectPeripheral_options_(self._peripheral, None)
if not self._connected.wait(timeout_sec):
rai... | [
"def",
"connect",
"(",
"self",
",",
"timeout_sec",
"=",
"TIMEOUT_SEC",
")",
":",
"self",
".",
"_central_manager",
".",
"connectPeripheral_options_",
"(",
"self",
".",
"_peripheral",
",",
"None",
")",
"if",
"not",
"self",
".",
"_connected",
".",
"wait",
"(",
... | 54.714286 | 14.285714 |
def _publish_status(self, status, parent=None):
"""send status (busy/idle) on IOPub"""
self.session.send(self.iopub_socket,
u'status',
{u'execution_state': status},
parent=parent,
ident=self._topic('s... | [
"def",
"_publish_status",
"(",
"self",
",",
"status",
",",
"parent",
"=",
"None",
")",
":",
"self",
".",
"session",
".",
"send",
"(",
"self",
".",
"iopub_socket",
",",
"u'status'",
",",
"{",
"u'execution_state'",
":",
"status",
"}",
",",
"parent",
"=",
... | 43.625 | 7.125 |
def _get(self, field):
"""
Return the value for the queried field.
Get the value of a given field. The list of all queryable fields is
documented in the beginning of the model class.
>>> out = m._get('graph')
Parameters
----------
field : string
... | [
"def",
"_get",
"(",
"self",
",",
"field",
")",
":",
"if",
"field",
"in",
"self",
".",
"_list_fields",
"(",
")",
":",
"return",
"self",
".",
"__proxy__",
".",
"get",
"(",
"field",
")",
"else",
":",
"raise",
"KeyError",
"(",
"'Key \\\"%s\\\" not in model. ... | 29.478261 | 22 |
def set_environment_variable(self, name, value):
"""
Set the value of an environment variable.
.. warning::
The server may reject this request depending on its ``AcceptEnv``
setting; such rejections will fail silently (which is common client
practice for this... | [
"def",
"set_environment_variable",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"m",
"=",
"Message",
"(",
")",
"m",
".",
"add_byte",
"(",
"cMSG_CHANNEL_REQUEST",
")",
"m",
".",
"add_int",
"(",
"self",
".",
"remote_chanid",
")",
"m",
".",
"add_string... | 36.2 | 19.32 |
def dual_csiszar_function(logu, csiszar_function, name=None):
"""Calculates the dual Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Csiszar-dual is defined as:
```none
f^*(u) = u f(1 / u)
```
where `f` is some other Csiszar-funct... | [
"def",
"dual_csiszar_function",
"(",
"logu",
",",
"csiszar_function",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"dual_csiszar_function\"",
",",
"[",
"logu",
"]",
")",
":",
"return",
... | 25.23913 | 26.673913 |
def program_unitary(program, n_qubits):
"""
Return the unitary of a pyQuil program.
:param program: A program consisting only of :py:class:`Gate`.:
:return: a unitary corresponding to the composition of the program's gates.
"""
umat = np.eye(2 ** n_qubits)
for instruction in program:
... | [
"def",
"program_unitary",
"(",
"program",
",",
"n_qubits",
")",
":",
"umat",
"=",
"np",
".",
"eye",
"(",
"2",
"**",
"n_qubits",
")",
"for",
"instruction",
"in",
"program",
":",
"if",
"isinstance",
"(",
"instruction",
",",
"Gate",
")",
":",
"unitary",
"... | 38.466667 | 18.066667 |
def status_mute(self, id):
"""
Mute notifications for a status.
Returns a `toot dict`_ with the now muted status
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/mute'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"status_mute",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/mute'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POS... | 31.111111 | 11.111111 |
def save(self, to, driver=None):
"""Save this instance to the path and format provided.
Arguments:
to -- output path as str, file, or MemFileIO instance
Keyword args:
driver -- GDAL driver name as string or ImageDriver
"""
path = getattr(to, 'name', to)
i... | [
"def",
"save",
"(",
"self",
",",
"to",
",",
"driver",
"=",
"None",
")",
":",
"path",
"=",
"getattr",
"(",
"to",
",",
"'name'",
",",
"to",
")",
"if",
"not",
"driver",
"and",
"hasattr",
"(",
"path",
",",
"'encode'",
")",
":",
"driver",
"=",
"driver... | 41.875 | 13.9375 |
def get_connection(self, command, args=()):
"""Get free connection from pool.
Returns connection.
"""
# TODO: find a better way to determine if connection is free
# and not havily used.
command = command.upper().strip()
is_pubsub = command in _PUBSUB_COMMAN... | [
"def",
"get_connection",
"(",
"self",
",",
"command",
",",
"args",
"=",
"(",
")",
")",
":",
"# TODO: find a better way to determine if connection is free",
"# and not havily used.",
"command",
"=",
"command",
".",
"upper",
"(",
")",
".",
"strip",
"(",
")",
"... | 37.115385 | 9.730769 |
def random_uniform(attrs, inputs, proto_obj):
"""Draw random samples from a uniform distribtuion."""
try:
from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
except ImportError:
raise ImportError("Onnx and protobuf need to be installed. "
"Instructions to install - http... | [
"def",
"random_uniform",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"try",
":",
"from",
"onnx",
".",
"mapping",
"import",
"TENSOR_TYPE_TO_NP_TYPE",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"Onnx and protobuf need to be installed. \"",... | 53.4 | 21.4 |
def get_model(model_fn, train_data, param):
"""Feed model_fn with train_data and param
"""
model_param = merge_dicts({"train_data": train_data}, param["model"], param.get("shared", {}))
return model_fn(**model_param) | [
"def",
"get_model",
"(",
"model_fn",
",",
"train_data",
",",
"param",
")",
":",
"model_param",
"=",
"merge_dicts",
"(",
"{",
"\"train_data\"",
":",
"train_data",
"}",
",",
"param",
"[",
"\"model\"",
"]",
",",
"param",
".",
"get",
"(",
"\"shared\"",
",",
... | 45.6 | 13.4 |
def ellipse(self, x, y, width, height, color):
"""
See the Processing function ellipse():
https://processing.org/reference/ellipse_.html
"""
self.context.set_source_rgb(*color)
self.context.save()
self.context.translate(self.tx(x + (width / 2.0)), self.ty(y + (hei... | [
"def",
"ellipse",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"color",
")",
":",
"self",
".",
"context",
".",
"set_source_rgb",
"(",
"*",
"color",
")",
"self",
".",
"context",
".",
"save",
"(",
")",
"self",
".",
"context",
... | 42.5 | 13.333333 |
def to_text(self):
"""Render a Text MessageElement as plain text
Args:
None
Returns:
Str the plain text representation of the Text MessageElement
Raises:
Errors are propagated
"""
if self.items is None:
return
els... | [
"def",
"to_text",
"(",
"self",
")",
":",
"if",
"self",
".",
"items",
"is",
"None",
":",
"return",
"else",
":",
"text",
"=",
"''",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"self",
".",
"items",
")",
":",
"text",
"+=",
"' %s. %s\\n'",
"%",
... | 23.1 | 22.3 |
def decode(cls, root_element):
"""
Decode the object to the object
:param root_element: the parsed xml Element
:type root_element: xml.etree.ElementTree.Element
:return: the decoded Element as object
:rtype: object
"""
new_object = cls()
field_nam... | [
"def",
"decode",
"(",
"cls",
",",
"root_element",
")",
":",
"new_object",
"=",
"cls",
"(",
")",
"field_names_to_attributes",
"=",
"new_object",
".",
"_get_field_names_to_attributes",
"(",
")",
"for",
"child_element",
"in",
"root_element",
":",
"new_object",
".",
... | 37.571429 | 15.714286 |
def get_cxflow_arg_parser(add_common_arguments: bool=False) -> ArgumentParser:
"""
Create the **cxflow** argument parser.
:return: an instance of the parser
"""
# create parser
main_parser = ArgumentParser('cxflow',
description='cxflow: lightweight framework for... | [
"def",
"get_cxflow_arg_parser",
"(",
"add_common_arguments",
":",
"bool",
"=",
"False",
")",
"->",
"ArgumentParser",
":",
"# create parser",
"main_parser",
"=",
"ArgumentParser",
"(",
"'cxflow'",
",",
"description",
"=",
"'cxflow: lightweight framework for machine learning ... | 64.863636 | 39.681818 |
def workflow_add_stage(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /workflow-xxxx/addStage API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fworkflow-xxxx%2FaddStage
"""
return DXHTTPRequest('/%s/... | [
"def",
"workflow_add_stage",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/addStage'",
"%",
"object_id",
",",
"input_params",
",",
"always_retry"... | 55.285714 | 36.142857 |
def input(self, _in, out, **kw):
"""Input filtering."""
args = [self.binary or 'cleancss'] + self.rebase_opt
if self.extra_args:
args.extend(self.extra_args)
self.subprocess(args, out, _in) | [
"def",
"input",
"(",
"self",
",",
"_in",
",",
"out",
",",
"*",
"*",
"kw",
")",
":",
"args",
"=",
"[",
"self",
".",
"binary",
"or",
"'cleancss'",
"]",
"+",
"self",
".",
"rebase_opt",
"if",
"self",
".",
"extra_args",
":",
"args",
".",
"extend",
"("... | 38 | 7 |
def gen_client_id():
"""
Generates random client ID
:return:
"""
import random
gen_id = 'hbmqtt/'
for i in range(7, 23):
gen_id += chr(random.randint(0, 74) + 48)
return gen_id | [
"def",
"gen_client_id",
"(",
")",
":",
"import",
"random",
"gen_id",
"=",
"'hbmqtt/'",
"for",
"i",
"in",
"range",
"(",
"7",
",",
"23",
")",
":",
"gen_id",
"+=",
"chr",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"74",
")",
"+",
"48",
")",
"retu... | 18.818182 | 16.818182 |
def modify_postquery_parts(self, postquery_parts):
"""
Make the comparison recipe a subquery that is left joined to the
base recipe using dimensions that are shared between the recipes.
Hoist the metric from the comparison recipe up to the base query
while adding the suffix.
... | [
"def",
"modify_postquery_parts",
"(",
"self",
",",
"postquery_parts",
")",
":",
"if",
"not",
"self",
".",
"blend_recipes",
":",
"return",
"postquery_parts",
"for",
"blend_recipe",
",",
"blend_type",
",",
"blend_criteria",
"in",
"zip",
"(",
"self",
".",
"blend_re... | 41.728395 | 17.358025 |
def _add_outcome_provenance(self, association, outcome):
"""
:param association: str association curie
:param outcome: dict (json)
:return: None
"""
provenance = Provenance(self.graph)
base = self.curie_map.get_base()
provenance.add_agent_to_graph(base, '... | [
"def",
"_add_outcome_provenance",
"(",
"self",
",",
"association",
",",
"outcome",
")",
":",
"provenance",
"=",
"Provenance",
"(",
"self",
".",
"graph",
")",
"base",
"=",
"self",
".",
"curie_map",
".",
"get_base",
"(",
")",
"provenance",
".",
"add_agent_to_g... | 37.090909 | 14 |
def _copy_delpoy_scripts(self, scripts):
"""
Copy the given deploy scripts to the scripts dir in the prefix
Args:
scripts(list of str): list of paths of the scripts to copy to the
prefix
Returns:
list of str: list with the paths to the copied scr... | [
"def",
"_copy_delpoy_scripts",
"(",
"self",
",",
"scripts",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"paths",
".",
"scripts",
"(",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"paths",
".",
"scripts",
"(... | 33.972222 | 19.527778 |
def Match(self, registry_key):
"""Determines if a Windows Registry key matches the filter.
Args:
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
Returns:
bool: True if the keys match.
"""
value_names = frozenset([
registry_value.name for registry_value in registry... | [
"def",
"Match",
"(",
"self",
",",
"registry_key",
")",
":",
"value_names",
"=",
"frozenset",
"(",
"[",
"registry_value",
".",
"name",
"for",
"registry_value",
"in",
"registry_key",
".",
"GetValues",
"(",
")",
"]",
")",
"return",
"self",
".",
"_value_names",
... | 29.076923 | 21.384615 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.