text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def is_transition_allowed(analyses, transition_id):
"""Returns whether all analyses can be transitioned or not
"""
if not analyses:
return True
if not isinstance(analyses, list):
return is_transition_allowed([analyses], transition_id)
for analysis in analyses:
if not wf.isTra... | [
"def",
"is_transition_allowed",
"(",
"analyses",
",",
"transition_id",
")",
":",
"if",
"not",
"analyses",
":",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"analyses",
",",
"list",
")",
":",
"return",
"is_transition_allowed",
"(",
"[",
"analyses",
"]",
... | 35.545455 | 0.002494 |
def close(self):
"""Closes the connection."""
if not self._closed:
self._closed = True
self.client.close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"_closed",
"=",
"True",
"self",
".",
"client",
".",
"close",
"(",
")"
] | 28.4 | 0.013699 |
def get_track_by_id(session, track_id, track_point_limit=None, track_point_offset=None):
"""
Gets a specific track
"""
tracking_data = {}
if track_point_limit:
tracking_data['track_point_limit'] = track_point_limit
if track_point_offset:
tracking_data['track_point_offset'] = tra... | [
"def",
"get_track_by_id",
"(",
"session",
",",
"track_id",
",",
"track_point_limit",
"=",
"None",
",",
"track_point_offset",
"=",
"None",
")",
":",
"tracking_data",
"=",
"{",
"}",
"if",
"track_point_limit",
":",
"tracking_data",
"[",
"'track_point_limit'",
"]",
... | 37.227273 | 0.002381 |
def check_aggregate(df, variable, components=None, exclude_on_fail=False,
multiplier=1, **kwargs):
"""Check whether the timeseries values match the aggregation
of sub-categories
Parameters
----------
df: IamDataFrame instance
args: see IamDataFrame.check_aggregate() for deta... | [
"def",
"check_aggregate",
"(",
"df",
",",
"variable",
",",
"components",
"=",
"None",
",",
"exclude_on_fail",
"=",
"False",
",",
"multiplier",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"fdf",
"=",
"df",
".",
"filter",
"(",
"*",
"*",
"kwargs",
")",... | 38.944444 | 0.001393 |
def command(self, command, full_response=False, **kwargs): # pragma: no cover
"""Method Interface to the command API for Nationstates"""
command = Shard(c=command)
return self.get_shards(*(command, Shard(**kwargs)), full_response=full_response) | [
"def",
"command",
"(",
"self",
",",
"command",
",",
"full_response",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"command",
"=",
"Shard",
"(",
"c",
"=",
"command",
")",
"return",
"self",
".",
"get_shards",
"(",
"*",
"(",
"com... | 66.25 | 0.014925 |
def repackage_hidden(h):
"""Wraps hidden states in new Tensors, to detach them from their history."""
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(repackage_hidden(v) for v in h) | [
"def",
"repackage_hidden",
"(",
"h",
")",
":",
"if",
"isinstance",
"(",
"h",
",",
"torch",
".",
"Tensor",
")",
":",
"return",
"h",
".",
"detach",
"(",
")",
"else",
":",
"return",
"tuple",
"(",
"repackage_hidden",
"(",
"v",
")",
"for",
"v",
"in",
"h... | 37.5 | 0.008696 |
def find_cycles(sub_network, weight='x_pu'):
"""
Find all cycles in the sub_network and record them in sub_network.C.
networkx collects the cycles with more than 2 edges; then the 2-edge cycles
from the MultiGraph must be collected separately (for cases where there
are multiple lines between the sa... | [
"def",
"find_cycles",
"(",
"sub_network",
",",
"weight",
"=",
"'x_pu'",
")",
":",
"branches_bus0",
"=",
"sub_network",
".",
"branches",
"(",
")",
"[",
"\"bus0\"",
"]",
"branches_i",
"=",
"branches_bus0",
".",
"index",
"#reduce to a non-multi-graph for cycles with > ... | 36 | 0.008631 |
def device_typename(item):
"""
Convert the old names to new-style names and types
:param str item: A device in the form of 'TYPE NAME'
:return: tuple containing device name and type details
"""
dev_type = {'ROUTER': {'from': 'ROUTER',
'des... | [
"def",
"device_typename",
"(",
"item",
")",
":",
"dev_type",
"=",
"{",
"'ROUTER'",
":",
"{",
"'from'",
":",
"'ROUTER'",
",",
"'desc'",
":",
"'Router'",
",",
"'type'",
":",
"'Router'",
",",
"'label_x'",
":",
"19.5",
"}",
",",
"'QEMU'",
":",
"{",
"'from'... | 45.072464 | 0.000629 |
def select_output_directory(self):
"""Select output directory"""
# Input layer
input_layer_path = self.layer.source()
input_file_name = os.path.basename(input_layer_path)
input_extension = os.path.splitext(input_file_name)[1]
# Get current path
current_file_path ... | [
"def",
"select_output_directory",
"(",
"self",
")",
":",
"# Input layer",
"input_layer_path",
"=",
"self",
".",
"layer",
".",
"source",
"(",
")",
"input_file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"input_layer_path",
")",
"input_extension",
"=",
... | 38.241379 | 0.001759 |
def _set_dac_value(self, channel, value):
'''Write DAC
'''
self._intf.write(self._base_addr + self.MAX_5380_ADD, array('B', pack('B', value))) | [
"def",
"_set_dac_value",
"(",
"self",
",",
"channel",
",",
"value",
")",
":",
"self",
".",
"_intf",
".",
"write",
"(",
"self",
".",
"_base_addr",
"+",
"self",
".",
"MAX_5380_ADD",
",",
"array",
"(",
"'B'",
",",
"pack",
"(",
"'B'",
",",
"value",
")",
... | 40.75 | 0.018072 |
def timeit(self, metric, func, *args, **kwargs):
"""Time execution of callable and emit metric then return result."""
return metrics.timeit(metric, func, *args, **kwargs) | [
"def",
"timeit",
"(",
"self",
",",
"metric",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"metrics",
".",
"timeit",
"(",
"metric",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 61.333333 | 0.010753 |
def _credential_allows_container_list(self):
# type: (StorageAccount) -> bool
"""Check if container list is allowed
:param StorageAccount self: this
:rtype: bool
:return: if container list is allowed
"""
if self.is_sas:
sasparts = self.key.split('&')
... | [
"def",
"_credential_allows_container_list",
"(",
"self",
")",
":",
"# type: (StorageAccount) -> bool",
"if",
"self",
".",
"is_sas",
":",
"sasparts",
"=",
"self",
".",
"key",
".",
"split",
"(",
"'&'",
")",
"caccess",
"=",
"self",
".",
"can_create_containers",
"# ... | 38.83871 | 0.002431 |
def sentry_exception (e, request, message = None):
"""Yes, this eats exceptions"""
try:
logtool.log_fault (e, message = message, level = logging.INFO)
data = {
"task": task,
"request": {
"args": task.request.args,
"callbacks": task.request.callbacks,
"called_directly": ta... | [
"def",
"sentry_exception",
"(",
"e",
",",
"request",
",",
"message",
"=",
"None",
")",
":",
"try",
":",
"logtool",
".",
"log_fault",
"(",
"e",
",",
"message",
"=",
"message",
",",
"level",
"=",
"logging",
".",
"INFO",
")",
"data",
"=",
"{",
"\"task\"... | 35.463415 | 0.014726 |
def arrow_respond(slider, event):
"""Event handler for arrow key events in plot windows.
Pass the slider object to update as a masked argument using a lambda function::
lambda evt: arrow_respond(my_slider, evt)
Parameters
----------
slider : Slider instance associated with... | [
"def",
"arrow_respond",
"(",
"slider",
",",
"event",
")",
":",
"if",
"event",
".",
"key",
"==",
"'right'",
":",
"slider",
".",
"set_val",
"(",
"min",
"(",
"slider",
".",
"val",
"+",
"1",
",",
"slider",
".",
"valmax",
")",
")",
"elif",
"event",
".",... | 33.5625 | 0.009058 |
def groups_create(self, name, **kwargs):
"""Creates a new private group, optionally including users, only if you’re part of the group."""
return self.__call_api_post('groups.create', name=name, kwargs=kwargs) | [
"def",
"groups_create",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'groups.create'",
",",
"name",
"=",
"name",
",",
"kwargs",
"=",
"kwargs",
")"
] | 74 | 0.013393 |
def _strip_placeholder_braces(p_matchobj):
"""
Returns string with conditional braces around placeholder stripped and
percent sign glued into placeholder character.
Returned string is composed from 'start', 'before', 'placeholder', 'after',
'whitespace', and 'end' match-groups of p_matchobj. Condit... | [
"def",
"_strip_placeholder_braces",
"(",
"p_matchobj",
")",
":",
"before",
"=",
"p_matchobj",
".",
"group",
"(",
"'before'",
")",
"or",
"''",
"placeholder",
"=",
"p_matchobj",
".",
"group",
"(",
"'placeholder'",
")",
"after",
"=",
"p_matchobj",
".",
"group",
... | 39.238095 | 0.001185 |
def iter_links_script_element(self, element):
'''Iterate a ``script`` element.'''
if self.javascript_scraper and element.text:
link_iter = self.javascript_scraper.scrape_links(element.text,
context=True)
for link, cont... | [
"def",
"iter_links_script_element",
"(",
"self",
",",
"element",
")",
":",
"if",
"self",
".",
"javascript_scraper",
"and",
"element",
".",
"text",
":",
"link_iter",
"=",
"self",
".",
"javascript_scraper",
".",
"scrape_links",
"(",
"element",
".",
"text",
",",
... | 36.04 | 0.002162 |
def replace_parent(self, parent_simples):
"""If ``&`` (or the legacy xCSS equivalent ``self``) appears in this
selector, replace it with the given iterable of parent selectors.
Returns a tuple of simple selectors.
"""
assert parent_simples
ancestors = parent_simples[:-1... | [
"def",
"replace_parent",
"(",
"self",
",",
"parent_simples",
")",
":",
"assert",
"parent_simples",
"ancestors",
"=",
"parent_simples",
"[",
":",
"-",
"1",
"]",
"parent",
"=",
"parent_simples",
"[",
"-",
"1",
"]",
"did_replace",
"=",
"False",
"new_tokens",
"=... | 40.4375 | 0.001006 |
def check_measurements_against_sensitivities(
self, magnitude, phase=0, return_plot=False):
"""Check for all configurations if the sensitivities add up to a given
homogeneous model
Parameters
----------
magnitude : float
magnitude used for the homogeneous... | [
"def",
"check_measurements_against_sensitivities",
"(",
"self",
",",
"magnitude",
",",
"phase",
"=",
"0",
",",
"return_plot",
"=",
"False",
")",
":",
"# generate a temporary tdMan instance",
"tdm",
"=",
"tdMan",
"(",
"grid",
"=",
"self",
".",
"grid",
",",
"confi... | 33.274809 | 0.000446 |
def measure_board_rms(control_board, n_samples=10, sampling_ms=10,
delay_between_samples_ms=0):
'''
Read RMS voltage samples from control board high-voltage feedback circuit.
'''
try:
results = control_board.measure_impedance(n_samples, sampling_ms,
... | [
"def",
"measure_board_rms",
"(",
"control_board",
",",
"n_samples",
"=",
"10",
",",
"sampling_ms",
"=",
"10",
",",
"delay_between_samples_ms",
"=",
"0",
")",
":",
"try",
":",
"results",
"=",
"control_board",
".",
"measure_impedance",
"(",
"n_samples",
",",
"sa... | 50 | 0.000981 |
def _bg(self, coro: coroutine) -> asyncio.Task:
"""Run coro in background, log errors"""
async def runner():
try:
await coro
except:
self._log.exception("async: Coroutine raised exception")
return asyncio.ensure_future(runner()) | [
"def",
"_bg",
"(",
"self",
",",
"coro",
":",
"coroutine",
")",
"->",
"asyncio",
".",
"Task",
":",
"async",
"def",
"runner",
"(",
")",
":",
"try",
":",
"await",
"coro",
"except",
":",
"self",
".",
"_log",
".",
"exception",
"(",
"\"async: Coroutine raise... | 37.625 | 0.00974 |
def random_insertion(self,fastq,rate,max_inserts=1):
"""Perform the permutation on the sequence. If authorized to do multiple bases they are done at hte rate defined here.
:param fastq: FASTQ sequence to permute
:type fastq: format.fastq.FASTQ
:param rate: how frequently to permute
:type rate: floa... | [
"def",
"random_insertion",
"(",
"self",
",",
"fastq",
",",
"rate",
",",
"max_inserts",
"=",
"1",
")",
":",
"sequence",
"=",
"fastq",
".",
"sequence",
"quality",
"=",
"fastq",
".",
"qual",
"seq",
"=",
"''",
"qual",
"=",
"None",
"ibase",
"=",
"rate_to_ph... | 32.22807 | 0.022715 |
def interp2d1d(x,y,Z,xout,yout,**kwargs):
"""
INTERP2D1d : Interpolate values from a 2D matrix along a 1D trajectory
@param x: 1st dimension vector of size NX
@param y: 2nd dimension vector of size NY
@param Z: Array to interpolate (NXxNY)
@param xout: 1st dimension vector of siz... | [
"def",
"interp2d1d",
"(",
"x",
",",
"y",
",",
"Z",
",",
"xout",
",",
"yout",
",",
"*",
"*",
"kwargs",
")",
":",
"gx",
"=",
"np",
".",
"reshape",
"(",
"np",
".",
"repeat",
"(",
"x",
",",
"y",
".",
"size",
")",
",",
"(",
"x",
".",
"size",
"... | 32.710526 | 0.022656 |
def fq_name(self):
"""Return FQDN of the resource
:rtype: FQName
"""
return self.get('fq_name', self.get('to', super(Resource, self).fq_name)) | [
"def",
"fq_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"get",
"(",
"'fq_name'",
",",
"self",
".",
"get",
"(",
"'to'",
",",
"super",
"(",
"Resource",
",",
"self",
")",
".",
"fq_name",
")",
")"
] | 28.333333 | 0.017143 |
def flatten(self, msg, unixfrom=False, linesep=None):
r"""Print the message object tree rooted at msg to the output file
specified when the Generator instance was created.
unixfrom is a flag that forces the printing of a Unix From_ delimiter
before the first object in the message tree. ... | [
"def",
"flatten",
"(",
"self",
",",
"msg",
",",
"unixfrom",
"=",
"False",
",",
"linesep",
"=",
"None",
")",
":",
"# We use the _XXX constants for operating on data that comes directly",
"# from the msg, and _encoded_XXX constants for operating on data that",
"# has already been c... | 45.869565 | 0.000928 |
def update_variable(self, variable, value) -> None:
"""Assign the given value(s) to the given target or base variable.
If the assignment fails, |ChangeItem.update_variable| raises an
error like the following:
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, pu... | [
"def",
"update_variable",
"(",
"self",
",",
"variable",
",",
"value",
")",
"->",
"None",
":",
"try",
":",
"variable",
"(",
"value",
")",
"except",
"BaseException",
":",
"objecttools",
".",
"augment_excmessage",
"(",
"f'When trying to update a target variable of '",
... | 46.76 | 0.001676 |
def encode_complex(data, complex_names):
""" Encodes complex data to having arbitrary complex field names.
Encodes complex `data` to have the real and imaginary field names
given in `complex_numbers`. This is needed because the field names
have to be set so that it can be written to an HDF5 file with t... | [
"def",
"encode_complex",
"(",
"data",
",",
"complex_names",
")",
":",
"# Grab the dtype name, and convert it to the right non-complex type",
"# if it isn't already one.",
"dtype_name",
"=",
"data",
".",
"dtype",
".",
"name",
"if",
"dtype_name",
"[",
"0",
":",
"7",
"]",
... | 34.902439 | 0.00068 |
def get_state_variable_from_storage(
self, address: str, params: Optional[List[str]] = None
) -> str:
"""
Get variables from the storage
:param address: The contract address
:param params: The list of parameters
param types: [position, length] or ["map... | [
"def",
"get_state_variable_from_storage",
"(",
"self",
",",
"address",
":",
"str",
",",
"params",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"str",
":",
"params",
"=",
"params",
"or",
"[",
"]",
"(",
"position",
",",
"... | 38.602273 | 0.001722 |
def from_hex(cls, hexval: str) -> 'ColorCode':
""" Return a ColorCode from a hex string. """
c = cls()
c._init_hex(hexval)
return c | [
"def",
"from_hex",
"(",
"cls",
",",
"hexval",
":",
"str",
")",
"->",
"'ColorCode'",
":",
"c",
"=",
"cls",
"(",
")",
"c",
".",
"_init_hex",
"(",
"hexval",
")",
"return",
"c"
] | 31.8 | 0.01227 |
def rpc(self, name, handler, value, request=None):
"""Perform RPC operation on PV
:param name: A single name string or list of name strings
:param callable handler: Completion notification. Called with a Value, RemoteError, or Cancelled
:param request: A :py:class:`p4p.Value` or string... | [
"def",
"rpc",
"(",
"self",
",",
"name",
",",
"handler",
",",
"value",
",",
"request",
"=",
"None",
")",
":",
"chan",
"=",
"self",
".",
"_channel",
"(",
"name",
")",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"Value",
"(",
"Type",
"(",
"[",
... | 52.5 | 0.009358 |
def parse_create_table(sql):
"""
Split output of SHOW CREATE TABLE into {column: column_spec}
"""
column_types = {}
for line in sql.splitlines()[1:]: # first line = CREATE TABLE
sline = line.strip()
if not sline.startswith('`'):
# We've finished parsing the columns
... | [
"def",
"parse_create_table",
"(",
"sql",
")",
":",
"column_types",
"=",
"{",
"}",
"for",
"line",
"in",
"sql",
".",
"splitlines",
"(",
")",
"[",
"1",
":",
"]",
":",
"# first line = CREATE TABLE",
"sline",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not"... | 28 | 0.001818 |
def wait_for_psexecsvc(host, port, username, password, timeout=900):
'''
Wait until psexec connection can be established.
'''
if has_winexe() and not HAS_PSEXEC:
return wait_for_winexe(host, port, username, password, timeout)
start = time.time()
try_count = 0
while True:
try_... | [
"def",
"wait_for_psexecsvc",
"(",
"host",
",",
"port",
",",
"username",
",",
"password",
",",
"timeout",
"=",
"900",
")",
":",
"if",
"has_winexe",
"(",
")",
"and",
"not",
"HAS_PSEXEC",
":",
"return",
"wait_for_winexe",
"(",
"host",
",",
"port",
",",
"use... | 33.222222 | 0.001083 |
def mergemat(args):
"""
%prog mergemat *.npy
Combine counts from multiple .npy data files.
"""
p = OptionParser(mergemat.__doc__)
p.set_outfile(outfile="out")
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
npyfiles = args
A = np.load(npy... | [
"def",
"mergemat",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mergemat",
".",
"__doc__",
")",
"p",
".",
"set_outfile",
"(",
"outfile",
"=",
"\"out\"",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
... | 27.461538 | 0.001353 |
def set_status(self, name, text='', row=0, fg='black', bg='white'):
'''set a status value'''
if self.is_alive():
self.parent_pipe_send.send(Value(name, text, row, fg, bg)) | [
"def",
"set_status",
"(",
"self",
",",
"name",
",",
"text",
"=",
"''",
",",
"row",
"=",
"0",
",",
"fg",
"=",
"'black'",
",",
"bg",
"=",
"'white'",
")",
":",
"if",
"self",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"parent_pipe_send",
".",
"send... | 49 | 0.01005 |
def match_rstring(self, tokens, item):
"""Match suffix string."""
name, suffix = tokens
return self.match_mstring((None, name, suffix), item, use_bytes=suffix.startswith("b")) | [
"def",
"match_rstring",
"(",
"self",
",",
"tokens",
",",
"item",
")",
":",
"name",
",",
"suffix",
"=",
"tokens",
"return",
"self",
".",
"match_mstring",
"(",
"(",
"None",
",",
"name",
",",
"suffix",
")",
",",
"item",
",",
"use_bytes",
"=",
"suffix",
... | 49 | 0.015075 |
def read_text_from_conll_file( file_name, layer_name=LAYER_CONLL, **kwargs ):
''' Reads the CONLL format syntactic analysis from given file, and returns as
a Text object.
The Text object has been tokenized for paragraphs, sentences, words, and it
contains syntactic analyses aligne... | [
"def",
"read_text_from_conll_file",
"(",
"file_name",
",",
"layer_name",
"=",
"LAYER_CONLL",
",",
"*",
"*",
"kwargs",
")",
":",
"# 1) Load conll analysed text from file",
"conll_lines",
"=",
"[",
"]",
"in_f",
"=",
"codecs",
".",
"open",
"(",
"file_name",
",",
"m... | 40.012658 | 0.016672 |
def generate_veq(R=1.3, dR=0.1, Prot=6, dProt=0.1,nsamples=1e4,plot=False,
R_samples=None,Prot_samples=None):
""" Returns the mean and std equatorial velocity given R,dR,Prot,dProt
Assumes all distributions are normal. This will be used mainly for
testing purposes; I can use MC-generated ... | [
"def",
"generate_veq",
"(",
"R",
"=",
"1.3",
",",
"dR",
"=",
"0.1",
",",
"Prot",
"=",
"6",
",",
"dProt",
"=",
"0.1",
",",
"nsamples",
"=",
"1e4",
",",
"plot",
"=",
"False",
",",
"R_samples",
"=",
"None",
",",
"Prot_samples",
"=",
"None",
")",
":"... | 40.071429 | 0.016536 |
def deterministic(cls, mnemonic, passphrase='', lang='english', index=0):
"""Generate a :class:`Keypair` object via a deterministic
phrase.
Using a mnemonic, such as one generated from :class:`StellarMnemonic`,
generate a new keypair deterministically. Uses :class:`StellarMnemonic`
... | [
"def",
"deterministic",
"(",
"cls",
",",
"mnemonic",
",",
"passphrase",
"=",
"''",
",",
"lang",
"=",
"'english'",
",",
"index",
"=",
"0",
")",
":",
"sm",
"=",
"StellarMnemonic",
"(",
"lang",
")",
"seed",
"=",
"sm",
".",
"to_seed",
"(",
"mnemonic",
",... | 53.275862 | 0.001907 |
def send_cluster_time(self, command, session, client):
"""Add cluster time for MongoDB >= 3.6."""
if self.max_wire_version >= 6 and client:
client._send_cluster_time(command, session) | [
"def",
"send_cluster_time",
"(",
"self",
",",
"command",
",",
"session",
",",
"client",
")",
":",
"if",
"self",
".",
"max_wire_version",
">=",
"6",
"and",
"client",
":",
"client",
".",
"_send_cluster_time",
"(",
"command",
",",
"session",
")"
] | 52 | 0.009479 |
def scatter_drag(
x_points: 'Array',
y_points: 'Array',
*,
fig=None,
show_eqn=True,
options={}
):
"""
Generates an interactive scatter plot with the best fit line plotted over
the points. The points can be dragged by the user and the line will
automatically update.
Args:
... | [
"def",
"scatter_drag",
"(",
"x_points",
":",
"'Array'",
",",
"y_points",
":",
"'Array'",
",",
"*",
",",
"fig",
"=",
"None",
",",
"show_eqn",
"=",
"True",
",",
"options",
"=",
"{",
"}",
")",
":",
"params",
"=",
"{",
"'marks'",
":",
"[",
"{",
"'x'",
... | 26.409091 | 0.000553 |
def gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env, rendered_env,
rendered_env_resize_to, sticky_actions):
"""Wraps a gym environment. see make_gym_env for details."""
# rl_env_max_episode_steps is None or int.
assert ((not rl_env_max_episode_steps) or
isinstance(rl_env_m... | [
"def",
"gym_env_wrapper",
"(",
"env",
",",
"rl_env_max_episode_steps",
",",
"maxskip_env",
",",
"rendered_env",
",",
"rendered_env_resize_to",
",",
"sticky_actions",
")",
":",
"# rl_env_max_episode_steps is None or int.",
"assert",
"(",
"(",
"not",
"rl_env_max_episode_steps... | 33.153846 | 0.012401 |
def _implicit_credentials_from_files():
"""Attempts to get implicit credentials from local credential files.
First checks if the environment variable GOOGLE_APPLICATION_CREDENTIALS
is set with a filename and then falls back to a configuration file (the
"well known" file) associated with... | [
"def",
"_implicit_credentials_from_files",
"(",
")",
":",
"credentials_filename",
"=",
"_get_environment_variable_file",
"(",
")",
"if",
"not",
"credentials_filename",
":",
"credentials_filename",
"=",
"_get_well_known_file",
"(",
")",
"if",
"os",
".",
"path",
".",
"i... | 44.564103 | 0.001126 |
def getBoneCount(self, action):
"""Reads the number of bones in skeleton associated with the given action"""
fn = self.function_table.getBoneCount
pBoneCount = c_uint32()
result = fn(action, byref(pBoneCount))
return result, pBoneCount.value | [
"def",
"getBoneCount",
"(",
"self",
",",
"action",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getBoneCount",
"pBoneCount",
"=",
"c_uint32",
"(",
")",
"result",
"=",
"fn",
"(",
"action",
",",
"byref",
"(",
"pBoneCount",
")",
")",
"return",
... | 39.428571 | 0.010638 |
def load_ssl_data(self, cert_file, key_file):
"""
A convenience method that loads a cert and a key from files and sets them
on this object. This can make enabling ssl easier (instead of you needing
to load the files yourself).
This does *not* change protocol/port for you, or sa... | [
"def",
"load_ssl_data",
"(",
"self",
",",
"cert_file",
",",
"key_file",
")",
":",
"# we're disabling warnings here because these attributes are defined dynamically",
"# through linode.objects.Base, and pylint isn't privy",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".... | 48.791667 | 0.008375 |
def invalidate(self):
"""Invalidate cached data for this page."""
cache.delete(self.PAGE_LANGUAGES_KEY % (self.pk))
cache.delete('PAGE_FIRST_ROOT_ID')
cache.delete(self.CHILDREN_KEY % self.pk)
cache.delete(self.PUB_CHILDREN_KEY % self.pk)
# XXX: Should this have a depth ... | [
"def",
"invalidate",
"(",
"self",
")",
":",
"cache",
".",
"delete",
"(",
"self",
".",
"PAGE_LANGUAGES_KEY",
"%",
"(",
"self",
".",
"pk",
")",
")",
"cache",
".",
"delete",
"(",
"'PAGE_FIRST_ROOT_ID'",
")",
"cache",
".",
"delete",
"(",
"self",
".",
"CHIL... | 32.358974 | 0.001538 |
def verifyNoUnwantedInteractions(*objs):
"""Verifies that expectations set via `expect` are met
E.g.::
expect(os.path, times=1).exists(...).thenReturn(True)
os.path('/foo')
verifyNoUnwantedInteractions(os.path) # ok, called once
If you leave out the argument *all* registered obje... | [
"def",
"verifyNoUnwantedInteractions",
"(",
"*",
"objs",
")",
":",
"if",
"objs",
":",
"theMocks",
"=",
"map",
"(",
"_get_mock_or_raise",
",",
"objs",
")",
"else",
":",
"theMocks",
"=",
"mock_registry",
".",
"get_registered_mocks",
"(",
")",
"for",
"mock",
"i... | 27.148148 | 0.001318 |
def execution_errors(self):
"""
Return a list of commands that encountered execution errors, with the error.
Each dictionary entry gives the command dictionary and the error dictionary
:return: list of commands that gave errors, with their error information
"""
if self.s... | [
"def",
"execution_errors",
"(",
"self",
")",
":",
"if",
"self",
".",
"split_actions",
":",
"# throttling split this action, get errors from the split",
"return",
"[",
"dict",
"(",
"e",
")",
"for",
"s",
"in",
"self",
".",
"split_actions",
"for",
"e",
"in",
"s",
... | 44.25 | 0.009225 |
def _target_classes(self, target):
"""Set of target's provided classes.
Call at the target level is to memoize efficiently.
"""
target_classes = set()
contents = ClasspathUtil.classpath_contents((target,), self.runtime_classpath)
for f in contents:
classname = ClasspathUtil.classname_for_... | [
"def",
"_target_classes",
"(",
"self",
",",
"target",
")",
":",
"target_classes",
"=",
"set",
"(",
")",
"contents",
"=",
"ClasspathUtil",
".",
"classpath_contents",
"(",
"(",
"target",
",",
")",
",",
"self",
".",
"runtime_classpath",
")",
"for",
"f",
"in",... | 34.083333 | 0.009524 |
def getImageObject(url, referrer, session, max_content_bytes=MaxImageBytes):
"""Get response object for given image URL."""
return urlopen(url, session, referrer=referrer, max_content_bytes=max_content_bytes, stream=True) | [
"def",
"getImageObject",
"(",
"url",
",",
"referrer",
",",
"session",
",",
"max_content_bytes",
"=",
"MaxImageBytes",
")",
":",
"return",
"urlopen",
"(",
"url",
",",
"session",
",",
"referrer",
"=",
"referrer",
",",
"max_content_bytes",
"=",
"max_content_bytes",... | 75.666667 | 0.008734 |
def load_molecule(name, format=None):
'''Read a `~chemlab.core.Molecule` from a file.
.. seealso:: `chemlab.io.datafile`
'''
mol = datafile(name, format=format).read('molecule')
display_system(System([mol])) | [
"def",
"load_molecule",
"(",
"name",
",",
"format",
"=",
"None",
")",
":",
"mol",
"=",
"datafile",
"(",
"name",
",",
"format",
"=",
"format",
")",
".",
"read",
"(",
"'molecule'",
")",
"display_system",
"(",
"System",
"(",
"[",
"mol",
"]",
")",
")"
] | 28.75 | 0.012658 |
def _set_SNR_grids(self):
""" Set the grids and weights for SNR used in numerical integration
of SNR parameters.
"""
if self.SNR_prior == 'unif':
SNR_grids = np.linspace(0, 1, self.SNR_bins)
SNR_weights = np.ones(self.SNR_bins) / (self.SNR_bins - 1)
... | [
"def",
"_set_SNR_grids",
"(",
"self",
")",
":",
"if",
"self",
".",
"SNR_prior",
"==",
"'unif'",
":",
"SNR_grids",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"self",
".",
"SNR_bins",
")",
"SNR_weights",
"=",
"np",
".",
"ones",
"(",
"self",
... | 49.142857 | 0.00114 |
def create_java_executor(self, dist=None):
"""Create java executor that uses this task's ng daemon, if allowed.
Call only in execute() or later. TODO: Enforce this.
"""
dist = dist or self.dist
if self.execution_strategy == self.NAILGUN:
classpath = os.pathsep.join(self.tool_classpath('nailgu... | [
"def",
"create_java_executor",
"(",
"self",
",",
"dist",
"=",
"None",
")",
":",
"dist",
"=",
"dist",
"or",
"self",
".",
"dist",
"if",
"self",
".",
"execution_strategy",
"==",
"self",
".",
"NAILGUN",
":",
"classpath",
"=",
"os",
".",
"pathsep",
".",
"jo... | 48 | 0.008413 |
def _determineVolumeSize(self, source_type, source_uuid):
"""
Determine the minimum size the volume needs to be for the source.
Returns the size in GiB.
"""
nova = self.novaclient
if source_type == 'image':
# The size returned for an image is in bytes. Round u... | [
"def",
"_determineVolumeSize",
"(",
"self",
",",
"source_type",
",",
"source_uuid",
")",
":",
"nova",
"=",
"self",
".",
"novaclient",
"if",
"source_type",
"==",
"'image'",
":",
"# The size returned for an image is in bytes. Round up to the next",
"# integer GiB.",
"image"... | 44.12 | 0.001775 |
def parse_item(self, location: str, item_type: Type[T], item_name_for_log: str = None,
file_mapping_conf: FileMappingConfiguration = None, options: Dict[str, Dict[str, Any]] = None) -> T:
"""
Main method to parse an item of type item_type
:param location:
:param item_... | [
"def",
"parse_item",
"(",
"self",
",",
"location",
":",
"str",
",",
"item_type",
":",
"Type",
"[",
"T",
"]",
",",
"item_name_for_log",
":",
"str",
"=",
"None",
",",
"file_mapping_conf",
":",
"FileMappingConfiguration",
"=",
"None",
",",
"options",
":",
"Di... | 41.625 | 0.008806 |
def offset_mask(mask):
""" Returns a mask shrunk to the 'minimum bounding rectangle' of the
nonzero portion of the previous mask, and its offset from the original.
Useful to find the smallest rectangular section of the image that can be
extracted to include the entire geometry. Conforms to t... | [
"def",
"offset_mask",
"(",
"mask",
")",
":",
"def",
"axis_data",
"(",
"axis",
")",
":",
"\"\"\"Gets the bounds of a masked area along a certain axis\"\"\"",
"x",
"=",
"mask",
".",
"sum",
"(",
"axis",
")",
"trimmed_front",
"=",
"N",
".",
"trim_zeros",
"(",
"x",
... | 38.380952 | 0.010896 |
def runcmd(command, command_input=None, cwd=None):
"""Run a command, potentially sending stdin, and capturing stdout/err."""
proc = subprocess.Popen(command, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
... | [
"def",
"runcmd",
"(",
"command",
",",
"command_input",
"=",
"None",
",",
"cwd",
"=",
"None",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",... | 51.230769 | 0.001475 |
def from_folder(cls, path:PathOrStr, extensions:Collection[str]=None, recurse:bool=True,
include:Optional[Collection[str]]=None, processor:PreProcessors=None, **kwargs)->'ItemList':
"""Create an `ItemList` in `path` from the filenames that have a suffix in `extensions`.
`recurse` det... | [
"def",
"from_folder",
"(",
"cls",
",",
"path",
":",
"PathOrStr",
",",
"extensions",
":",
"Collection",
"[",
"str",
"]",
"=",
"None",
",",
"recurse",
":",
"bool",
"=",
"True",
",",
"include",
":",
"Optional",
"[",
"Collection",
"[",
"str",
"]",
"]",
"... | 83.333333 | 0.041584 |
def headers(self):
"""
Get http headers or the http/https request.
@return: A dictionary of header/values.
@rtype: dict
"""
action = self.method.soap.action
stock = { 'Content-Type' : 'text/xml; charset=utf-8', 'SOAPAction': action }
result = dict(stock, *... | [
"def",
"headers",
"(",
"self",
")",
":",
"action",
"=",
"self",
".",
"method",
".",
"soap",
".",
"action",
"stock",
"=",
"{",
"'Content-Type'",
":",
"'text/xml; charset=utf-8'",
",",
"'SOAPAction'",
":",
"action",
"}",
"result",
"=",
"dict",
"(",
"stock",
... | 36 | 0.014778 |
def read(self, size=None): # pylint: disable=missing-docstring
"""Read at most size bytes from this slice.
Compared to other streams, there is one case where we may
unexpectedly raise an exception on read: if the underlying stream
is exhausted (i.e. returns no bytes on read), and the s... | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"# pylint: disable=missing-docstring",
"if",
"size",
"is",
"not",
"None",
":",
"read_size",
"=",
"min",
"(",
"size",
",",
"self",
".",
"__remaining_bytes",
")",
"else",
":",
"read_size",
"=",
... | 36.71875 | 0.001658 |
def calc_area_extent(self, key):
"""Calculate area extent for a dataset."""
# Calculate the area extent of the swath based on start line and column
# information, total number of segments and channel resolution
xyres = {500: 22272, 1000: 11136, 2000: 5568}
chkres = xyres[key.reso... | [
"def",
"calc_area_extent",
"(",
"self",
",",
"key",
")",
":",
"# Calculate the area extent of the swath based on start line and column",
"# information, total number of segments and channel resolution",
"xyres",
"=",
"{",
"500",
":",
"22272",
",",
"1000",
":",
"11136",
",",
... | 48.594595 | 0.002181 |
def get_environment(self):
"""
Get environment facts.
power and fan are currently not implemented
cpu is using 1-minute average
"""
environment = {}
# sys_resources contains cpu and mem output
sys_resources = self._send_command("show system resources")
... | [
"def",
"get_environment",
"(",
"self",
")",
":",
"environment",
"=",
"{",
"}",
"# sys_resources contains cpu and mem output",
"sys_resources",
"=",
"self",
".",
"_send_command",
"(",
"\"show system resources\"",
")",
"temp_cmd",
"=",
"\"show environment temperature\"",
"#... | 38.680556 | 0.001751 |
def signed_face_areas(faces, axis=1):
'''
signed_face_areas(faces) yields a potential function f(x) that calculates the signed area of
each face represented by the simplices matrix faces.
If faces is None, then the parameters must arrive in the form of a flattened (n x 3 x 2) matrix
where n is th... | [
"def",
"signed_face_areas",
"(",
"faces",
",",
"axis",
"=",
"1",
")",
":",
"faces",
"=",
"np",
".",
"asarray",
"(",
"faces",
")",
"if",
"len",
"(",
"faces",
".",
"shape",
")",
"==",
"2",
":",
"if",
"faces",
".",
"shape",
"[",
"1",
"]",
"!=",
"3... | 52.73913 | 0.011336 |
def cli(env, identifier):
"""Edit firewall rules."""
mgr = SoftLayer.FirewallManager(env.client)
firewall_type, firewall_id = firewall.parse_id(identifier)
if firewall_type == 'vlan':
orig_rules = mgr.get_dedicated_fwl_rules(firewall_id)
else:
orig_rules = mgr.get_standard_fwl_rule... | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"FirewallManager",
"(",
"env",
".",
"client",
")",
"firewall_type",
",",
"firewall_id",
"=",
"firewall",
".",
"parse_id",
"(",
"identifier",
")",
"if",
"firewall_type",
"=... | 43.609756 | 0.000547 |
def set_el(cls, el, value):
"""
Set given `el` tag element to `value`.
Automatically choose proper method to set the `value` based on the type
of the `el`.
Args:
el (obj): Element reference to the input you want to convert to
typeahead.
v... | [
"def",
"set_el",
"(",
"cls",
",",
"el",
",",
"value",
")",
":",
"if",
"not",
"el",
":",
"return",
"tag_name",
"=",
"el",
".",
"elt",
".",
"tagName",
".",
"lower",
"(",
")",
"if",
"tag_name",
"==",
"\"textarea\"",
":",
"cls",
".",
"_set_textarea",
"... | 31.551724 | 0.002121 |
def aer2enu(az: float, el: float, srange: float, deg: bool = True) -> Tuple[float, float, float]:
"""
Azimuth, Elevation, Slant range to target to East, north, Up
Parameters
----------
azimuth : float or np.ndarray of float
azimuth clockwise from north (degrees)
elevation : float or... | [
"def",
"aer2enu",
"(",
"az",
":",
"float",
",",
"el",
":",
"float",
",",
"srange",
":",
"float",
",",
"deg",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"if",
"deg",
":",
"el",
"=",
"radians... | 30.542857 | 0.001813 |
def to_args(self):
# type: () -> List[str]
"""
Return the VCS-specific command arguments.
"""
args = [] # type: List[str]
rev = self.arg_rev
if rev is not None:
args += self.vcs.get_base_rev_args(rev)
args += self.extra_args
return ar... | [
"def",
"to_args",
"(",
"self",
")",
":",
"# type: () -> List[str]",
"args",
"=",
"[",
"]",
"# type: List[str]",
"rev",
"=",
"self",
".",
"arg_rev",
"if",
"rev",
"is",
"not",
"None",
":",
"args",
"+=",
"self",
".",
"vcs",
".",
"get_base_rev_args",
"(",
"r... | 25.916667 | 0.009317 |
def _retry_usb_function(count, func, *args, **kwargs):
"""Helper function to retry USB."""
helper = timeouts.RetryHelper(count)
while True:
try:
return func(*args, **kwargs)
except usb_exceptions.CommonUsbError:
if not helper.retry_if_possible():
raise
time.sleep(0.1)
else:
... | [
"def",
"_retry_usb_function",
"(",
"count",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"helper",
"=",
"timeouts",
".",
"RetryHelper",
"(",
"count",
")",
"while",
"True",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",... | 26.583333 | 0.024242 |
def GLOBAL(self, node):
"""Keep track of globals declarations."""
if isinstance(self.scope, FunctionScope):
self.scope.globals.update(node.names) | [
"def",
"GLOBAL",
"(",
"self",
",",
"node",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"scope",
",",
"FunctionScope",
")",
":",
"self",
".",
"scope",
".",
"globals",
".",
"update",
"(",
"node",
".",
"names",
")"
] | 42.5 | 0.011561 |
def gpg_unstash_key( appname, key_id, config_dir=None, gpghome=None ):
"""
Remove a public key locally from our local app keyring
Return True on success
Return False on error
"""
assert is_valid_appname(appname)
if gpghome is None:
config_dir = get_config_dir( config_dir )
k... | [
"def",
"gpg_unstash_key",
"(",
"appname",
",",
"key_id",
",",
"config_dir",
"=",
"None",
",",
"gpghome",
"=",
"None",
")",
":",
"assert",
"is_valid_appname",
"(",
"appname",
")",
"if",
"gpghome",
"is",
"None",
":",
"config_dir",
"=",
"get_config_dir",
"(",
... | 30.034483 | 0.015573 |
def get_content_macro_by_hash(self, content_id, version, macro_hash, callback=None):
"""
Returns the body of a macro (in storage format) with the given hash.
This resource is primarily used by connect applications that require the body of macro to perform their work.
The hash is generat... | [
"def",
"get_content_macro_by_hash",
"(",
"self",
",",
"content_id",
",",
"version",
",",
"macro_hash",
",",
"callback",
"=",
"None",
")",
":",
"return",
"self",
".",
"_service_get_request",
"(",
"\"rest/api/content/{id}/history/{version}/macro/hash/{hash}\"",
"\"\"",
".... | 70.407407 | 0.008303 |
def _get_axes(kwargs: Dict[str, Any], *, use_3d: bool = False, use_polar: bool = False) -> Tuple[Figure, Union[Axes, Axes3D]]:
"""Prepare the axis to draw into.
Parameters
----------
use_3d: If True, an axis with 3D projection is created.
use_polar: If True, the plot will have polar coordinates.
... | [
"def",
"_get_axes",
"(",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"*",
",",
"use_3d",
":",
"bool",
"=",
"False",
",",
"use_polar",
":",
"bool",
"=",
"False",
")",
"->",
"Tuple",
"[",
"Figure",
",",
"Union",
"[",
"Axes",
",",
"Axes... | 29.757576 | 0.001972 |
def reindex(self, fq= [], **kwargs):
'''
Starts Reindexing Process. All parameter arguments will be passed down to the getter function.
:param string fq: FilterQuery to pass to source Solr to retrieve items. This can be used to limit the results.
'''
for items in self._gette... | [
"def",
"reindex",
"(",
"self",
",",
"fq",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"items",
"in",
"self",
".",
"_getter",
"(",
"fq",
"=",
"fq",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_putter",
"(",
"items",
")",
"if"... | 56 | 0.008787 |
async def get_artifacts(self, agent=None):
'''Return artifacts published to the environment.
:param agent:
If not ``None``, then returns only artifacts created by the agent.
:returns: All artifacts published (by the agent).
:rtype: list
If environment has a :attr:`... | [
"async",
"def",
"get_artifacts",
"(",
"self",
",",
"agent",
"=",
"None",
")",
":",
"# TODO: Figure better way for this",
"if",
"hasattr",
"(",
"self",
",",
"'manager'",
")",
"and",
"self",
".",
"manager",
"is",
"not",
"None",
":",
"artifacts",
"=",
"await",
... | 40.142857 | 0.002317 |
def list_fonts(self, pattern, max_names):
"""Return a list of font names matching pattern. No more than
max_names will be returned."""
r = request.ListFonts(display = self.display,
max_names = max_names,
pattern = pattern)
retur... | [
"def",
"list_fonts",
"(",
"self",
",",
"pattern",
",",
"max_names",
")",
":",
"r",
"=",
"request",
".",
"ListFonts",
"(",
"display",
"=",
"self",
".",
"display",
",",
"max_names",
"=",
"max_names",
",",
"pattern",
"=",
"pattern",
")",
"return",
"r",
".... | 46.142857 | 0.024316 |
def ansi_format_iter( self, x_start=0, y_start=0, width=None, height=None, frame=0, columns=1, downsample=1, frame_index=None, frame_flip_v=0, frame_flip_h=0 ):
"""Return the ANSI escape sequence to render the image.
x_start
Offset from the left of the image data to render from. Defaults to... | [
"def",
"ansi_format_iter",
"(",
"self",
",",
"x_start",
"=",
"0",
",",
"y_start",
"=",
"0",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"frame",
"=",
"0",
",",
"columns",
"=",
"1",
",",
"downsample",
"=",
"1",
",",
"frame_index",
"=... | 36.670886 | 0.014454 |
def findUniques(mapF):
"""Finds the unique markers in a MAP.
:param mapF: representation of a ``map`` file.
:type mapF: list
:returns: a :py:class:`dict` containing unique markers (according to their
genomic localisation).
"""
uSNPs = {}
dSNPs = defaultdict(list)
for i,... | [
"def",
"findUniques",
"(",
"mapF",
")",
":",
"uSNPs",
"=",
"{",
"}",
"dSNPs",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"mapF",
")",
":",
"chromosome",
"=",
"row",
"[",
"0",
"]",
"position",
"=",
"row",
... | 29.2 | 0.000947 |
def coupling_to_arc(coupling_map:List[List[int]]) -> Architecture:
"""
Produces a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Architecture` corresponding to a (directed) coupling map,
stating the pairs of qubits between which two-qubit interactions
(e.g. CXs) can be applied.
:param coupling... | [
"def",
"coupling_to_arc",
"(",
"coupling_map",
":",
"List",
"[",
"List",
"[",
"int",
"]",
"]",
")",
"->",
"Architecture",
":",
"coupling",
"=",
"CouplingMap",
"(",
"couplinglist",
"=",
"coupling_map",
")",
"return",
"DirectedGraph",
"(",
"coupling_map",
",",
... | 49.769231 | 0.009105 |
def _get_pages(self, locations, project_name):
"""
Yields (page, page_url) from the given locations, skipping
locations that have errors, and adding download/homepage links
"""
all_locations = list(locations)
seen = set()
normalized = normalize_name(project_name)
... | [
"def",
"_get_pages",
"(",
"self",
",",
"locations",
",",
"project_name",
")",
":",
"all_locations",
"=",
"list",
"(",
"locations",
")",
"seen",
"=",
"set",
"(",
")",
"normalized",
"=",
"normalize_name",
"(",
"project_name",
")",
"while",
"all_locations",
":"... | 33.804348 | 0.00125 |
def aboveAt(self, offset=0):
""" Returns point in the center of the region's top side (offset to the top
by negative ``offset``) """
return Location(self.getX() + (self.getW() / 2), self.getY() + offset) | [
"def",
"aboveAt",
"(",
"self",
",",
"offset",
"=",
"0",
")",
":",
"return",
"Location",
"(",
"self",
".",
"getX",
"(",
")",
"+",
"(",
"self",
".",
"getW",
"(",
")",
"/",
"2",
")",
",",
"self",
".",
"getY",
"(",
")",
"+",
"offset",
")"
] | 56 | 0.013216 |
async def __check_last_ping(self, run_listen):
""" Check if the last timeout is too old. If it is, kills the run_listen task """
if self.__last_ping < time.time()-10:
self._logger.warning("Last ping too old. Restarting the agent.")
run_listen.cancel()
self.__cancel_re... | [
"async",
"def",
"__check_last_ping",
"(",
"self",
",",
"run_listen",
")",
":",
"if",
"self",
".",
"__last_ping",
"<",
"time",
".",
"time",
"(",
")",
"-",
"10",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"\"Last ping too old. Restarting the agent.\"",
... | 55.5 | 0.008869 |
def instances_changed(self):
"""True if any instance has changed."""
value = bool(lib.EnvGetInstancesChanged(self._env))
lib.EnvSetInstancesChanged(self._env, int(False))
return value | [
"def",
"instances_changed",
"(",
"self",
")",
":",
"value",
"=",
"bool",
"(",
"lib",
".",
"EnvGetInstancesChanged",
"(",
"self",
".",
"_env",
")",
")",
"lib",
".",
"EnvSetInstancesChanged",
"(",
"self",
".",
"_env",
",",
"int",
"(",
"False",
")",
")",
... | 35.166667 | 0.009259 |
def main(argv=None):
'''Command line options.'''
if argv is None:
argv = sys.argv
else:
sys.argv.extend(argv)
program_name = os.path.basename(sys.argv[0])
program_version = "v%s" % __version__
program_build_date = str(__updated__)
program_version_message = '%%(prog)s %s (%s... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"else",
":",
"sys",
".",
"argv",
".",
"extend",
"(",
"argv",
")",
"program_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
... | 43.009524 | 0.000216 |
def print_err(*args, **kwargs):
""" A wrapper for print() that uses stderr by default. """
if kwargs.get('file', None) is None:
kwargs['file'] = sys.stderr
color = dict_pop_or(kwargs, 'color', True)
# Use color if asked, but only if the file is a tty.
if color and kwargs['file'].isatty():
... | [
"def",
"print_err",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'file'",
",",
"None",
")",
"is",
"None",
":",
"kwargs",
"[",
"'file'",
"]",
"=",
"sys",
".",
"stderr",
"color",
"=",
"dict_pop_or",
"(",
"k... | 35.956522 | 0.001178 |
def norm(values, min=None, max=None):
"""Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
Args:
values: Array of values to be normalized
min (float, optional): Lower bound of normalization range
max (float, optional): Upper bound of normaliza... | [
"def",
"norm",
"(",
"values",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
")",
":",
"min",
"=",
"np",
".",
"min",
"(",
"values",
")",
"if",
"min",
"is",
"None",
"else",
"min",
"max",
"=",
"np",
".",
"max",
"(",
"values",
")",
"if",
"max... | 31.75 | 0.001912 |
def state(self, state):
"""Set state."""
self._state = state
self._manager[ATTR_STATE] = state
_LOGGER.info('state changed to %s', state) | [
"def",
"state",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_state",
"=",
"state",
"self",
".",
"_manager",
"[",
"ATTR_STATE",
"]",
"=",
"state",
"_LOGGER",
".",
"info",
"(",
"'state changed to %s'",
",",
"state",
")"
] | 33 | 0.011834 |
def get_banks_by_item(self, item_id):
"""Gets the list of ``Banks`` mapped to an ``Item``.
arg: item_id (osid.id.Id): ``Id`` of an ``Item``
return: (osid.assessment.BankList) - list of banks
raise: NotFound - ``item_id`` is not found
raise: NullArgument - ``item_id`` is ``n... | [
"def",
"get_banks_by_item",
"(",
"self",
",",
"item_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinSession.get_bins_by_resource",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'ASSESSMENT'",
",",
"local",
"=",
"True",
")",
"lookup_... | 46.833333 | 0.002326 |
def event_table(self):
"""Event table (`~astropy.table.Table`).
Columns: GLON, GLAT, SOURCE_IDX
"""
# Create event list table for each source
tables = []
for source in self.source_table:
lon = source['GLON'] * np.ones(source['COUNTS'])
lat = sourc... | [
"def",
"event_table",
"(",
"self",
")",
":",
"# Create event list table for each source",
"tables",
"=",
"[",
"]",
"for",
"source",
"in",
"self",
".",
"source_table",
":",
"lon",
"=",
"source",
"[",
"'GLON'",
"]",
"*",
"np",
".",
"ones",
"(",
"source",
"["... | 29.961538 | 0.002488 |
def rm_regions(a, b, a_start_ind, a_stop_ind):
'''Remove contiguous regions in `a` before region `b`
Boolean arrays `a` and `b` should have alternating occuances of regions of
`True` values. This routine removes additional contiguous regions in `a`
that occur before a complimentary region in `b` has oc... | [
"def",
"rm_regions",
"(",
"a",
",",
"b",
",",
"a_start_ind",
",",
"a_stop_ind",
")",
":",
"import",
"numpy",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a_stop_ind",
")",
")",
":",
"next_a_start",
"=",
"numpy",
".",
"argmax",
"(",
"a",
"[",
"a_stop_... | 30.264706 | 0.001883 |
def blk_nd_short(blk, shape):
"""Iterate trough the blocks that strictly cover an array.
Iterate trough the blocks that recover the part of the array
given by max_blk_coverage.
:param blk: the N-dimensional shape of the block
:param shape: the N-dimensional shape of the array
:return: a genera... | [
"def",
"blk_nd_short",
"(",
"blk",
",",
"shape",
")",
":",
"internals",
"=",
"(",
"blk_1d_short",
"(",
"b",
",",
"s",
")",
"for",
"b",
",",
"s",
"in",
"zip",
"(",
"blk",
",",
"shape",
")",
")",
"return",
"product",
"(",
"*",
"internals",
")"
] | 30.181818 | 0.000973 |
def _match_literal(self, a, b=None):
"""Match two names."""
return a.lower() == b if not self.case_sensitive else a == b | [
"def",
"_match_literal",
"(",
"self",
",",
"a",
",",
"b",
"=",
"None",
")",
":",
"return",
"a",
".",
"lower",
"(",
")",
"==",
"b",
"if",
"not",
"self",
".",
"case_sensitive",
"else",
"a",
"==",
"b"
] | 33.5 | 0.014599 |
def calculate_recommendations(output_filename, model_name="als"):
""" Generates artist recommendations for each user in the dataset """
# train the model based off input params
artists, users, plays = get_lastfm()
# create a model from the input data
model = get_model(model_name)
# if we're tr... | [
"def",
"calculate_recommendations",
"(",
"output_filename",
",",
"model_name",
"=",
"\"als\"",
")",
":",
"# train the model based off input params",
"artists",
",",
"users",
",",
"plays",
"=",
"get_lastfm",
"(",
")",
"# create a model from the input data",
"model",
"=",
... | 41.555556 | 0.00196 |
def perms_check(perms, prefix, ambiguous=False):
"""
Return the user's perms for the specified prefix
perms <dict> permissions dict
prefix <string> namespace to check for perms
ambiguous <bool=False> if True reverse wildcard matching is active and a perm check for a.b.* will
be matched by the user havi... | [
"def",
"perms_check",
"(",
"perms",
",",
"prefix",
",",
"ambiguous",
"=",
"False",
")",
":",
"try",
":",
"token",
"=",
"prefix",
".",
"split",
"(",
"\".\"",
")",
"i",
"=",
"1",
"l",
"=",
"len",
"(",
"token",
")",
"r",
"=",
"0",
"# collect permissio... | 24.888889 | 0.022699 |
def get_registered_credits (self):
""" 登録単位数合計の取得 """
self.req("RSW0001000-flow")
r = self.get({
"_eventId": "search",
"moduleCode": 1,
"gakkiKbnCode": "A"
})
html = r.text
# XXX
... | [
"def",
"get_registered_credits",
"(",
"self",
")",
":",
"self",
".",
"req",
"(",
"\"RSW0001000-flow\"",
")",
"r",
"=",
"self",
".",
"get",
"(",
"{",
"\"_eventId\"",
":",
"\"search\"",
",",
"\"moduleCode\"",
":",
"1",
",",
"\"gakkiKbnCode\"",
":",
"\"A\"",
... | 28.888889 | 0.009311 |
def load_existing_catalog(self, cat, **kwargs):
"""Load sources from an existing catalog object.
Parameters
----------
cat : `~fermipy.catalog.Catalog`
Catalog object.
"""
coordsys = kwargs.get('coordsys', 'CEL')
extdir = kwargs.get('extdir', self.ex... | [
"def",
"load_existing_catalog",
"(",
"self",
",",
"cat",
",",
"*",
"*",
"kwargs",
")",
":",
"coordsys",
"=",
"kwargs",
".",
"get",
"(",
"'coordsys'",
",",
"'CEL'",
")",
"extdir",
"=",
"kwargs",
".",
"get",
"(",
"'extdir'",
",",
"self",
".",
"extdir",
... | 43.4 | 0.000601 |
def get_config_multiline_option(parser: ConfigParser,
section: str,
option: str,
default: List[str] = None) -> List[str]:
"""
Retrieves a multi-line string value from a parser as a list of strings
(one per line, ... | [
"def",
"get_config_multiline_option",
"(",
"parser",
":",
"ConfigParser",
",",
"section",
":",
"str",
",",
"option",
":",
"str",
",",
"default",
":",
"List",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"str",
"]",
":",
"default",
"=",
"defaul... | 32.741935 | 0.000957 |
def retrieve(endpoint='incidents',
api_url=None,
page_id=None,
api_key=None,
api_version=None):
'''
Retrieve a specific endpoint from the Statuspage API.
endpoint: incidents
Request a specific endpoint.
page_id
Page ID. Can also be sp... | [
"def",
"retrieve",
"(",
"endpoint",
"=",
"'incidents'",
",",
"api_url",
"=",
"None",
",",
"page_id",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"api_version",
"=",
"None",
")",
":",
"params",
"=",
"_get_api_params",
"(",
"api_url",
"=",
"api_url",
",... | 30.789474 | 0.00071 |
def json(self):
"""
Return response body deserialized into JSON object.
"""
if six.PY3:
return json.loads(self.body.decode(self.charset))
else:
return json.loads(self.body) | [
"def",
"json",
"(",
"self",
")",
":",
"if",
"six",
".",
"PY3",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"body",
".",
"decode",
"(",
"self",
".",
"charset",
")",
")",
"else",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"... | 25.444444 | 0.008439 |
def dirpath_to_list(p):
'''
dirpath_to_list(path) yields a list of directories contained in the given path specification.
A path may be either a single directory name (==> [path]), a :-separated list of directories
(==> path.split(':')), a list of directory names (==> path), or None (==> []). Note that... | [
"def",
"dirpath_to_list",
"(",
"p",
")",
":",
"if",
"p",
"is",
"None",
":",
"p",
"=",
"[",
"]",
"elif",
"pimms",
".",
"is_str",
"(",
"p",
")",
":",
"p",
"=",
"p",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"p",
")",
">",
"0",
"and",
... | 48.615385 | 0.01087 |
def remove_dirs(self, directory):
"""Delete a directory recursively.
:param directory: $PATH to directory.
:type directory: ``str``
"""
LOG.info('Removing directory [ %s ]', directory)
local_files = self._drectory_local_files(directory=directory)
for file_name i... | [
"def",
"remove_dirs",
"(",
"self",
",",
"directory",
")",
":",
"LOG",
".",
"info",
"(",
"'Removing directory [ %s ]'",
",",
"directory",
")",
"local_files",
"=",
"self",
".",
"_drectory_local_files",
"(",
"directory",
"=",
"directory",
")",
"for",
"file_name",
... | 30.310345 | 0.002205 |
def stop(name, call=None):
'''
Stop a node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Stopping node %s', name)
instance_id = _get_node(name)['instanceId']
__utils__['cloud.fire_event'](
... | [
"def",
"stop",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The stop action must be called with -a or --action.'",
")",
"log",
".",
"info",
"(",
"'Stopping node %s'",
",",
"name",
")... | 26.741935 | 0.001164 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.