text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def verify_signature(self, signedtext, cert_file=None, cert_type='pem', node_name=NODE_NAME, node_id=None, id_attr=''):
""" Verifies the signature of a XML document.
:param signedtext: The XML document as a string
:param cert_file: The public key that was used to sign the document
:para... | [
"def",
"verify_signature",
"(",
"self",
",",
"signedtext",
",",
"cert_file",
"=",
"None",
",",
"cert_type",
"=",
"'pem'",
",",
"node_name",
"=",
"NODE_NAME",
",",
"node_id",
"=",
"None",
",",
"id_attr",
"=",
"''",
")",
":",
"# This is only for testing purposes... | 42.571429 | 18.428571 |
def all_thumbnails(path, recursive=True, prefix=None, subdir=None):
"""
Return a dictionary referencing all files which match the thumbnail format.
Each key is a source image filename, relative to path.
Each value is a list of dictionaries as explained in `thumbnails_for_file`.
"""
if prefix is... | [
"def",
"all_thumbnails",
"(",
"path",
",",
"recursive",
"=",
"True",
",",
"prefix",
"=",
"None",
",",
"subdir",
"=",
"None",
")",
":",
"if",
"prefix",
"is",
"None",
":",
"prefix",
"=",
"settings",
".",
"THUMBNAIL_PREFIX",
"if",
"subdir",
"is",
"None",
... | 40.235294 | 16.901961 |
def valid_url(url):
"""Validate url.
:rtype: str
:return: url
:param str url: package homepage url.
"""
regex = re.compile(
r'^(?:http)s?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?))'
r'(?:/?|[/?]\S+)$', re.IGNORECA... | [
"def",
"valid_url",
"(",
"url",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'^(?:http)s?://'",
"r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+'",
"r'(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?))'",
"r'(?:/?|[/?]\\S+)$'",
",",
"re",
".",
"IGNORECASE",
")",
"if",
"not",... | 26.875 | 17.6875 |
def run(self, config, workflow_id, signal, *, data=None):
""" Run the dag by calling the tasks in the correct order.
Args:
config (Config): Reference to the configuration object from which the
settings for the dag are retrieved.
workflow_id (str): Th... | [
"def",
"run",
"(",
"self",
",",
"config",
",",
"workflow_id",
",",
"signal",
",",
"*",
",",
"data",
"=",
"None",
")",
":",
"graph",
"=",
"self",
".",
"make_graph",
"(",
"self",
".",
"_schema",
")",
"# pre-checks",
"self",
".",
"validate",
"(",
"graph... | 46.657143 | 22 |
def relative_path(path, from_file):
"""
Return the relative path of a file or directory, specified
as ``path`` relative to (the parent directory of) ``from_file``.
This method is intented to be called with ``__file__``
as second argument.
The returned path is relative to the current working di... | [
"def",
"relative_path",
"(",
"path",
",",
"from_file",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"None",
"abs_path_target",
"=",
"absolute_path",
"(",
"path",
",",
"from_file",
")",
"abs_path_cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"is... | 32.805556 | 19.194444 |
def computeAccuracyEnding(predictions, truths, iterations,
resets=None, randoms=None, num=None,
sequenceCounter=None):
"""
Compute accuracy on the sequence ending
"""
accuracy = []
numIteration = []
numSequences = []
for i in xrange(len(predictions) - 1):
if nu... | [
"def",
"computeAccuracyEnding",
"(",
"predictions",
",",
"truths",
",",
"iterations",
",",
"resets",
"=",
"None",
",",
"randoms",
"=",
"None",
",",
"num",
"=",
"None",
",",
"sequenceCounter",
"=",
"None",
")",
":",
"accuracy",
"=",
"[",
"]",
"numIteration"... | 26.714286 | 16.571429 |
def validate(self, value):
"""
Applies the validation criteria.
Returns value, new value, or None if invalid.
"""
try:
coord.Angle(value, unit=self.unit)
return value
except ValueError:
return None | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"coord",
".",
"Angle",
"(",
"value",
",",
"unit",
"=",
"self",
".",
"unit",
")",
"return",
"value",
"except",
"ValueError",
":",
"return",
"None"
] | 27.2 | 10.8 |
def _get_table_rows(parent_table, table_name, row_name):
"""
Inconsistent behavior:
{'TABLE_intf': [{'ROW_intf': {
vs
{'TABLE_mac_address': {'ROW_mac_address': [{
vs
{'TABLE_vrf': {'ROW_vrf': {'TABLE_adj': {'ROW_adj': {
"""
if parent_table is None:... | [
"def",
"_get_table_rows",
"(",
"parent_table",
",",
"table_name",
",",
"row_name",
")",
":",
"if",
"parent_table",
"is",
"None",
":",
"return",
"[",
"]",
"_table",
"=",
"parent_table",
".",
"get",
"(",
"table_name",
")",
"_table_rows",
"=",
"[",
"]",
"if",... | 35.4 | 11.9 |
def pack_sources(sources, normalize=True):
'''
Accepts list of dicts (or a string representing a list of dicts) and packs
the key/value pairs into a single dict.
``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become
``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}``
nor... | [
"def",
"pack_sources",
"(",
"sources",
",",
"normalize",
"=",
"True",
")",
":",
"if",
"normalize",
"and",
"'pkg.normalize_name'",
"in",
"__salt__",
":",
"_normalize_name",
"=",
"__salt__",
"[",
"'pkg.normalize_name'",
"]",
"else",
":",
"_normalize_name",
"=",
"l... | 36.644444 | 25.355556 |
def list(declared, undeclared):
"""List configured queues."""
queues = current_queues.queues.values()
if declared:
queues = filter(lambda queue: queue.exists, queues)
elif undeclared:
queues = filter(lambda queue: not queue.exists, queues)
queue_names = [queue.routing_key for queue i... | [
"def",
"list",
"(",
"declared",
",",
"undeclared",
")",
":",
"queues",
"=",
"current_queues",
".",
"queues",
".",
"values",
"(",
")",
"if",
"declared",
":",
"queues",
"=",
"filter",
"(",
"lambda",
"queue",
":",
"queue",
".",
"exists",
",",
"queues",
")... | 36.272727 | 14.363636 |
def obtain_to(filename):
"""
Return the digital elevation map projected to the lat lon matrix coordenates.
Keyword arguments:
filename -- the name of a netcdf file.
"""
root, _ = nc.open(filename)
lat, lon = nc.getvar(root, 'lat')[0,:], nc.getvar(root, 'lon')[0,:]
nc.close(root)
ret... | [
"def",
"obtain_to",
"(",
"filename",
")",
":",
"root",
",",
"_",
"=",
"nc",
".",
"open",
"(",
"filename",
")",
"lat",
",",
"lon",
"=",
"nc",
".",
"getvar",
"(",
"root",
",",
"'lat'",
")",
"[",
"0",
",",
":",
"]",
",",
"nc",
".",
"getvar",
"("... | 30 | 17.454545 |
def reports_list(request):
''' Lists all of the reports currently available. '''
reports = []
for report in get_all_reports():
reports.append({
"name": report.__name__,
"url": reverse(report),
"description": report.__doc__,
})
reports.sort(key=lambd... | [
"def",
"reports_list",
"(",
"request",
")",
":",
"reports",
"=",
"[",
"]",
"for",
"report",
"in",
"get_all_reports",
"(",
")",
":",
"reports",
".",
"append",
"(",
"{",
"\"name\"",
":",
"report",
".",
"__name__",
",",
"\"url\"",
":",
"reverse",
"(",
"re... | 23.210526 | 22.578947 |
def validate_id(request):
"""Validate request id."""
if 'id' in request:
correct_id = isinstance(
request['id'],
(string_types, int, None),
)
error = 'Incorrect identifier'
assert correct_id, error | [
"def",
"validate_id",
"(",
"request",
")",
":",
"if",
"'id'",
"in",
"request",
":",
"correct_id",
"=",
"isinstance",
"(",
"request",
"[",
"'id'",
"]",
",",
"(",
"string_types",
",",
"int",
",",
"None",
")",
",",
")",
"error",
"=",
"'Incorrect identifier'... | 25.3 | 13.7 |
def cmd_ADSB(self, args):
'''adsb command parser'''
usage = "usage: adsb <set>"
if len(args) == 0:
print(usage)
return
if args[0] == "status":
print("total threat count: %u active threat count: %u" %
(len(self.threat_vehicles), len(s... | [
"def",
"cmd_ADSB",
"(",
"self",
",",
"args",
")",
":",
"usage",
"=",
"\"usage: adsb <set>\"",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"print",
"(",
"usage",
")",
"return",
"if",
"args",
"[",
"0",
"]",
"==",
"\"status\"",
":",
"print",
"(",
"... | 48.894737 | 27.947368 |
def detail_dict(self):
"""A more detailed dict that includes the descriptions, sub descriptions, table
and columns."""
d = self.dict
def aug_col(c):
d = c.dict
d['stats'] = [s.dict for s in c.stats]
return d
d['table'] = self.table.dict
... | [
"def",
"detail_dict",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"dict",
"def",
"aug_col",
"(",
"c",
")",
":",
"d",
"=",
"c",
".",
"dict",
"d",
"[",
"'stats'",
"]",
"=",
"[",
"s",
".",
"dict",
"for",
"s",
"in",
"c",
".",
"stats",
"]",
"r... | 26.133333 | 21.466667 |
def _ge_from_le(self, other):
"""Return a >= b. Computed by @total_ordering from (not a <= b) or (a == b)."""
op_result = self.__le__(other)
if op_result is NotImplemented:
return NotImplemented
return not op_result or self == other | [
"def",
"_ge_from_le",
"(",
"self",
",",
"other",
")",
":",
"op_result",
"=",
"self",
".",
"__le__",
"(",
"other",
")",
"if",
"op_result",
"is",
"NotImplemented",
":",
"return",
"NotImplemented",
"return",
"not",
"op_result",
"or",
"self",
"==",
"other"
] | 42 | 5.666667 |
def get_ips_from_steamids(self, server_steam_ids, timeout=30):
"""Resolve IPs from SteamIDs
:param server_steam_ids: a list of steamids
:type server_steam_ids: list
:param timeout: (optional) timeout for request in seconds
:type timeout: int
:return: map of ips to stea... | [
"def",
"get_ips_from_steamids",
"(",
"self",
",",
"server_steam_ids",
",",
"timeout",
"=",
"30",
")",
":",
"resp",
",",
"error",
"=",
"self",
".",
"_um",
".",
"send_and_wait",
"(",
"\"GameServers.GetServerIPsBySteamID#1\"",
",",
"{",
"\"server_steamids\"",
":",
... | 36.592593 | 23.148148 |
def compute(self, *inputs, **kwargs):
"""
Compute based on NeuralVariable.
:type inputs: list of NeuralVariable
:return: NeuralVariable
"""
from deepy.core.neural_var import NeuralVariable
from deepy.core.graph import graph
if type(inputs[0]) != NeuralVar... | [
"def",
"compute",
"(",
"self",
",",
"*",
"inputs",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"deepy",
".",
"core",
".",
"neural_var",
"import",
"NeuralVariable",
"from",
"deepy",
".",
"core",
".",
"graph",
"import",
"graph",
"if",
"type",
"(",
"inputs... | 37.678571 | 16.535714 |
def write_output_files(self,traj):
"""
The total hydrogen bond count per frame is provided as CSV output file.
Each trajectory has a separate file.
"""
try:
os.chdir("analysis")
except Exception as e:
os.mkdir("analysis")
os.chdir("anal... | [
"def",
"write_output_files",
"(",
"self",
",",
"traj",
")",
":",
"try",
":",
"os",
".",
"chdir",
"(",
"\"analysis\"",
")",
"except",
"Exception",
"as",
"e",
":",
"os",
".",
"mkdir",
"(",
"\"analysis\"",
")",
"os",
".",
"chdir",
"(",
"\"analysis\"",
")"... | 46.666667 | 17.583333 |
def ReleaseClick(cls):
''' 释放按压操作 '''
element = cls._element()
action = ActionChains(Web.driver)
action.release(element)
action.perform() | [
"def",
"ReleaseClick",
"(",
"cls",
")",
":",
"element",
"=",
"cls",
".",
"_element",
"(",
")",
"action",
"=",
"ActionChains",
"(",
"Web",
".",
"driver",
")",
"action",
".",
"release",
"(",
"element",
")",
"action",
".",
"perform",
"(",
")"
] | 28 | 12.857143 |
def lastname(random=random, *args, **kwargs):
"""
Return a first name!
>>> mock_random.seed(0)
>>> lastname(random=mock_random)
'chimp'
>>> mock_random.seed(1)
>>> lastname(random=mock_random, capitalize=True)
'Wonderful'
>>> mock_random.seed(2)
>>> lastname(random=mock_random, ... | [
"def",
"lastname",
"(",
"random",
"=",
"random",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"types",
"=",
"[",
"\"{noun}\"",
",",
"\"{adjective}\"",
",",
"\"{noun}{second_noun}\"",
",",
"\"{adjective}{noun}\"",
",",
"\"{adjective}{plural}\"",
",",
"\... | 34.2 | 22.333333 |
def render_latex_sub_super(
name, subs=None, supers=None, translate_symbols=True, sep=','):
r'''Assemble a string from the primary name and the given sub- and
superscripts::
>>> render_latex_sub_super(name='alpha', subs=['mu', 'nu'], supers=[2])
'\\alpha_{\\mu,\\nu}^{2}'
>>> re... | [
"def",
"render_latex_sub_super",
"(",
"name",
",",
"subs",
"=",
"None",
",",
"supers",
"=",
"None",
",",
"translate_symbols",
"=",
"True",
",",
"sep",
"=",
"','",
")",
":",
"if",
"subs",
"is",
"None",
":",
"subs",
"=",
"[",
"]",
"if",
"supers",
"is",... | 34.378378 | 20.972973 |
def holtWintersConfidenceBands(requestContext, seriesList, delta=3):
"""
Performs a Holt-Winters forecast using the series as input data and plots
upper and lower bands with the predicted forecast deviations.
"""
previewSeconds = 7 * 86400 # 7 days
# ignore original data and pull new, including... | [
"def",
"holtWintersConfidenceBands",
"(",
"requestContext",
",",
"seriesList",
",",
"delta",
"=",
"3",
")",
":",
"previewSeconds",
"=",
"7",
"*",
"86400",
"# 7 days",
"# ignore original data and pull new, including our preview",
"newContext",
"=",
"requestContext",
".",
... | 44.296296 | 18.407407 |
def find_modules(import_path, include_packages=False, recursive=False):
"""Finds all the modules below a package. This can be useful to
automatically import all views / controllers so that their metaclasses /
function decorators have a chance to register themselves on the
application.
Packages are... | [
"def",
"find_modules",
"(",
"import_path",
",",
"include_packages",
"=",
"False",
",",
"recursive",
"=",
"False",
")",
":",
"module",
"=",
"import_string",
"(",
"import_path",
")",
"path",
"=",
"getattr",
"(",
"module",
",",
"\"__path__\"",
",",
"None",
")",... | 43.266667 | 20.766667 |
def cli(env, keyword, package_type):
"""List packages that can be ordered via the placeOrder API.
::
# List out all packages for ordering
slcli order package-list
# List out all packages with "server" in the name
slcli order package-list --keyword server
# Select onl... | [
"def",
"cli",
"(",
"env",
",",
"keyword",
",",
"package_type",
")",
":",
"manager",
"=",
"ordering",
".",
"OrderingManager",
"(",
"env",
".",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"COLUMNS",
")",
"_filter",
"=",
"{",
"'type'",
"... | 28.676471 | 20.176471 |
def close(self, code: int = None, reason: str = None) -> None:
"""Closes the WebSocket connection."""
if not self.server_terminated:
if not self.stream.closed():
if code is None and reason is not None:
code = 1000 # "normal closure" status code
... | [
"def",
"close",
"(",
"self",
",",
"code",
":",
"int",
"=",
"None",
",",
"reason",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"server_terminated",
":",
"if",
"not",
"self",
".",
"stream",
".",
"closed",
"(",
")",
":... | 43.75 | 11.607143 |
def set_vm_status(status, name=None, vmid=None):
'''
Convenience function for setting VM status
'''
log.debug('Set status to %s for %s (%s)', status, name, vmid)
if vmid is not None:
log.debug('set_vm_status: via ID - VMID %s (%s): %s',
vmid, name, status)
vmobj = ... | [
"def",
"set_vm_status",
"(",
"status",
",",
"name",
"=",
"None",
",",
"vmid",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'Set status to %s for %s (%s)'",
",",
"status",
",",
"name",
",",
"vmid",
")",
"if",
"vmid",
"is",
"not",
"None",
":",
"log"... | 34.903226 | 21.741935 |
def get_contact(self, msisdn):
"""
Returns the WhatsApp ID for the given MSISDN
"""
response = self.session.post(
urllib_parse.urljoin(self.api_url, "/v1/contacts"),
json={"blocking": "wait", "contacts": [msisdn]},
)
response.raise_for_status()
... | [
"def",
"get_contact",
"(",
"self",
",",
"msisdn",
")",
":",
"response",
"=",
"self",
".",
"session",
".",
"post",
"(",
"urllib_parse",
".",
"urljoin",
"(",
"self",
".",
"api_url",
",",
"\"/v1/contacts\"",
")",
",",
"json",
"=",
"{",
"\"blocking\"",
":",
... | 36.692308 | 12.846154 |
def get_body(name):
"""Retrieve the Body structure of a JPL .bsp file object
Args:
name (str)
Return:
:py:class:`~beyond.constants.Body`
"""
body = Pck()[name]
body.propagate = lambda date: get_orbit(name, date)
return body | [
"def",
"get_body",
"(",
"name",
")",
":",
"body",
"=",
"Pck",
"(",
")",
"[",
"name",
"]",
"body",
".",
"propagate",
"=",
"lambda",
"date",
":",
"get_orbit",
"(",
"name",
",",
"date",
")",
"return",
"body"
] | 21.5 | 20.25 |
def handle_symbol_search(self, call_id, payload):
"""Handler for symbol search results"""
self.log.debug('handle_symbol_search: in %s', Pretty(payload))
syms = payload["syms"]
qfList = []
for sym in syms:
p = sym.get("pos")
if p:
item = se... | [
"def",
"handle_symbol_search",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'handle_symbol_search: in %s'",
",",
"Pretty",
"(",
"payload",
")",
")",
"syms",
"=",
"payload",
"[",
"\"syms\"",
"]",
"qfList",
"... | 42.8 | 19 |
def get(context, request, username=None):
"""Plone users route
"""
user_ids = []
# Don't allow anonymous users to query a user other than themselves
if api.is_anonymous():
username = "current"
# query all users if no username was given
if username is None:
user_ids = api.ge... | [
"def",
"get",
"(",
"context",
",",
"request",
",",
"username",
"=",
"None",
")",
":",
"user_ids",
"=",
"[",
"]",
"# Don't allow anonymous users to query a user other than themselves",
"if",
"api",
".",
"is_anonymous",
"(",
")",
":",
"username",
"=",
"\"current\"",... | 28.657143 | 15.142857 |
def _regexp(filename):
"""Get a list of patterns from a file and make a regular expression."""
lines = _get_resource_content(filename).decode('utf-8').splitlines()
return re.compile('|'.join(lines)) | [
"def",
"_regexp",
"(",
"filename",
")",
":",
"lines",
"=",
"_get_resource_content",
"(",
"filename",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"splitlines",
"(",
")",
"return",
"re",
".",
"compile",
"(",
"'|'",
".",
"join",
"(",
"lines",
")",
")"
] | 51.75 | 13 |
def apply(f, args):
"""Apply function f to the arguments provided.
The last argument must always be coercible to a Seq. Intermediate
arguments are not modified.
For example:
(apply max [1 2 3]) ;=> 3
(apply max 4 [1 2 3]) ;=> 4"""
final = list(args[:-1])
try:
last = ar... | [
"def",
"apply",
"(",
"f",
",",
"args",
")",
":",
"final",
"=",
"list",
"(",
"args",
"[",
":",
"-",
"1",
"]",
")",
"try",
":",
"last",
"=",
"args",
"[",
"-",
"1",
"]",
"except",
"TypeError",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"\"Igno... | 25.526316 | 19.947368 |
def intersection(self, other, sort=False):
"""
Form the intersection of two MultiIndex objects.
Parameters
----------
other : MultiIndex or array / Index of tuples
sort : False or None, default False
Sort the resulting MultiIndex if possible
.. v... | [
"def",
"intersection",
"(",
"self",
",",
"other",
",",
"sort",
"=",
"False",
")",
":",
"self",
".",
"_validate_sort_keyword",
"(",
"sort",
")",
"self",
".",
"_assert_can_do_setop",
"(",
"other",
")",
"other",
",",
"result_names",
"=",
"self",
".",
"_conver... | 31.071429 | 19.309524 |
async def connect(self, next_time=None):
"""Connect with store
:return: a coroutine and therefore it must be awaited
"""
if self.status in can_connect:
loop = self._loop
if loop.is_running():
self.status = StatusType.connecting
awa... | [
"async",
"def",
"connect",
"(",
"self",
",",
"next_time",
"=",
"None",
")",
":",
"if",
"self",
".",
"status",
"in",
"can_connect",
":",
"loop",
"=",
"self",
".",
"_loop",
"if",
"loop",
".",
"is_running",
"(",
")",
":",
"self",
".",
"status",
"=",
"... | 33.8 | 9.8 |
def uniquify(model):
'''
Remove all duplicate relationships
'''
seen = set()
to_remove = set()
for ix, (o, r, t, a) in model:
hashable_link = (o, r, t) + tuple(sorted(a.items()))
#print(hashable_link)
if hashable_link in seen:
to_remove.add(ix)
seen.ad... | [
"def",
"uniquify",
"(",
"model",
")",
":",
"seen",
"=",
"set",
"(",
")",
"to_remove",
"=",
"set",
"(",
")",
"for",
"ix",
",",
"(",
"o",
",",
"r",
",",
"t",
",",
"a",
")",
"in",
"model",
":",
"hashable_link",
"=",
"(",
"o",
",",
"r",
",",
"t... | 24.133333 | 18.533333 |
def escapeUnderscores(self):
"""
Escape underscores so that the markdown is correct
"""
new_metrics = []
for m in self.metrics:
m['name'] = m['name'].replace("_", "\_")
new_metrics.append(m)
self.metrics = new_metrics | [
"def",
"escapeUnderscores",
"(",
"self",
")",
":",
"new_metrics",
"=",
"[",
"]",
"for",
"m",
"in",
"self",
".",
"metrics",
":",
"m",
"[",
"'name'",
"]",
"=",
"m",
"[",
"'name'",
"]",
".",
"replace",
"(",
"\"_\"",
",",
"\"\\_\"",
")",
"new_metrics",
... | 31.222222 | 9 |
def handle_event(self, packet):
"""Handle incoming packet from rflink gateway."""
if packet.get('command'):
task = self.send_command_ack(packet['id'], packet['command'])
self.loop.create_task(task) | [
"def",
"handle_event",
"(",
"self",
",",
"packet",
")",
":",
"if",
"packet",
".",
"get",
"(",
"'command'",
")",
":",
"task",
"=",
"self",
".",
"send_command_ack",
"(",
"packet",
"[",
"'id'",
"]",
",",
"packet",
"[",
"'command'",
"]",
")",
"self",
"."... | 46.6 | 10 |
def getSectionByOffset(self, offset):
"""
Given an offset in the file, tries to determine the section this offset belong to.
@type offset: int
@param offset: Offset value.
@rtype: int
@return: An index, starting at 0, that represents the section the give... | [
"def",
"getSectionByOffset",
"(",
"self",
",",
"offset",
")",
":",
"index",
"=",
"-",
"1",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"sectionHeaders",
")",
")",
":",
"if",
"(",
"offset",
"<",
"self",
".",
"sectionHeaders",
"[",
"i",
... | 37.0625 | 23.5625 |
def _get_dns_cname(name, link=False):
"""
Looks for associated domain zone, nameservers and linked record name until no
more linked record name was found for the given fully qualified record name or
the CNAME lookup was disabled, and then returns the parameters as a tuple.
"""
... | [
"def",
"_get_dns_cname",
"(",
"name",
",",
"link",
"=",
"False",
")",
":",
"resolver",
"=",
"dns",
".",
"resolver",
".",
"Resolver",
"(",
")",
"resolver",
".",
"lifetime",
"=",
"1",
"domain",
"=",
"dns",
".",
"resolver",
".",
"zone_for_name",
"(",
"nam... | 46 | 18.5625 |
def merge(cls, edge1, edge2):
""" Merges multi-color information from two supplied :class:`BGEdge` instances into a new :class:`BGEdge`
Since :class:`BGEdge` represents an undirected edge, created edge's vertices are assign according to the order in first supplied edge.
Accounts for subclassin... | [
"def",
"merge",
"(",
"cls",
",",
"edge1",
",",
"edge2",
")",
":",
"if",
"edge1",
".",
"vertex1",
"!=",
"edge2",
".",
"vertex1",
"and",
"edge1",
".",
"vertex1",
"!=",
"edge2",
".",
"vertex2",
":",
"raise",
"ValueError",
"(",
"\"Edges to be merged do not con... | 62.65 | 35.15 |
def doc_open():
"""Build the HTML docs and open them in a web browser."""
doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html')
if sys.platform == 'darwin':
# Mac OS X
subprocess.check_call(['open', doc_index])
elif sys.platform == 'win32':
# Windows
sub... | [
"def",
"doc_open",
"(",
")",
":",
"doc_index",
"=",
"os",
".",
"path",
".",
"join",
"(",
"DOCS_DIRECTORY",
",",
"'build'",
",",
"'html'",
",",
"'index.html'",
")",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"# Mac OS X",
"subprocess",
".",
"che... | 39.625 | 16.4375 |
def fold(self, strand, temp=37.0, dangles=2, nolp=False, nogu=False,
noclosinggu=False, constraints=None, canonicalbponly=False,
partition=False, pfscale=None, imfeelinglucky=False, gquad=False):
'''Run the RNAfold command and retrieve the result in a dictionary.
:param strand... | [
"def",
"fold",
"(",
"self",
",",
"strand",
",",
"temp",
"=",
"37.0",
",",
"dangles",
"=",
"2",
",",
"nolp",
"=",
"False",
",",
"nogu",
"=",
"False",
",",
"noclosinggu",
"=",
"False",
",",
"constraints",
"=",
"None",
",",
"canonicalbponly",
"=",
"Fals... | 45.613208 | 21.009434 |
def apply_one_hot_encoding(self, one_hot_encoding):
"""Apply one hot encoding to generate a specific config.
Arguments:
one_hot_encoding (list): A list of one hot encodings,
1 for each parameter. The shape of each encoding
should match that ``ParameterSpace`... | [
"def",
"apply_one_hot_encoding",
"(",
"self",
",",
"one_hot_encoding",
")",
":",
"config",
"=",
"{",
"}",
"for",
"ps",
",",
"one_hot",
"in",
"zip",
"(",
"self",
".",
"param_list",
",",
"one_hot_encoding",
")",
":",
"index",
"=",
"np",
".",
"argmax",
"(",... | 34.705882 | 19.470588 |
def instantiate(self, **extra_args):
""" Instantiate the model """
input_block = self.input_block.instantiate()
backbone = self.backbone.instantiate(**extra_args)
return QRainbowModel(
input_block=input_block,
backbone=backbone,
action_space=extra_arg... | [
"def",
"instantiate",
"(",
"self",
",",
"*",
"*",
"extra_args",
")",
":",
"input_block",
"=",
"self",
".",
"input_block",
".",
"instantiate",
"(",
")",
"backbone",
"=",
"self",
".",
"backbone",
".",
"instantiate",
"(",
"*",
"*",
"extra_args",
")",
"retur... | 34.733333 | 13.2 |
def _check_attributes(self, attributes, extra=None):
"""Check if attributes given to the constructor can be used to
instanciate a valid node."""
extra = extra or ()
unknown_keys = set(attributes) - set(self._possible_attributes) - set(extra)
if unknown_keys:
logger.wa... | [
"def",
"_check_attributes",
"(",
"self",
",",
"attributes",
",",
"extra",
"=",
"None",
")",
":",
"extra",
"=",
"extra",
"or",
"(",
")",
"unknown_keys",
"=",
"set",
"(",
"attributes",
")",
"-",
"set",
"(",
"self",
".",
"_possible_attributes",
")",
"-",
... | 52.625 | 16.625 |
def _get_variant_regions(items):
"""Retrieve variant regions defined in any of the input items.
"""
return list(filter(lambda x: x is not None,
[tz.get_in(("config", "algorithm", "variant_regions"), data)
for data in items
if tz.get_in([... | [
"def",
"_get_variant_regions",
"(",
"items",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"[",
"tz",
".",
"get_in",
"(",
"(",
"\"config\"",
",",
"\"algorithm\"",
",",
"\"variant_regions\"",
")",
",",
... | 54.142857 | 17.428571 |
def build_docker_build_command(configuration):
"""
Translate a declarative docker `configuration` to a `docker build` command.
Parameters
----------
configuration : dict
configuration
Returns
-------
args : list
sequence of command line arguments to build an image
"... | [
"def",
"build_docker_build_command",
"(",
"configuration",
")",
":",
"parts",
"=",
"configuration",
".",
"pop",
"(",
"'docker'",
",",
"'docker'",
")",
".",
"split",
"(",
")",
"parts",
".",
"append",
"(",
"'build'",
")",
"build",
"=",
"configuration",
".",
... | 27.413793 | 23.965517 |
def next_code_is_indented(lines):
"""Is the next unescaped line indented?"""
for line in lines:
if _BLANK_LINE.match(line) or _PY_COMMENT.match(line):
continue
return _PY_INDENTED.match(line)
return False | [
"def",
"next_code_is_indented",
"(",
"lines",
")",
":",
"for",
"line",
"in",
"lines",
":",
"if",
"_BLANK_LINE",
".",
"match",
"(",
"line",
")",
"or",
"_PY_COMMENT",
".",
"match",
"(",
"line",
")",
":",
"continue",
"return",
"_PY_INDENTED",
".",
"match",
... | 34 | 13.142857 |
def xml(self):
"""
Get xml representation of the object.
@return: The root node.
@rtype: L{Element}
"""
root = Element('Security', ns=wssens)
root.set('mustUnderstand', str(self.mustUnderstand).lower())
for t in self.tokens:
root.append(t.xml()... | [
"def",
"xml",
"(",
"self",
")",
":",
"root",
"=",
"Element",
"(",
"'Security'",
",",
"ns",
"=",
"wssens",
")",
"root",
".",
"set",
"(",
"'mustUnderstand'",
",",
"str",
"(",
"self",
".",
"mustUnderstand",
")",
".",
"lower",
"(",
")",
")",
"for",
"t"... | 30.090909 | 11.545455 |
def error(self, s, pos):
"""Show text and a caret under that. For example:
x = 2y + z
^
"""
print("Lexical error:")
print("%s" % s[:pos+10]) # + 10 for trailing context
print("%s^" % (" "*(pos-1)))
for t in self.rv: print(t)
raise SystemExit | [
"def",
"error",
"(",
"self",
",",
"s",
",",
"pos",
")",
":",
"print",
"(",
"\"Lexical error:\"",
")",
"print",
"(",
"\"%s\"",
"%",
"s",
"[",
":",
"pos",
"+",
"10",
"]",
")",
"# + 10 for trailing context",
"print",
"(",
"\"%s^\"",
"%",
"(",
"\" \"",
"... | 28.6 | 13.6 |
def btc_script_serialize(_script):
"""
Given a deserialized script (i.e. an array of Nones, ints, and strings), or an existing script,
turn it back into a hex script
Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools)
by Vitalik Buterin
"""
script = _script
if... | [
"def",
"btc_script_serialize",
"(",
"_script",
")",
":",
"script",
"=",
"_script",
"if",
"encoding",
".",
"json_is_base",
"(",
"_script",
",",
"16",
")",
":",
"# hex-to-bin all hex strings in this script",
"script",
"=",
"encoding",
".",
"json_changebase",
"(",
"_... | 41.333333 | 23.066667 |
def destroy_venv(env_path, venvscache=None):
"""Destroy a venv."""
# remove the venv itself in disk
logger.debug("Destroying virtualenv at: %s", env_path)
shutil.rmtree(env_path, ignore_errors=True)
# remove venv from cache
if venvscache is not None:
venvscache.remove(env_path) | [
"def",
"destroy_venv",
"(",
"env_path",
",",
"venvscache",
"=",
"None",
")",
":",
"# remove the venv itself in disk",
"logger",
".",
"debug",
"(",
"\"Destroying virtualenv at: %s\"",
",",
"env_path",
")",
"shutil",
".",
"rmtree",
"(",
"env_path",
",",
"ignore_errors... | 33.666667 | 11.111111 |
def create_timeline(self, timeline, scope_identifier, hub_name, plan_id):
"""CreateTimeline.
:param :class:`<Timeline> <azure.devops.v5_0.task.models.Timeline>` timeline:
:param str scope_identifier: The project GUID to scope the request
:param str hub_name: The name of the server hub: "... | [
"def",
"create_timeline",
"(",
"self",
",",
"timeline",
",",
"scope_identifier",
",",
"hub_name",
",",
"plan_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"scope_identifier",
"is",
"not",
"None",
":",
"route_values",
"[",
"'scopeIdentifier'",
"]",
"=",
... | 58.909091 | 24.954545 |
def _format_results(_keywords, combined_keywords, split, scores):
"""
:param keywords:dict of keywords:scores
:param combined_keywords:list of word/s
"""
combined_keywords.sort(key=lambda w: _get_average_score(w, _keywords), reverse=True)
if scores:
return [(word, _get_average_score(word... | [
"def",
"_format_results",
"(",
"_keywords",
",",
"combined_keywords",
",",
"split",
",",
"scores",
")",
":",
"combined_keywords",
".",
"sort",
"(",
"key",
"=",
"lambda",
"w",
":",
"_get_average_score",
"(",
"w",
",",
"_keywords",
")",
",",
"reverse",
"=",
... | 40.090909 | 17.363636 |
def manage_view(request, semester, profile=None):
"""
View all members' preferences. This view also includes forms to create an
entire semester's worth of weekly workshifts.
"""
page_name = "Manage Workshift"
pools = WorkshiftPool.objects.filter(semester=semester)
full_management = utils.can... | [
"def",
"manage_view",
"(",
"request",
",",
"semester",
",",
"profile",
"=",
"None",
")",
":",
"page_name",
"=",
"\"Manage Workshift\"",
"pools",
"=",
"WorkshiftPool",
".",
"objects",
".",
"filter",
"(",
"semester",
"=",
"semester",
")",
"full_management",
"=",... | 35.839506 | 17.691358 |
def discover(url, timeout=None):
"""Discover the hub url and topic url of a given url. Firstly, by inspecting
the page's headers, secondarily by inspecting the content for link tags.
timeout determines how long to wait for the url to load. It defaults to 3.
"""
resp = get_content({'REQUEST_TIMEOUT... | [
"def",
"discover",
"(",
"url",
",",
"timeout",
"=",
"None",
")",
":",
"resp",
"=",
"get_content",
"(",
"{",
"'REQUEST_TIMEOUT'",
":",
"timeout",
"}",
",",
"url",
")",
"parser",
"=",
"LinkParser",
"(",
")",
"parser",
".",
"hub_url",
"=",
"(",
"resp",
... | 38 | 24.238095 |
def unsubscribe_all(self, callback=False):
"""Send an unsubscribe for all active subscriptions"""
futures = ((f, r) for f, r in self._requests.items()
if isinstance(r, Subscribe)
and f not in self._pending_unsubscribes)
if futures:
for future, re... | [
"def",
"unsubscribe_all",
"(",
"self",
",",
"callback",
"=",
"False",
")",
":",
"futures",
"=",
"(",
"(",
"f",
",",
"r",
")",
"for",
"f",
",",
"r",
"in",
"self",
".",
"_requests",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",
"r",
",",
"Subscr... | 46.166667 | 13 |
def change_dir(directory):
"""
Wraps a function to run in a given directory.
"""
def cd_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
org_path = os.getcwd()
os.chdir(directory)
func(*args, **kwargs)
os.chdir(org_path)
return wrapper
return cd_decorator | [
"def",
"change_dir",
"(",
"directory",
")",
":",
"def",
"cd_decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"org_path",
"=",
"os",
".",
"getcwd",
"(",
")",
... | 21.428571 | 14.571429 |
def generate_bytecode_from_obb(obb: object, previous: bytes) -> bytes:
"""
Generates a bytecode from an object.
:param obb: The object to generate.
:param previous: The previous bytecode to use when generating subobjects.
:return: The generated bytecode.
"""
# Generates bytecode from a spec... | [
"def",
"generate_bytecode_from_obb",
"(",
"obb",
":",
"object",
",",
"previous",
":",
"bytes",
")",
"->",
"bytes",
":",
"# Generates bytecode from a specified object, be it a validator or an int or bytes even.",
"if",
"isinstance",
"(",
"obb",
",",
"pyte",
".",
"superclas... | 44.521739 | 20.608696 |
def status(self, obj):
"""Get the wifi interface status."""
reply = self._send_cmd_to_wpas(obj['name'], 'STATUS', True)
result = reply.split('\n')
status = ''
for l in result:
if l.startswith('wpa_state='):
status = l[10:]
return stat... | [
"def",
"status",
"(",
"self",
",",
"obj",
")",
":",
"reply",
"=",
"self",
".",
"_send_cmd_to_wpas",
"(",
"obj",
"[",
"'name'",
"]",
",",
"'STATUS'",
",",
"True",
")",
"result",
"=",
"reply",
".",
"split",
"(",
"'\\n'",
")",
"status",
"=",
"''",
"fo... | 30.272727 | 17.181818 |
async def get_my_did_with_meta(wallet_handle: int, did: str) -> str:
"""
Get DID metadata and verkey stored in the wallet.
:param wallet_handle: wallet handler (created by open_wallet).
:param did: The DID to retrieve metadata.
:return: DID with verkey and metadata.
"""
logger = logging.ge... | [
"async",
"def",
"get_my_did_with_meta",
"(",
"wallet_handle",
":",
"int",
",",
"did",
":",
"str",
")",
"->",
"str",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"get_my_did_with_meta: >>> wallet_handle: %r... | 34.966667 | 19.966667 |
def endpoint(self):
"""
The endpoint for this route.
"""
if self._endpoint:
return self._endpoint
elif self._controller_cls:
endpoint = f'{snake_case(self._controller_cls.__name__)}.{self.method_name}'
return endpoint if not self.bp_name else f... | [
"def",
"endpoint",
"(",
"self",
")",
":",
"if",
"self",
".",
"_endpoint",
":",
"return",
"self",
".",
"_endpoint",
"elif",
"self",
".",
"_controller_cls",
":",
"endpoint",
"=",
"f'{snake_case(self._controller_cls.__name__)}.{self.method_name}'",
"return",
"endpoint",
... | 40.333333 | 16.166667 |
def UNas(self, to='name_short'):
"""
Return UN member states in the specified classification
Parameters
----------
to : str, optional
Output classification (valid str for an index of
country_data file), default: name_short
Returns
-------... | [
"def",
"UNas",
"(",
"self",
",",
"to",
"=",
"'name_short'",
")",
":",
"if",
"isinstance",
"(",
"to",
",",
"str",
")",
":",
"to",
"=",
"[",
"to",
"]",
"return",
"self",
".",
"data",
"[",
"self",
".",
"data",
".",
"UNmember",
">",
"0",
"]",
"[",
... | 24.888889 | 19.222222 |
def build_byte_align_buff(bits):
"""Pad the left side of a bitarray with 0s to align its length with byte boundaries.
Args:
bits: A bitarray to be padded and aligned.
Returns:
A newly aligned bitarray.
"""
bitmod = len(bits)%8
if bitmod == 0:
rdiff = bitarray()
else... | [
"def",
"build_byte_align_buff",
"(",
"bits",
")",
":",
"bitmod",
"=",
"len",
"(",
"bits",
")",
"%",
"8",
"if",
"bitmod",
"==",
"0",
":",
"rdiff",
"=",
"bitarray",
"(",
")",
"else",
":",
"#KEEP bitarray",
"rdiff",
"=",
"bitarray",
"(",
"8",
"-",
"bitm... | 24.294118 | 17.764706 |
def get_resource_pools(service_instance, resource_pool_names, datacenter_name=None,
get_all_resource_pools=False):
'''
Retrieves resource pool objects
service_instance
The service instance object to query the vCenter
resource_pool_names
Resource pool names
d... | [
"def",
"get_resource_pools",
"(",
"service_instance",
",",
"resource_pool_names",
",",
"datacenter_name",
"=",
"None",
",",
"get_all_resource_pools",
"=",
"False",
")",
":",
"properties",
"=",
"[",
"'name'",
"]",
"if",
"not",
"resource_pool_names",
":",
"resource_po... | 33.511111 | 24.888889 |
def _special_value_maxLength(em, newValue=NOT_PROVIDED):
'''
_special_value_maxLength - Handle the special "maxLength" property
@param em <AdvancedTag> - The tag element
@param newValue - Default NOT_PROVIDED, if provided will use that value instead of the
current ... | [
"def",
"_special_value_maxLength",
"(",
"em",
",",
"newValue",
"=",
"NOT_PROVIDED",
")",
":",
"if",
"newValue",
"is",
"NOT_PROVIDED",
":",
"if",
"not",
"em",
".",
"hasAttribute",
"(",
"'maxlength'",
")",
":",
"return",
"-",
"1",
"curValue",
"=",
"em",
".",... | 35.142857 | 30.428571 |
def attach(self, engine, metric_names=None, output_transform=None,
event_name=Events.ITERATION_COMPLETED,
closing_event_name=Events.EPOCH_COMPLETED):
"""
Attaches the progress bar to an engine object.
Args:
engine (Engine): engine object.
me... | [
"def",
"attach",
"(",
"self",
",",
"engine",
",",
"metric_names",
"=",
"None",
",",
"output_transform",
"=",
"None",
",",
"event_name",
"=",
"Events",
".",
"ITERATION_COMPLETED",
",",
"closing_event_name",
"=",
"Events",
".",
"EPOCH_COMPLETED",
")",
":",
"desc... | 58.064516 | 32 |
def remove_class(self, cls):
"""
Remove a XSO class `cls` from parsing. This method raises
:class:`KeyError` with the classes :attr:`TAG` attribute as argument if
removing fails because the class is not registered.
"""
del self._tag_map[cls.TAG]
del self._class_ma... | [
"def",
"remove_class",
"(",
"self",
",",
"cls",
")",
":",
"del",
"self",
".",
"_tag_map",
"[",
"cls",
".",
"TAG",
"]",
"del",
"self",
".",
"_class_map",
"[",
"cls",
"]"
] | 39.875 | 13.625 |
def _left_motion(self, event):
"""Function bound to move event for marker canvas"""
iid = self.current_iid
if iid is None:
return
marker = self._markers[iid]
if marker["move"] is False:
return
delta = marker["finish"] - marker["start"]
# Li... | [
"def",
"_left_motion",
"(",
"self",
",",
"event",
")",
":",
"iid",
"=",
"self",
".",
"current_iid",
"if",
"iid",
"is",
"None",
":",
"return",
"marker",
"=",
"self",
".",
"_markers",
"[",
"iid",
"]",
"if",
"marker",
"[",
"\"move\"",
"]",
"is",
"False"... | 51.64 | 20.653333 |
def get_deps_manager(self, *args, **kwargs):
"""
Return instance of the dependancies manager using given args and kwargs
Add 'silent_key_error' option in kwargs if not given.
"""
if 'silent_key_error' not in kwargs:
kwargs['silent_key_error'] = self.silent_key_error
... | [
"def",
"get_deps_manager",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'silent_key_error'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'silent_key_error'",
"]",
"=",
"self",
".",
"silent_key_error",
"return",
"self",
".",
"dep... | 40.111111 | 15.444444 |
def random_get_instance() -> tcod.random.Random:
"""Return the default Random instance.
Returns:
Random: A Random instance using the default random number generator.
"""
return tcod.random.Random._new_from_cdata(
ffi.cast("mersenne_data_t*", lib.TCOD_random_get_instance())
) | [
"def",
"random_get_instance",
"(",
")",
"->",
"tcod",
".",
"random",
".",
"Random",
":",
"return",
"tcod",
".",
"random",
".",
"Random",
".",
"_new_from_cdata",
"(",
"ffi",
".",
"cast",
"(",
"\"mersenne_data_t*\"",
",",
"lib",
".",
"TCOD_random_get_instance",
... | 33.777778 | 20.111111 |
def read_samples(self, sr=None, offset=0, duration=None):
"""
Read the samples of the utterance.
Args:
sr (int): If None uses the sampling rate given by the track,
otherwise resamples to the given sampling rate.
offset (float): Offset in seconds to ... | [
"def",
"read_samples",
"(",
"self",
",",
"sr",
"=",
"None",
",",
"offset",
"=",
"0",
",",
"duration",
"=",
"None",
")",
":",
"read_duration",
"=",
"self",
".",
"duration",
"if",
"offset",
">",
"0",
"and",
"read_duration",
"is",
"not",
"None",
":",
"r... | 33.0625 | 19.5 |
def from_inline(cls: Type[WS2PEndpointType], inline: str) -> WS2PEndpointType:
"""
Return WS2PEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = WS2PEndpoint.re_inline.match(inline)
if m is None:
raise MalformedDocu... | [
"def",
"from_inline",
"(",
"cls",
":",
"Type",
"[",
"WS2PEndpointType",
"]",
",",
"inline",
":",
"str",
")",
"->",
"WS2PEndpointType",
":",
"m",
"=",
"WS2PEndpoint",
".",
"re_inline",
".",
"match",
"(",
"inline",
")",
"if",
"m",
"is",
"None",
":",
"rai... | 31.411765 | 15.411765 |
def discard(self, element):
"""Remove an element. Do not raise an exception if absent."""
key = self._transform(element)
if key in self._elements:
del self._elements[key] | [
"def",
"discard",
"(",
"self",
",",
"element",
")",
":",
"key",
"=",
"self",
".",
"_transform",
"(",
"element",
")",
"if",
"key",
"in",
"self",
".",
"_elements",
":",
"del",
"self",
".",
"_elements",
"[",
"key",
"]"
] | 40.6 | 5.4 |
def bin2hexline(data, add_addr=True, width=16):
"""
Format binary data to a Hex-Editor like format...
e.g.:
with open("C:\Python27\python.exe", "rb") as f:
data = f.read(150)
print("\n".join(bin2hexline(data, width=16)))
0000 4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00 MZ............ | [
"def",
"bin2hexline",
"(",
"data",
",",
"add_addr",
"=",
"True",
",",
"width",
"=",
"16",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"binary_type",
")",
",",
"(",
"\"is type: %s and not bytes/str: %s\"",
"%",
"(",
"type",
"(",
"data",
")",
",",
... | 30.896552 | 21.586207 |
def get_all_attribute_value(
self, tag_name, attribute, format_value=True, **attribute_filter
):
"""
Yields all the attribute values in xml files which match with the tag name and the specific attribute
:param str tag_name: specify the tag name
:param str attribute: specify ... | [
"def",
"get_all_attribute_value",
"(",
"self",
",",
"tag_name",
",",
"attribute",
",",
"format_value",
"=",
"True",
",",
"*",
"*",
"attribute_filter",
")",
":",
"tags",
"=",
"self",
".",
"find_tags",
"(",
"tag_name",
",",
"*",
"*",
"attribute_filter",
")",
... | 41.722222 | 21.055556 |
def DoxyEmitter(source, target, env):
"""Doxygen Doxyfile emitter"""
# possible output formats and their default values and output locations
output_formats = {
"HTML": ("YES", "html"),
"LATEX": ("YES", "latex"),
"RTF": ("NO", "rtf"),
"MAN": ("YES", "man"),
"XML": ("NO", "xml"),
... | [
"def",
"DoxyEmitter",
"(",
"source",
",",
"target",
",",
"env",
")",
":",
"# possible output formats and their default values and output locations",
"output_formats",
"=",
"{",
"\"HTML\"",
":",
"(",
"\"YES\"",
",",
"\"html\"",
")",
",",
"\"LATEX\"",
":",
"(",
"\"YES... | 29.536585 | 17.512195 |
def _average_precision(self, rec, prec):
"""
calculate average precision
Params:
----------
rec : numpy.array
cumulated recall
prec : numpy.array
cumulated precision
Returns:
----------
ap as float
"""
# app... | [
"def",
"_average_precision",
"(",
"self",
",",
"rec",
",",
"prec",
")",
":",
"# append sentinel values at both ends",
"mrec",
"=",
"np",
".",
"concatenate",
"(",
"(",
"[",
"0.",
"]",
",",
"rec",
",",
"[",
"1.",
"]",
")",
")",
"mpre",
"=",
"np",
".",
... | 27.857143 | 15.428571 |
def handleOneClientMsg(self, wrappedMsg):
"""
Validate and process a client message
:param wrappedMsg: a message from a client
"""
try:
vmsg = self.validateClientMsg(wrappedMsg)
if vmsg:
self.unpackClientMsg(*vmsg)
except BlowUp:
... | [
"def",
"handleOneClientMsg",
"(",
"self",
",",
"wrappedMsg",
")",
":",
"try",
":",
"vmsg",
"=",
"self",
".",
"validateClientMsg",
"(",
"wrappedMsg",
")",
"if",
"vmsg",
":",
"self",
".",
"unpackClientMsg",
"(",
"*",
"vmsg",
")",
"except",
"BlowUp",
":",
"... | 30.894737 | 13.736842 |
def load_hdf5(path):
"""Load data from a HDF5 file.
Args:
path (str): A path to the HDF5 format file containing data.
dense (boolean): An optional variable indicating if the return matrix
should be dense. By default, it is false.
Returns:
Data matrix X and... | [
"def",
"load_hdf5",
"(",
"path",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"is_sparse",
"=",
"f",
"[",
"'issparse'",
"]",
"[",
"...",
"]",
"if",
"is_sparse",
":",
"shape",
"=",
"tuple",
"(",
"f",
"[",
... | 28.307692 | 19.807692 |
def send_response(self, transaction):
"""
Handles the Blocks option in a outgoing response.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:rtype : Transaction
:return: the edited transaction
"""
host, port = tra... | [
"def",
"send_response",
"(",
"self",
",",
"transaction",
")",
":",
"host",
",",
"port",
"=",
"transaction",
".",
"request",
".",
"source",
"key_token",
"=",
"hash",
"(",
"str",
"(",
"host",
")",
"+",
"str",
"(",
"port",
")",
"+",
"str",
"(",
"transac... | 38.487805 | 22.634146 |
def docx_preprocess(docx, batch=False):
"""
Load docx files from local filepath if not already b64 encoded
"""
if batch:
return [docx_preprocess(doc, batch=False) for doc in docx]
if os.path.isfile(docx):
# a filepath is provided, read and encode
return b64encode(open(docx, ... | [
"def",
"docx_preprocess",
"(",
"docx",
",",
"batch",
"=",
"False",
")",
":",
"if",
"batch",
":",
"return",
"[",
"docx_preprocess",
"(",
"doc",
",",
"batch",
"=",
"False",
")",
"for",
"doc",
"in",
"docx",
"]",
"if",
"os",
".",
"path",
".",
"isfile",
... | 30.384615 | 15.769231 |
def query_recent_edited(timstamp, kind='1'):
'''
Query posts recently update.
'''
return TabPost.select().where(
(TabPost.kind == kind) &
(TabPost.time_update > timstamp)
).order_by(
TabPost.time_update.desc()
) | [
"def",
"query_recent_edited",
"(",
"timstamp",
",",
"kind",
"=",
"'1'",
")",
":",
"return",
"TabPost",
".",
"select",
"(",
")",
".",
"where",
"(",
"(",
"TabPost",
".",
"kind",
"==",
"kind",
")",
"&",
"(",
"TabPost",
".",
"time_update",
">",
"timstamp",... | 28.6 | 13 |
def reconstruct_mds(edm, all_points, completion='optspace', mask=None, method='geometric', print_out=False, n=1):
""" Reconstruct point set using MDS and matrix completion algorithms.
"""
from .point_set import dm_from_edm
from .mds import MDS
N = all_points.shape[0]
d = all_points.shape[1]
... | [
"def",
"reconstruct_mds",
"(",
"edm",
",",
"all_points",
",",
"completion",
"=",
"'optspace'",
",",
"mask",
"=",
"None",
",",
"method",
"=",
"'geometric'",
",",
"print_out",
"=",
"False",
",",
"n",
"=",
"1",
")",
":",
"from",
".",
"point_set",
"import",
... | 44 | 15.407407 |
def events_this_week(context):
"""
Displays a week's worth of events. Starts week with Monday, unless today is Sunday.
"""
request = context['request']
home = request.site.root_page
cal = CalendarPage.objects.live().descendant_of(home).first()
calUrl = cal.get_url(request) if cal else None... | [
"def",
"events_this_week",
"(",
"context",
")",
":",
"request",
"=",
"context",
"[",
"'request'",
"]",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"cal",
"=",
"CalendarPage",
".",
"objects",
".",
"live",
"(",
")",
".",
"descendant_of",
"(",
"h... | 37.038462 | 11.961538 |
def _determine_filtered_package_requirements(self):
"""
Parse the configuration file for [blacklist]packages
Returns
-------
list of packaging.requirements.Requirement
For all PEP440 package specifiers
"""
filtered_requirements = set()
try:
... | [
"def",
"_determine_filtered_package_requirements",
"(",
"self",
")",
":",
"filtered_requirements",
"=",
"set",
"(",
")",
"try",
":",
"lines",
"=",
"self",
".",
"configuration",
"[",
"\"blacklist\"",
"]",
"[",
"\"packages\"",
"]",
"package_lines",
"=",
"lines",
"... | 35.809524 | 14.095238 |
def _distributeCells(numCellsPop):
''' distribute cells across compute nodes using round-robin'''
from .. import sim
hostCells = {}
for i in range(sim.nhosts):
hostCells[i] = []
for i in range(numCellsPop):
hostCells[sim.nextHost].append(i)
sim.next... | [
"def",
"_distributeCells",
"(",
"numCellsPop",
")",
":",
"from",
".",
".",
"import",
"sim",
"hostCells",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"sim",
".",
"nhosts",
")",
":",
"hostCells",
"[",
"i",
"]",
"=",
"[",
"]",
"for",
"i",
"in",
"... | 30.722222 | 21.944444 |
def add_listener(self, event_name: str, listener: Callable):
"""Add a listener."""
self.listeners[event_name].append(listener)
return self | [
"def",
"add_listener",
"(",
"self",
",",
"event_name",
":",
"str",
",",
"listener",
":",
"Callable",
")",
":",
"self",
".",
"listeners",
"[",
"event_name",
"]",
".",
"append",
"(",
"listener",
")",
"return",
"self"
] | 39.75 | 13 |
def is_writeable(value,
**kwargs):
"""Indicate whether ``value`` is a writeable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can man... | [
"def",
"is_writeable",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sys",
".",
"platform",
"in",
"[",
"'win32'",
",",
"'cygwin'",
"]",
":",
"raise",
"NotImplementedError",
"(",
"'not supported on Windows'",
")",
"try",
":",
"validators",
".",
"w... | 36.493151 | 27.109589 |
def simplex_compute_potentials(self, t, root):
'''
API:
simplex_compute_potentials(self, t, root)
Description:
Computes node potentials for a minimum cost flow problem and stores
them as node attribute 'potential'. Based on pseudocode given in
Netw... | [
"def",
"simplex_compute_potentials",
"(",
"self",
",",
"t",
",",
"root",
")",
":",
"self",
".",
"get_node",
"(",
"root",
")",
".",
"set_attr",
"(",
"'potential'",
",",
"0",
")",
"j",
"=",
"t",
".",
"get_node",
"(",
"root",
")",
".",
"get_attr",
"(",
... | 44.033333 | 18.633333 |
def sg_cast(tensor, opt):
r"""Casts a tensor to a new type.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
dtype : The destination type.
name : If provided, it replaces current tensor's name
Returns:
... | [
"def",
"sg_cast",
"(",
"tensor",
",",
"opt",
")",
":",
"assert",
"opt",
".",
"dtype",
"is",
"not",
"None",
",",
"'dtype is mandatory.'",
"return",
"tf",
".",
"cast",
"(",
"tensor",
",",
"opt",
".",
"dtype",
",",
"name",
"=",
"opt",
".",
"name",
")"
] | 30 | 20.875 |
def p_expression_Xnor(self, p):
'expression : expression XNOR expression'
p[0] = Xnor(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_expression_Xnor",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Xnor",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
... | 41.75 | 8.25 |
def xml_to_bytes(element, pretty_print=False):
"""Wrapper for etree.tostring, that takes care of unsupported pretty_print
option and prepends an encoding header."""
if use_lxml:
xml = etree.tostring(
element, encoding="UTF-8", xml_declaration=True, pretty_print=pretty_print
)
... | [
"def",
"xml_to_bytes",
"(",
"element",
",",
"pretty_print",
"=",
"False",
")",
":",
"if",
"use_lxml",
":",
"xml",
"=",
"etree",
".",
"tostring",
"(",
"element",
",",
"encoding",
"=",
"\"UTF-8\"",
",",
"xml_declaration",
"=",
"True",
",",
"pretty_print",
"=... | 40.928571 | 21.071429 |
def __emulate_axis(self, axis_changes, timeval=None):
"""Make the axis events use the Linux style format."""
events = []
for axis in axis_changes:
code, value = self.__map_axis(axis)
event = self.create_event_object(
"Absolute",
code,
... | [
"def",
"__emulate_axis",
"(",
"self",
",",
"axis_changes",
",",
"timeval",
"=",
"None",
")",
":",
"events",
"=",
"[",
"]",
"for",
"axis",
"in",
"axis_changes",
":",
"code",
",",
"value",
"=",
"self",
".",
"__map_axis",
"(",
"axis",
")",
"event",
"=",
... | 34.5 | 11.5 |
def set_hint_style(self, hint_style):
"""Changes the :ref:`HINT_STYLE` for the font options object.
This controls whether to fit font outlines to the pixel grid,
and if so, whether to optimize for fidelity or contrast.
"""
cairo.cairo_font_options_set_hint_style(self._pointer, h... | [
"def",
"set_hint_style",
"(",
"self",
",",
"hint_style",
")",
":",
"cairo",
".",
"cairo_font_options_set_hint_style",
"(",
"self",
".",
"_pointer",
",",
"hint_style",
")",
"self",
".",
"_check_status",
"(",
")"
] | 44 | 17.75 |
def request_timeout(self, timeout):
"""
Context manager implements opportunity to change request timeout in current context
:param timeout:
:return:
"""
timeout = self._prepare_timeout(timeout)
token = self._ctx_timeout.set(timeout)
try:
yield... | [
"def",
"request_timeout",
"(",
"self",
",",
"timeout",
")",
":",
"timeout",
"=",
"self",
".",
"_prepare_timeout",
"(",
"timeout",
")",
"token",
"=",
"self",
".",
"_ctx_timeout",
".",
"set",
"(",
"timeout",
")",
"try",
":",
"yield",
"finally",
":",
"self"... | 28.307692 | 17.538462 |
def read_instances(self):
"""
Read `.dsb/instances.yaml`
Populates `self.cluster`
"""
logger.debug('Reading instances from: %s', self.instances_path)
if os.path.exists(self.instances_path):
with open(self.instances_path, 'r') as f:
list_ = yaml... | [
"def",
"read_instances",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Reading instances from: %s'",
",",
"self",
".",
"instances_path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"instances_path",
")",
":",
"with",
"open",
"(",... | 40.6 | 12.2 |
def set_org_processor(request):
"""
Simple context processor that automatically sets 'org' on the context if it
is present in the request.
"""
if getattr(request, "org", None):
org = request.org
pattern_bg = org.backgrounds.filter(is_active=True, background_type="P")
pattern_... | [
"def",
"set_org_processor",
"(",
"request",
")",
":",
"if",
"getattr",
"(",
"request",
",",
"\"org\"",
",",
"None",
")",
":",
"org",
"=",
"request",
".",
"org",
"pattern_bg",
"=",
"org",
".",
"backgrounds",
".",
"filter",
"(",
"is_active",
"=",
"True",
... | 39 | 20.333333 |
def resources_from_resource_arguments(default_num_cpus, default_num_gpus,
default_resources, runtime_num_cpus,
runtime_num_gpus, runtime_resources):
"""Determine a task's resource requirements.
Args:
default_num_cpus: The defau... | [
"def",
"resources_from_resource_arguments",
"(",
"default_num_cpus",
",",
"default_num_gpus",
",",
"default_resources",
",",
"runtime_num_cpus",
",",
"runtime_num_gpus",
",",
"runtime_resources",
")",
":",
"if",
"runtime_resources",
"is",
"not",
"None",
":",
"resources",
... | 38.511628 | 20.767442 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.