text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def fit(self, **kwargs):
"""Call the fit method of the primitive.
The given keyword arguments will be passed directly to the `fit`
method of the primitive instance specified in the JSON annotation.
If any of the arguments expected by the produce method had been
given during the... | [
"def",
"fit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"fit_method",
"is",
"not",
"None",
":",
"fit_args",
"=",
"self",
".",
"_fit_params",
".",
"copy",
"(",
")",
"fit_args",
".",
"update",
"(",
"kwargs",
")",
"getattr",
"... | 41.166667 | 0.001978 |
def evalMetricFromSamples(self, q_samples, grad_samples=None, method=None):
'''Evaluates the horsetail matching metric from given samples of the quantity
of interest and gradient instead of evaluating them at a design.
:param np.ndarray q_samples: samples of the quantity of interest,
... | [
"def",
"evalMetricFromSamples",
"(",
"self",
",",
"q_samples",
",",
"grad_samples",
"=",
"None",
",",
"method",
"=",
"None",
")",
":",
"# Make sure dimensions are correct",
"# u_sample_dimensions = self._processDimensions()",
"q_samples",
"=",
"np",
".",
"array",
... | 40.315789 | 0.001912 |
def get_data(self) -> bytes:
"""Return a compressed datablob representing this object.
To restore the object, use :func:`fints.client.NeedRetryResponse.from_data`.
"""
data = {
"_class_name": self.__class__.__name__,
"version": 1,
"segments_bi... | [
"def",
"get_data",
"(",
"self",
")",
"->",
"bytes",
":",
"data",
"=",
"{",
"\"_class_name\"",
":",
"self",
".",
"__class__",
".",
"__name__",
",",
"\"version\"",
":",
"1",
",",
"\"segments_bin\"",
":",
"SegmentSequence",
"(",
"[",
"self",
".",
"command_seg... | 44 | 0.008562 |
def paintEvent(self, event):
"""Override Qt method.
Paint breakpoints icons.
"""
super(DebuggerPanel, self).paintEvent(event)
painter = QPainter(self)
painter.fillRect(event.rect(), self.editor.sideareas_color)
for top, line_number, block in self.editor.visible_... | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"DebuggerPanel",
",",
"self",
")",
".",
"paintEvent",
"(",
"event",
")",
"painter",
"=",
"QPainter",
"(",
"self",
")",
"painter",
".",
"fillRect",
"(",
"event",
".",
"rect",
"(",
... | 38.869565 | 0.002183 |
def new_board(self, name):
"""Make a board for a character name, and switch to it."""
char = self.engine.character[name]
board = Board(character=char)
self.mainscreen.boards[name] = board
self.character = char | [
"def",
"new_board",
"(",
"self",
",",
"name",
")",
":",
"char",
"=",
"self",
".",
"engine",
".",
"character",
"[",
"name",
"]",
"board",
"=",
"Board",
"(",
"character",
"=",
"char",
")",
"self",
".",
"mainscreen",
".",
"boards",
"[",
"name",
"]",
"... | 40.666667 | 0.008032 |
def _insert_data(self, name, value, timestamp, interval, config, **kwargs):
'''Helper to insert data into sql.'''
conn = self._client.connect()
if not self._update_data(name, value, timestamp, interval, config, conn):
try:
kwargs = {
'name' : name,
'interval' : in... | [
"def",
"_insert_data",
"(",
"self",
",",
"name",
",",
"value",
",",
"timestamp",
",",
"interval",
",",
"config",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"self",
".",
"_client",
".",
"connect",
"(",
")",
"if",
"not",
"self",
".",
"_update_data... | 39.947368 | 0.014157 |
def uriref_startswith_iriref(v1: URIRef, v2: Union[str, ShExJ.IRIREF]) -> bool:
""" Determine whether a :py:class:`rdflib.URIRef` value starts with the text of a :py:class:`ShExJ.IRIREF` value """
return str(v1).startswith(str(v2)) | [
"def",
"uriref_startswith_iriref",
"(",
"v1",
":",
"URIRef",
",",
"v2",
":",
"Union",
"[",
"str",
",",
"ShExJ",
".",
"IRIREF",
"]",
")",
"->",
"bool",
":",
"return",
"str",
"(",
"v1",
")",
".",
"startswith",
"(",
"str",
"(",
"v2",
")",
")"
] | 79 | 0.008368 |
def gradients(ys, xs, grad_ys=None):
"""Compute gradients in dtf.
Args:
ys: a list of Tensors
xs: a list of Tensors
grad_ys: an optional list of Tensors
Returns:
grad_xs: a list of Tensors
"""
graph = ys[0].graph
if not grad_ys:
grad_ys = [Constant(y.mesh, 1.0, y.shape, y.dtype).output... | [
"def",
"gradients",
"(",
"ys",
",",
"xs",
",",
"grad_ys",
"=",
"None",
")",
":",
"graph",
"=",
"ys",
"[",
"0",
"]",
".",
"graph",
"if",
"not",
"grad_ys",
":",
"grad_ys",
"=",
"[",
"Constant",
"(",
"y",
".",
"mesh",
",",
"1.0",
",",
"y",
".",
... | 35 | 0.012637 |
def to_json(self, variables=None):
"""Render the blueprint and return the template in json form.
Args:
variables (dict):
Optional dictionary providing/overriding variable values.
Returns:
str: the rendered CFN JSON template
"""
variables... | [
"def",
"to_json",
"(",
"self",
",",
"variables",
"=",
"None",
")",
":",
"variables_to_resolve",
"=",
"[",
"]",
"if",
"variables",
":",
"for",
"key",
",",
"value",
"in",
"variables",
".",
"items",
"(",
")",
":",
"variables_to_resolve",
".",
"append",
"(",... | 39.5 | 0.00206 |
def check_perms(perms, user, slug, raise_exception=False):
"""a helper user to check if a user has the permissions
for a given slug"""
if isinstance(perms, string_types):
perms = {perms}
else:
perms = set(perms)
allowed_users = ACLRule.get_users_for(perms, slug)
if allowed_user... | [
"def",
"check_perms",
"(",
"perms",
",",
"user",
",",
"slug",
",",
"raise_exception",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"perms",
",",
"string_types",
")",
":",
"perms",
"=",
"{",
"perms",
"}",
"else",
":",
"perms",
"=",
"set",
"(",
"pe... | 31.666667 | 0.00227 |
def getFeedContent(self, feed, excludeRead=False, continuation=None, loadLimit=20, since=None, until=None):
"""
Return items for a particular feed
"""
return self._getFeedContent(feed.fetchUrl, excludeRead, continuation, loadLimit, since, until) | [
"def",
"getFeedContent",
"(",
"self",
",",
"feed",
",",
"excludeRead",
"=",
"False",
",",
"continuation",
"=",
"None",
",",
"loadLimit",
"=",
"20",
",",
"since",
"=",
"None",
",",
"until",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getFeedContent",
... | 54.6 | 0.01444 |
def archive_all_alerts(self):
"""Archive all Alerts
"""
js = json.dumps({'cmd': 'archive-all-alarms'})
params = urllib.urlencode({'json': js})
answer = self._read(self.api_url + 'cmd/evtmgr', params) | [
"def",
"archive_all_alerts",
"(",
"self",
")",
":",
"js",
"=",
"json",
".",
"dumps",
"(",
"{",
"'cmd'",
":",
"'archive-all-alarms'",
"}",
")",
"params",
"=",
"urllib",
".",
"urlencode",
"(",
"{",
"'json'",
":",
"js",
"}",
")",
"answer",
"=",
"self",
... | 39 | 0.008368 |
def route(self, dst=None, verbose=conf.verb):
"""Returns the IPv4 routes to a host.
parameters:
- dst: the IPv4 of the destination host
returns: (iface, output_ip, gateway_ip)
- iface: the interface used to connect to the host
- output_ip: the outgoing IP that will be... | [
"def",
"route",
"(",
"self",
",",
"dst",
"=",
"None",
",",
"verbose",
"=",
"conf",
".",
"verb",
")",
":",
"dst",
"=",
"dst",
"or",
"\"0.0.0.0\"",
"# Enable route(None) to return default route",
"if",
"isinstance",
"(",
"dst",
",",
"bytes",
")",
":",
"try",... | 37.45098 | 0.00102 |
def item(*args, **kwargs):
'''
Return one or more grains
CLI Example:
.. code-block:: bash
salt '*' grains.item os
salt '*' grains.item os osrelease oscodename
Sanitized CLI Example:
.. code-block:: bash
salt '*' grains.item host sanitize=True
'''
ret = {}
... | [
"def",
"item",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"arg",
"in",
"args",
":",
"try",
":",
"ret",
"[",
"arg",
"]",
"=",
"__grains__",
"[",
"arg",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"salt",
... | 21.392857 | 0.001597 |
def get_figure(
self, emin=None, emax=None,
width=800, height=400,
margin_left=100, margin_bottom=60, margin_top=30, margin_right=0,
colorbar_size=0.4,
xaxis_label=None, yaxis_label=None,
xaxis_nticks=None, yaxis_nticks=None,
xtick_angl... | [
"def",
"get_figure",
"(",
"self",
",",
"emin",
"=",
"None",
",",
"emax",
"=",
"None",
",",
"width",
"=",
"800",
",",
"height",
"=",
"400",
",",
"margin_left",
"=",
"100",
",",
"margin_bottom",
"=",
"60",
",",
"margin_top",
"=",
"30",
",",
"margin_rig... | 32.93266 | 0.001786 |
def hosting_history(self, query, **kwargs):
"""Returns the hosting history from the given domain name"""
return self._results('hosting-history', '/v1/{0}/hosting-history'.format(query), cls=GroupedIterable, **kwargs) | [
"def",
"hosting_history",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_results",
"(",
"'hosting-history'",
",",
"'/v1/{0}/hosting-history'",
".",
"format",
"(",
"query",
")",
",",
"cls",
"=",
"GroupedIterable",
",",
... | 76.666667 | 0.012931 |
def parse_from_dict(json_dict):
"""
Given a Unified Uploader message, parse the contents and return a
MarketOrderList.
:param dict json_dict: A Unified Uploader message as a JSON dict.
:rtype: MarketOrderList
:returns: An instance of MarketOrderList, containing the orders
within.
""... | [
"def",
"parse_from_dict",
"(",
"json_dict",
")",
":",
"order_columns",
"=",
"json_dict",
"[",
"'columns'",
"]",
"order_list",
"=",
"MarketOrderList",
"(",
"upload_keys",
"=",
"json_dict",
"[",
"'uploadKeys'",
"]",
",",
"order_generator",
"=",
"json_dict",
"[",
"... | 32.567568 | 0.001612 |
def _bsd_stp(br, state, iface):
'''
Internal, sets STP state. On BSD-like, it is required to specify the
STP physical interface
'''
kernel = __grains__['kernel']
if kernel == 'NetBSD':
cmd = _tool_path('brconfig')
else:
cmd = _tool_path('ifconfig')
if not br or not iface... | [
"def",
"_bsd_stp",
"(",
"br",
",",
"state",
",",
"iface",
")",
":",
"kernel",
"=",
"__grains__",
"[",
"'kernel'",
"]",
"if",
"kernel",
"==",
"'NetBSD'",
":",
"cmd",
"=",
"_tool_path",
"(",
"'brconfig'",
")",
"else",
":",
"cmd",
"=",
"_tool_path",
"(",
... | 28.6875 | 0.00211 |
def modification_time(self):
"""dfdatetime.DateTimeValues: modification time or None if not available."""
if self._zip_info is None:
return None
time_elements = getattr(self._zip_info, 'date_time', None)
return dfdatetime_time_elements.TimeElements(time_elements) | [
"def",
"modification_time",
"(",
"self",
")",
":",
"if",
"self",
".",
"_zip_info",
"is",
"None",
":",
"return",
"None",
"time_elements",
"=",
"getattr",
"(",
"self",
".",
"_zip_info",
",",
"'date_time'",
",",
"None",
")",
"return",
"dfdatetime_time_elements",
... | 40 | 0.01049 |
def read(tex):
"""Read and parse all LaTeX source
:param Union[str,iterable] tex: LaTeX source
:return TexEnv: the global environment
"""
if isinstance(tex, str):
tex = tex
else:
tex = ''.join(itertools.chain(*tex))
buf, children = Buffer(tokenize(tex)), []
while buf.has... | [
"def",
"read",
"(",
"tex",
")",
":",
"if",
"isinstance",
"(",
"tex",
",",
"str",
")",
":",
"tex",
"=",
"tex",
"else",
":",
"tex",
"=",
"''",
".",
"join",
"(",
"itertools",
".",
"chain",
"(",
"*",
"tex",
")",
")",
"buf",
",",
"children",
"=",
... | 28.4375 | 0.002128 |
def get(cls, func_hint):
"""Return a registered hash function matching the given hint.
The hint may be a `Func` member, a function name (with hyphens or
underscores), or its code. A `Func` member is returned for standard
multihash functions and an integer code for application-specific ... | [
"def",
"get",
"(",
"cls",
",",
"func_hint",
")",
":",
"# Different possibilities of `func_hint`, most to least probable.",
"try",
":",
"# `Func` member (or its value)",
"return",
"Func",
"(",
"func_hint",
")",
"except",
"ValueError",
":",
"pass",
"if",
"func_hint",
"in"... | 43.24 | 0.00181 |
def fetch_image(self,rtsp_server_uri = _source,timeout_secs = 15):
""" Fetch a single frame using FFMPEG. Convert to PIL Image. Slow. """
self._check_ffmpeg()
cmd = "ffmpeg -rtsp_transport tcp -i {} -loglevel quiet -frames 1 -f image2pipe -".format(rtsp_server_uri)
#stdout = _s... | [
"def",
"fetch_image",
"(",
"self",
",",
"rtsp_server_uri",
"=",
"_source",
",",
"timeout_secs",
"=",
"15",
")",
":",
"self",
".",
"_check_ffmpeg",
"(",
")",
"cmd",
"=",
"\"ffmpeg -rtsp_transport tcp -i {} -loglevel quiet -frames 1 -f image2pipe -\"",
".",
"format",
"(... | 49.266667 | 0.01992 |
def _copy_unidimensional_measurement(
self, phase, name, measurement, mfg_event):
"""Copy uni-dimensional measurements to the MfgEvent."""
mfg_measurement = mfg_event.measurement.add()
# Copy basic measurement fields.
mfg_measurement.name = name
if measurement.docstring:
mfg_measurement... | [
"def",
"_copy_unidimensional_measurement",
"(",
"self",
",",
"phase",
",",
"name",
",",
"measurement",
",",
"mfg_event",
")",
":",
"mfg_measurement",
"=",
"mfg_event",
".",
"measurement",
".",
"add",
"(",
")",
"# Copy basic measurement fields.",
"mfg_measurement",
"... | 42.964286 | 0.008939 |
def chunks(self):
"""
Returns an iterator over all the chunks in the heap.
"""
raise NotImplementedError("%s not implemented for %s" % (self.chunks.__func__.__name__,
self.__class__.__name__)) | [
"def",
"chunks",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"%s not implemented for %s\"",
"%",
"(",
"self",
".",
"chunks",
".",
"__func__",
".",
"__name__",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")"
] | 47.333333 | 0.013841 |
def differentiator(self, A):
"""Differentiate a set of Chebyshev polynomial expansion
coefficients
Originally from http://www.scientificpython.net/pyblog/chebyshev-differentiation
+ (lots of) bug fixing + pythonisation
"""
m = len(A)
SA = (A.T* 2*np.a... | [
"def",
"differentiator",
"(",
"self",
",",
"A",
")",
":",
"m",
"=",
"len",
"(",
"A",
")",
"SA",
"=",
"(",
"A",
".",
"T",
"*",
"2",
"*",
"np",
".",
"arange",
"(",
"m",
")",
")",
".",
"T",
"DA",
"=",
"np",
".",
"zeros_like",
"(",
"A",
")",
... | 34.5 | 0.012694 |
def create_context_menu(self, event, shape):
'''
Parameters
----------
event : gtk.gdk.Event
GTK mouse click event.
shape : str
Electrode shape identifier (e.g., `"electrode028"`).
Returns
-------
gtk.Menu
Context menu.... | [
"def",
"create_context_menu",
"(",
"self",
",",
"event",
",",
"shape",
")",
":",
"routes",
"=",
"self",
".",
"df_routes",
".",
"loc",
"[",
"self",
".",
"df_routes",
".",
"electrode_i",
"==",
"shape",
",",
"'route_i'",
"]",
".",
"astype",
"(",
"int",
")... | 38.028571 | 0.000488 |
def collision_send(self, src, id, action, threat_level, time_to_minimum_delta, altitude_minimum_delta, horizontal_minimum_delta, force_mavlink1=False):
'''
Information about a potential collision
src : Collision data source (uint8_t)
... | [
"def",
"collision_send",
"(",
"self",
",",
"src",
",",
"id",
",",
"action",
",",
"threat_level",
",",
"time_to_minimum_delta",
",",
"altitude_minimum_delta",
",",
"horizontal_minimum_delta",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"... | 82.785714 | 0.008532 |
def type_inherits_of_type(inheriting_type, base_type):
"""Checks whether inheriting_type inherits from base_type
:param str inheriting_type:
:param str base_type:
:return: True is base_type is base of inheriting_type
"""
assert isinstance(inheriting_type, type) or isclass(inheriting_type)
a... | [
"def",
"type_inherits_of_type",
"(",
"inheriting_type",
",",
"base_type",
")",
":",
"assert",
"isinstance",
"(",
"inheriting_type",
",",
"type",
")",
"or",
"isclass",
"(",
"inheriting_type",
")",
"assert",
"isinstance",
"(",
"base_type",
",",
"type",
")",
"or",
... | 36.1875 | 0.001684 |
def read_kw_file():
"""
Read content of the file containing keyword informations in JSON. File is
packed using BZIP.
Returns:
list: List of dictionaries containing keywords.
"""
self_path = os.path.dirname(__file__)
kw_list_path = join(self_path, "../templates/keyword_list.json.bz2"... | [
"def",
"read_kw_file",
"(",
")",
":",
"self_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"kw_list_path",
"=",
"join",
"(",
"self_path",
",",
"\"../templates/keyword_list.json.bz2\"",
")",
"with",
"bz2",
".",
"BZ2File",
"(",
"kw_list_pat... | 27.2 | 0.00237 |
def _find_frame_imports(name, frame):
"""
Detect imports in the frame, with the required
*name*. Such imports can be considered assignments.
Returns True if an import for the given name was found.
"""
imports = frame.nodes_of_class((astroid.Import, astroid.ImportFrom))
for import_node in imp... | [
"def",
"_find_frame_imports",
"(",
"name",
",",
"frame",
")",
":",
"imports",
"=",
"frame",
".",
"nodes_of_class",
"(",
"(",
"astroid",
".",
"Import",
",",
"astroid",
".",
"ImportFrom",
")",
")",
"for",
"import_node",
"in",
"imports",
":",
"for",
"import_n... | 40.117647 | 0.001433 |
def set_backbuffer(self, preferred_backbuffer_size, flags=0):
"""Create the backbuffer for the game."""
if not (isinstance(preferred_backbuffer_size, Vector2)):
raise ValueError("preferred_backbuffer_size must be of type Vector2")
self.__backbuffer = pygame.display.set_mode(preferre... | [
"def",
"set_backbuffer",
"(",
"self",
",",
"preferred_backbuffer_size",
",",
"flags",
"=",
"0",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"preferred_backbuffer_size",
",",
"Vector2",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"preferred_backbuffer_size must... | 58 | 0.009709 |
def find_all(self, seq):
'''
Generator expression. Yields tuples of `(begin, length, value)`,
where:
- `begin` is an integer identifying the character index where
the match begins (0-based)
- `length` is an integer indicating the length of the match (1
or mo... | [
"def",
"find_all",
"(",
"self",
",",
"seq",
")",
":",
"if",
"not",
"self",
".",
"_suffix_links_set",
":",
"self",
".",
"_set_suffix_links",
"(",
")",
"current",
"=",
"self",
".",
"root",
"for",
"pos",
",",
"char",
"in",
"enumerate",
"(",
"seq",
")",
... | 41.606061 | 0.002135 |
def update(self):
"""Gets the latest version of your metadata from the infrastructure and updates your local copy
Returns `True` if successful, `False` otherwise - OR -
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrast... | [
"def",
"update",
"(",
"self",
")",
":",
"graph",
"=",
"Graph",
"(",
")",
"graph",
".",
"parse",
"(",
"data",
"=",
"self",
".",
"__parent",
".",
"get_meta_rdf",
"(",
"fmt",
"=",
"self",
".",
"__fmt",
")",
",",
"format",
"=",
"self",
".",
"__fmt",
... | 47.142857 | 0.008915 |
def formfield(self, **kwargs):
"""
Returns a :class:`PlaceholderFormField` instance for this database Field.
"""
defaults = {
'label': capfirst(self.verbose_name),
'help_text': self.help_text,
'required': not self.blank,
}
defaults.upda... | [
"def",
"formfield",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"defaults",
"=",
"{",
"'label'",
":",
"capfirst",
"(",
"self",
".",
"verbose_name",
")",
",",
"'help_text'",
":",
"self",
".",
"help_text",
",",
"'required'",
":",
"not",
"self",
".",
... | 37 | 0.009592 |
def _decode(self, data, algorithm, key=None):
'''Decode data with specific algorithm'''
if algorithm['type'] == 'hmac':
verify_signature = data[-algorithm['hash_size']:]
data = data[:-algorithm['hash_size']]
signature = self._hmac_generate(data, algorithm, key)
... | [
"def",
"_decode",
"(",
"self",
",",
"data",
",",
"algorithm",
",",
"key",
"=",
"None",
")",
":",
"if",
"algorithm",
"[",
"'type'",
"]",
"==",
"'hmac'",
":",
"verify_signature",
"=",
"data",
"[",
"-",
"algorithm",
"[",
"'hash_size'",
"]",
":",
"]",
"d... | 43.454545 | 0.002047 |
def load(self, filename=None):
"""Method was overriden to set spectrum.filename as well"""
DataFile.load(self, filename)
self.spectrum.filename = filename | [
"def",
"load",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"DataFile",
".",
"load",
"(",
"self",
",",
"filename",
")",
"self",
".",
"spectrum",
".",
"filename",
"=",
"filename"
] | 43.75 | 0.011236 |
def getpcmd(pid):
"""
Returns command of process.
:param pid:
"""
if os.name == "nt":
# Use wmic command instead of ps on Windows.
cmd = 'wmic path win32_process where ProcessID=%s get Commandline 2> nul' % (pid, )
with os.popen(cmd, 'r') as p:
lines = [line for ... | [
"def",
"getpcmd",
"(",
"pid",
")",
":",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"# Use wmic command instead of ps on Windows.",
"cmd",
"=",
"'wmic path win32_process where ProcessID=%s get Commandline 2> nul'",
"%",
"(",
"pid",
",",
")",
"with",
"os",
".",
"po... | 37.680851 | 0.002201 |
def extend_path(path, name):
"""Extend a package's path.
Intended use is to place the following code in a package's __init__.py:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
This will add to the package's __path__ all subdirectories of
directories on 'con... | [
"def",
"extend_path",
"(",
"path",
",",
"name",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"list",
")",
":",
"# This could happen e.g. when this is called from inside a",
"# frozen package. Return the path unchanged in that case.",
"return",
"path",
"pname",
... | 39.104167 | 0.00052 |
def write(self, inputdata):
"""Write to a port on dummy_serial.
Args:
inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response
for subsequent read operations.
Note that for Python2, the inputdata should be a **string**. For Pytho... | [
"def",
"write",
"(",
"self",
",",
"inputdata",
")",
":",
"if",
"VERBOSE",
":",
"_print_out",
"(",
"'\\nDummy_serial: Writing to port. Given:'",
"+",
"repr",
"(",
"inputdata",
")",
"+",
"'\\n'",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2"... | 38.896552 | 0.010381 |
def _hook_write_mem(self, uc, access, address, size, value, data):
"""
Captures memory written by Unicorn
"""
self._mem_delta[address] = (value, size)
return True | [
"def",
"_hook_write_mem",
"(",
"self",
",",
"uc",
",",
"access",
",",
"address",
",",
"size",
",",
"value",
",",
"data",
")",
":",
"self",
".",
"_mem_delta",
"[",
"address",
"]",
"=",
"(",
"value",
",",
"size",
")",
"return",
"True"
] | 32.833333 | 0.009901 |
def add_seqs_to_alignment(seqs_fp, aln_fp, moltype=DNA,
params=None, accurate=False):
"""Returns an Alignment object from seqs and existing Alignment.
The "--seed" option can be used for adding unaligned sequences into
a highly reliable alignment (seed) consisting of a small numbe... | [
"def",
"add_seqs_to_alignment",
"(",
"seqs_fp",
",",
"aln_fp",
",",
"moltype",
"=",
"DNA",
",",
"params",
"=",
"None",
",",
"accurate",
"=",
"False",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"'--seed'",
":",
"aln_fp",
"}",
"else... | 31.888889 | 0.001127 |
def _add_variant_gene_relationship(self, patient_var_map, gene_coordinate_map):
"""
Right now it is unclear the best approach on how to connect
variants to genes. In most cases has_affected_locus/GENO:0000418
is accurate; however, there are cases where a variant is in the intron
... | [
"def",
"_add_variant_gene_relationship",
"(",
"self",
",",
"patient_var_map",
",",
"gene_coordinate_map",
")",
":",
"# genotype = Genotype(self.graph)",
"dipper_util",
"=",
"DipperUtil",
"(",
")",
"model",
"=",
"Model",
"(",
"self",
".",
"graph",
")",
"# Note this cou... | 54.387931 | 0.001557 |
def try_read_file(s):
""" If `s` is a file name, read the file and return it's content.
Otherwise, return the original string.
Returns None if the file was opened, but errored during reading.
"""
try:
with open(s, 'r') as f:
data = f.read()
except FileNotFoundError:
... | [
"def",
"try_read_file",
"(",
"s",
")",
":",
"try",
":",
"with",
"open",
"(",
"s",
",",
"'r'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"except",
"FileNotFoundError",
":",
"# Not a file name.",
"return",
"s",
"except",
"EnvironmentE... | 32.4 | 0.002 |
def publish(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False, udp=False):
'''Send a 1-way message
:param service: the service name (the routing top level)
:type service: anything hash-able
:param int routing_id:
the id used for routing w... | [
"def",
"publish",
"(",
"self",
",",
"service",
",",
"routing_id",
",",
"method",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"broadcast",
"=",
"False",
",",
"udp",
"=",
"False",
")",
":",
"if",
"udp",
":",
"func",
"=",
"self",
".",
... | 44.59375 | 0.002058 |
def abstract_equality_comparison(self, other):
''' returns the result of JS == compare.
result is PyJs type: bool'''
tx, ty = self.TYPE, other.TYPE
if tx == ty:
if tx == 'Undefined' or tx == 'Null':
return true
if tx == 'Number' or tx == 'String... | [
"def",
"abstract_equality_comparison",
"(",
"self",
",",
"other",
")",
":",
"tx",
",",
"ty",
"=",
"self",
".",
"TYPE",
",",
"other",
".",
"TYPE",
"if",
"tx",
"==",
"ty",
":",
"if",
"tx",
"==",
"'Undefined'",
"or",
"tx",
"==",
"'Null'",
":",
"return",... | 50.296296 | 0.001445 |
def get_json_val(source, path, *, ignore_bad_path=False):
"""Get the nested value identified by the json path, rooted at source."""
try:
return JP.find(source, path)
except JP.JSONPathError as ex:
if ignore_bad_path:
return None
else:
raise | [
"def",
"get_json_val",
"(",
"source",
",",
"path",
",",
"*",
",",
"ignore_bad_path",
"=",
"False",
")",
":",
"try",
":",
"return",
"JP",
".",
"find",
"(",
"source",
",",
"path",
")",
"except",
"JP",
".",
"JSONPathError",
"as",
"ex",
":",
"if",
"ignor... | 29.111111 | 0.022222 |
def play_next(self, stream_url=None, offset=0, opaque_token=None):
"""Replace all streams in the queue but does not impact the currently playing stream."""
directive = self._play_directive('REPLACE_ENQUEUED')
directive['audioItem'] = self._audio_item(stream_url=stream_url, offset=offset, opaque... | [
"def",
"play_next",
"(",
"self",
",",
"stream_url",
"=",
"None",
",",
"offset",
"=",
"0",
",",
"opaque_token",
"=",
"None",
")",
":",
"directive",
"=",
"self",
".",
"_play_directive",
"(",
"'REPLACE_ENQUEUED'",
")",
"directive",
"[",
"'audioItem'",
"]",
"=... | 58.428571 | 0.009639 |
def _remove_unexpected_query_parameters(schema, req):
"""Remove unexpected properties from the req.GET."""
additional_properties = schema.get('addtionalProperties', True)
if additional_properties:
pattern_regexes = []
patterns = schema.get('patternProperties', None)
if patterns:
... | [
"def",
"_remove_unexpected_query_parameters",
"(",
"schema",
",",
"req",
")",
":",
"additional_properties",
"=",
"schema",
".",
"get",
"(",
"'addtionalProperties'",
",",
"True",
")",
"if",
"additional_properties",
":",
"pattern_regexes",
"=",
"[",
"]",
"patterns",
... | 38.294118 | 0.001499 |
def get_cert_and_update_domain(
zappa_instance,
lambda_name,
api_stage,
domain=None,
manual=False,
):
"""
Main cert installe... | [
"def",
"get_cert_and_update_domain",
"(",
"zappa_instance",
",",
"lambda_name",
",",
"api_stage",
",",
"domain",
"=",
"None",
",",
"manual",
"=",
"False",
",",
")",
":",
"try",
":",
"create_domain_key",
"(",
")",
"create_domain_csr",
"(",
"domain",
")",
"get_c... | 37.181818 | 0.000794 |
def setspan(self, *args):
"""Sets the span of the span element anew, erases all data inside.
Arguments:
*args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme`
"""
self.data = []
for child in args:
self.append(child) | [
"def",
"setspan",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"data",
"=",
"[",
"]",
"for",
"child",
"in",
"args",
":",
"self",
".",
"append",
"(",
"child",
")"
] | 32.222222 | 0.010067 |
def recheck_limits(self):
"""
Re-check that the cached limits are the current limits.
"""
limit_data = self.control_daemon.get_limits()
try:
# Get the new checksum and list of limits
new_sum, new_limits = limit_data.get_limits(self.limit_sum)
... | [
"def",
"recheck_limits",
"(",
"self",
")",
":",
"limit_data",
"=",
"self",
".",
"control_daemon",
".",
"get_limits",
"(",
")",
"try",
":",
"# Get the new checksum and list of limits",
"new_sum",
",",
"new_limits",
"=",
"limit_data",
".",
"get_limits",
"(",
"self",... | 36.041667 | 0.001125 |
def generate_unicode_table():
"""Generate the Unicode table for the given Python version."""
uver = get_unicodedata()
fail = False
path = os.path.join(os.path.dirname(__file__), 'tools')
fp, pathname, desc = imp.find_module('unipropgen', [path])
try:
unipropgen = imp.load_module('unipro... | [
"def",
"generate_unicode_table",
"(",
")",
":",
"uver",
"=",
"get_unicodedata",
"(",
")",
"fail",
"=",
"False",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'tools'",
")",
"fp",
",",... | 29.782609 | 0.001414 |
def compile(self, model):
"""Compile this file into a SensorGraph.
You must have preivously called parse_file to parse a
sensor graph file into statements that are then executed
by this command to build a sensor graph.
The results are stored in self.sensor_graph and can be
... | [
"def",
"compile",
"(",
"self",
",",
"model",
")",
":",
"log",
"=",
"SensorLog",
"(",
"InMemoryStorageEngine",
"(",
"model",
")",
",",
"model",
")",
"self",
".",
"sensor_graph",
"=",
"SensorGraph",
"(",
"log",
",",
"model",
")",
"allocator",
"=",
"StreamA... | 32.967742 | 0.001901 |
def _K_compute_eq(self):
"""Compute covariance for latent covariance."""
t_eq = self._t[self._index==0]
if self._t2 is None:
if t_eq.size==0:
self._K_eq = np.zeros((0, 0))
return
self._dist2 = np.square(t_eq[:, None] - t_eq[None, :])
... | [
"def",
"_K_compute_eq",
"(",
"self",
")",
":",
"t_eq",
"=",
"self",
".",
"_t",
"[",
"self",
".",
"_index",
"==",
"0",
"]",
"if",
"self",
".",
"_t2",
"is",
"None",
":",
"if",
"t_eq",
".",
"size",
"==",
"0",
":",
"self",
".",
"_K_eq",
"=",
"np",
... | 40.888889 | 0.011952 |
def initialize( self ):
"""
Begins to load the item data for each tree level.
:return <bool> | success
"""
if ( self._initialized ):
return True
self._initialized = True
# load the item's children
model = self.mod... | [
"def",
"initialize",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_initialized",
")",
":",
"return",
"True",
"self",
".",
"_initialized",
"=",
"True",
"# load the item's children",
"model",
"=",
"self",
".",
"model",
"(",
")",
"signalsBlocked",
"=",
"Fa... | 24.958333 | 0.025723 |
def push(self, buf):
""" Push a buffer into the source. """
self._src.emit('push-buffer', Gst.Buffer.new_wrapped(buf)) | [
"def",
"push",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"_src",
".",
"emit",
"(",
"'push-buffer'",
",",
"Gst",
".",
"Buffer",
".",
"new_wrapped",
"(",
"buf",
")",
")"
] | 44 | 0.014925 |
def _fft(x, s_freq, detrend='linear', taper=None, output='spectraldensity',
sides='one', scaling='power', halfbandwidth=4, NW=None, n_fft=None):
"""
Core function taking care of computing the power spectrum / power spectral
density or the complex representation.
Parameters
----------
x... | [
"def",
"_fft",
"(",
"x",
",",
"s_freq",
",",
"detrend",
"=",
"'linear'",
",",
"taper",
"=",
"None",
",",
"output",
"=",
"'spectraldensity'",
",",
"sides",
"=",
"'one'",
",",
"scaling",
"=",
"'power'",
",",
"halfbandwidth",
"=",
"4",
",",
"NW",
"=",
"... | 36.344633 | 0.00121 |
def get_inner_data(dictionary):
"""Gets 2nd-level data into 1st-level dictionary
:param dictionary: dict
:return: with 2nd-level data
"""
out = {}
for key in dictionary.keys():
inner_keys = dictionary[key].keys()
for inner_key in inner_keys:
new_key = key + " " + i... | [
"def",
"get_inner_data",
"(",
"dictionary",
")",
":",
"out",
"=",
"{",
"}",
"for",
"key",
"in",
"dictionary",
".",
"keys",
"(",
")",
":",
"inner_keys",
"=",
"dictionary",
"[",
"key",
"]",
".",
"keys",
"(",
")",
"for",
"inner_key",
"in",
"inner_keys",
... | 24.875 | 0.002421 |
def _iter_decode_generator(input, decoder):
"""Return a generator that first yields the :obj:`Encoding`,
then yields output chukns as Unicode strings.
"""
decode = decoder.decode
input = iter(input)
for chunck in input:
output = decode(chunck)
if output:
assert decod... | [
"def",
"_iter_decode_generator",
"(",
"input",
",",
"decoder",
")",
":",
"decode",
"=",
"decoder",
".",
"decode",
"input",
"=",
"iter",
"(",
"input",
")",
"for",
"chunck",
"in",
"input",
":",
"output",
"=",
"decode",
"(",
"chunck",
")",
"if",
"output",
... | 27.033333 | 0.00119 |
def get_SAM(self,min_intron_size=68):
"""Get a SAM object representation of the alignment.
:returns: SAM representation
:rtype: SAM
"""
from seqtools.format.sam import SAM
#ar is target then query
qname = self.alignment_ranges[0][1].chr
flag = 0
if self.strand == '-': flag = 16
... | [
"def",
"get_SAM",
"(",
"self",
",",
"min_intron_size",
"=",
"68",
")",
":",
"from",
"seqtools",
".",
"format",
".",
"sam",
"import",
"SAM",
"#ar is target then query",
"qname",
"=",
"self",
".",
"alignment_ranges",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"chr... | 31.222222 | 0.015531 |
def max_sliding_window(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not nums:
return nums
queue = collections.deque()
res = []
for num in nums:
if len(queue) < k:
queue.append(num)
else:
res.append(max(queue... | [
"def",
"max_sliding_window",
"(",
"nums",
",",
"k",
")",
":",
"if",
"not",
"nums",
":",
"return",
"nums",
"queue",
"=",
"collections",
".",
"deque",
"(",
")",
"res",
"=",
"[",
"]",
"for",
"num",
"in",
"nums",
":",
"if",
"len",
"(",
"queue",
")",
... | 21.263158 | 0.00237 |
def get_highest_build_tool(sdk_version=None):
"""
Gets the highest build tool version based on major version sdk version.
:param sdk_version(int) - sdk version to be used as the marjor build tool version context.
Returns:
A string containg the build tool version (default is 23.0.2 if none is found)
"""
... | [
"def",
"get_highest_build_tool",
"(",
"sdk_version",
"=",
"None",
")",
":",
"if",
"sdk_version",
"is",
"None",
":",
"sdk_version",
"=",
"config",
".",
"sdk_version",
"android_home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'AG_MOBILE_SDK'",
",",
"os",
".... | 40.277778 | 0.01752 |
def make_hookitem_hookingmodule(hooking_module, condition='contains', negate=False, preserve_case=False):
"""
Create a node for HookItem/HookingModule
:return: A IndicatorItem represented as an Element node
"""
document = 'HookItem'
search = 'HookItem/HookingModule'
content_type = 'stri... | [
"def",
"make_hookitem_hookingmodule",
"(",
"hooking_module",
",",
"condition",
"=",
"'contains'",
",",
"negate",
"=",
"False",
",",
"preserve_case",
"=",
"False",
")",
":",
"document",
"=",
"'HookItem'",
"search",
"=",
"'HookItem/HookingModule'",
"content_type",
"="... | 42.076923 | 0.008945 |
def copy_files_to_folder(files, target_folder, overwrite=True):
"""Copy a list of files to a new target folder.
Returns:
A list of fullpath of the new files.
"""
if not files:
return []
for f in files:
target = os.path.join(target_folder, os.path.split(f)[-1])
if t... | [
"def",
"copy_files_to_folder",
"(",
"files",
",",
"target_folder",
",",
"overwrite",
"=",
"True",
")",
":",
"if",
"not",
"files",
":",
"return",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_folde... | 30.454545 | 0.000964 |
def close(self):
"""Close the channel to the queue."""
self.cancel()
self.backend.close()
self._closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"cancel",
"(",
")",
"self",
".",
"backend",
".",
"close",
"(",
")",
"self",
".",
"_closed",
"=",
"True"
] | 27.4 | 0.014184 |
def standarize( trainingset ):
"""
Morph the input signal to a mean of 0 and scale the signal strength by
dividing with the standard deviation (rather that forcing a [0, 1] range)
"""
def encoder( dataset ):
for instance in dataset:
if np.any(stds == 0):
non... | [
"def",
"standarize",
"(",
"trainingset",
")",
":",
"def",
"encoder",
"(",
"dataset",
")",
":",
"for",
"instance",
"in",
"dataset",
":",
"if",
"np",
".",
"any",
"(",
"stds",
"==",
"0",
")",
":",
"nonzero_indexes",
"=",
"np",
".",
"where",
"(",
"stds",... | 37.047619 | 0.02005 |
def hex(self, value, text=None, back=None, style=None, rgb_mode=False):
""" A chained method that sets the fore color to an hex value.
Arguments:
value : Hex value to convert.
text : Text to style if not building up color codes.
back : Back ... | [
"def",
"hex",
"(",
"self",
",",
"value",
",",
"text",
"=",
"None",
",",
"back",
"=",
"None",
",",
"style",
"=",
"None",
",",
"rgb_mode",
"=",
"False",
")",
":",
"if",
"rgb_mode",
":",
"try",
":",
"colrval",
"=",
"hex2rgb",
"(",
"value",
",",
"all... | 42.136364 | 0.00211 |
def _parse_date_string(date_str):
"""
Get a datetime.date object from a string date representation.
The FCS standard includes an optional keyword parameter $DATE in
which the acquistion date is stored. In FCS 2.0, the date is saved
as 'dd-mmm-yy', whereas in FCS 3.0 and 3.1 the ... | [
"def",
"_parse_date_string",
"(",
"date_str",
")",
":",
"# If input is None, return None",
"if",
"date_str",
"is",
"None",
":",
"return",
"None",
"# Standard format for FCS2.0",
"try",
":",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"date_str",
","... | 31.117647 | 0.001222 |
def add_service(self, service_name):
"""
Add the given service to the manifest.
"""
if service_name not in self.manifest['services']:
self.manifest['services'].append(service_name) | [
"def",
"add_service",
"(",
"self",
",",
"service_name",
")",
":",
"if",
"service_name",
"not",
"in",
"self",
".",
"manifest",
"[",
"'services'",
"]",
":",
"self",
".",
"manifest",
"[",
"'services'",
"]",
".",
"append",
"(",
"service_name",
")"
] | 36.5 | 0.008929 |
def setfields(self, *fldNames):
"""Define the name and order of the fields to access
with the read() and write() methods.
Args::
fldNames variable length argument specifying one or more
vdata field names
Returns::
None
C library equiv... | [
"def",
"setfields",
"(",
"self",
",",
"*",
"fldNames",
")",
":",
"_checkErr",
"(",
"'setfields'",
",",
"_C",
".",
"VSsetfields",
"(",
"self",
".",
"_id",
",",
"','",
".",
"join",
"(",
"fldNames",
")",
")",
",",
"'cannot execute'",
")",
"self",
".",
"... | 40.102564 | 0.001248 |
def varmax(self, data: ['SASdata', str] = None,
bound: str = None,
by: [str, list] = None,
causal: str = None,
cointeg: str = None,
condfore: str = None,
garch: str = None,
id: [str, list] = None,
ini... | [
"def",
"varmax",
"(",
"self",
",",
"data",
":",
"[",
"'SASdata'",
",",
"str",
"]",
"=",
"None",
",",
"bound",
":",
"str",
"=",
"None",
",",
"by",
":",
"[",
"str",
",",
"list",
"]",
"=",
"None",
",",
"causal",
":",
"str",
"=",
"None",
",",
"co... | 57.530612 | 0.008022 |
def ipv4_is_defined(address):
"""
The function for checking if an IPv4 address is defined (does not need to
be resolved).
Args:
address (:obj:`str`): An IPv4 address.
Returns:
namedtuple:
:is_defined (bool): True if given address is defined, otherwise
False
... | [
"def",
"ipv4_is_defined",
"(",
"address",
")",
":",
"# Initialize the IP address object.",
"query_ip",
"=",
"IPv4Address",
"(",
"str",
"(",
"address",
")",
")",
"# Initialize the results named tuple",
"results",
"=",
"namedtuple",
"(",
"'ipv4_is_defined_results'",
",",
... | 27.021053 | 0.000376 |
def get_all_boundary_algorithms():
"""Gets all the possible boundary algorithms in MSAF.
Returns
-------
algo_ids : list
List of all the IDs of boundary algorithms (strings).
"""
algo_ids = []
for name in msaf.algorithms.__all__:
module = eval(msaf.algorithms.__name__ + "." ... | [
"def",
"get_all_boundary_algorithms",
"(",
")",
":",
"algo_ids",
"=",
"[",
"]",
"for",
"name",
"in",
"msaf",
".",
"algorithms",
".",
"__all__",
":",
"module",
"=",
"eval",
"(",
"msaf",
".",
"algorithms",
".",
"__name__",
"+",
"\".\"",
"+",
"name",
")",
... | 29.571429 | 0.002342 |
def get_mysql_core(connection_args, *, cursor_factory=None, edit_connection=None):
"""Creates a simple MySQL core. Requires the pymysql library."""
import pymysql
def opener():
"""Opens a single connection with the scope-captured connection string."""
cn = pymysql.connect(**connection_args)
if cursor... | [
"def",
"get_mysql_core",
"(",
"connection_args",
",",
"*",
",",
"cursor_factory",
"=",
"None",
",",
"edit_connection",
"=",
"None",
")",
":",
"import",
"pymysql",
"def",
"opener",
"(",
")",
":",
"\"\"\"Opens a single connection with the scope-captured connection string.... | 31.454545 | 0.01122 |
def GetKeyByPath(self, key_path):
"""Retrieves the key for a specific path.
Args:
key_path (str): Windows Registry key path.
Returns:
WinRegistryKey: Windows Registry key or None if not available.
"""
key_path_upper = key_path.upper()
if key_path_upper.startswith(self._key_path_pre... | [
"def",
"GetKeyByPath",
"(",
"self",
",",
"key_path",
")",
":",
"key_path_upper",
"=",
"key_path",
".",
"upper",
"(",
")",
"if",
"key_path_upper",
".",
"startswith",
"(",
"self",
".",
"_key_path_prefix_upper",
")",
":",
"relative_key_path",
"=",
"key_path",
"["... | 30 | 0.008909 |
def signMsg(self,
msg: Dict,
identifier: Identifier=None,
otherIdentifier: Identifier=None):
"""
Creates signature for message using specified signer
:param msg: message to sign
:param identifier: signer identifier
:param otherIden... | [
"def",
"signMsg",
"(",
"self",
",",
"msg",
":",
"Dict",
",",
"identifier",
":",
"Identifier",
"=",
"None",
",",
"otherIdentifier",
":",
"Identifier",
"=",
"None",
")",
":",
"idr",
"=",
"self",
".",
"requiredIdr",
"(",
"idr",
"=",
"identifier",
"or",
"o... | 34.6875 | 0.015789 |
def cache_instrument_models(self):
"""
Queries Smoothie for the model and ID strings of attached pipettes, and
saves them so they can be reported without querying Smoothie again (as
this could interrupt a command if done during a run or other movement).
Shape of return dict shou... | [
"def",
"cache_instrument_models",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Updating instrument model cache\"",
")",
"for",
"mount",
"in",
"self",
".",
"model_by_mount",
".",
"keys",
"(",
")",
":",
"model_value",
"=",
"self",
".",
"_driver",
".",
"... | 33.763158 | 0.001515 |
def change_vlan_id(self, vlan_id):
"""
Change a VLAN id
:param str vlan_id: new vlan
"""
first, _ = self.nicid.split('.')
self.update(nicid='{}.{}'.format(first, str(vlan_id))) | [
"def",
"change_vlan_id",
"(",
"self",
",",
"vlan_id",
")",
":",
"first",
",",
"_",
"=",
"self",
".",
"nicid",
".",
"split",
"(",
"'.'",
")",
"self",
".",
"update",
"(",
"nicid",
"=",
"'{}.{}'",
".",
"format",
"(",
"first",
",",
"str",
"(",
"vlan_id... | 28.25 | 0.012876 |
def range_per_level(start, stop):
"""
Given an interval `start:stop`, make an iterator that returns for each
level the first and last bin overlapping the interval, starting with the
smallest bins.
Zero-length intervals are binned according to the one-position interval
following it.
Algorit... | [
"def",
"range_per_level",
"(",
"start",
",",
"stop",
")",
":",
"if",
"start",
"<",
"0",
"or",
"stop",
">",
"MAX_POSITION",
"+",
"1",
":",
"raise",
"OutOfRangeError",
"(",
"'Interval %d:%d is out of range (maximum position is %d)'",
"%",
"(",
"start",
",",
"stop"... | 34.763158 | 0.000736 |
def refresh_permissions(permissions):
"""Refresh permission:
Remove deprecated permissions,
Add generated permissions."""
available_permissions = [x.codename for x in
Permission.objects.filter(
codename__startswith=ACL_CODE_PREFIX)]
... | [
"def",
"refresh_permissions",
"(",
"permissions",
")",
":",
"available_permissions",
"=",
"[",
"x",
".",
"codename",
"for",
"x",
"in",
"Permission",
".",
"objects",
".",
"filter",
"(",
"codename__startswith",
"=",
"ACL_CODE_PREFIX",
")",
"]",
"active_permissions",... | 42.909091 | 0.001036 |
def set_cookie(self, key, value, **kargs):
""" Add a new cookie with various options.
If the cookie value is not a string, a secure cookie is created.
Possible options are:
expires, path, comment, domain, max_age, secure, version, httponly
See http://de.... | [
"def",
"set_cookie",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"sec",
"=",
"self",
".",
"app",
".",
"config",
"[",
"'securecookie.key'",
"]",
"value",
"="... | 43.8 | 0.008942 |
def find_root(filename, target='bids'):
"""Find base directory (root) for a filename.
Parameters
----------
filename : instance of Path
search the root for this file
target: str
'bids' (the directory containing 'participants.tsv'), 'subject' (the
directory starting with 'sub... | [
"def",
"find_root",
"(",
"filename",
",",
"target",
"=",
"'bids'",
")",
":",
"lg",
".",
"debug",
"(",
"f'Searching root in {filename}'",
")",
"if",
"target",
"==",
"'bids'",
"and",
"(",
"filename",
"/",
"'dataset_description.json'",
")",
".",
"exists",
"(",
... | 29.423077 | 0.001266 |
def send_error(self, msgid, error):
"""Send an error."""
msg = dumps([3, msgid, error])
self.send(msg) | [
"def",
"send_error",
"(",
"self",
",",
"msgid",
",",
"error",
")",
":",
"msg",
"=",
"dumps",
"(",
"[",
"3",
",",
"msgid",
",",
"error",
"]",
")",
"self",
".",
"send",
"(",
"msg",
")"
] | 30.75 | 0.015873 |
def _rm_redundant_points(self, geometry, geo_type):
"""
Remove redundant coordinate pairs from geometry
geometry: array of coordinates or nested-array of coordinates
geo_type: GeoJSON type attribute for provided geometry, used to
determine structure of provid... | [
"def",
"_rm_redundant_points",
"(",
"self",
",",
"geometry",
",",
"geo_type",
")",
":",
"if",
"geo_type",
"in",
"(",
"'MultiPoint'",
",",
"'LineString'",
")",
":",
"close",
"=",
"(",
"geo_type",
"==",
"'LineString'",
")",
"output",
"=",
"[",
"]",
"for",
... | 45.043478 | 0.00189 |
def send_image(self, number, path, caption=None):
"""
Send image message
:param str number: phone number with cc (country code)
:param str path: image file path
"""
return self._send_media_path(number, path, RequestUploadIqProtocolEntity.MEDIA_TYPE_IMAGE, caption) | [
"def",
"send_image",
"(",
"self",
",",
"number",
",",
"path",
",",
"caption",
"=",
"None",
")",
":",
"return",
"self",
".",
"_send_media_path",
"(",
"number",
",",
"path",
",",
"RequestUploadIqProtocolEntity",
".",
"MEDIA_TYPE_IMAGE",
",",
"caption",
")"
] | 43.714286 | 0.009615 |
def find_by_campaign(campaign_id, _connection=None, page_size=100,
page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos for a given campaign.
"""
return connection.ItemResultSet(
'find_videos_by_campaign_id', ... | [
"def",
"find_by_campaign",
"(",
"campaign_id",
",",
"_connection",
"=",
"None",
",",
"page_size",
"=",
"100",
",",
"page_number",
"=",
"0",
",",
"sort_by",
"=",
"enums",
".",
"DEFAULT_SORT_BY",
",",
"sort_order",
"=",
"enums",
".",
"DEFAULT_SORT_ORDER",
")",
... | 45.888889 | 0.009501 |
def list_connections(self, nome_interface, id_equipamento):
"""List interfaces linked to back and front of specified interface.
:param nome_interface: Interface name.
:param id_equipamento: Equipment identifier.
:return: Dictionary with the following:
::
{'interfa... | [
"def",
"list_connections",
"(",
"self",
",",
"nome_interface",
",",
"id_equipamento",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_equipamento",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Equipment identifier is none or was not informed.'",
")",
"if",
... | 42.255319 | 0.002461 |
def is_json_file(filename, show_warnings = False):
"""Check configuration file type is JSON
Return a boolean indicating wheather the file is JSON format or not
"""
try:
config_dict = load_config(filename, file_type = "json")
is_json = True
except:
is_json = False
return(i... | [
"def",
"is_json_file",
"(",
"filename",
",",
"show_warnings",
"=",
"False",
")",
":",
"try",
":",
"config_dict",
"=",
"load_config",
"(",
"filename",
",",
"file_type",
"=",
"\"json\"",
")",
"is_json",
"=",
"True",
"except",
":",
"is_json",
"=",
"False",
"r... | 31.8 | 0.018349 |
def download(self, updates):
'''
Download the updates passed in the updates collection. Load the updates
collection using ``search`` or ``available``
Args:
updates (Updates): An instance of the Updates class containing a
the updates to be downloaded.
Re... | [
"def",
"download",
"(",
"self",
",",
"updates",
")",
":",
"# Check for empty list",
"if",
"updates",
".",
"count",
"(",
")",
"==",
"0",
":",
"ret",
"=",
"{",
"'Success'",
":",
"False",
",",
"'Updates'",
":",
"'Nothing to download'",
"}",
"return",
"ret",
... | 34.342342 | 0.000765 |
def register(explicit=True):
"""
Register Pandas Formatters and Converters with matplotlib
This function modifies the global ``matplotlib.units.registry``
dictionary. Pandas adds custom converters for
* pd.Timestamp
* pd.Period
* np.datetime64
* datetime.datetime
* datetime.date
... | [
"def",
"register",
"(",
"explicit",
"=",
"True",
")",
":",
"# Renamed in pandas.plotting.__init__",
"global",
"_WARN",
"if",
"explicit",
":",
"_WARN",
"=",
"False",
"pairs",
"=",
"get_pairs",
"(",
")",
"for",
"type_",
",",
"cls",
"in",
"pairs",
":",
"convert... | 23.258065 | 0.001332 |
def get_max_levels_metadata(self):
"""get the metadata for max levels"""
metadata = dict(self._max_levels_metadata)
metadata.update({'existing_cardinal_values': self.my_osid_object_form._my_map['maxLevels']})
return Metadata(**metadata) | [
"def",
"get_max_levels_metadata",
"(",
"self",
")",
":",
"metadata",
"=",
"dict",
"(",
"self",
".",
"_max_levels_metadata",
")",
"metadata",
".",
"update",
"(",
"{",
"'existing_cardinal_values'",
":",
"self",
".",
"my_osid_object_form",
".",
"_my_map",
"[",
"'ma... | 52.8 | 0.011194 |
def sign_remote_certificate(argdic, **kwargs):
'''
Request a certificate to be remotely signed according to a signing policy.
argdic:
A dict containing all the arguments to be passed into the
create_certificate function. This will become kwargs when passed
to create_certificate.
... | [
"def",
"sign_remote_certificate",
"(",
"argdic",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'signing_policy'",
"not",
"in",
"argdic",
":",
"return",
"'signing_policy must be specified'",
"if",
"not",
"isinstance",
"(",
"argdic",
",",
"dict",
")",
":",
"argdic",
... | 34.941176 | 0.001638 |
def meminfo():
'''
Return the memory info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.meminfo
'''
def linux_meminfo():
'''... | [
"def",
"meminfo",
"(",
")",
":",
"def",
"linux_meminfo",
"(",
")",
":",
"'''\n linux specific implementation of meminfo\n '''",
"ret",
"=",
"{",
"}",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/proc/meminfo'",
",",... | 34.670807 | 0.002264 |
def node_set_to_surface(self, tag):
"""
Converts a node set to surface.
"""
# Create a dummy node with label 0
nodes = self.nodes.copy()
dummy = nodes.iloc[0].copy()
dummy["coords"] *= np.nan
dummy["sets"] = True
nodes.loc[0] = dummy
# Getting element surfaces
element_surface... | [
"def",
"node_set_to_surface",
"(",
"self",
",",
"tag",
")",
":",
"# Create a dummy node with label 0",
"nodes",
"=",
"self",
".",
"nodes",
".",
"copy",
"(",
")",
"dummy",
"=",
"nodes",
".",
"iloc",
"[",
"0",
"]",
".",
"copy",
"(",
")",
"dummy",
"[",
"\... | 35.809524 | 0.011658 |
def select_by_pattern_in_fname(self,
pattern,
recursive=True,
case_sensitive=False):
"""
Select file path by text pattern in file name.
**中文文档**
选择文件名中包含指定子字符串的文件。
"""
... | [
"def",
"select_by_pattern_in_fname",
"(",
"self",
",",
"pattern",
",",
"recursive",
"=",
"True",
",",
"case_sensitive",
"=",
"False",
")",
":",
"if",
"case_sensitive",
":",
"def",
"filters",
"(",
"p",
")",
":",
"return",
"pattern",
"in",
"p",
".",
"fname",... | 27.380952 | 0.008403 |
def get_bin(self, arch='x86'):
"""
Get binaries of Visual C++.
"""
bin_dir = os.path.join(self.vc_dir, 'bin')
if arch == 'x86':
arch = ''
cl_path = os.path.join(bin_dir, arch, 'cl.exe')
link_path = os.path.join(bin_dir, arch, 'link.exe')
ml_nam... | [
"def",
"get_bin",
"(",
"self",
",",
"arch",
"=",
"'x86'",
")",
":",
"bin_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"vc_dir",
",",
"'bin'",
")",
"if",
"arch",
"==",
"'x86'",
":",
"arch",
"=",
"''",
"cl_path",
"=",
"os",
".",
"... | 43.444444 | 0.001668 |
def minify(tokens, options):
"""
Performs minification on *tokens* according to the values in *options*
"""
# Remove comments
remove_comments(tokens)
# Remove docstrings
remove_docstrings(tokens)
result = token_utils.untokenize(tokens)
# Minify our input script
result = multiline... | [
"def",
"minify",
"(",
"tokens",
",",
"options",
")",
":",
"# Remove comments",
"remove_comments",
"(",
"tokens",
")",
"# Remove docstrings",
"remove_docstrings",
"(",
"tokens",
")",
"result",
"=",
"token_utils",
".",
"untokenize",
"(",
"tokens",
")",
"# Minify our... | 34.315789 | 0.001493 |
def find_handfile(names=None):
"""
尝试定位 ``handfile`` 文件,明确指定或逐级搜索父路径
:param str names: 可选,待查找的文件名,主要用于调试,默认使用终端传入的配置
:return: ``handfile`` 文件所在的绝对路径,默认为 None
:rtype: str
"""
# 如果没有明确指定,则包含 env 中的值
names = names or [env.handfile]
# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾
if not nam... | [
"def",
"find_handfile",
"(",
"names",
"=",
"None",
")",
":",
"# 如果没有明确指定,则包含 env 中的值",
"names",
"=",
"names",
"or",
"[",
"env",
".",
"handfile",
"]",
"# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾",
"if",
"not",
"names",
"[",
"0",
"]",
".",
"endswith",
"(",
"'.py'",
... | 30 | 0.000873 |
def _trim_external_pores(self, shape):
r'''
'''
# Find all pores within the domain
Ps = topotools.isoutside(coords=self['pore.coords'], shape=shape)
self['pore.external'] = False
self['pore.external'][Ps] = True
# Find which internal pores are delaunay
Ps... | [
"def",
"_trim_external_pores",
"(",
"self",
",",
"shape",
")",
":",
"# Find all pores within the domain",
"Ps",
"=",
"topotools",
".",
"isoutside",
"(",
"coords",
"=",
"self",
"[",
"'pore.coords'",
"]",
",",
"shape",
"=",
"shape",
")",
"self",
"[",
"'pore.exte... | 39.666667 | 0.000745 |
def fit_model(p, d, q, ts, includeIntercept=True, method="css-cgd", userInitParams=None, sc=None):
"""
Given a time series, fit a non-seasonal ARIMA model of order (p, d, q), where p represents
the autoregression terms, d represents the order of differencing, and q moving average error
terms. If include... | [
"def",
"fit_model",
"(",
"p",
",",
"d",
",",
"q",
",",
"ts",
",",
"includeIntercept",
"=",
"True",
",",
"method",
"=",
"\"css-cgd\"",
",",
"userInitParams",
"=",
"None",
",",
"sc",
"=",
"None",
")",
":",
"assert",
"sc",
"!=",
"None",
",",
"\"Missing ... | 50.093023 | 0.008197 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.