text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def open_instance_resource(self, path: FilePath, mode: str='rb') -> IO[AnyStr]:
"""Open a file for reading.
Use as
.. code-block:: python
with app.open_instance_resouce(path) as file_:
file_.read()
"""
return open(self.instance_path / file_path_to_p... | [
"def",
"open_instance_resource",
"(",
"self",
",",
"path",
":",
"FilePath",
",",
"mode",
":",
"str",
"=",
"'rb'",
")",
"->",
"IO",
"[",
"AnyStr",
"]",
":",
"return",
"open",
"(",
"self",
".",
"instance_path",
"/",
"file_path_to_path",
"(",
"path",
")",
... | 29.636364 | 23.272727 |
def items(self):
"""Return result values"""
if self._result_cache:
return self._result_cache.items
return self.all().items | [
"def",
"items",
"(",
"self",
")",
":",
"if",
"self",
".",
"_result_cache",
":",
"return",
"self",
".",
"_result_cache",
".",
"items",
"return",
"self",
".",
"all",
"(",
")",
".",
"items"
] | 25.666667 | 14.333333 |
def dom_lt(graph):
"""Dominator algorithm from Lengauer-Tarjan"""
def _dfs(v, n):
semi[v] = n = n + 1
vertex[n] = label[v] = v
ancestor[v] = 0
for w in graph.all_sucs(v):
if not semi[w]:
parent[w] = v
n = _dfs(w, n)
pred[w]... | [
"def",
"dom_lt",
"(",
"graph",
")",
":",
"def",
"_dfs",
"(",
"v",
",",
"n",
")",
":",
"semi",
"[",
"v",
"]",
"=",
"n",
"=",
"n",
"+",
"1",
"vertex",
"[",
"n",
"]",
"=",
"label",
"[",
"v",
"]",
"=",
"v",
"ancestor",
"[",
"v",
"]",
"=",
"... | 24.065574 | 17.377049 |
def clean_german_number(x):
"""Convert a string with a German number into a Decimal
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a number with German formatting,
or an array of these strings, e.g. list, ndarray, df.
Returns
-------
... | [
"def",
"clean_german_number",
"(",
"x",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"pandas",
"as",
"pd",
"import",
"re",
"def",
"proc_elem",
"(",
"e",
")",
":",
"# abort if it is not a string",
"if",
"not",
"isinstance",
"(",
"e",
",",
"str",
")",
... | 26.775 | 20.341667 |
def getAlgorithmInstance(self, layer="L2", column=0):
"""
Returns an instance of the underlying algorithm. For example,
layer=L2 and column=1 could return the actual instance of ColumnPooler
that is responsible for column 1.
"""
assert ( (column>=0) and (column<self.numColumns)), ("Column number... | [
"def",
"getAlgorithmInstance",
"(",
"self",
",",
"layer",
"=",
"\"L2\"",
",",
"column",
"=",
"0",
")",
":",
"assert",
"(",
"(",
"column",
">=",
"0",
")",
"and",
"(",
"column",
"<",
"self",
".",
"numColumns",
")",
")",
",",
"(",
"\"Column number not \""... | 39.466667 | 18.533333 |
def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused.
"""
copy_source = self.get_client_kwarg... | [
"def",
"copy",
"(",
"self",
",",
"src",
",",
"dst",
",",
"other_system",
"=",
"None",
")",
":",
"copy_source",
"=",
"self",
".",
"get_client_kwargs",
"(",
"src",
")",
"copy_destination",
"=",
"self",
".",
"get_client_kwargs",
"(",
"dst",
")",
"with",
"_h... | 37.384615 | 14.307692 |
def min_max(obj, val, is_max):
""" min/max validator for float and integer
"""
n = getattr(obj, 'maximum' if is_max else 'minimum', None)
if n == None:
return
_eq = getattr(obj, 'exclusiveMaximum' if is_max else 'exclusiveMinimum', False)
if is_max:
to_raise = val >= n if _eq el... | [
"def",
"min_max",
"(",
"obj",
",",
"val",
",",
"is_max",
")",
":",
"n",
"=",
"getattr",
"(",
"obj",
",",
"'maximum'",
"if",
"is_max",
"else",
"'minimum'",
",",
"None",
")",
"if",
"n",
"==",
"None",
":",
"return",
"_eq",
"=",
"getattr",
"(",
"obj",
... | 34.866667 | 25.933333 |
def set_entity_info(self, chain_indices, sequence, description, entity_type):
"""Set the entity level information for the structure.
:param chain_indices: the indices of the chains for this entity
:param sequence: the one letter code sequence for this entity
:param description: the descr... | [
"def",
"set_entity_info",
"(",
"self",
",",
"chain_indices",
",",
"sequence",
",",
"description",
",",
"entity_type",
")",
":",
"self",
".",
"entity_list",
".",
"append",
"(",
"make_entity_dict",
"(",
"chain_indices",
",",
"sequence",
",",
"description",
",",
... | 64.625 | 25.5 |
def fs_obj_exists(self, path, follow_symlinks):
"""Checks whether a file system object (file, directory, etc) exists in
the guest or not.
in path of type str
Path to the file system object to check the existance of. Guest
path style.
in follow_symlinks of type ... | [
"def",
"fs_obj_exists",
"(",
"self",
",",
"path",
",",
"follow_symlinks",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"path can only be an instance of type basestring\"",
")",
"if",
"not",
"isinstance... | 42.5 | 20.928571 |
def _copy_database_data_clientside(self, tables, source, destination):
"""Copy the data from a table into another table."""
# Retrieve database rows
rows = self.get_database_rows(tables, source)
# Retrieve database columns
cols = self.get_database_columns(tables, source)
... | [
"def",
"_copy_database_data_clientside",
"(",
"self",
",",
"tables",
",",
"source",
",",
"destination",
")",
":",
"# Retrieve database rows",
"rows",
"=",
"self",
".",
"get_database_rows",
"(",
"tables",
",",
"source",
")",
"# Retrieve database columns",
"cols",
"="... | 32.772727 | 16.681818 |
def action_listlocal(all_details=True):
" select a file from the local repo "
options = get_localontologies()
counter = 1
# printDebug("------------------", 'comment')
if not options:
printDebug(
"Your local library is empty. Use 'ontospy lib --bootstrap' to add some o... | [
"def",
"action_listlocal",
"(",
"all_details",
"=",
"True",
")",
":",
"options",
"=",
"get_localontologies",
"(",
")",
"counter",
"=",
"1",
"# printDebug(\"------------------\", 'comment')\r",
"if",
"not",
"options",
":",
"printDebug",
"(",
"\"Your local library is empt... | 33.054054 | 19.216216 |
def can_update(self, user, **kwargs):
"""Org admins may not update organisation_id or service_type"""
if user.is_admin():
raise Return((True, set([])))
is_creator = self.created_by == user.id
if not (user.is_org_admin(self.organisation_id) or is_creator):
raise R... | [
"def",
"can_update",
"(",
"self",
",",
"user",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"user",
".",
"is_admin",
"(",
")",
":",
"raise",
"Return",
"(",
"(",
"True",
",",
"set",
"(",
"[",
"]",
")",
")",
")",
"is_creator",
"=",
"self",
".",
"crea... | 37.428571 | 15.928571 |
def prepare_gag_lsm(self, lsm_precip_data_var, lsm_precip_type, interpolation_type=None):
"""
Prepares Gage output for GSSHA simulation
Parameters:
lsm_precip_data_var(list or str): String of name for precipitation variable name or list of precip variable names. See: :func:`~gsshap... | [
"def",
"prepare_gag_lsm",
"(",
"self",
",",
"lsm_precip_data_var",
",",
"lsm_precip_type",
",",
"interpolation_type",
"=",
"None",
")",
":",
"if",
"self",
".",
"l2g",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"LSM converter not loaded ...\"",
")",
"# remove... | 51.625 | 32.5 |
def get_configs(cls):
"""Get rate limiters configuration
specified at application level
:rtype: dict of configurations
"""
import docido_sdk.config
http_config = docido_sdk.config.get('http') or {}
session_config = http_config.get('session') or {}
rate_li... | [
"def",
"get_configs",
"(",
"cls",
")",
":",
"import",
"docido_sdk",
".",
"config",
"http_config",
"=",
"docido_sdk",
".",
"config",
".",
"get",
"(",
"'http'",
")",
"or",
"{",
"}",
"session_config",
"=",
"http_config",
".",
"get",
"(",
"'session'",
")",
"... | 34.727273 | 12.636364 |
def read(self, n):
"""
Read n bytes.
Will raise BufferUnderflow if there's not enough bytes in the buffer.
"""
self._check_underflow(n)
rval = self._input[self._pos:self._pos + n]
self._pos += n
return rval | [
"def",
"read",
"(",
"self",
",",
"n",
")",
":",
"self",
".",
"_check_underflow",
"(",
"n",
")",
"rval",
"=",
"self",
".",
"_input",
"[",
"self",
".",
"_pos",
":",
"self",
".",
"_pos",
"+",
"n",
"]",
"self",
".",
"_pos",
"+=",
"n",
"return",
"rv... | 26.2 | 17.6 |
def closed(self):
"""
If the first point is the same as the end point
the entity is closed
"""
closed = (len(self.points) > 2 and
self.points[0] == self.points[-1])
return closed | [
"def",
"closed",
"(",
"self",
")",
":",
"closed",
"=",
"(",
"len",
"(",
"self",
".",
"points",
")",
">",
"2",
"and",
"self",
".",
"points",
"[",
"0",
"]",
"==",
"self",
".",
"points",
"[",
"-",
"1",
"]",
")",
"return",
"closed"
] | 29.625 | 10.375 |
def get_adcm(self):
"""
Absolute deviation around class median (ADCM).
Calculates the absolute deviations of each observation about its class
median as a measure of fit for the classification method.
Returns sum of ADCM over all classes
"""
adcm = 0
for ... | [
"def",
"get_adcm",
"(",
"self",
")",
":",
"adcm",
"=",
"0",
"for",
"class_def",
"in",
"self",
".",
"classes",
":",
"if",
"len",
"(",
"class_def",
")",
">",
"0",
":",
"yc",
"=",
"self",
".",
"y",
"[",
"class_def",
"]",
"yc_med",
"=",
"np",
".",
... | 31.647059 | 14.588235 |
def confd_state_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
version = ET.SubElement(confd_state, "version")
version.text = kwargs.pop(... | [
"def",
"confd_state_version",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"confd_state",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"confd-state\"",
",",
"xmlns",
"=",
"\"http://tail... | 41.2 | 15.5 |
def averageSize(self):
"""Calculate the average size of a mesh.
This is the mean of the vertex distances from the center of mass."""
cm = self.centerOfMass()
coords = self.coordinates(copy=False)
if not len(coords):
return 0
s, c = 0.0, 0.0
n = len(coo... | [
"def",
"averageSize",
"(",
"self",
")",
":",
"cm",
"=",
"self",
".",
"centerOfMass",
"(",
")",
"coords",
"=",
"self",
".",
"coordinates",
"(",
"copy",
"=",
"False",
")",
"if",
"not",
"len",
"(",
"coords",
")",
":",
"return",
"0",
"s",
",",
"c",
"... | 33.571429 | 10.571429 |
def save_csv(X, y, path):
"""Save data as a CSV file.
Args:
X (numpy or scipy sparse matrix): Data matrix
y (numpy array): Target vector.
path (str): Path to the CSV file to save data.
"""
if sparse.issparse(X):
X = X.todense()
np.savetxt(path, np.hstack((y.reshape... | [
"def",
"save_csv",
"(",
"X",
",",
"y",
",",
"path",
")",
":",
"if",
"sparse",
".",
"issparse",
"(",
"X",
")",
":",
"X",
"=",
"X",
".",
"todense",
"(",
")",
"np",
".",
"savetxt",
"(",
"path",
",",
"np",
".",
"hstack",
"(",
"(",
"y",
".",
"re... | 26 | 19.692308 |
def convert(self, expr):
"""
EXPAND INSTANCES OF name TO value
"""
if expr is True or expr == None or expr is False:
return expr
elif is_number(expr):
return expr
elif expr == ".":
return "."
elif is_variable_name(expr):
... | [
"def",
"convert",
"(",
"self",
",",
"expr",
")",
":",
"if",
"expr",
"is",
"True",
"or",
"expr",
"==",
"None",
"or",
"expr",
"is",
"False",
":",
"return",
"expr",
"elif",
"is_number",
"(",
"expr",
")",
":",
"return",
"expr",
"elif",
"expr",
"==",
"\... | 37.4375 | 15.0625 |
def _set_slot(self, v, load=False):
"""
Setter method for slot, mapped from YANG variable /qos/cpu/slot (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_slot is considered as a private
method. Backends looking to populate this variable should
do so via call... | [
"def",
"_set_slot",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 115.318182 | 55.272727 |
def kl(self):
r'''Thermal conductivity of the mixture in the liquid phase at its current
temperature, pressure, and composition in units of [Pa*s].
For calculation of this property at other temperatures and pressures,
or specifying manually the method used to calculate it, and more - se... | [
"def",
"kl",
"(",
"self",
")",
":",
"return",
"self",
".",
"ThermalConductivityLiquidMixture",
"(",
"self",
".",
"T",
",",
"self",
".",
"P",
",",
"self",
".",
"zs",
",",
"self",
".",
"ws",
")"
] | 44.4375 | 29.5625 |
def Page_searchInResource(self, frameId, url, query, **kwargs):
"""
Function path: Page.searchInResource
Domain: Page
Method name: searchInResource
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'frameId' (type: FrameId) -> Frame id for resource to search... | [
"def",
"Page_searchInResource",
"(",
"self",
",",
"frameId",
",",
"url",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"url",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'url' must be of type '['str']'. Received type: '%s'\""... | 41.761905 | 21.714286 |
def add_soup(response, soup_config):
"""Attaches a soup object to a requests response."""
if ("text/html" in response.headers.get("Content-Type", "") or
Browser.__looks_like_html(response)):
response.soup = bs4.BeautifulSoup(response.content, **soup_config)
else:
... | [
"def",
"add_soup",
"(",
"response",
",",
"soup_config",
")",
":",
"if",
"(",
"\"text/html\"",
"in",
"response",
".",
"headers",
".",
"get",
"(",
"\"Content-Type\"",
",",
"\"\"",
")",
"or",
"Browser",
".",
"__looks_like_html",
"(",
"response",
")",
")",
":"... | 48.857143 | 17.142857 |
def prettyDateDifference(startTime, finishTime=None):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
from datetime import datetime
if startTime is None:
return None
if not isin... | [
"def",
"prettyDateDifference",
"(",
"startTime",
",",
"finishTime",
"=",
"None",
")",
":",
"from",
"datetime",
"import",
"datetime",
"if",
"startTime",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"startTime",
",",
"(",
"int",
",",
... | 28.434783 | 17.086957 |
def _download_response(self):
"""Returns a response body string from the server."""
if self.network.limit_rate:
self.network._delay_call()
data = []
for name in self.params.keys():
data.append("=".join((name, url_quote_plus(_string(self.params[name])))))
... | [
"def",
"_download_response",
"(",
"self",
")",
":",
"if",
"self",
".",
"network",
".",
"limit_rate",
":",
"self",
".",
"network",
".",
"_delay_call",
"(",
")",
"data",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".",
"params",
".",
"keys",
"(",
")",
... | 31.166667 | 20.481481 |
def retrieveVals(self):
"""Retrieve values for graphs."""
if self.hasGraph('tomcat_memory'):
stats = self._tomcatInfo.getMemoryStats()
self.setGraphVal('tomcat_memory', 'used',
stats['total'] - stats['free'])
self.setGraphVal('tomcat_memo... | [
"def",
"retrieveVals",
"(",
"self",
")",
":",
"if",
"self",
".",
"hasGraph",
"(",
"'tomcat_memory'",
")",
":",
"stats",
"=",
"self",
".",
"_tomcatInfo",
".",
"getMemoryStats",
"(",
")",
"self",
".",
"setGraphVal",
"(",
"'tomcat_memory'",
",",
"'used'",
","... | 54.566667 | 16 |
def densify(self,
geometries,
sr,
maxSegmentLength,
lengthUnit,
geodesic=False,
):
"""
The densify operation is performed on a geometry service resource. This
operation densifies geometries by plotti... | [
"def",
"densify",
"(",
"self",
",",
"geometries",
",",
"sr",
",",
"maxSegmentLength",
",",
"lengthUnit",
",",
"geodesic",
"=",
"False",
",",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/densify\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
"... | 45.090909 | 19.636364 |
def visit_delete(self, node, parent):
"""visit a Delete node by returning a fresh instance of it"""
newnode = nodes.Delete(node.lineno, node.col_offset, parent)
newnode.postinit([self.visit(child, newnode) for child in node.targets])
return newnode | [
"def",
"visit_delete",
"(",
"self",
",",
"node",
",",
"parent",
")",
":",
"newnode",
"=",
"nodes",
".",
"Delete",
"(",
"node",
".",
"lineno",
",",
"node",
".",
"col_offset",
",",
"parent",
")",
"newnode",
".",
"postinit",
"(",
"[",
"self",
".",
"visi... | 55.2 | 17.8 |
def set_labels(self, labels, axis='rows'):
'''
Set the row/col labels.
Note that this method doesn't check that enough labels were set for all the assigned positions.
'''
if axis.lower() in ('rows', 'row', 'r', 0):
assigned_pos = set(v[0] for v in self._positions.iter... | [
"def",
"set_labels",
"(",
"self",
",",
"labels",
",",
"axis",
"=",
"'rows'",
")",
":",
"if",
"axis",
".",
"lower",
"(",
")",
"in",
"(",
"'rows'",
",",
"'row'",
",",
"'r'",
",",
"0",
")",
":",
"assigned_pos",
"=",
"set",
"(",
"v",
"[",
"0",
"]",... | 45.0625 | 18.5625 |
def capture_sys_output():
"""Capture standard output and error."""
capture_out, capture_err = StringIO(), StringIO()
current_out, current_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = capture_out, capture_err
yield capture_out, capture_err
finally:
sys.stdout, sy... | [
"def",
"capture_sys_output",
"(",
")",
":",
"capture_out",
",",
"capture_err",
"=",
"StringIO",
"(",
")",
",",
"StringIO",
"(",
")",
"current_out",
",",
"current_err",
"=",
"sys",
".",
"stdout",
",",
"sys",
".",
"stderr",
"try",
":",
"sys",
".",
"stdout"... | 38.555556 | 15.222222 |
def submit(self, command="", blocksize=1, job_name="parsl.auto"):
''' The submit method takes the command string to be executed upon
instantiation of a resource most often to start a pilot (such as IPP engine
or even Swift-T engines).
Args :
- command (str) : The bash comma... | [
"def",
"submit",
"(",
"self",
",",
"command",
"=",
"\"\"",
",",
"blocksize",
"=",
"1",
",",
"job_name",
"=",
"\"parsl.auto\"",
")",
":",
"# Note: Fix this later to avoid confusing behavior.",
"# We should always allocate blocks in integer counts of node_granularity",
"if",
... | 40.02 | 27.54 |
def toLocalTime(seconds, microseconds=0):
"""toLocalTime(seconds, microseconds=0) -> datetime
Converts the given number of seconds since the GPS Epoch (midnight
on January 6th, 1980) to this computer's local time. Returns a
Python datetime object.
Examples:
>>> toLocalTime(0)
datetime.da... | [
"def",
"toLocalTime",
"(",
"seconds",
",",
"microseconds",
"=",
"0",
")",
":",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"seconds",
",",
"microseconds",
"=",
"microseconds",
")",
"return",
"GPS_Epoch",
"+",
"delta"
] | 30.235294 | 19.529412 |
def p_program_def(t):
"""program_def : PROGRAM ID LBRACE version_def version_def_list RBRACE EQUALS constant SEMI"""
print("Ignoring program {0:s} = {1:s}".format(t[2], t[8]))
global name_dict
id = t[2]
value = t[8]
lineno = t.lineno(1)
if id_unique(id, 'program', lineno):
name_dict[... | [
"def",
"p_program_def",
"(",
"t",
")",
":",
"print",
"(",
"\"Ignoring program {0:s} = {1:s}\"",
".",
"format",
"(",
"t",
"[",
"2",
"]",
",",
"t",
"[",
"8",
"]",
")",
")",
"global",
"name_dict",
"id",
"=",
"t",
"[",
"2",
"]",
"value",
"=",
"t",
"[",... | 38.555556 | 15.666667 |
def _process_graph(self):
"""
Gets the list of the output nodes present in the graph for inference
:return: list of node names
"""
all_nodes = [x.name for x in self.graph.as_graph_def().node]
nodes = [x for x in all_nodes if x in self.possible_output_nodes]
logger... | [
"def",
"_process_graph",
"(",
"self",
")",
":",
"all_nodes",
"=",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"self",
".",
"graph",
".",
"as_graph_def",
"(",
")",
".",
"node",
"]",
"nodes",
"=",
"[",
"x",
"for",
"x",
"in",
"all_nodes",
"if",
"x",
"i... | 41.545455 | 18.454545 |
def _ParseEntryArrayObject(self, file_object, file_offset):
"""Parses an entry array object.
Args:
file_object (dfvfs.FileIO): a file-like object.
file_offset (int): offset of the entry array object relative to the start
of the file-like object.
Returns:
systemd_journal_entry_a... | [
"def",
"_ParseEntryArrayObject",
"(",
"self",
",",
"file_object",
",",
"file_offset",
")",
":",
"entry_array_object_map",
"=",
"self",
".",
"_GetDataTypeMap",
"(",
"'systemd_journal_entry_array_object'",
")",
"try",
":",
"entry_array_object",
",",
"_",
"=",
"self",
... | 36.5 | 22.647059 |
def get_service_url(request, redirect_to=None):
"""Generates application django service URL for CAS"""
if hasattr(django_settings, 'CAS_ROOT_PROXIED_AS'):
service = django_settings.CAS_ROOT_PROXIED_AS + request.path
else:
protocol = get_protocol(request)
host = request.get_host()
... | [
"def",
"get_service_url",
"(",
"request",
",",
"redirect_to",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"django_settings",
",",
"'CAS_ROOT_PROXIED_AS'",
")",
":",
"service",
"=",
"django_settings",
".",
"CAS_ROOT_PROXIED_AS",
"+",
"request",
".",
"path",
"els... | 36.473684 | 15.526316 |
def get_dependencies_from_wheel_cache(ireq):
"""Retrieves dependencies for the given install requirement from the wheel cache.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallReq... | [
"def",
"get_dependencies_from_wheel_cache",
"(",
"ireq",
")",
":",
"if",
"ireq",
".",
"editable",
"or",
"not",
"is_pinned_requirement",
"(",
"ireq",
")",
":",
"return",
"matches",
"=",
"WHEEL_CACHE",
".",
"get",
"(",
"ireq",
".",
"link",
",",
"name_from_req",
... | 38.388889 | 20.055556 |
def doc_uri(self, args, range=None):
"""Request doc of whatever at cursor."""
self.log.debug('doc_uri: in')
self.send_at_position("DocUri", False, "point") | [
"def",
"doc_uri",
"(",
"self",
",",
"args",
",",
"range",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'doc_uri: in'",
")",
"self",
".",
"send_at_position",
"(",
"\"DocUri\"",
",",
"False",
",",
"\"point\"",
")"
] | 44 | 5.5 |
def parse(self, record, is_first_dir_record_of_root, bytes_to_skip, continuation):
# type: (bytes, bool, int, bool) -> None
'''
Method to parse a rock ridge record.
Parameters:
record - The record to parse.
is_first_dir_record_of_root - Whether this is the first direct... | [
"def",
"parse",
"(",
"self",
",",
"record",
",",
"is_first_dir_record_of_root",
",",
"bytes_to_skip",
",",
"continuation",
")",
":",
"# type: (bytes, bool, int, bool) -> None",
"# Note that we very explicitly do not check if self._initialized is True",
"# here; this can be called mul... | 46.6 | 21.969697 |
def decompose(self):
"""Recursively destroys the contents of this tree."""
contents = [i for i in self.contents]
for i in contents:
if isinstance(i, Tag):
i.decompose()
else:
i.extract()
self.extract() | [
"def",
"decompose",
"(",
"self",
")",
":",
"contents",
"=",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"contents",
"]",
"for",
"i",
"in",
"contents",
":",
"if",
"isinstance",
"(",
"i",
",",
"Tag",
")",
":",
"i",
".",
"decompose",
"(",
")",
"else",
... | 31.222222 | 12.222222 |
def validate_instance(cls, opts):
"""Validates an instance of global options for cases that are not prohibited via registration.
For example: mutually exclusive options may be registered by passing a `mutually_exclusive_group`,
but when multiple flags must be specified together, it can be necessary to spec... | [
"def",
"validate_instance",
"(",
"cls",
",",
"opts",
")",
":",
"if",
"opts",
".",
"loop",
"and",
"(",
"not",
"opts",
".",
"v2",
"or",
"opts",
".",
"v1",
")",
":",
"raise",
"OptionsError",
"(",
"'The --loop option only works with @console_rules, and thus requires... | 51.882353 | 29.470588 |
def switch(stage):
"""
Switch to given stage (dev/qa/production) + pull
"""
stage = stage.lower()
local("git pull")
if stage in ['dev', 'devel', 'develop']:
branch_name = 'develop'
elif stage in ['qa', 'release']:
branches = local('git branch -r', capture=True)
po... | [
"def",
"switch",
"(",
"stage",
")",
":",
"stage",
"=",
"stage",
".",
"lower",
"(",
")",
"local",
"(",
"\"git pull\"",
")",
"if",
"stage",
"in",
"[",
"'dev'",
",",
"'devel'",
",",
"'develop'",
"]",
":",
"branch_name",
"=",
"'develop'",
"elif",
"stage",
... | 36.84 | 12.36 |
def do_extra_polishing(self):
'''
Goes over each EXTRA_POLISH_FUNCTION to see if it applies to this page, if so, calls it
'''
for f in self.EXTRA_POLISH_FUNCTIONS:
if not hasattr(f, 'polish_commit_indexes'):
if hasattr(f, 'polish_urls') and self.URL in f.polis... | [
"def",
"do_extra_polishing",
"(",
"self",
")",
":",
"for",
"f",
"in",
"self",
".",
"EXTRA_POLISH_FUNCTIONS",
":",
"if",
"not",
"hasattr",
"(",
"f",
",",
"'polish_commit_indexes'",
")",
":",
"if",
"hasattr",
"(",
"f",
",",
"'polish_urls'",
")",
"and",
"self... | 45.625 | 30.625 |
def find_revision_id(self, revision=None):
"""Find the global revision id of the given revision."""
# Make sure the local repository exists.
self.create()
# Try to find the revision id of the specified revision.
revision = revision or self.default_revision
output = self.c... | [
"def",
"find_revision_id",
"(",
"self",
",",
"revision",
"=",
"None",
")",
":",
"# Make sure the local repository exists.",
"self",
".",
"create",
"(",
")",
"# Try to find the revision id of the specified revision.",
"revision",
"=",
"revision",
"or",
"self",
".",
"defa... | 44.933333 | 16.133333 |
def update_pypsa_storage_timeseries(network, storages_to_update=None,
timesteps=None):
"""
Updates storage time series in pypsa representation.
This function overwrites p_set and q_set of storage_unit_t attribute of
pypsa network.
Be aware that if you call this f... | [
"def",
"update_pypsa_storage_timeseries",
"(",
"network",
",",
"storages_to_update",
"=",
"None",
",",
"timesteps",
"=",
"None",
")",
":",
"_update_pypsa_timeseries_by_type",
"(",
"network",
",",
"type",
"=",
"'storage'",
",",
"components_to_update",
"=",
"storages_to... | 50.676471 | 26.088235 |
def get_brain(brain_or_object):
"""Return a ZCatalog brain for the object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: True if the object is a catalog brain
:rtype: bool
"""
if is_brain(brai... | [
"def",
"get_brain",
"(",
"brain_or_object",
")",
":",
"if",
"is_brain",
"(",
"brain_or_object",
")",
":",
"return",
"brain_or_object",
"if",
"is_root",
"(",
"brain_or_object",
")",
":",
"return",
"brain_or_object",
"# fetch the brain by UID",
"uid",
"=",
"get_uid",
... | 34.045455 | 17.590909 |
def _getStrips(self, scraperobj):
"""Get all strips from a scraper."""
if self.options.all or self.options.cont:
numstrips = None
elif self.options.numstrips:
numstrips = self.options.numstrips
else:
# get current strip
numstrips = 1
... | [
"def",
"_getStrips",
"(",
"self",
",",
"scraperobj",
")",
":",
"if",
"self",
".",
"options",
".",
"all",
"or",
"self",
".",
"options",
".",
"cont",
":",
"numstrips",
"=",
"None",
"elif",
"self",
".",
"options",
".",
"numstrips",
":",
"numstrips",
"=",
... | 43.333333 | 16.962963 |
def _find_hstreaming():
"""Finds the whole path to the hadoop streaming jar.
If the environmental var HADOOP_HOME is specified, then start the search
from there.
Returns:
Full path to the hadoop streaming jar if found, else return an empty
string.
"""
global WARNED_HADOOP_HOME,... | [
"def",
"_find_hstreaming",
"(",
")",
":",
"global",
"WARNED_HADOOP_HOME",
",",
"HADOOP_STREAMING_PATH_CACHE",
"if",
"HADOOP_STREAMING_PATH_CACHE",
":",
"return",
"HADOOP_STREAMING_PATH_CACHE",
"try",
":",
"search_root",
"=",
"os",
".",
"environ",
"[",
"'HADOOP_HOME'",
"... | 44.5 | 24.846154 |
def hide_routemap_holder_route_map_content_match_route_type_route_type_rmm(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET... | [
"def",
"hide_routemap_holder_route_map_content_match_route_type_route_type_rmm",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
... | 52.25 | 19.4 |
def load_adjusted_array(self, domain, columns, dates, sids, mask):
"""
Load data from our stored baseline.
"""
if len(columns) != 1:
raise ValueError(
"Can't load multiple columns with DataFrameLoader"
)
column = columns[0]
self._v... | [
"def",
"load_adjusted_array",
"(",
"self",
",",
"domain",
",",
"columns",
",",
"dates",
",",
"sids",
",",
"mask",
")",
":",
"if",
"len",
"(",
"columns",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Can't load multiple columns with DataFrameLoader\"",
")... | 33.151515 | 19.333333 |
def do_set_queue_config(self, line):
"""set_queue_config <peer> <target> <queue> <key> <value>
eg. set_queue_config sw1 running LogicalSwitch7-Port1-Queue922 \
max-rate 100
"""
def f(p, args):
try:
target, queue, key, value = args
except:
... | [
"def",
"do_set_queue_config",
"(",
"self",
",",
"line",
")",
":",
"def",
"f",
"(",
"p",
",",
"args",
")",
":",
"try",
":",
"target",
",",
"queue",
",",
"key",
",",
"value",
"=",
"args",
"except",
":",
"print",
"(",
"\"argument error\"",
")",
"print",... | 31.025641 | 16.564103 |
def apply_settings(settings):
"""
Allows new settings to be added without users having to lose all their configuration
"""
for key, value in settings.items():
ConfigManager.SETTINGS[key] = value | [
"def",
"apply_settings",
"(",
"settings",
")",
":",
"for",
"key",
",",
"value",
"in",
"settings",
".",
"items",
"(",
")",
":",
"ConfigManager",
".",
"SETTINGS",
"[",
"key",
"]",
"=",
"value"
] | 35.5 | 10.5 |
def list_all_python_programs(self):
"""
collects a filelist of all .py programs
"""
self.tot_lines = 0
self.tot_bytes = 0
self.tot_files = 0
self.tot_loc = 0
self.lstPrograms = []
fl = mod_fl.FileList([self.fldr], ['*.py'], ["__pycache__", "/venv/"... | [
"def",
"list_all_python_programs",
"(",
"self",
")",
":",
"self",
".",
"tot_lines",
"=",
"0",
"self",
".",
"tot_bytes",
"=",
"0",
"self",
".",
"tot_files",
"=",
"0",
"self",
".",
"tot_loc",
"=",
"0",
"self",
".",
"lstPrograms",
"=",
"[",
"]",
"fl",
"... | 41.238095 | 15.904762 |
def convert_to_base(self, unit_system=None, equivalence=None, **kwargs):
"""
Convert the array in-place to the equivalent base units in
the specified unit system.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions... | [
"def",
"convert_to_base",
"(",
"self",
",",
"unit_system",
"=",
"None",
",",
"equivalence",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"convert_to_units",
"(",
"self",
".",
"units",
".",
"get_base_equivalent",
"(",
"unit_system",
")",
","... | 35 | 20.631579 |
def censor(self, input_text):
"""Returns input_text with any profane words censored."""
bad_words = self.get_profane_words()
res = input_text
for word in bad_words:
# Apply word boundaries to the bad word
regex_string = r'{0}' if self._no_word_boundaries else r'\... | [
"def",
"censor",
"(",
"self",
",",
"input_text",
")",
":",
"bad_words",
"=",
"self",
".",
"get_profane_words",
"(",
")",
"res",
"=",
"input_text",
"for",
"word",
"in",
"bad_words",
":",
"# Apply word boundaries to the bad word",
"regex_string",
"=",
"r'{0}'",
"i... | 39.538462 | 19 |
def get_tail(self, n=10, raw=True, output=False, include_latest=False):
"""Get the last n lines from the history database.
Parameters
----------
n : int
The number of lines to get
raw, output : bool
See :meth:`get_range`
include_latest : bool
... | [
"def",
"get_tail",
"(",
"self",
",",
"n",
"=",
"10",
",",
"raw",
"=",
"True",
",",
"output",
"=",
"False",
",",
"include_latest",
"=",
"False",
")",
":",
"self",
".",
"writeout_cache",
"(",
")",
"if",
"not",
"include_latest",
":",
"n",
"+=",
"1",
"... | 34.615385 | 18.192308 |
def _transform_list_args(self, args):
# type: (dict) -> None
"""Transforms all list arguments from json-server to model-resource ones.
This modifies the given arguments.
"""
if '_limit' in args:
args['limit'] = int(args['_limit'])
del args['_limit']
... | [
"def",
"_transform_list_args",
"(",
"self",
",",
"args",
")",
":",
"# type: (dict) -> None",
"if",
"'_limit'",
"in",
"args",
":",
"args",
"[",
"'limit'",
"]",
"=",
"int",
"(",
"args",
"[",
"'_limit'",
"]",
")",
"del",
"args",
"[",
"'_limit'",
"]",
"if",
... | 26.976744 | 17.395349 |
def install(
ctx,
state,
**kwargs
):
"""Installs provided packages and adds them to Pipfile, or (if no packages are given), installs all packages from Pipfile."""
from ..core import do_install
retcode = do_install(
dev=state.installstate.dev,
three=state.three,
python=st... | [
"def",
"install",
"(",
"ctx",
",",
"state",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"core",
"import",
"do_install",
"retcode",
"=",
"do_install",
"(",
"dev",
"=",
"state",
".",
"installstate",
".",
"dev",
",",
"three",
"=",
"state",
".",... | 35.096774 | 15.580645 |
def varinit(task=None):
'''
Initializes (or re-initializes for testing purposes) all of a task's task-local variables
Precondition:
If task is None, this must be called from task context
'''
if task is None:
task = asyncio.current_task()
taskvars = {}
task._syn_taskvars = ta... | [
"def",
"varinit",
"(",
"task",
"=",
"None",
")",
":",
"if",
"task",
"is",
"None",
":",
"task",
"=",
"asyncio",
".",
"current_task",
"(",
")",
"taskvars",
"=",
"{",
"}",
"task",
".",
"_syn_taskvars",
"=",
"taskvars",
"return",
"taskvars"
] | 27.916667 | 24.583333 |
def cotton(args):
"""
%prog cotton seqids karyotype.layout mcscan.out all.bed synteny.layout
Build a composite figure that calls graphics.karyotype and graphic.synteny.
"""
p = OptionParser(cotton.__doc__)
p.add_option("--depthfile",
help="Use depth info in this file [default: ... | [
"def",
"cotton",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"cotton",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--depthfile\"",
",",
"help",
"=",
"\"Use depth info in this file [default: %default]\"",
")",
"p",
".",
"add_option",
"(",
"\"... | 32.481013 | 19.797468 |
def breakLines(self, width):
"""
Returns a broken line structure. There are two cases
A) For the simple case of a single formatting input fragment the output is
A fragment specifier with
- kind = 0
- fontName, fontSize, leading, textColor
... | [
"def",
"breakLines",
"(",
"self",
",",
"width",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"id",
"(",
"self",
")",
",",
"\"breakLines\"",
")",
"if",
"not",
"isinstance",
"(",
"width",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"... | 45.565891 | 20.24031 |
def convert_padding(net, node, module, builder):
"""Convert a padding layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neu... | [
"def",
"convert_padding",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"param",
"=",
"_get_attr",
... | 23.071429 | 19.52381 |
def solve_kkt_ir(Q, D, G, A, rx, rs, rz, ry, niter=1):
"""Inefficient iterative refinement."""
nineq, nz, neq, nBatch = get_sizes(G, A)
eps = 1e-7
Q_tilde = Q + eps * torch.eye(nz).type_as(Q).repeat(nBatch, 1, 1)
D_tilde = D + eps * torch.eye(nineq).type_as(Q).repeat(nBatch, 1, 1)
dx, ds, dz, ... | [
"def",
"solve_kkt_ir",
"(",
"Q",
",",
"D",
",",
"G",
",",
"A",
",",
"rx",
",",
"rs",
",",
"rz",
",",
"ry",
",",
"niter",
"=",
"1",
")",
":",
"nineq",
",",
"nz",
",",
"neq",
",",
"nBatch",
"=",
"get_sizes",
"(",
"G",
",",
"A",
")",
"eps",
... | 42.444444 | 20.407407 |
def expectation(p, obj1, obj2=None, nghp=None):
"""
Compute the expectation <obj1(x) obj2(x)>_p(x)
Uses multiple-dispatch to select an analytical implementation,
if one is available. If not, it falls back to quadrature.
:type p: (mu, cov) tuple or a `ProbabilityDistribution` object
:type obj1: ... | [
"def",
"expectation",
"(",
"p",
",",
"obj1",
",",
"obj2",
"=",
"None",
",",
"nghp",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"p",
",",
"tuple",
")",
":",
"assert",
"len",
"(",
"p",
")",
"==",
"2",
"if",
"p",
"[",
"1",
"]",
".",
"shape"... | 36.442623 | 23.327869 |
def post_data(self, path, data, content_type, **params):
"""
Make a POST request to the given path, with `data` in its body.
Return the JSON-decoded result.
The content_type must be set to reflect the kind of data being sent,
which is often `application/json`.
Keyword p... | [
"def",
"post_data",
"(",
"self",
",",
"path",
",",
"data",
",",
"content_type",
",",
"*",
"*",
"params",
")",
":",
"params",
"=",
"jsonify_parameters",
"(",
"params",
")",
"url",
"=",
"ensure_trailing_slash",
"(",
"self",
".",
"url",
"+",
"path",
".",
... | 38.545455 | 20.272727 |
def bed(args):
"""
%prog bed agpfile
print out the tiling paths in bed/gff3 format
"""
from jcvi.formats.obo import validate_term
p = OptionParser(bed.__doc__)
p.add_option("--gaps", default=False, action="store_true",
help="Only print bed lines for gaps [default: %default]")
... | [
"def",
"bed",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"obo",
"import",
"validate_term",
"p",
"=",
"OptionParser",
"(",
"bed",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--gaps\"",
",",
"default",
"=",
"False",
",",
"action... | 36.985294 | 21.514706 |
def indexes(self, collection=None):
"""Return a list with the current indexes
Skip the mandatory _id_ indexes
Args:
collection(str)
Returns:
indexes(list)
"""
indexes = []
for collection_name in self.collections... | [
"def",
"indexes",
"(",
"self",
",",
"collection",
"=",
"None",
")",
":",
"indexes",
"=",
"[",
"]",
"for",
"collection_name",
"in",
"self",
".",
"collections",
"(",
")",
":",
"if",
"collection",
"and",
"collection",
"!=",
"collection_name",
":",
"continue",... | 27.428571 | 18.380952 |
def random_square_mask(shape, fraction):
"""Create a numpy array with specified shape and masked fraction.
Args:
shape: tuple, shape of the mask to create.
fraction: float, fraction of the mask area to populate with `mask_scalar`.
Returns:
numpy.array: A numpy array storing the mask.
"""
mask =... | [
"def",
"random_square_mask",
"(",
"shape",
",",
"fraction",
")",
":",
"mask",
"=",
"np",
".",
"ones",
"(",
"shape",
")",
"patch_area",
"=",
"shape",
"[",
"0",
"]",
"*",
"shape",
"[",
"1",
"]",
"*",
"fraction",
"patch_dim",
"=",
"np",
".",
"int",
"(... | 26.166667 | 20.916667 |
def fix_grpc_import():
'''
Snippet to fix the gRPC import path
'''
with open(GARUDA_GRPC_PATH, 'r') as f:
filedata = f.read()
filedata = filedata.replace(
'import garuda_pb2 as garuda__pb2',
f'import {GARUDA_DIR}.garuda_pb2 as garuda__pb2')
with open(GARUDA_GRPC_PATH, 'w'... | [
"def",
"fix_grpc_import",
"(",
")",
":",
"with",
"open",
"(",
"GARUDA_GRPC_PATH",
",",
"'r'",
")",
"as",
"f",
":",
"filedata",
"=",
"f",
".",
"read",
"(",
")",
"filedata",
"=",
"filedata",
".",
"replace",
"(",
"'import garuda_pb2 as garuda__pb2'",
",",
"f'... | 31.181818 | 13.181818 |
def set_locale(lang):
"""Set the 'locale' used by a program.
This affects the entire application, changing the way dates,
currencies and numbers are represented. It should not be called
from a library routine that may be used in another program.
The ``lang`` parameter can be any string that is rec... | [
"def",
"set_locale",
"(",
"lang",
")",
":",
"# get the default locale",
"lc",
",",
"encoding",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"try",
":",
"if",
"'.'",
"in",
"lang",
":",
"locale",
".",
"setlocale",
"(",
"locale",
".",
"LC_ALL",
",",
"l... | 30.346154 | 21.615385 |
def get_sig(ir, name):
'''
Return a list of potential signature
It is a list, as Constant variables can be converted to int256
Args:
ir (slithIR.operation)
Returns:
list(str)
'''
sig = '{}({})'
# list of list of arguments
argss = convert_arguments(ir.argument... | [
"def",
"get_sig",
"(",
"ir",
",",
"name",
")",
":",
"sig",
"=",
"'{}({})'",
"# list of list of arguments",
"argss",
"=",
"convert_arguments",
"(",
"ir",
".",
"arguments",
")",
"return",
"[",
"sig",
".",
"format",
"(",
"name",
",",
"','",
".",
"join",
"("... | 26.642857 | 21.928571 |
def GetVolumeByIndex(self, volume_index):
"""Retrieves a specific volume based on the index.
Args:
volume_index (int): index of the volume.
Returns:
Volume: a volume or None if not available.
"""
if not self._is_parsed:
self._Parse()
self._is_parsed = True
if volume_in... | [
"def",
"GetVolumeByIndex",
"(",
"self",
",",
"volume_index",
")",
":",
"if",
"not",
"self",
".",
"_is_parsed",
":",
"self",
".",
"_Parse",
"(",
")",
"self",
".",
"_is_parsed",
"=",
"True",
"if",
"volume_index",
"<",
"0",
"or",
"volume_index",
">=",
"len"... | 27 | 20.055556 |
def CrearLiquidacion(self, tipo_cbte, pto_vta, nro_cbte, fecha, periodo,
iibb_adquirente=None, domicilio_sede=None,
inscripcion_registro_publico=None,
datos_adicionales=None, alicuota_iva=None, **kwargs):
"Inicializa internamente los da... | [
"def",
"CrearLiquidacion",
"(",
"self",
",",
"tipo_cbte",
",",
"pto_vta",
",",
"nro_cbte",
",",
"fecha",
",",
"periodo",
",",
"iibb_adquirente",
"=",
"None",
",",
"domicilio_sede",
"=",
"None",
",",
"inscripcion_registro_publico",
"=",
"None",
",",
"datos_adicio... | 54.666667 | 20.666667 |
def verifyInputs(self):
"""
Used in propagate() to verify that the network input
activations have been set.
"""
for layer in self.layers:
if (layer.verify and
layer.type == 'Input' and
layer.kind != 'Context' and
layer.a... | [
"def",
"verifyInputs",
"(",
"self",
")",
":",
"for",
"layer",
"in",
"self",
".",
"layers",
":",
"if",
"(",
"layer",
".",
"verify",
"and",
"layer",
".",
"type",
"==",
"'Input'",
"and",
"layer",
".",
"kind",
"!=",
"'Context'",
"and",
"layer",
".",
"act... | 38.071429 | 12.071429 |
def _parse_trunk_native_vlan(self, config):
"""Scans the specified config and parse the trunk native vlan value
Args:
config (str): The interface configuration block to scan
Returns:
dict: A Python dict object with the value of switchport trunk
native vl... | [
"def",
"_parse_trunk_native_vlan",
"(",
"self",
",",
"config",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'switchport trunk native vlan (\\d+)'",
",",
"config",
")",
"return",
"dict",
"(",
"trunk_native_vlan",
"=",
"match",
".",
"group",
"(",
"1",
")"... | 41.461538 | 21.153846 |
def curl(self):
"""Sending a single cURL request to download"""
c = self._pycurl
# Resume download
if os.path.exists(self.path) and self.resume:
mode = 'ab'
self.downloaded = os.path.getsize(self.path)
c.setopt(pycurl.RESUME_FROM, self.downloaded)
... | [
"def",
"curl",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"_pycurl",
"# Resume download",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
"and",
"self",
".",
"resume",
":",
"mode",
"=",
"'ab'",
"self",
".",
"downloaded",
"... | 39.222222 | 11.555556 |
def delete_eventtype(self, test_type_str=None):
"""Action: create dialog to delete event type."""
if test_type_str:
answer = test_type_str, True
else:
answer = QInputDialog.getText(self, 'Delete Event Type',
'Enter event\'s name t... | [
"def",
"delete_eventtype",
"(",
"self",
",",
"test_type_str",
"=",
"None",
")",
":",
"if",
"test_type_str",
":",
"answer",
"=",
"test_type_str",
",",
"True",
"else",
":",
"answer",
"=",
"QInputDialog",
".",
"getText",
"(",
"self",
",",
"'Delete Event Type'",
... | 42.636364 | 13.454545 |
def dict_copy(a_dict, exclude_keys_lst=[], exclude_values_lst=[]):
"""a **SALLOW** copy of a dict that excludes items in exclude_keys_lst and exclude_values_lst
useful for copying locals() etc..
:param dict a_dict: dictionary to be copied
:param list exclude_keys_lst: a list or tuple of keys to exclude... | [
"def",
"dict_copy",
"(",
"a_dict",
",",
"exclude_keys_lst",
"=",
"[",
"]",
",",
"exclude_values_lst",
"=",
"[",
"]",
")",
":",
"return",
"dict",
"(",
"[",
"copy",
"(",
"i",
")",
"for",
"i",
"in",
"list",
"(",
"a_dict",
".",
"items",
"(",
")",
")",
... | 48.333333 | 20.166667 |
def generate(self):
"""Generate a signed request from this instance."""
payload = {
'algorithm': 'HMAC-SHA256'
}
if self.data:
payload['app_data'] = self.data
if self.page:
payload['page'] = {}
if self.page.id:
pa... | [
"def",
"generate",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'algorithm'",
":",
"'HMAC-SHA256'",
"}",
"if",
"self",
".",
"data",
":",
"payload",
"[",
"'app_data'",
"]",
"=",
"self",
".",
"data",
"if",
"self",
".",
"page",
":",
"payload",
"[",
"'pa... | 30.545455 | 22.075758 |
def select(self, predicate=None, headers=None):
"""
Select rows from the reader using a predicate to select rows and and itemgetter to return a
subset of elements
:param predicate: If defined, a callable that is called for each row, and if it returns true, the
row is included in ... | [
"def",
"select",
"(",
"self",
",",
"predicate",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"# FIXME; in Python 3, use yield from",
"with",
"self",
".",
"reader",
"as",
"r",
":",
"for",
"row",
"in",
"r",
".",
"select",
"(",
"predicate",
",",
"hea... | 50.26087 | 32.521739 |
def can_update(self, user, **data):
"""
Sys admins can always update an organisation.
Organisation admins and creators can update, but may not update the following fields:
- star_rating
:param user: a User
:param data: data that the user wants to update
:re... | [
"def",
"can_update",
"(",
"self",
",",
"user",
",",
"*",
"*",
"data",
")",
":",
"if",
"user",
".",
"is_admin",
"(",
")",
":",
"raise",
"Return",
"(",
"(",
"True",
",",
"set",
"(",
"[",
"]",
")",
")",
")",
"org_admin",
"=",
"user",
".",
"is_org_... | 32.08 | 18.16 |
def entity_categories(self, entity_id):
"""
Get a list of entity categories for an entity id.
:param entity_id: Entity id
:return: Entity categories
:type entity_id: string
:rtype: [string]
"""
attributes = self.entity_attributes(entity_id)
retur... | [
"def",
"entity_categories",
"(",
"self",
",",
"entity_id",
")",
":",
"attributes",
"=",
"self",
".",
"entity_attributes",
"(",
"entity_id",
")",
"return",
"attributes",
".",
"get",
"(",
"ENTITY_CATEGORY",
",",
"[",
"]",
")"
] | 28.833333 | 13.166667 |
def save_discrete_trajectory(filename, dtraj):
r"""Write discrete trajectory to binary file.
The discrete trajectory is stored as ndarray of integers
in numpy .npy format.
Parameters
----------
filename : str
The filename of the discrete state trajectory file.
The filename can ... | [
"def",
"save_discrete_trajectory",
"(",
"filename",
",",
"dtraj",
")",
":",
"dtraj",
"=",
"np",
".",
"asarray",
"(",
"dtraj",
")",
"np",
".",
"save",
"(",
"filename",
",",
"dtraj",
")"
] | 24.6 | 20.2 |
def getChildWithDefault(self, path, request):
"""
Retrieve a static or dynamically generated child resource from me.
"""
cached_resource = self.getCachedResource(request)
if cached_resource:
reactor.callInThread(
responseInColor,
reques... | [
"def",
"getChildWithDefault",
"(",
"self",
",",
"path",
",",
"request",
")",
":",
"cached_resource",
"=",
"self",
".",
"getCachedResource",
"(",
"request",
")",
"if",
"cached_resource",
":",
"reactor",
".",
"callInThread",
"(",
"responseInColor",
",",
"request",... | 32.052632 | 11.105263 |
def getOption(self, name):
"""
.. _getOption:
Retrieve option of a value.
:param name: The name of the option.
:type name: string
:return: The value
:rtype: boolean, integer, string or None
:see: getOptionAsBool_, getOptionAsInt_, getOptionAsString_
... | [
"def",
"getOption",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"PyOptionList",
":",
"return",
"None",
"if",
"PyOptionList",
"[",
"name",
"]",
"[",
"'type'",
"]",
"==",
"\"String\"",
":",
"return",
"self",
".",
"getOptionAsString",
"("... | 29.565217 | 15.217391 |
def _toSKLGLM(self, model, is_classifier):
""" Private method for converting a GLM to a scikit-learn model
TODO: Add model parameters as well.
"""
py_cls = type(model)
skl_cls = self._spark2skl_classes[py_cls]
intercept = model.intercept
weights = model.coefficien... | [
"def",
"_toSKLGLM",
"(",
"self",
",",
"model",
",",
"is_classifier",
")",
":",
"py_cls",
"=",
"type",
"(",
"model",
")",
"skl_cls",
"=",
"self",
".",
"_spark2skl_classes",
"[",
"py_cls",
"]",
"intercept",
"=",
"model",
".",
"intercept",
"weights",
"=",
"... | 37.285714 | 7.857143 |
def load_folder_files(folder_path, recursive=True):
""" load folder path, return all files endswith yml/yaml/json in list.
Args:
folder_path (str): specified folder path to load
recursive (bool): load files recursively if True
Returns:
list: files endswith yml/yaml/json
"""
... | [
"def",
"load_folder_files",
"(",
"folder_path",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"folder_path",
",",
"(",
"list",
",",
"set",
")",
")",
":",
"files",
"=",
"[",
"]",
"for",
"path",
"in",
"set",
"(",
"folder_path",
")",
... | 25.871795 | 20.974359 |
def define_noisy_gate(self, name, qubit_indices, kraus_ops):
"""
Overload a static ideal gate with a noisy one defined in terms of a Kraus map.
.. note::
The matrix elements along each axis are ordered by bitstring. For two qubits the order
is ``00, 01, 10, 11``, where ... | [
"def",
"define_noisy_gate",
"(",
"self",
",",
"name",
",",
"qubit_indices",
",",
"kraus_ops",
")",
":",
"kraus_ops",
"=",
"[",
"np",
".",
"asarray",
"(",
"k",
",",
"dtype",
"=",
"np",
".",
"complex128",
")",
"for",
"k",
"in",
"kraus_ops",
"]",
"_check_... | 48.714286 | 30.809524 |
def random_offspring(self):
"Returns an offspring with the associated weight(s)"
function_set = self.function_set
function_selection = self._function_selection_ins
function_selection.density = self.population.density
function_selection.unfeasible_functions.clear()
for i i... | [
"def",
"random_offspring",
"(",
"self",
")",
":",
"function_set",
"=",
"self",
".",
"function_set",
"function_selection",
"=",
"self",
".",
"_function_selection_ins",
"function_selection",
".",
"density",
"=",
"self",
".",
"population",
".",
"density",
"function_sel... | 46.043478 | 16.217391 |
def upsert(self, dataset_identifier, payload, content_type="json"):
'''
Insert, update or delete data to/from an existing dataset. Currently
supports json and csv file objects. See here for the upsert
documentation:
http://dev.socrata.com/publishers/upsert.html
'''
... | [
"def",
"upsert",
"(",
"self",
",",
"dataset_identifier",
",",
"payload",
",",
"content_type",
"=",
"\"json\"",
")",
":",
"resource",
"=",
"_format_new_api_request",
"(",
"dataid",
"=",
"dataset_identifier",
",",
"content_type",
"=",
"content_type",
")",
"return",
... | 46.9 | 30.1 |
def _is_common_binary(self, inpath):
"""private method to compare file path mime type to common binary file types"""
# make local variables for the available char numbers in the suffix types to be tested
two_suffix = inpath[-3:]
three_suffix = inpath[-4:]
four_suffix = inpath[-5:... | [
"def",
"_is_common_binary",
"(",
"self",
",",
"inpath",
")",
":",
"# make local variables for the available char numbers in the suffix types to be tested",
"two_suffix",
"=",
"inpath",
"[",
"-",
"3",
":",
"]",
"three_suffix",
"=",
"inpath",
"[",
"-",
"4",
":",
"]",
... | 41.625 | 17.5625 |
def get_user_contact_list(self, id, contact_list_id, **data):
"""
GET /users/:id/contact_lists/:contact_list_id/
Gets a user's :format:`contact_list` by ID as ``contact_list``.
"""
return self.get("/users/{0}/contact_lists/{0}/".format(id,contact_list_id), data=data) | [
"def",
"get_user_contact_list",
"(",
"self",
",",
"id",
",",
"contact_list_id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"get",
"(",
"\"/users/{0}/contact_lists/{0}/\"",
".",
"format",
"(",
"id",
",",
"contact_list_id",
")",
",",
"data",
"=",
... | 44.285714 | 21.714286 |
def beautify(string, *args, **kwargs):
"""
Convenient interface to the ecstasy package.
Arguments:
string (str): The string to beautify with ecstasy.
args (list): The positional arguments.
kwargs (dict): The keyword ('always') arguments.
"""
parser = Parser(args, kwargs)
return parser.beautify(string... | [
"def",
"beautify",
"(",
"string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"parser",
"=",
"Parser",
"(",
"args",
",",
"kwargs",
")",
"return",
"parser",
".",
"beautify",
"(",
"string",
")"
] | 25.833333 | 13.333333 |
def _get_value(self, source, bitarray):
''' Get value, based on the data in XML '''
raw_value = self._get_raw(source, bitarray)
rng = source.find('range')
rng_min = float(rng.find('min').text)
rng_max = float(rng.find('max').text)
scl = source.find('scale')
scl_... | [
"def",
"_get_value",
"(",
"self",
",",
"source",
",",
"bitarray",
")",
":",
"raw_value",
"=",
"self",
".",
"_get_raw",
"(",
"source",
",",
"bitarray",
")",
"rng",
"=",
"source",
".",
"find",
"(",
"'range'",
")",
"rng_min",
"=",
"float",
"(",
"rng",
"... | 34.8 | 17.2 |
def reset(self):
"""Reset widget to original state."""
self.filename = None
self.dataset = None
# about the recordings
self.idx_filename.setText('Open Recordings...')
self.idx_s_freq.setText('')
self.idx_n_chan.setText('')
self.idx_start_time.setText('')
... | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"filename",
"=",
"None",
"self",
".",
"dataset",
"=",
"None",
"# about the recordings",
"self",
".",
"idx_filename",
".",
"setText",
"(",
"'Open Recordings...'",
")",
"self",
".",
"idx_s_freq",
".",
"setTex... | 30.705882 | 11.352941 |
def _clear_output(self):
"""
Clears progress output (if any) that was written to the screen.
"""
# If progress output was being written, clear it from the screen.
if self.progress_output:
sys.stderr.write("\r".ljust(self.last_line_len))
sys.stderr.write("\... | [
"def",
"_clear_output",
"(",
"self",
")",
":",
"# If progress output was being written, clear it from the screen.",
"if",
"self",
".",
"progress_output",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\r\"",
".",
"ljust",
"(",
"self",
".",
"last_line_len",
")",
... | 38.444444 | 13.777778 |
def defaultSessionFactory(env={}, usePTY=False, *args, **kwargs):
"""Create a SSHChannel of the given :channelType: type
"""
return SSHSession(env, usePTY, *args, **kwargs) | [
"def",
"defaultSessionFactory",
"(",
"env",
"=",
"{",
"}",
",",
"usePTY",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"SSHSession",
"(",
"env",
",",
"usePTY",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 45.25 | 9 |
def upload(ctx, tileset, datasource, name, patch):
"""Upload data to Mapbox accounts.
Uploaded data lands at https://www.mapbox.com/data/ and can be used
in new or existing projects. All endpoints require authentication.
You can specify the tileset id and input file
$ mapbox upload username.dat... | [
"def",
"upload",
"(",
"ctx",
",",
"tileset",
",",
"datasource",
",",
"name",
",",
"patch",
")",
":",
"access_token",
"=",
"(",
"ctx",
".",
"obj",
"and",
"ctx",
".",
"obj",
".",
"get",
"(",
"'access_token'",
")",
")",
"or",
"None",
"service",
"=",
"... | 34.25 | 23.65 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.