text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def build(self, builder):
"""Build XML by appending to builder"""
builder.start("CheckValue", {})
builder.data(str(self.value))
builder.end("CheckValue") | [
"def",
"build",
"(",
"self",
",",
"builder",
")",
":",
"builder",
".",
"start",
"(",
"\"CheckValue\"",
",",
"{",
"}",
")",
"builder",
".",
"data",
"(",
"str",
"(",
"self",
".",
"value",
")",
")",
"builder",
".",
"end",
"(",
"\"CheckValue\"",
")"
] | 36.2 | 0.010811 |
def makerandCIJdegreesfixed(inv, outv, seed=None):
'''
This function generates a directed random network with a specified
in-degree and out-degree sequence.
Parameters
----------
inv : Nx1 np.ndarray
in-degree vector
outv : Nx1 np.ndarray
out-degree vector
seed : hashabl... | [
"def",
"makerandCIJdegreesfixed",
"(",
"inv",
",",
"outv",
",",
"seed",
"=",
"None",
")",
":",
"rng",
"=",
"get_rng",
"(",
"seed",
")",
"n",
"=",
"len",
"(",
"inv",
")",
"k",
"=",
"np",
".",
"sum",
"(",
"inv",
")",
"in_inv",
"=",
"np",
".",
"ze... | 32.662651 | 0.001074 |
def _template(node_id, value=None):
"Check if a template is assigned to it and render that with the value"
result = []
select_template_from_node = fetch_query_string('select_template_from_node.sql')
try:
result = db.execute(text(select_template_from_node), node_id=node_id)
template_resul... | [
"def",
"_template",
"(",
"node_id",
",",
"value",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"select_template_from_node",
"=",
"fetch_query_string",
"(",
"'select_template_from_node.sql'",
")",
"try",
":",
"result",
"=",
"db",
".",
"execute",
"(",
"text",... | 40.1 | 0.002436 |
def Collect(self, knowledge_base):
"""Collects values from the knowledge base.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
Raises:
PreProcessFail: if the preprocessing fails.
"""
environment_variable = knowledge_base.GetEnvironmentVariable(
'pr... | [
"def",
"Collect",
"(",
"self",
",",
"knowledge_base",
")",
":",
"environment_variable",
"=",
"knowledge_base",
".",
"GetEnvironmentVariable",
"(",
"'programdata'",
")",
"allusersprofile",
"=",
"getattr",
"(",
"environment_variable",
",",
"'value'",
",",
"None",
")",... | 36.034483 | 0.008388 |
def persistent_popen_align3(clusts, maxseqs=200, is_gbs=False):
""" keeps a persistent bash shell open and feeds it muscle alignments """
## create a separate shell for running muscle in, this is much faster
## than spawning a separate subprocess for each muscle call
proc = sps.Popen(["bash"],
... | [
"def",
"persistent_popen_align3",
"(",
"clusts",
",",
"maxseqs",
"=",
"200",
",",
"is_gbs",
"=",
"False",
")",
":",
"## create a separate shell for running muscle in, this is much faster",
"## than spawning a separate subprocess for each muscle call",
"proc",
"=",
"sps",
".",
... | 42.993243 | 0.011521 |
def _get_concatenation(extractors, text, *, ignore_whitespace=True):
"""Returns a concatenation ParseNode whose children are the nodes returned by each of the
methods in the extractors enumerable.
If ignore_whitespace is True, whitespace will be ignored and then attached to the child it
preceeded.
"""
igno... | [
"def",
"_get_concatenation",
"(",
"extractors",
",",
"text",
",",
"*",
",",
"ignore_whitespace",
"=",
"True",
")",
":",
"ignored_ws",
",",
"use_text",
"=",
"_split_ignored",
"(",
"text",
",",
"ignore_whitespace",
")",
"extractor",
",",
"",
"*",
"remaining",
... | 44.678571 | 0.014867 |
def as_bel(self) -> str:
"""Return this node as a BEL string."""
return "{}({}:{})".format(
self._func,
self.namespace,
ensure_quotes(self._priority_id)
) | [
"def",
"as_bel",
"(",
"self",
")",
"->",
"str",
":",
"return",
"\"{}({}:{})\"",
".",
"format",
"(",
"self",
".",
"_func",
",",
"self",
".",
"namespace",
",",
"ensure_quotes",
"(",
"self",
".",
"_priority_id",
")",
")"
] | 29.714286 | 0.009346 |
def python_details():
"""
Returns a dictionary containing details about the Python interpreter
"""
build_no, build_date = platform.python_build()
results = {
# Version of interpreter
"build.number": build_no,
"build.date": build_date,
... | [
"def",
"python_details",
"(",
")",
":",
"build_no",
",",
"build_date",
"=",
"platform",
".",
"python_build",
"(",
")",
"results",
"=",
"{",
"# Version of interpreter",
"\"build.number\"",
":",
"build_no",
",",
"\"build.date\"",
":",
"build_date",
",",
"\"compiler\... | 39.85 | 0.001225 |
def json_data(self, data=None):
"""Adds the default_data to data and dumps it to a json."""
if data is None:
data = {}
data.update(self.default_data)
return json.dumps(data) | [
"def",
"json_data",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"data",
".",
"update",
"(",
"self",
".",
"default_data",
")",
"return",
"json",
".",
"dumps",
"(",
"data",
")"
] | 35.333333 | 0.009217 |
def logical_intf_helper(interface):
"""
Logical Interface finder by name. Create if it doesn't exist.
This is useful when adding logical interfaces to for inline
or capture interfaces.
:param interface: logical interface name
:return str href: href of logical interface
"""
if interface ... | [
"def",
"logical_intf_helper",
"(",
"interface",
")",
":",
"if",
"interface",
"is",
"None",
":",
"return",
"LogicalInterface",
".",
"get_or_create",
"(",
"name",
"=",
"'default_eth'",
")",
".",
"href",
"elif",
"isinstance",
"(",
"interface",
",",
"LogicalInterfac... | 36.9375 | 0.00165 |
def configuration(self):
"""Dict of variables that we make available as globals in the module.
Can be used as ::
globals().update(GMXConfigParser.configuration) # update configdir, templatesdir ...
"""
configuration = {
'configfilename': self.... | [
"def",
"configuration",
"(",
"self",
")",
":",
"configuration",
"=",
"{",
"'configfilename'",
":",
"self",
".",
"filename",
",",
"'logfilename'",
":",
"self",
".",
"getpath",
"(",
"'Logging'",
",",
"'logfilename'",
")",
",",
"'loglevel_console'",
":",
"self",
... | 48.85 | 0.008032 |
def adjust_spines(ax, spines):
"""function for removing spines and ticks.
:param ax: axes object
:param spines: a list of spines names to keep. e.g [left, right, top, bottom]
if spines = []. remove all spines and ticks.
"""
for loc, spine in ax.spines.items():
if loc in... | [
"def",
"adjust_spines",
"(",
"ax",
",",
"spines",
")",
":",
"for",
"loc",
",",
"spine",
"in",
"ax",
".",
"spines",
".",
"items",
"(",
")",
":",
"if",
"loc",
"in",
"spines",
":",
"# spine.set_position(('outward', 10)) # outward by 10 points",
"# spine.set_smart_... | 29.642857 | 0.002334 |
def predict_proba(self, X):
"""Returns the predicted probabilities for ``X``.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
Returns:
... | [
"def",
"predict_proba",
"(",
"self",
",",
"X",
")",
":",
"return",
"collections",
".",
"deque",
"(",
"self",
".",
"iter_predict_proba",
"(",
"X",
")",
",",
"maxlen",
"=",
"1",
")",
".",
"pop",
"(",
")"
] | 43.636364 | 0.010204 |
def _convert_fancy(self, field):
"""Convert to a list (sep != None) and convert list elements."""
if self.sep is False:
x = self._convert_singlet(field)
else:
x = tuple([self._convert_singlet(s) for s in field.split(self.sep)])
if len(x) == 0:
... | [
"def",
"_convert_fancy",
"(",
"self",
",",
"field",
")",
":",
"if",
"self",
".",
"sep",
"is",
"False",
":",
"x",
"=",
"self",
".",
"_convert_singlet",
"(",
"field",
")",
"else",
":",
"x",
"=",
"tuple",
"(",
"[",
"self",
".",
"_convert_singlet",
"(",
... | 35.583333 | 0.009132 |
def findBinomialNsWithExpectedSampleMinimum(desiredValuesSorted, p, numSamples, nMax):
"""
For each desired value, find an approximate n for which the sample minimum
has a expected value equal to this value.
For each value, find an adjacent pair of n values whose expected sample minima
are below and above th... | [
"def",
"findBinomialNsWithExpectedSampleMinimum",
"(",
"desiredValuesSorted",
",",
"p",
",",
"numSamples",
",",
"nMax",
")",
":",
"# mapping from n -> expected value",
"actualValues",
"=",
"[",
"getExpectedValue",
"(",
"SampleMinimumDistribution",
"(",
"numSamples",
",",
... | 30.195652 | 0.008368 |
def douglas_rachford_pd_stepsize(L, tau=None, sigma=None):
r"""Default step sizes for `douglas_rachford_pd`.
Parameters
----------
L : sequence of `Operator` or float
The operators or the norms of the operators that are used in the
`douglas_rachford_pd` method. For `Operator` entries, t... | [
"def",
"douglas_rachford_pd_stepsize",
"(",
"L",
",",
"tau",
"=",
"None",
",",
"sigma",
"=",
"None",
")",
":",
"if",
"tau",
"is",
"None",
"and",
"sigma",
"is",
"None",
":",
"L_norms",
"=",
"_operator_norms",
"(",
"L",
")",
"tau",
"=",
"1",
"/",
"sum"... | 30.155844 | 0.000417 |
def add_program_dir(self, directory):
"""Hack in program directory"""
dirs = list(self.PROGRAM_DIRS)
dirs.append(directory)
self.PROGRAM_DIRS = dirs | [
"def",
"add_program_dir",
"(",
"self",
",",
"directory",
")",
":",
"dirs",
"=",
"list",
"(",
"self",
".",
"PROGRAM_DIRS",
")",
"dirs",
".",
"append",
"(",
"directory",
")",
"self",
".",
"PROGRAM_DIRS",
"=",
"dirs"
] | 35.2 | 0.011111 |
def truncate_graph_bbox(G, north, south, east, west, truncate_by_edge=False, retain_all=False):
"""
Remove every node in graph that falls outside a bounding box.
Needed because overpass returns entire ways that also include nodes outside
the bbox if the way (that is, a way with a single OSM ID) has a n... | [
"def",
"truncate_graph_bbox",
"(",
"G",
",",
"north",
",",
"south",
",",
"east",
",",
"west",
",",
"truncate_by_edge",
"=",
"False",
",",
"retain_all",
"=",
"False",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"G",
"=",
"G",
".",
"cop... | 36.676471 | 0.002343 |
def defineOperator( self, operator, widget = -1 ):
"""
Adds a new operator for this rule. If widget is supplied as -1, then \
a QLineEdit will be used by default.
:param operator | <str>
widget | <subclass of QWidget> || None || -1
"""
... | [
"def",
"defineOperator",
"(",
"self",
",",
"operator",
",",
"widget",
"=",
"-",
"1",
")",
":",
"if",
"(",
"widget",
"==",
"-",
"1",
")",
":",
"widget",
"=",
"QLineEdit",
"self",
".",
"_operators",
"[",
"nativestring",
"(",
"operator",
")",
"]",
"=",
... | 35.916667 | 0.022624 |
def add(self, nb = 1, name = None):
"""
Create one or many workers.
"""
for x in xrange(nb):
self.count_lock.acquire()
self.shared['workers'] += 1
xid = self.shared['workers']
self.kill_event.clear()
self.count_lock.release()
... | [
"def",
"add",
"(",
"self",
",",
"nb",
"=",
"1",
",",
"name",
"=",
"None",
")",
":",
"for",
"x",
"in",
"xrange",
"(",
"nb",
")",
":",
"self",
".",
"count_lock",
".",
"acquire",
"(",
")",
"self",
".",
"shared",
"[",
"'workers'",
"]",
"+=",
"1",
... | 38 | 0.01581 |
def build_filter(predicate: Callable[[Any], bool] = None, *,
unpack: bool = False):
""" Decorator to wrap a function to return a Filter operator.
:param predicate: function to be wrapped
:param unpack: value from emits will be unpacked (*value)
"""
def _build_filter(predicate: Call... | [
"def",
"build_filter",
"(",
"predicate",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"bool",
"]",
"=",
"None",
",",
"*",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"def",
"_build_filter",
"(",
"predicate",
":",
"Callable",
"[",
"[",
"Any",
... | 36 | 0.001425 |
def assertFileEncodingNotEqual(self, filename, encoding, msg=None):
'''Fail if ``filename`` is encoded with the given ``encoding``
as determined by the '!=' operator.
Parameters
----------
filename : str, bytes, file-like
encoding : str, bytes
msg : str
... | [
"def",
"assertFileEncodingNotEqual",
"(",
"self",
",",
"filename",
",",
"encoding",
",",
"msg",
"=",
"None",
")",
":",
"fencoding",
"=",
"self",
".",
"_get_file_encoding",
"(",
"filename",
")",
"fname",
"=",
"self",
".",
"_get_file_name",
"(",
"filename",
")... | 33.730769 | 0.002217 |
def rm_rf(path):
"""
Act as 'rm -rf' in the shell
"""
if os.path.isfile(path):
os.unlink(path)
elif os.path.isdir(path):
for root, dirs, files in os.walk(path, topdown=False):
for filename in files:
filepath = os.path.join(root, filename)
l... | [
"def",
"rm_rf",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"os",
".",
"unlink",
"(",
"path",
")",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"for",
"root",
",",
"dirs",
",",
"fil... | 36.227273 | 0.001222 |
def addMenuItem( self, newItem, atItem ):
"""
Adds a new menu item at the given item.
:param newItem | <QTreeWidgetItem>
atItem | <QTreeWidgetItem>
"""
tree = self.uiMenuTREE
if ( not atItem ):
tree.addTopLevelItem(n... | [
"def",
"addMenuItem",
"(",
"self",
",",
"newItem",
",",
"atItem",
")",
":",
"tree",
"=",
"self",
".",
"uiMenuTREE",
"if",
"(",
"not",
"atItem",
")",
":",
"tree",
".",
"addTopLevelItem",
"(",
"newItem",
")",
"elif",
"(",
"atItem",
".",
"data",
"(",
"0... | 32 | 0.02069 |
def add_action_callback(self, key_value, modifier_mask, a_dict=False):
"""Callback method for add action"""
if react_to_event(self.view, self.tree_view, event=(key_value, modifier_mask)) and self.active_entry_widget is None:
self.on_add(None, a_dict)
return True | [
"def",
"add_action_callback",
"(",
"self",
",",
"key_value",
",",
"modifier_mask",
",",
"a_dict",
"=",
"False",
")",
":",
"if",
"react_to_event",
"(",
"self",
".",
"view",
",",
"self",
".",
"tree_view",
",",
"event",
"=",
"(",
"key_value",
",",
"modifier_m... | 59.6 | 0.009934 |
def connect(self, object, callback):
"""Subscribe to the signal."""
return subscription(self.map.setdefault(object, []), callback) | [
"def",
"connect",
"(",
"self",
",",
"object",
",",
"callback",
")",
":",
"return",
"subscription",
"(",
"self",
".",
"map",
".",
"setdefault",
"(",
"object",
",",
"[",
"]",
")",
",",
"callback",
")"
] | 44 | 0.029851 |
def stream_restore_write( obj_name_or_list,
mode='merge', apply_immediately=False, **obj_kws ):
'''Update module-stream-restore db entry for specified name.
Can be passed PulseExtStreamRestoreInfo object or list of them as argument,
or name string there and object init keywords (e.g. volume, mute, channel_l... | [
"def",
"stream_restore_write",
"(",
"obj_name_or_list",
",",
"mode",
"=",
"'merge'",
",",
"apply_immediately",
"=",
"False",
",",
"*",
"*",
"obj_kws",
")",
":",
"mode",
"=",
"PulseUpdateEnum",
"[",
"mode",
"]",
".",
"_c_val",
"if",
"is_str",
"(",
"obj_name_o... | 60.166667 | 0.024545 |
def notify(self, state, notifications):
'''
Call this to schedule sending partner notification.
'''
def do_append(desc, notifications):
for notification in notifications:
if not isinstance(notification, PendingNotification):
raise ValueErr... | [
"def",
"notify",
"(",
"self",
",",
"state",
",",
"notifications",
")",
":",
"def",
"do_append",
"(",
"desc",
",",
"notifications",
")",
":",
"for",
"notification",
"in",
"notifications",
":",
"if",
"not",
"isinstance",
"(",
"notification",
",",
"PendingNotif... | 46.705882 | 0.002469 |
def eigen(matrix):
""" Calculates the eigenvalues and eigenvectors of the input matrix.
Returns a tuple of (eigenvalues, eigenvectors, cumulative percentage of
variance explained). Eigenvalues and eigenvectors are sorted in order of
eigenvalue magnitude, high to low """
(vals, vecs) = np.linalg.eig... | [
"def",
"eigen",
"(",
"matrix",
")",
":",
"(",
"vals",
",",
"vecs",
")",
"=",
"np",
".",
"linalg",
".",
"eigh",
"(",
"matrix",
")",
"ind",
"=",
"vals",
".",
"argsort",
"(",
")",
"[",
":",
":",
"-",
"1",
"]",
"vals",
"=",
"vals",
"[",
"ind",
... | 39.214286 | 0.001779 |
def get_neuroglancer_link(self, resource, resolution, x_range, y_range, z_range, **kwargs):
"""
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step.
Args:
resource (intern.resource.Resource): Resource compatible w... | [
"def",
"get_neuroglancer_link",
"(",
"self",
",",
"resource",
",",
"resolution",
",",
"x_range",
",",
"y_range",
",",
"z_range",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_volume",
".",
"get_neuroglancer_link",
"(",
"resource",
",",
"resolut... | 54.631579 | 0.010417 |
def rmR(kls, path):
"""`rm -R path`. Deletes, but does not recurse into, symlinks.
If the path does not exist, silently return."""
if os.path.islink(path) or os.path.isfile(path):
os.unlink(path)
elif os.path.isdir(path):
walker = os.walk(path, topdown=False, followlinks=False)
for dirpath, dirnames,... | [
"def",
"rmR",
"(",
"kls",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"islink",
"(",
"path",
")",
"or",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"os",
".",
"unlink",
"(",
"path",
")",
"elif",
"os",
".",
"path",
".",
... | 36.615385 | 0.032787 |
def read_cz_sem(fh, byteorder, dtype, count, offsetsize):
"""Read Zeiss SEM tag and return as dict.
See https://sourceforge.net/p/gwyddion/mailman/message/29275000/ for
unnamed values.
"""
result = {'': ()}
key = None
data = bytes2str(stripnull(fh.read(count)))
for line in data.splitli... | [
"def",
"read_cz_sem",
"(",
"fh",
",",
"byteorder",
",",
"dtype",
",",
"count",
",",
"offsetsize",
")",
":",
"result",
"=",
"{",
"''",
":",
"(",
")",
"}",
"key",
"=",
"None",
"data",
"=",
"bytes2str",
"(",
"stripnull",
"(",
"fh",
".",
"read",
"(",
... | 31.204545 | 0.000706 |
def decide_child_program(args_executable, args_child_program):
"""Decide which the child program really is (if any)."""
# We get the logger here because it's not defined at module level
logger = logging.getLogger('fades')
if args_executable:
# if --exec given, check that it's just the executabl... | [
"def",
"decide_child_program",
"(",
"args_executable",
",",
"args_child_program",
")",
":",
"# We get the logger here because it's not defined at module level",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'fades'",
")",
"if",
"args_executable",
":",
"# if --exec given, ... | 48.810811 | 0.002172 |
def _startRelay(self, client):
"""Start relaying data between the process and the protocol.
This method is called when the protocol is connected.
"""
process = client.transport.connector.process
# Relay any buffered data that was received from the process before
# we got ... | [
"def",
"_startRelay",
"(",
"self",
",",
"client",
")",
":",
"process",
"=",
"client",
".",
"transport",
".",
"connector",
".",
"process",
"# Relay any buffered data that was received from the process before",
"# we got connected and started relaying.",
"for",
"_",
",",
"d... | 37.590909 | 0.002358 |
def barh(self, x=None, y=None, **kwds):
"""
Make a horizontal bar plot.
A horizontal bar plot is a plot that presents quantitative data with
rectangular bars with lengths proportional to the values that they
represent. A bar plot shows comparisons among discrete categories. One
... | [
"def",
"barh",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
"(",
"kind",
"=",
"'barh'",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"*",
"*",
"kwds",
")"
] | 36.164557 | 0.000681 |
def updateEventType(self, eventTypeId, name, schemaId, description=None):
"""
Updates an event type.
Parameters: eventTypeId (string), name (string), schemaId (string), description (string, optional).
Throws APIException on failure.
"""
req = ApiClient.oneEventTypesUrl % ... | [
"def",
"updateEventType",
"(",
"self",
",",
"eventTypeId",
",",
"name",
",",
"schemaId",
",",
"description",
"=",
"None",
")",
":",
"req",
"=",
"ApiClient",
".",
"oneEventTypesUrl",
"%",
"(",
"self",
".",
"host",
",",
"\"/draft\"",
",",
"eventTypeId",
")",... | 50.647059 | 0.009122 |
def _file_lists(load, form):
'''
Return a dict containing the file lists for files and dirs
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
list_cachedir = os.path.join(__opts__['cachedir'], 'file_lists/hgfs')
if not os.path.isdir(list_cachedir):
... | [
"def",
"_file_lists",
"(",
"load",
",",
"form",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"list_cachedir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"... | 35.088235 | 0.000816 |
def integral(wave, indep_min=None, indep_max=None):
r"""
Return the running integral of a waveform's dependent variable vector.
The method used is the `trapezoidal
<https://en.wikipedia.org/wiki/Trapezoidal_rule>`_ method
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:p... | [
"def",
"integral",
"(",
"wave",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"ret",
"=",
"copy",
".",
"copy",
"(",
"wave",
")",
"_bound_waveform",
"(",
"ret",
",",
"indep_min",
",",
"indep_max",
")",
"ret",
".",
"_dep_vector"... | 31.75 | 0.000764 |
def smooth(x, rho, penalty, axis=0, newshape=None):
"""
Applies a smoothing operator along one dimension
currently only accepts a matrix as input
Parameters
----------
penalty : float
axis : int, optional
Axis along which to apply the smoothing (Default: 0)
newshape : tuple, ... | [
"def",
"smooth",
"(",
"x",
",",
"rho",
",",
"penalty",
",",
"axis",
"=",
"0",
",",
"newshape",
"=",
"None",
")",
":",
"orig_shape",
"=",
"x",
".",
"shape",
"if",
"newshape",
"is",
"not",
"None",
":",
"x",
"=",
"x",
".",
"reshape",
"(",
"newshape"... | 30 | 0.00095 |
def knapsack_iterative(items, maxweight):
# Knapsack requires integral weights
weights = [t[1] for t in items]
max_exp = max([number_of_decimals(w_) for w_ in weights])
coeff = 10 ** max_exp
# Adjust weights to be integral
int_maxweight = int(maxweight * coeff)
int_items = [(v, int(w * coeff... | [
"def",
"knapsack_iterative",
"(",
"items",
",",
"maxweight",
")",
":",
"# Knapsack requires integral weights",
"weights",
"=",
"[",
"t",
"[",
"1",
"]",
"for",
"t",
"in",
"items",
"]",
"max_exp",
"=",
"max",
"(",
"[",
"number_of_decimals",
"(",
"w_",
")",
"... | 35.923077 | 0.002088 |
def sort(self, search):
"""
Add sorting information to the request.
"""
if self._sort:
search = search.sort(*self._sort)
return search | [
"def",
"sort",
"(",
"self",
",",
"search",
")",
":",
"if",
"self",
".",
"_sort",
":",
"search",
"=",
"search",
".",
"sort",
"(",
"*",
"self",
".",
"_sort",
")",
"return",
"search"
] | 25.714286 | 0.010753 |
def datafind_keep_unique_backups(backup_outs, orig_outs):
"""This function will take a list of backup datafind files, presumably
obtained by querying a remote datafind server, e.g. CIT, and compares
these against a list of original datafind files, presumably obtained by
querying the local datafind serve... | [
"def",
"datafind_keep_unique_backups",
"(",
"backup_outs",
",",
"orig_outs",
")",
":",
"# NOTE: This function is not optimized and could be made considerably",
"# quicker if speed becomes in issue. With 4s frame files this might",
"# be slow, but for >1000s files I don't foresee any ... | 41.3 | 0.000591 |
def solve(self):
'''
Solves a one period consumption saving problem with risky income and
shocks to medical need.
Parameters
----------
None
Returns
-------
solution : ConsumerSolution
The solution to the one period problem, including... | [
"def",
"solve",
"(",
"self",
")",
":",
"aLvl",
",",
"trash",
"=",
"self",
".",
"prepareToCalcEndOfPrdvP",
"(",
")",
"EndOfPrdvP",
"=",
"self",
".",
"calcEndOfPrdvP",
"(",
")",
"if",
"self",
".",
"vFuncBool",
":",
"self",
".",
"makeEndOfPrdvFunc",
"(",
"E... | 37.064516 | 0.008482 |
def add(self, new_hw_map):
"""
Add the HW map only if it doesn't exist for a given key, and no address collisions
"""
new_route = new_hw_map.route
if new_route in self.raw_maps:
raise KeyError("HW Map already exists: {0:s}".format(new_hw_map.route))
commo... | [
"def",
"add",
"(",
"self",
",",
"new_hw_map",
")",
":",
"new_route",
"=",
"new_hw_map",
".",
"route",
"if",
"new_route",
"in",
"self",
".",
"raw_maps",
":",
"raise",
"KeyError",
"(",
"\"HW Map already exists: {0:s}\"",
".",
"format",
"(",
"new_hw_map",
".",
... | 42.214286 | 0.008278 |
def present(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (... | [
"def",
"present",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_state",
"(",
"subset",
"=",
"subset",
",",
"... | 30.130435 | 0.001399 |
def any_from_filename(filename, prefix_dir=None):
"""
Create a MeshIO instance according to the kind of `filename`.
Parameters
----------
filename : str, function or MeshIO subclass instance
The name of the mesh file. It can be also a user-supplied function
accepting two arguments: ... | [
"def",
"any_from_filename",
"(",
"filename",
",",
"prefix_dir",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"basestr",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"MeshIO",
")",
":",
"return",
"filename",
"else",
":",
... | 31.076923 | 0.0008 |
def qsize(self, qname):
"""Return the approximate size of the queue."""
if qname in self._queues:
return self._queues[qname].qsize()
else:
raise ValueError(_("queue %s is not defined"), qname) | [
"def",
"qsize",
"(",
"self",
",",
"qname",
")",
":",
"if",
"qname",
"in",
"self",
".",
"_queues",
":",
"return",
"self",
".",
"_queues",
"[",
"qname",
"]",
".",
"qsize",
"(",
")",
"else",
":",
"raise",
"ValueError",
"(",
"_",
"(",
"\"queue %s is not ... | 39.166667 | 0.008333 |
def request(self, method, url, **kwargs):
"""Override request method disabling verify on token renewal if disabled on session."""
if not url.startswith('https'):
url = '{}{}'.format(self.args.tc_api_path, url)
return super(TcExSession, self).request(method, url, **kwargs) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"url",
".",
"startswith",
"(",
"'https'",
")",
":",
"url",
"=",
"'{}{}'",
".",
"format",
"(",
"self",
".",
"args",
".",
"tc_api_path",
",",
... | 60.8 | 0.00974 |
def get_decor(self, c, match_only=None):
"""
Get the decor for a component.
Args:
c (component): The component to look up.
match_only (list of str): The component attributes to include in the
comparison. Default: All of them.
Returns:
Dec... | [
"def",
"get_decor",
"(",
"self",
",",
"c",
",",
"match_only",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"c",
",",
"Component",
")",
":",
"if",
"c",
":",
"if",
"match_only",
":",
"# Filter the component only those attributes",
"c",
"=",
"Component",
"... | 37.225806 | 0.001689 |
def resolve_and_build(self):
""" resolves the dependencies of this build target and builds it """
pdebug("resolving and building task '%s'" % self.name,
groups=["build_task"])
indent_text(indent="++2")
toret = self.build(**self.resolve_dependencies())
indent_text(... | [
"def",
"resolve_and_build",
"(",
"self",
")",
":",
"pdebug",
"(",
"\"resolving and building task '%s'\"",
"%",
"self",
".",
"name",
",",
"groups",
"=",
"[",
"\"build_task\"",
"]",
")",
"indent_text",
"(",
"indent",
"=",
"\"++2\"",
")",
"toret",
"=",
"self",
... | 43.375 | 0.008475 |
def perf_stats_bootstrap(returns, factor_returns=None, return_stats=True,
**kwargs):
"""Calculates various bootstrapped performance metrics of a strategy.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explana... | [
"def",
"perf_stats_bootstrap",
"(",
"returns",
",",
"factor_returns",
"=",
"None",
",",
"return_stats",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"bootstrap_values",
"=",
"OrderedDict",
"(",
")",
"for",
"stat_func",
"in",
"SIMPLE_STAT_FUNCS",
":",
"stat_... | 36.980769 | 0.000507 |
def _compute_next_evaluations(self, pending_zipped_X=None, ignored_zipped_X=None):
"""
Computes the location of the new evaluation (optimizes the acquisition in the standard case).
:param pending_zipped_X: matrix of input configurations that are in a pending state (i.e., do not have an evaluatio... | [
"def",
"_compute_next_evaluations",
"(",
"self",
",",
"pending_zipped_X",
"=",
"None",
",",
"ignored_zipped_X",
"=",
"None",
")",
":",
"## --- Update the context if any",
"self",
".",
"acquisition",
".",
"optimizer",
".",
"context_manager",
"=",
"ContextManager",
"(",... | 59.684211 | 0.011285 |
def get_platform():
"""Get the current platform data.
Returns a dictionary with keys: `os_name`, `os_bits`
"""
platform_data = {
'os_name': None,
'os_bits': None
}
os_name = platform.system()
normalize_os = {
'Windows': 'windows',
'Linux': 'linux',
'Da... | [
"def",
"get_platform",
"(",
")",
":",
"platform_data",
"=",
"{",
"'os_name'",
":",
"None",
",",
"'os_bits'",
":",
"None",
"}",
"os_name",
"=",
"platform",
".",
"system",
"(",
")",
"normalize_os",
"=",
"{",
"'Windows'",
":",
"'windows'",
",",
"'Linux'",
"... | 30.642857 | 0.00113 |
def run(command, parser, args, unknown_args):
""" run command """
# get the command for detailed help
command_help = args['help-command']
# if no command is provided, just print main help
if command_help == 'help':
parser.print_help()
return True
# get the subparser for the specific command
subp... | [
"def",
"run",
"(",
"command",
",",
"parser",
",",
"args",
",",
"unknown_args",
")",
":",
"# get the command for detailed help",
"command_help",
"=",
"args",
"[",
"'help-command'",
"]",
"# if no command is provided, just print main help",
"if",
"command_help",
"==",
"'he... | 27.944444 | 0.019231 |
def upgrade():
"""Upgrade database."""
op.create_table(
'communities_community',
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('updated', sa.DateTime(), nullable=False),
sa.Column('id', sa.String(length=100), nullable=False),
sa.Column('id_user', sa.Integ... | [
"def",
"upgrade",
"(",
")",
":",
"op",
".",
"create_table",
"(",
"'communities_community'",
",",
"sa",
".",
"Column",
"(",
"'created'",
",",
"sa",
".",
"DateTime",
"(",
")",
",",
"nullable",
"=",
"False",
")",
",",
"sa",
".",
"Column",
"(",
"'updated'"... | 48.92 | 0.000401 |
def run_gmsh(self):
"""
Makes the mesh using gmsh.
"""
argiope.utils.run_gmsh(gmsh_path = self.gmsh_path,
gmsh_space = self.gmsh_space,
gmsh_options = self.gmsh_options,
name = self.file_name + ".geo",
... | [
"def",
"run_gmsh",
"(",
"self",
")",
":",
"argiope",
".",
"utils",
".",
"run_gmsh",
"(",
"gmsh_path",
"=",
"self",
".",
"gmsh_path",
",",
"gmsh_space",
"=",
"self",
".",
"gmsh_space",
",",
"gmsh_options",
"=",
"self",
".",
"gmsh_options",
",",
"name",
"=... | 42 | 0.027972 |
def is_connectable(host: str, port: Union[int, str]) -> bool:
"""Tries to connect to the device to see if it is connectable.
Args:
host: The host to connect.
port: The port to connect.
Returns:
True or False.
"""
socket_ = None
try:
socket_ = socket.create_conne... | [
"def",
"is_connectable",
"(",
"host",
":",
"str",
",",
"port",
":",
"Union",
"[",
"int",
",",
"str",
"]",
")",
"->",
"bool",
":",
"socket_",
"=",
"None",
"try",
":",
"socket_",
"=",
"socket",
".",
"create_connection",
"(",
"(",
"host",
",",
"port",
... | 23.7 | 0.002028 |
def sqlupdate(table, rowupdate, where):
"""Generates SQL update table set ...
Returns (sql, parameters)
>>> sqlupdate('mytable', {'field1': 3, 'field2': 'hello'}, {'id': 5})
('update mytable set field1=%s, field2=%s where id=%s', [3, 'hello', 5])
"""
validate_name(table)
fields = sorted(row... | [
"def",
"sqlupdate",
"(",
"table",
",",
"rowupdate",
",",
"where",
")",
":",
"validate_name",
"(",
"table",
")",
"fields",
"=",
"sorted",
"(",
"rowupdate",
".",
"keys",
"(",
")",
")",
"validate_names",
"(",
"fields",
")",
"values",
"=",
"[",
"rowupdate",
... | 38.222222 | 0.001418 |
def with_lock(lock):
"""Make sure the lock is held while in this function."""
def decorator(func):
@functools.wraps(func)
def _with_lock(*args, **kwargs):
with lock:
return func(*args, **kwargs)
return _with_lock
return decorator | [
"def",
"with_lock",
"(",
"lock",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"_with_lock",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"lock",
":",
"return",
"func",... | 28.111111 | 0.019157 |
def _encrypt(cipher, key, data, iv, padding):
"""
Encrypts plaintext
:param cipher:
A unicode string of "aes128", "aes192", "aes256", "des",
"tripledes_2key", "tripledes_3key", "rc2", "rc4"
:param key:
The encryption key - a byte string 5-32 bytes long
:param data:
... | [
"def",
"_encrypt",
"(",
"cipher",
",",
"key",
",",
"data",
",",
"iv",
",",
"padding",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"byte_cls",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n key must be a byte string, not... | 29.555556 | 0.002122 |
def wvalue(wave, indep_var):
r"""
Return the dependent variable value at a given independent variable point.
If the independent variable point is not in the independent variable vector
the dependent variable value is obtained by linear interpolation
:param wave: Waveform
:type wave: :py:class... | [
"def",
"wvalue",
"(",
"wave",
",",
"indep_var",
")",
":",
"close_min",
"=",
"np",
".",
"isclose",
"(",
"indep_var",
",",
"wave",
".",
"_indep_vector",
"[",
"0",
"]",
",",
"FP_RTOL",
",",
"FP_ATOL",
")",
"close_max",
"=",
"np",
".",
"isclose",
"(",
"i... | 36.040816 | 0.001103 |
def _invert(self, pos):
"""Flip bit at pos 1<->0."""
assert 0 <= pos < self.len
self._datastore.invertbit(pos) | [
"def",
"_invert",
"(",
"self",
",",
"pos",
")",
":",
"assert",
"0",
"<=",
"pos",
"<",
"self",
".",
"len",
"self",
".",
"_datastore",
".",
"invertbit",
"(",
"pos",
")"
] | 32.75 | 0.014925 |
def remove_from_context(self, name, *args):
"""Remove attributes from a context.
"""
context = self.get_context(name=name)
attrs_ = context['context']
for a in args:
del attrs_[a] | [
"def",
"remove_from_context",
"(",
"self",
",",
"name",
",",
"*",
"args",
")",
":",
"context",
"=",
"self",
".",
"get_context",
"(",
"name",
"=",
"name",
")",
"attrs_",
"=",
"context",
"[",
"'context'",
"]",
"for",
"a",
"in",
"args",
":",
"del",
"att... | 32.142857 | 0.008658 |
def luminosities_of_galaxies_within_ellipses_in_units(self, major_axis : dim.Length, unit_luminosity='eps',
exposure_time=None):
"""
Compute the total luminosity of all galaxies in this plane within a ellipse of specified major-axis.
The... | [
"def",
"luminosities_of_galaxies_within_ellipses_in_units",
"(",
"self",
",",
"major_axis",
":",
"dim",
".",
"Length",
",",
"unit_luminosity",
"=",
"'eps'",
",",
"exposure_time",
"=",
"None",
")",
":",
"return",
"list",
"(",
"map",
"(",
"lambda",
"galaxy",
":",
... | 51.708333 | 0.008703 |
def set(self, key, value):
"""Set value at key and return a Future
:rtype: tornado.concurrent.Future
"""
return DatastoreLegacy.store[self.domain].set(key, value) | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"DatastoreLegacy",
".",
"store",
"[",
"self",
".",
"domain",
"]",
".",
"set",
"(",
"key",
",",
"value",
")"
] | 31.666667 | 0.010256 |
def start(self, name):
"""Start a service
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Starting service: %s...', name)
init.start() | [
"def",
"start",
"(",
"self",
",",
"name",
")",
":",
"init",
"=",
"self",
".",
"_get_implementation",
"(",
"name",
")",
"self",
".",
"_assert_service_installed",
"(",
"init",
",",
"name",
")",
"logger",
".",
"info",
"(",
"'Starting service: %s...'",
",",
"n... | 32.285714 | 0.008621 |
def build_sha1(self):
"""
get sha1 hash of build.
:return: build sha1 or None if not found
"""
# pylint: disable=len-as-condition
if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None):
return self.dutinformation.get(0).build.sha1
... | [
"def",
"build_sha1",
"(",
"self",
")",
":",
"# pylint: disable=len-as-condition",
"if",
"len",
"(",
"self",
".",
"dutinformation",
")",
">",
"0",
"and",
"(",
"self",
".",
"dutinformation",
".",
"get",
"(",
"0",
")",
".",
"build",
"is",
"not",
"None",
")"... | 33 | 0.00885 |
def cmd(*args, **kwargs):
"""Decorate a callable to replace it with a manufactured command
class.
Extends the interface of ``CommandDecorator``, allowing the same
``cmd`` to be used as a decorator or as a decorator factory::
@cmd(root=True)
def build():
...
@build.... | [
"def",
"cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"(",
"first",
",",
"*",
"remainder",
")",
"=",
"args",
"except",
"ValueError",
":",
"pass",
"else",
":",
"if",
"callable",
"(",
"first",
")",
":",
"return",
"CommandDeco... | 23.517241 | 0.001408 |
def pgcd(numa, numb):
"""
Calculate the greatest common divisor (GCD) of two numbers.
:param numa: First number
:type numa: number
:param numb: Second number
:type numb: number
:rtype: number
For example:
>>> import pmisc, fractions
>>> pmisc.pgcd(10, 15)
5... | [
"def",
"pgcd",
"(",
"numa",
",",
"numb",
")",
":",
"# Test for integers this way to be valid also for Numpy data types without",
"# actually importing (and package depending on) Numpy",
"int_args",
"=",
"(",
"int",
"(",
"numa",
")",
"==",
"numa",
")",
"and",
"(",
"int",
... | 30.773585 | 0.000594 |
def ParseOptions(cls, options, output_module):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (TimesketchOutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadCo... | [
"def",
"ParseOptions",
"(",
"cls",
",",
"options",
",",
"output_module",
")",
":",
"if",
"not",
"isinstance",
"(",
"output_module",
",",
"timesketch_out",
".",
"TimesketchOutputModule",
")",
":",
"raise",
"errors",
".",
"BadConfigObject",
"(",
"'Output module is n... | 38.647059 | 0.001485 |
def import_ecdsa_publickey_from_file(filepath):
"""
<Purpose>
Load the ECDSA public key object (conformant to
'securesystemslib.formats.KEY_SCHEMA') stored in 'filepath'. Return
'filepath' in securesystemslib.formats.ECDSAKEY_SCHEMA format.
If the key object in 'filepath' contains a private key, i... | [
"def",
"import_ecdsa_publickey_from_file",
"(",
"filepath",
")",
":",
"# Does 'filepath' have the correct format?",
"# Ensure the arguments have the appropriate number of objects and object",
"# types, and that all dict keys are properly named.",
"# Raise 'securesystemslib.exceptions.FormatError' ... | 38.130435 | 0.010561 |
def rewind(self, new_state):
"""
Rewind can be used as an exceptional way to roll back the state of a
:class:`OrderedStateMachine`.
Rewinding is not the usual use case for an
:class:`OrderedStateMachine`. Usually, if the current state `A` is
greater than any given state ... | [
"def",
"rewind",
"(",
"self",
",",
"new_state",
")",
":",
"if",
"new_state",
">",
"self",
".",
"_state",
":",
"raise",
"ValueError",
"(",
"\"cannot forward using rewind \"",
"\"({} > {})\"",
".",
"format",
"(",
"new_state",
",",
"self",
".",
"_state",
")",
"... | 48.105263 | 0.002146 |
def convert2(self, imtls, sids):
"""
Convert a probability map into a composite array of shape (N,)
and dtype `imtls.dt`.
:param imtls:
DictArray instance
:param sids:
the IDs of the sites we are interested in
:returns:
an array of cur... | [
"def",
"convert2",
"(",
"self",
",",
"imtls",
",",
"sids",
")",
":",
"assert",
"self",
".",
"shape_z",
"==",
"1",
",",
"self",
".",
"shape_z",
"curves",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"sids",
")",
",",
"imtls",
".",
"dt",
")",
"for"... | 33.666667 | 0.002407 |
def color_print(*args, **kwargs):
"""
Prints colors and styles to the terminal uses ANSI escape
sequences.
::
color_print('This is the color ', 'default', 'GREEN', 'green')
Parameters
----------
positional args : str
The positional arguments come in pairs (*msg*, *color*), ... | [
"def",
"color_print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"file",
"=",
"kwargs",
".",
"get",
"(",
"'file'",
",",
"_get_stdout",
"(",
")",
")",
"end",
"=",
"kwargs",
".",
"get",
"(",
"'end'",
",",
"'\\n'",
")",
"write",
"=",
"file... | 33.863636 | 0.000435 |
def headers_to_dict(headers):
"""
Converts a sequence of (name, value) tuples into a dict where if
a given name occurs more than once its value in the dict will be
a list of values.
"""
hdrs = {}
for h, v in headers:
h = h.lower()
if h in hdrs:
if isinstance(hdrs[... | [
"def",
"headers_to_dict",
"(",
"headers",
")",
":",
"hdrs",
"=",
"{",
"}",
"for",
"h",
",",
"v",
"in",
"headers",
":",
"h",
"=",
"h",
".",
"lower",
"(",
")",
"if",
"h",
"in",
"hdrs",
":",
"if",
"isinstance",
"(",
"hdrs",
"[",
"h",
"]",
",",
"... | 27 | 0.002105 |
def __create_and_save_state(cls, job_config, mapreduce_spec):
"""Save map job state to datastore.
Save state to datastore so that UI can see it immediately.
Args:
job_config: map_job.JobConfig.
mapreduce_spec: model.MapreduceSpec.
Returns:
model.MapreduceState for this job.
"""
... | [
"def",
"__create_and_save_state",
"(",
"cls",
",",
"job_config",
",",
"mapreduce_spec",
")",
":",
"state",
"=",
"model",
".",
"MapreduceState",
".",
"create_new",
"(",
"job_config",
".",
"job_id",
")",
"state",
".",
"mapreduce_spec",
"=",
"mapreduce_spec",
"stat... | 30.9 | 0.00157 |
def wavefunction_payload(quil_program, random_seed):
"""REST payload for :py:func:`ForestConnection._wavefunction`"""
if not isinstance(quil_program, Program):
raise TypeError("quil_program must be a Quil program object")
payload = {'type': TYPE_WAVEFUNCTION,
'compiled-quil': quil_pr... | [
"def",
"wavefunction_payload",
"(",
"quil_program",
",",
"random_seed",
")",
":",
"if",
"not",
"isinstance",
"(",
"quil_program",
",",
"Program",
")",
":",
"raise",
"TypeError",
"(",
"\"quil_program must be a Quil program object\"",
")",
"payload",
"=",
"{",
"'type'... | 34.666667 | 0.002342 |
def validate_v3_endpoint_data(self, endpoints, admin_port, internal_port,
public_port, expected, expected_num_eps=3):
"""Validate keystone v3 endpoint data.
Validate the v3 endpoint data which has changed from v2. The
ports are used to find the matching endpoi... | [
"def",
"validate_v3_endpoint_data",
"(",
"self",
",",
"endpoints",
",",
"admin_port",
",",
"internal_port",
",",
"public_port",
",",
"expected",
",",
"expected_num_eps",
"=",
"3",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Validating v3 endpoint data...'",... | 45.44898 | 0.001319 |
def call(self, method = '', params = None) :
""" Call T411 API """
# authentification request
if method == 'auth' :
req = requests.post(API_URL % method, data=params)
# download torrent request
elif 'download' in method:
torrentid = os.path.basen... | [
"def",
"call",
"(",
"self",
",",
"method",
"=",
"''",
",",
"params",
"=",
"None",
")",
":",
"# authentification request",
"if",
"method",
"==",
"'auth'",
":",
"req",
"=",
"requests",
".",
"post",
"(",
"API_URL",
"%",
"method",
",",
"data",
"=",
"params... | 47.631579 | 0.013713 |
def request(self, path_segment, method="GET", headers=None, body="",
owner=None, app=None, sharing=None):
"""Issues an arbitrary HTTP request to the REST path segment.
This method is named to match ``httplib.request``. This function
makes a single round trip to the server.
... | [
"def",
"request",
"(",
"self",
",",
"path_segment",
",",
"method",
"=",
"\"GET\"",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"\"\"",
",",
"owner",
"=",
"None",
",",
"app",
"=",
"None",
",",
"sharing",
"=",
"None",
")",
":",
"if",
"headers",
"i... | 46.573529 | 0.002165 |
def pydoc_cli_monkey_patched(port):
"""In Python 3, run pydoc.cli with builtins.input monkey-patched
so that pydoc can be run as a process.
"""
# Monkey-patch input so that input does not raise EOFError when
# called by pydoc.cli
def input(_): # pylint: disable=W0622
"""Monkey-patched ... | [
"def",
"pydoc_cli_monkey_patched",
"(",
"port",
")",
":",
"# Monkey-patch input so that input does not raise EOFError when",
"# called by pydoc.cli",
"def",
"input",
"(",
"_",
")",
":",
"# pylint: disable=W0622",
"\"\"\"Monkey-patched version of builtins.input\"\"\"",
"while",
"1",... | 29.4375 | 0.002058 |
def GetPixelColorsVertically(self, x: int, y: int, count: int) -> ctypes.Array:
"""
x: int.
y: int.
count: int.
Return `ctypes.Array`, an iterable array of int values in argb form point x,y vertically.
"""
arrayType = ctypes.c_uint32 * count
values = array... | [
"def",
"GetPixelColorsVertically",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"count",
":",
"int",
")",
"->",
"ctypes",
".",
"Array",
":",
"arrayType",
"=",
"ctypes",
".",
"c_uint32",
"*",
"count",
"values",
"=",
"arrayType",
"(",
... | 40.909091 | 0.008696 |
def from_dict(data, ctx):
"""
Instantiate a new Price from a dict (generally from loading a JSON
response). The data used to instantiate the Price is a shallow copy of
the dict passed in, with any complex child types instantiated
appropriately.
"""
data = data.co... | [
"def",
"from_dict",
"(",
"data",
",",
"ctx",
")",
":",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"if",
"data",
".",
"get",
"(",
"'baseBid'",
")",
"is",
"not",
"None",
":",
"data",
"[",
"'baseBid'",
"]",
"=",
"ctx",
".",
"convert_decimal_number",
... | 30.976744 | 0.001456 |
def check_bitdepth_rescale(
palette, bitdepth, transparent, alpha, greyscale):
"""
Returns (bitdepth, rescale) pair.
"""
if palette:
if len(bitdepth) != 1:
raise ProtocolError(
"with palette, only a single bitdepth may be used")
(bitdepth, ) = bitdept... | [
"def",
"check_bitdepth_rescale",
"(",
"palette",
",",
"bitdepth",
",",
"transparent",
",",
"alpha",
",",
"greyscale",
")",
":",
"if",
"palette",
":",
"if",
"len",
"(",
"bitdepth",
")",
"!=",
"1",
":",
"raise",
"ProtocolError",
"(",
"\"with palette, only a sing... | 31.854167 | 0.000635 |
def add_block_options(self, top):
"""
Return a list of URLs and titles for blocks which can be added to this column.
All available blocks are grouped by block category.
"""
from .blockadmin import blocks
block_choices = []
# Group all block by category
... | [
"def",
"add_block_options",
"(",
"self",
",",
"top",
")",
":",
"from",
".",
"blockadmin",
"import",
"blocks",
"block_choices",
"=",
"[",
"]",
"# Group all block by category",
"for",
"category",
"in",
"sorted",
"(",
"blocks",
".",
"site",
".",
"block_list",
")"... | 36.029412 | 0.002385 |
def retrieve_mail_attachments(self,
name,
mail_folder='INBOX',
check_regex=False,
latest_only=False,
not_found_mode='raise'):
"""
Retr... | [
"def",
"retrieve_mail_attachments",
"(",
"self",
",",
"name",
",",
"mail_folder",
"=",
"'INBOX'",
",",
"check_regex",
"=",
"False",
",",
"latest_only",
"=",
"False",
",",
"not_found_mode",
"=",
"'raise'",
")",
":",
"mail_attachments",
"=",
"self",
".",
"_retri... | 51.8 | 0.008121 |
def partition_by_vid(self, ref):
"""A much faster way to get partitions, by vid only"""
from ambry.orm import Partition
p = self.session.query(Partition).filter(Partition.vid == str(ref)).first()
if p:
return self.wrap_partition(p)
else:
return None | [
"def",
"partition_by_vid",
"(",
"self",
",",
"ref",
")",
":",
"from",
"ambry",
".",
"orm",
"import",
"Partition",
"p",
"=",
"self",
".",
"session",
".",
"query",
"(",
"Partition",
")",
".",
"filter",
"(",
"Partition",
".",
"vid",
"==",
"str",
"(",
"r... | 34 | 0.009554 |
def f_theta(cos_theta, zint, z, n2n1=0.95, sph6_ab=None, **kwargs):
"""
Returns the wavefront aberration for an aberrated, defocused lens.
Calculates the portions of the wavefront distortion due to z, theta
only, for a lens with defocus and spherical aberration induced by
coverslip mismatch. (The r... | [
"def",
"f_theta",
"(",
"cos_theta",
",",
"zint",
",",
"z",
",",
"n2n1",
"=",
"0.95",
",",
"sph6_ab",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"wvfront",
"=",
"(",
"np",
".",
"outer",
"(",
"np",
".",
"ones_like",
"(",
"z",
")",
"*",
"zint... | 41.146341 | 0.001737 |
def list_queues(self, prefix=None, num_results=None, include_metadata=False,
marker=None, timeout=None):
'''
Returns a generator to list the queues. The generator will lazily follow
the continuation tokens returned by the service and stop when all queues
have been r... | [
"def",
"list_queues",
"(",
"self",
",",
"prefix",
"=",
"None",
",",
"num_results",
"=",
"None",
",",
"include_metadata",
"=",
"False",
",",
"marker",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"include",
"=",
"'metadata'",
"if",
"include_metadata"... | 53.72973 | 0.01087 |
def Serialize(self, writer):
"""
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
"""
super(StorageItem, self).Serialize(writer)
writer.WriteVarBytes(self.Value) | [
"def",
"Serialize",
"(",
"self",
",",
"writer",
")",
":",
"super",
"(",
"StorageItem",
",",
"self",
")",
".",
"Serialize",
"(",
"writer",
")",
"writer",
".",
"WriteVarBytes",
"(",
"self",
".",
"Value",
")"
] | 24.888889 | 0.008621 |
def save_graph(self, fname, style='flat', format='png', **kwargs): # @ReservedAssignment @IgnorePep8
"""
Saves a graph of the pipeline to file
Parameters
----------
fname : str
The filename for the saved graph
style : str
The style of the graph, ... | [
"def",
"save_graph",
"(",
"self",
",",
"fname",
",",
"style",
"=",
"'flat'",
",",
"format",
"=",
"'png'",
",",
"*",
"*",
"kwargs",
")",
":",
"# @ReservedAssignment @IgnorePep8",
"fname",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"fname",
")",
"if",... | 36.212121 | 0.002445 |
def next(self):
"""Next point in iteration
"""
if self.count < len(self.reservoir):
self.count += 1
return self.reservoir[self.count-1]
raise StopIteration("Reservoir exhausted") | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"count",
"<",
"len",
"(",
"self",
".",
"reservoir",
")",
":",
"self",
".",
"count",
"+=",
"1",
"return",
"self",
".",
"reservoir",
"[",
"self",
".",
"count",
"-",
"1",
"]",
"raise",
"StopIt... | 28.5 | 0.008511 |
def add_arguments(parser, default_level=logging.INFO):
"""
Add arguments to an ArgumentParser or OptionParser for purposes of
grabbing a logging level.
"""
adder = (
getattr(parser, 'add_argument', None)
or getattr(parser, 'add_option')
)
adder(
'-l', '--log-level', default=default_level, type=lo... | [
"def",
"add_arguments",
"(",
"parser",
",",
"default_level",
"=",
"logging",
".",
"INFO",
")",
":",
"adder",
"=",
"(",
"getattr",
"(",
"parser",
",",
"'add_argument'",
",",
"None",
")",
"or",
"getattr",
"(",
"parser",
",",
"'add_option'",
")",
")",
"adde... | 31 | 0.031332 |
def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str:
""" Handles the requirements in the target repository, returns a path to a executable of the virtualenv.
"""
return str(self.get_or_create_venv(repo_path).resolve() / "bin" / "python") | [
"def",
"get_or_create_environment",
"(",
"self",
",",
"repo",
":",
"str",
",",
"branch",
":",
"str",
",",
"git_repo",
":",
"Repo",
",",
"repo_path",
":",
"Path",
")",
"->",
"str",
":",
"return",
"str",
"(",
"self",
".",
"get_or_create_venv",
"(",
"repo_p... | 76.5 | 0.016181 |
def translate(conic, vector):
"""
Translates a conic by a vector
"""
# Translation matrix
T = N.identity(len(conic))
T[:-1,-1] = -vector
return conic.transform(T) | [
"def",
"translate",
"(",
"conic",
",",
"vector",
")",
":",
"# Translation matrix",
"T",
"=",
"N",
".",
"identity",
"(",
"len",
"(",
"conic",
")",
")",
"T",
"[",
":",
"-",
"1",
",",
"-",
"1",
"]",
"=",
"-",
"vector",
"return",
"conic",
".",
"trans... | 26.375 | 0.013761 |
def histogram(self, number_concentration=True):
"""Read and reset the histogram. As of v1.3.0, histogram
values are reported in particle number concentration (#/cc) by default.
:param number_concentration: If true, histogram bins are reported in number concentration vs. raw values.
:ty... | [
"def",
"histogram",
"(",
"self",
",",
"number_concentration",
"=",
"True",
")",
":",
"resp",
"=",
"[",
"]",
"data",
"=",
"{",
"}",
"# Send the command byte",
"self",
".",
"cnxn",
".",
"xfer",
"(",
"[",
"0x30",
"]",
")",
"# Wait 10 ms",
"sleep",
"(",
"1... | 43.057554 | 0.011106 |
def batch_list(sequence, batch_size, mod = 0, randomize = False):
'''
Converts a list into a list of lists with equal batch_size.
Parameters
----------
sequence : list
list of items to be placed in batches
batch_size : int
length of each sub list
mod : int
remainder ... | [
"def",
"batch_list",
"(",
"sequence",
",",
"batch_size",
",",
"mod",
"=",
"0",
",",
"randomize",
"=",
"False",
")",
":",
"if",
"randomize",
":",
"sequence",
"=",
"random",
".",
"sample",
"(",
"sequence",
",",
"len",
"(",
"sequence",
")",
")",
"return",... | 29.5 | 0.010448 |
def _propagate_glyph_anchors(self, ufo, parent, processed):
"""Propagate anchors for a single parent glyph."""
if parent.name in processed:
return
processed.add(parent.name)
base_components = []
mark_components = []
anchor_names = set()
to_add = {}
for component in parent.compo... | [
"def",
"_propagate_glyph_anchors",
"(",
"self",
",",
"ufo",
",",
"parent",
",",
"processed",
")",
":",
"if",
"parent",
".",
"name",
"in",
"processed",
":",
"return",
"processed",
".",
"add",
"(",
"parent",
".",
"name",
")",
"base_components",
"=",
"[",
"... | 37.926829 | 0.001254 |
def vimeo_download_by_channel(url, output_dir='.', merge=False, info_only=False, **kwargs):
"""str->None"""
# https://vimeo.com/channels/464686
channel_id = match1(url, r'http://vimeo.com/channels/(\w+)')
vimeo_download_by_channel_id(channel_id, output_dir, merge, info_only, **kwargs) | [
"def",
"vimeo_download_by_channel",
"(",
"url",
",",
"output_dir",
"=",
"'.'",
",",
"merge",
"=",
"False",
",",
"info_only",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# https://vimeo.com/channels/464686",
"channel_id",
"=",
"match1",
"(",
"url",
",",
... | 59.4 | 0.009967 |
def guess_bytes(bstring):
"""
NOTE: Using `guess_bytes` is not the recommended way of using ftfy. ftfy
is not designed to be an encoding detector.
In the unfortunate situation that you have some bytes in an unknown
encoding, ftfy can guess a reasonable strategy for decoding them, by trying
a fe... | [
"def",
"guess_bytes",
"(",
"bstring",
")",
":",
"if",
"isinstance",
"(",
"bstring",
",",
"str",
")",
":",
"raise",
"UnicodeError",
"(",
"\"This string was already decoded as Unicode. You should pass \"",
"\"bytes to guess_bytes, not Unicode.\"",
")",
"if",
"bstring",
".",... | 46.564103 | 0.00027 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.