text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def restore_db(release=None):
"""
Restores backup back to version, uses current version by default.
"""
assert "mysql_user" in env, "Missing mysqL_user in env"
assert "mysql_password" in env, "Missing mysql_password in env"
assert "mysql_host" in env, "Missing mysql_host in env"
assert "mys... | [
"def",
"restore_db",
"(",
"release",
"=",
"None",
")",
":",
"assert",
"\"mysql_user\"",
"in",
"env",
",",
"\"Missing mysqL_user in env\"",
"assert",
"\"mysql_password\"",
"in",
"env",
",",
"\"Missing mysql_password in env\"",
"assert",
"\"mysql_host\"",
"in",
"env",
"... | 34.28 | 21.8 |
def file_list(self, tgt_env):
'''
Get file list for the target environment using pygit2
'''
def _traverse(tree, blobs, prefix):
'''
Traverse through a pygit2 Tree object recursively, accumulating all
the file paths and symlink info in the "blobs" dict
... | [
"def",
"file_list",
"(",
"self",
",",
"tgt_env",
")",
":",
"def",
"_traverse",
"(",
"tree",
",",
"blobs",
",",
"prefix",
")",
":",
"'''\n Traverse through a pygit2 Tree object recursively, accumulating all\n the file paths and symlink info in the \"blobs\" d... | 42.839286 | 17.410714 |
def allow_user(user):
"""Allow a user identified by an email address."""
def processor(action, argument):
db.session.add(
ActionUsers.allow(action, argument=argument, user_id=user.id)
)
return processor | [
"def",
"allow_user",
"(",
"user",
")",
":",
"def",
"processor",
"(",
"action",
",",
"argument",
")",
":",
"db",
".",
"session",
".",
"add",
"(",
"ActionUsers",
".",
"allow",
"(",
"action",
",",
"argument",
"=",
"argument",
",",
"user_id",
"=",
"user",
... | 33.714286 | 17.714286 |
def istext(s, text_characters=None, threshold=0.3):
"""
Determines if the string is a set of binary data or a text file.
This is done by checking if a large proportion of characters are > 0X7E
(0x7F is <DEL> and unprintable) or low bit control codes. In other words
things that you wouldn't see (ofte... | [
"def",
"istext",
"(",
"s",
",",
"text_characters",
"=",
"None",
",",
"threshold",
"=",
"0.3",
")",
":",
"text_characters",
"=",
"\"\"",
".",
"join",
"(",
"map",
"(",
"chr",
",",
"range",
"(",
"32",
",",
"127",
")",
")",
")",
"+",
"\"\\n\\r\\t\\b\"",
... | 44.217391 | 20.913043 |
def tweet(ctx, message):
"""Sends a tweet directly to your timeline"""
if not valid_tweet(message):
click.echo("Message is too long for twitter.")
click.echo("Message:" + message)
ctx.exit(2)
if not ctx.obj['DRYRUN']:
ctx.obj['TWEEPY_API'].update_status(message)
else:
... | [
"def",
"tweet",
"(",
"ctx",
",",
"message",
")",
":",
"if",
"not",
"valid_tweet",
"(",
"message",
")",
":",
"click",
".",
"echo",
"(",
"\"Message is too long for twitter.\"",
")",
"click",
".",
"echo",
"(",
"\"Message:\"",
"+",
"message",
")",
"ctx",
".",
... | 33.181818 | 15.454545 |
def update(self, figure):
"""Updates figure on data change
Parameters
----------
* figure: matplotlib.figure.Figure
\tMatplotlib figure object that is displayed in self
"""
if hasattr(self, "figure_canvas"):
self.figure_canvas.Destroy()
sel... | [
"def",
"update",
"(",
"self",
",",
"figure",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"figure_canvas\"",
")",
":",
"self",
".",
"figure_canvas",
".",
"Destroy",
"(",
")",
"self",
".",
"figure_canvas",
"=",
"self",
".",
"_get_figure_canvas",
"(",
"f... | 26.173913 | 19.869565 |
def normalLines(actor, ratio=1, c=(0.6, 0.6, 0.6), alpha=0.8):
"""
Build an ``vtkActor`` made of the normals at vertices shown as lines.
"""
maskPts = vtk.vtkMaskPoints()
maskPts.SetOnRatio(ratio)
maskPts.RandomModeOff()
actor = actor.computeNormals()
src = actor.polydata()
maskPts.S... | [
"def",
"normalLines",
"(",
"actor",
",",
"ratio",
"=",
"1",
",",
"c",
"=",
"(",
"0.6",
",",
"0.6",
",",
"0.6",
")",
",",
"alpha",
"=",
"0.8",
")",
":",
"maskPts",
"=",
"vtk",
".",
"vtkMaskPoints",
"(",
")",
"maskPts",
".",
"SetOnRatio",
"(",
"rat... | 34.827586 | 13.103448 |
def find_interfaces(*args):
'''
Returns the bridge to which the interfaces are bond to
CLI Example:
.. code-block:: bash
salt '*' bridge.find_interfaces eth0 [eth1...]
'''
brs = _os_dispatch('brshow')
if not brs:
return None
iflist = {}
for iface in args:
... | [
"def",
"find_interfaces",
"(",
"*",
"args",
")",
":",
"brs",
"=",
"_os_dispatch",
"(",
"'brshow'",
")",
"if",
"not",
"brs",
":",
"return",
"None",
"iflist",
"=",
"{",
"}",
"for",
"iface",
"in",
"args",
":",
"for",
"br",
"in",
"brs",
":",
"try",
":"... | 21.08 | 23.48 |
def _module_env(self, execution):
"""Set current process environment according
to execution `environment` and `modules`
"""
env = copy.copy(os.environ)
try:
for mod in execution.get('modules') or []:
Module.load(mod)
os.environ.update(execu... | [
"def",
"_module_env",
"(",
"self",
",",
"execution",
")",
":",
"env",
"=",
"copy",
".",
"copy",
"(",
"os",
".",
"environ",
")",
"try",
":",
"for",
"mod",
"in",
"execution",
".",
"get",
"(",
"'modules'",
")",
"or",
"[",
"]",
":",
"Module",
".",
"l... | 33.583333 | 12.833333 |
def create_item(self, name):
"""
create a new todo list item
"""
elem = self.controlled_list.create_item(name)
if elem:
return TodoElementUX(parent=self, controlled_element=elem) | [
"def",
"create_item",
"(",
"self",
",",
"name",
")",
":",
"elem",
"=",
"self",
".",
"controlled_list",
".",
"create_item",
"(",
"name",
")",
"if",
"elem",
":",
"return",
"TodoElementUX",
"(",
"parent",
"=",
"self",
",",
"controlled_element",
"=",
"elem",
... | 32 | 12 |
def _default_value_cell_data_func(self, tree_view_column, cell, model, iter, data=None):
"""Function set renderer properties for every single cell independently
The function controls the editable and color scheme for every cell in the default value column according
the use_runtime_value flag an... | [
"def",
"_default_value_cell_data_func",
"(",
"self",
",",
"tree_view_column",
",",
"cell",
",",
"model",
",",
"iter",
",",
"data",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"model",
".",
"state",
",",
"LibraryState",
")",
":",
"use_runti... | 57.958333 | 32.208333 |
def read_aims(filename):
"""Method to read FHI-aims geometry files in phonopy context."""
lines = open(filename, 'r').readlines()
cell = []
is_frac = []
positions = []
symbols = []
magmoms = []
for line in lines:
fields = line.split()
if not len(fields):
con... | [
"def",
"read_aims",
"(",
"filename",
")",
":",
"lines",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"cell",
"=",
"[",
"]",
"is_frac",
"=",
"[",
"]",
"positions",
"=",
"[",
"]",
"symbols",
"=",
"[",
"]",
"magmoms",
"... | 34.568182 | 19.159091 |
def epsilon_lexicase(self, F, sizes, num_selections=None, survival = False):
"""conducts epsilon lexicase selection for de-aggregated fitness vectors"""
# pdb.set_trace()
if num_selections is None:
num_selections = F.shape[0]
if self.c: # use c library
# defi... | [
"def",
"epsilon_lexicase",
"(",
"self",
",",
"F",
",",
"sizes",
",",
"num_selections",
"=",
"None",
",",
"survival",
"=",
"False",
")",
":",
"# pdb.set_trace()",
"if",
"num_selections",
"is",
"None",
":",
"num_selections",
"=",
"F",
".",
"shape",
"[",
"0",... | 47.44186 | 23.883721 |
def transform(self, buffer, mode=None, vertices=-1, *, first=0, instances=1) -> None:
'''
Transform vertices.
Stores the output in a single buffer.
The transform primitive (mode) must be the same as
the input primitive of the GeometryShader.
Args:
... | [
"def",
"transform",
"(",
"self",
",",
"buffer",
",",
"mode",
"=",
"None",
",",
"vertices",
"=",
"-",
"1",
",",
"*",
",",
"first",
"=",
"0",
",",
"instances",
"=",
"1",
")",
"->",
"None",
":",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"POINT... | 38.095238 | 26.285714 |
def getMessageCharge(self, apiMsgId):
"""
See parent method for documentation
"""
content = self.parseRest(self.request('rest/message/' + apiMsgId))
return {
'id': apiMsgId,
'status': content['messageStatus'].encode('utf-8'),
'description': se... | [
"def",
"getMessageCharge",
"(",
"self",
",",
"apiMsgId",
")",
":",
"content",
"=",
"self",
".",
"parseRest",
"(",
"self",
".",
"request",
"(",
"'rest/message/'",
"+",
"apiMsgId",
")",
")",
"return",
"{",
"'id'",
":",
"apiMsgId",
",",
"'status'",
":",
"co... | 33.75 | 17.083333 |
def save(self, file_path):
"""
Method to save the dataset to disk.
Parameters
----------
file_path : str
File path to save the current dataset to
Raises
------
IOError
If saving to disk is not successful.
"""
# T... | [
"def",
"save",
"(",
"self",
",",
"file_path",
")",
":",
"# TODO need a file format that is flexible and efficient to allow the following:",
"# 1) being able to read just meta info without having to load the ENTIRE dataset",
"# i.e. use case: compatibility check with #subjects, ids and th... | 34.941176 | 24.294118 |
def save_coo(x, row_names, col_names, filename, chunk=None):
"""write a PEST-compatible binary file. The data format is
[int,int,float] for i,j,value. It is autodetected during
the read with Matrix.from_binary().
Parameters
----------
x : numpy.sparse
coo sparse matrix
row_names ... | [
"def",
"save_coo",
"(",
"x",
",",
"row_names",
",",
"col_names",
",",
"filename",
",",
"chunk",
"=",
"None",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'wb'",
")",
"# print(\"counting nnz\")",
"# write the header",
"header",
"=",
"np",
".",
"array"... | 32.787234 | 18.702128 |
def _EntriesGenerator(self):
"""Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
TSKPartitionPathSpec: a path specification.
"""
location = getattr(self.path_spec, 'location', None)
part_index = ge... | [
"def",
"_EntriesGenerator",
"(",
"self",
")",
":",
"location",
"=",
"getattr",
"(",
"self",
".",
"path_spec",
",",
"'location'",
",",
"None",
")",
"part_index",
"=",
"getattr",
"(",
"self",
".",
"path_spec",
",",
"'part_index'",
",",
"None",
")",
"start_of... | 36.357143 | 22.785714 |
def detect_with_url(
self, url, return_face_id=True, return_face_landmarks=False, return_face_attributes=None, recognition_model="recognition_01", return_recognition_model=False, custom_headers=None, raw=False, **operation_config):
"""Detect human faces in an image, return face rectangles, and optio... | [
"def",
"detect_with_url",
"(",
"self",
",",
"url",
",",
"return_face_id",
"=",
"True",
",",
"return_face_landmarks",
"=",
"False",
",",
"return_face_attributes",
"=",
"None",
",",
"recognition_model",
"=",
"\"recognition_01\"",
",",
"return_recognition_model",
"=",
... | 56.604478 | 29.679104 |
def _makes_clone(_func, *args, **kw):
"""
A decorator that returns a clone of the current object so that
we can re-use the object for similar requests.
"""
self = args[0]._clone()
_func(self, *args[1:], **kw)
return self | [
"def",
"_makes_clone",
"(",
"_func",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
".",
"_clone",
"(",
")",
"_func",
"(",
"self",
",",
"*",
"args",
"[",
"1",
":",
"]",
",",
"*",
"*",
"kw",
")",
"return... | 30.125 | 10.625 |
def _assign_posterior(self):
"""assign posterior to the right prior based on
Hungarian algorithm
Returns
-------
HTFA
Returns the instance itself.
"""
prior_centers = self.get_centers(self.global_prior_)
posterior_centers = self.get_center... | [
"def",
"_assign_posterior",
"(",
"self",
")",
":",
"prior_centers",
"=",
"self",
".",
"get_centers",
"(",
"self",
".",
"global_prior_",
")",
"posterior_centers",
"=",
"self",
".",
"get_centers",
"(",
"self",
".",
"global_posterior_",
")",
"posterior_widths",
"="... | 40.193548 | 15.677419 |
def search_unit(current):
"""
Search on units for subscribing it's users to a channel
.. code-block:: python
# request:
{
'view':'_zops_search_unit',
'query': string,
}
# response:
{
... | [
"def",
"search_unit",
"(",
"current",
")",
":",
"current",
".",
"output",
"=",
"{",
"'results'",
":",
"[",
"]",
",",
"'status'",
":",
"'OK'",
",",
"'code'",
":",
"201",
"}",
"for",
"user",
"in",
"UnitModel",
"(",
"current",
")",
".",
"objects",
".",
... | 28.111111 | 20.851852 |
def logging_decorator(func):
"""Allow logging function calls"""
def you_will_never_see_this_name(*args, **kwargs):
"""Neither this docstring"""
print('calling %s ...' % func.__name__)
result = func(*args, **kwargs)
print('completed: %s' % func.__name__)
return resu... | [
"def",
"logging_decorator",
"(",
"func",
")",
":",
"def",
"you_will_never_see_this_name",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Neither this docstring\"\"\"",
"print",
"(",
"'calling %s ...'",
"%",
"func",
".",
"__name__",
")",
"result",
"=... | 39.444444 | 6.777778 |
def ResolveForRead(self, partition_key):
"""Resolves the collection for reading/querying the documents based on the partition key.
:param dict document:
The document to be read/queried.
:return:
Collection Self link(s) or Name based link(s) which should handle the Read ... | [
"def",
"ResolveForRead",
"(",
"self",
",",
"partition_key",
")",
":",
"if",
"partition_key",
"is",
"None",
":",
"return",
"self",
".",
"collection_links",
"else",
":",
"return",
"[",
"self",
".",
"consistent_hash_ring",
".",
"GetCollectionNode",
"(",
"partition_... | 35.333333 | 19.866667 |
def separation_cos_angle(lon0, lat0, lon1, lat1):
"""Evaluate the cosine of the angular separation between two
direction vectors."""
return (np.sin(lat1) * np.sin(lat0) + np.cos(lat1) * np.cos(lat0) *
np.cos(lon1 - lon0)) | [
"def",
"separation_cos_angle",
"(",
"lon0",
",",
"lat0",
",",
"lon1",
",",
"lat1",
")",
":",
"return",
"(",
"np",
".",
"sin",
"(",
"lat1",
")",
"*",
"np",
".",
"sin",
"(",
"lat0",
")",
"+",
"np",
".",
"cos",
"(",
"lat1",
")",
"*",
"np",
".",
... | 48.2 | 9.6 |
def search(cookie, tokens, key, path='/'):
'''搜索全部文件, 根据文件名.
key - 搜索的关键词
path - 如果指定目录名的话, 只搜索本目录及其子目录里的文件名.
'''
url = ''.join([
const.PAN_API_URL,
'search?channel=chunlei&clienttype=0&web=1',
'&dir=', path,
'&key=', key,
'&recursion',
'&timeStamp=',... | [
"def",
"search",
"(",
"cookie",
",",
"tokens",
",",
"key",
",",
"path",
"=",
"'/'",
")",
":",
"url",
"=",
"''",
".",
"join",
"(",
"[",
"const",
".",
"PAN_API_URL",
",",
"'search?channel=chunlei&clienttype=0&web=1'",
",",
"'&dir='",
",",
"path",
",",
"'&k... | 26.142857 | 18.428571 |
def finalize(self, **kwargs):
"""
Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments.
"""
# Divide out the two features
feature_one... | [
"def",
"finalize",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Divide out the two features",
"feature_one",
",",
"feature_two",
"=",
"self",
".",
"features_",
"# Set the title",
"self",
".",
"set_title",
"(",
"'Scatter Plot: {0} vs {1}'",
".",
"format",
"("... | 30.65 | 15.25 |
def namedb_get_name_DID_info(cur, name, block_height):
"""
Given a name and a DB cursor, find out its DID info at the given block.
Returns {'name_type': ..., 'address': ..., 'index': ...} on success
Return None if there is no such name
"""
# get the latest creator addresses for this name, as wel... | [
"def",
"namedb_get_name_DID_info",
"(",
"cur",
",",
"name",
",",
"block_height",
")",
":",
"# get the latest creator addresses for this name, as well as where this name was created in the blockchain",
"sql",
"=",
"\"SELECT name_records.name,history.creator_address,history.block_id,history.... | 46.638889 | 30.027778 |
def from_node(index, name, session, data):
"""
>>> Member.from_node(-1, '', '', '{"conn_url": "postgres://foo@bar/postgres"}') is not None
True
>>> Member.from_node(-1, '', '', '{')
Member(index=-1, name='', session='', data={})
"""
if data.startswith('postgres'):... | [
"def",
"from_node",
"(",
"index",
",",
"name",
",",
"session",
",",
"data",
")",
":",
"if",
"data",
".",
"startswith",
"(",
"'postgres'",
")",
":",
"conn_url",
",",
"api_url",
"=",
"parse_connection_string",
"(",
"data",
")",
"data",
"=",
"{",
"'conn_url... | 38.75 | 14.375 |
def on_recv(self, cf):
"""Function that must be called every time a CAN frame is received, to
advance the state machine."""
data = bytes(cf.data)
if len(data) < 2:
return
ae = 0
if self.extended_rx_addr is not None:
ae = 1
if len(dat... | [
"def",
"on_recv",
"(",
"self",
",",
"cf",
")",
":",
"data",
"=",
"bytes",
"(",
"cf",
".",
"data",
")",
"if",
"len",
"(",
"data",
")",
"<",
"2",
":",
"return",
"ae",
"=",
"0",
"if",
"self",
".",
"extended_rx_addr",
"is",
"not",
"None",
":",
"ae"... | 28.258065 | 15.193548 |
def decode_full_layer_uri(full_layer_uri_string):
"""Decode the full layer URI.
:param full_layer_uri_string: The full URI provided by our helper.
:type full_layer_uri_string: basestring
:return: A tuple with the QGIS URI and the provider key.
:rtype: tuple
"""
if not full_layer_uri_string... | [
"def",
"decode_full_layer_uri",
"(",
"full_layer_uri_string",
")",
":",
"if",
"not",
"full_layer_uri_string",
":",
"return",
"None",
",",
"None",
"split",
"=",
"full_layer_uri_string",
".",
"split",
"(",
"'|qgis_provider='",
")",
"if",
"len",
"(",
"split",
")",
... | 28 | 19.058824 |
def holiday_name(self, value=None):
"""Corresponds to IDD Field `holiday_name`
Args:
value (str): value for IDD Field `holiday_name`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
... | [
"def",
"holiday_name",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"str",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type str... | 35.347826 | 21.043478 |
def _empty_value(self, formattype):
'''
returns default empty value
:param formattype:
:param buff:
:param start:
:param end:
'''
if formattype.value.idx <= FormatType.BIN_32.value.idx: # @UndefinedVariable
return b''
elif formatt... | [
"def",
"_empty_value",
"(",
"self",
",",
"formattype",
")",
":",
"if",
"formattype",
".",
"value",
".",
"idx",
"<=",
"FormatType",
".",
"BIN_32",
".",
"value",
".",
"idx",
":",
"# @UndefinedVariable",
"return",
"b''",
"elif",
"formattype",
".",
"value",
".... | 38.25 | 22.25 |
def _get_kind(cls):
"""Override.
Make sure that the kind returned is the root class of the
polymorphic hierarchy.
"""
bases = cls._get_hierarchy()
if not bases:
# We have to jump through some hoops to call the superclass'
# _get_kind() method. First, this is called by the metaclass... | [
"def",
"_get_kind",
"(",
"cls",
")",
":",
"bases",
"=",
"cls",
".",
"_get_hierarchy",
"(",
")",
"if",
"not",
"bases",
":",
"# We have to jump through some hoops to call the superclass'",
"# _get_kind() method. First, this is called by the metaclass",
"# before the PolyModel na... | 37 | 18.588235 |
def addPrivateKey(self, wif):
""" Add a private key to the wallet database
"""
try:
pub = self.publickey_from_wif(wif)
except Exception:
raise InvalidWifError("Invalid Key format!")
if str(pub) in self.store:
raise KeyAlreadyInStoreException("K... | [
"def",
"addPrivateKey",
"(",
"self",
",",
"wif",
")",
":",
"try",
":",
"pub",
"=",
"self",
".",
"publickey_from_wif",
"(",
"wif",
")",
"except",
"Exception",
":",
"raise",
"InvalidWifError",
"(",
"\"Invalid Key format!\"",
")",
"if",
"str",
"(",
"pub",
")"... | 37.9 | 11.6 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkspaceContext for this WorkspaceInstance
:rtype: twilio.rest.taskrouter.v1.workspace.Workspace... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"WorkspaceContext",
"(",
"self",
".",
"_version",
",",
"sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
")",
"return"... | 43.727273 | 23.909091 |
def _compute_operation(string, idx):
# type: (str, int) -> Optional[int]
"""
Tries to compute the LDAP operation at the given index
Valid operations are :
* & : AND
* | : OR
* ! : NOT
:param string: A LDAP filter string
:param idx: An index in the given string
:return: The cor... | [
"def",
"_compute_operation",
"(",
"string",
",",
"idx",
")",
":",
"# type: (str, int) -> Optional[int]",
"operator",
"=",
"string",
"[",
"idx",
"]",
"if",
"operator",
"==",
"\"&\"",
":",
"return",
"AND",
"elif",
"operator",
"==",
"\"|\"",
":",
"return",
"OR",
... | 21.541667 | 18.875 |
def get_draw(self, index: Index, additional_key: Any=None) -> pd.Series:
"""Get an indexed sequence of floats pulled from a uniform distribution over [0.0, 1.0)
Parameters
----------
index :
An index whose length is the number of random draws made
and which index... | [
"def",
"get_draw",
"(",
"self",
",",
"index",
":",
"Index",
",",
"additional_key",
":",
"Any",
"=",
"None",
")",
"->",
"pd",
".",
"Series",
":",
"if",
"self",
".",
"_for_initialization",
":",
"draw",
"=",
"random",
"(",
"self",
".",
"_key",
"(",
"add... | 37.043478 | 25.478261 |
async def close_interface(self, conn_id, interface):
"""Close an interface on this IOTile device.
See :meth:`AbstractDeviceAdapter.close_interface`.
"""
self._ensure_connection(conn_id, True)
connection_string = self._get_property(conn_id, "connection_string")
msg = di... | [
"async",
"def",
"close_interface",
"(",
"self",
",",
"conn_id",
",",
"interface",
")",
":",
"self",
".",
"_ensure_connection",
"(",
"conn_id",
",",
"True",
")",
"connection_string",
"=",
"self",
".",
"_get_property",
"(",
"conn_id",
",",
"\"connection_string\"",... | 42.636364 | 26 |
def post(self, url, data=None, files=None, headers=None, raw=False,
send_as_json=True, content_type=None, **request_kwargs):
"""
POST request to AmigoCloud endpoint.
"""
return self._secure_request(
url, 'post', data=data, files=files, headers=headers, raw=raw,
... | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"files",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"send_as_json",
"=",
"True",
",",
"content_type",
"=",
"None",
",",
"*",
"*",
"request_kwargs",
... | 37.636364 | 18.727273 |
def _get_grad_method(self, data):
r"""Get the gradient
This method calculates the gradient step from the input data
Parameters
----------
data : np.ndarray
Input data array
Notes
-----
Implements the following equation:
.. math::
... | [
"def",
"_get_grad_method",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"grad",
"=",
"self",
".",
"trans_op",
"(",
"self",
".",
"op",
"(",
"data",
")",
"-",
"self",
".",
"obs_data",
")"
] | 22.55 | 24.1 |
def rebuild(self, **kwargs):
"Update a property value with (used by the designer)"
for name, value in kwargs.items():
setattr(self, name, value) | [
"def",
"rebuild",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"name",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"name",
",",
"value",
")"
] | 43 | 9.5 |
def load_siemens_dicom(filename):
"""
Imports a file in the Siemens .IMA format.
:param filename: The filename of the file to import
"""
# the .IMA format is a DICOM standard, unfortunately most of the information is contained inside a private and very
# complicated header with its own data stor... | [
"def",
"load_siemens_dicom",
"(",
"filename",
")",
":",
"# the .IMA format is a DICOM standard, unfortunately most of the information is contained inside a private and very",
"# complicated header with its own data storage format, we have to get that information out along with the data",
"# start by... | 48.596774 | 22.016129 |
def _lint(dxapp_json_filename, mode):
"""
Examines the specified dxapp.json file and warns about any
violations of app guidelines.
Precondition: the dxapp.json file exists and can be parsed.
"""
def _find_readme(dirname):
for basename in ['README.md', 'Readme.md', 'readme.md']:
... | [
"def",
"_lint",
"(",
"dxapp_json_filename",
",",
"mode",
")",
":",
"def",
"_find_readme",
"(",
"dirname",
")",
":",
"for",
"basename",
"in",
"[",
"'README.md'",
",",
"'Readme.md'",
",",
"'readme.md'",
"]",
":",
"if",
"os",
".",
"path",
".",
"exists",
"("... | 54.825 | 33.35 |
def config_add(self, key, value, **kwargs):
"""
Add a value to a key.
Returns a list of warnings Conda may have emitted.
"""
cmd_list = ['config', '--add', key, value]
cmd_list.extend(self._setup_config_from_kwargs(kwargs))
return self._call_and_parse(
... | [
"def",
"config_add",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd_list",
"=",
"[",
"'config'",
",",
"'--add'",
",",
"key",
",",
"value",
"]",
"cmd_list",
".",
"extend",
"(",
"self",
".",
"_setup_config_from_kwargs",
"(... | 32.769231 | 14.769231 |
def max_parameter_substitution():
"""
SQLite has a limit on the max number of variables allowed for parameter substitution. This limit is usually 999, but
can be compiled to a different number. This function calculates what the max is for the sqlite version running on the device.
We use the calculated v... | [
"def",
"max_parameter_substitution",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"SQLITE_VARIABLE_FILE_CACHE",
")",
":",
"return",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"':memory:'",
")",
"low",
"=",
"1",
"high",
"=",
"1000",
"# hard... | 43.714286 | 23.785714 |
def delete_compliance_task(self, id):
'''**Description**
Delete the compliance task with the given id
**Arguments**
- id: the id of the compliance task to delete
'''
res = requests.delete(self.url + '/api/complianceTasks/{}'.format(id), headers=self.hdrs, verify=... | [
"def",
"delete_compliance_task",
"(",
"self",
",",
"id",
")",
":",
"res",
"=",
"requests",
".",
"delete",
"(",
"self",
".",
"url",
"+",
"'/api/complianceTasks/{}'",
".",
"format",
"(",
"id",
")",
",",
"headers",
"=",
"self",
".",
"hdrs",
",",
"verify",
... | 36 | 23 |
def setWorkingSeatedZeroPoseToRawTrackingPose(self):
"""Sets the preferred seated position in the working copy."""
fn = self.function_table.setWorkingSeatedZeroPoseToRawTrackingPose
pMatSeatedZeroPoseToRawTrackingPose = HmdMatrix34_t()
fn(byref(pMatSeatedZeroPoseToRawTrackingPose))
... | [
"def",
"setWorkingSeatedZeroPoseToRawTrackingPose",
"(",
"self",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setWorkingSeatedZeroPoseToRawTrackingPose",
"pMatSeatedZeroPoseToRawTrackingPose",
"=",
"HmdMatrix34_t",
"(",
")",
"fn",
"(",
"byref",
"(",
"pMatSeat... | 51.428571 | 18.714286 |
def build_map_async(coro=None, *, mode=None, unpack: bool = False):
""" Decorator to wrap a coroutine to return a MapAsync operator.
:param coro: coroutine to be wrapped
:param mode: behavior when a value is currently processed
:param unpack: value from emits will be unpacked (*value)
"""
_mode... | [
"def",
"build_map_async",
"(",
"coro",
"=",
"None",
",",
"*",
",",
"mode",
"=",
"None",
",",
"unpack",
":",
"bool",
"=",
"False",
")",
":",
"_mode",
"=",
"mode",
"def",
"_build_map_async",
"(",
"coro",
")",
":",
"@",
"wraps",
"(",
"coro",
")",
"def... | 35.173913 | 20.782609 |
def __restore_selection(self, start_pos, end_pos):
"""Restore cursor selection from position bounds"""
cursor = self.textCursor()
cursor.setPosition(start_pos)
cursor.setPosition(end_pos, QTextCursor.KeepAnchor)
self.setTextCursor(cursor) | [
"def",
"__restore_selection",
"(",
"self",
",",
"start_pos",
",",
"end_pos",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"start_pos",
")",
"cursor",
".",
"setPosition",
"(",
"end_pos",
",",
"QTextCursor",
... | 46.333333 | 7.333333 |
def offline(f):
""" This decorator allows you to access ``ctx.bitshares`` which is
an instance of BitShares with ``offline=True``.
"""
@click.pass_context
@verbose
def new_func(ctx, *args, **kwargs):
ctx.obj["offline"] = True
ctx.bitshares = BitShares(**ctx.obj)
ctx.... | [
"def",
"offline",
"(",
"f",
")",
":",
"@",
"click",
".",
"pass_context",
"@",
"verbose",
"def",
"new_func",
"(",
"ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
".",
"obj",
"[",
"\"offline\"",
"]",
"=",
"True",
"ctx",
".",
"bit... | 30.8 | 12.6 |
def update_signature(self, location):
"""
Uses GET to get a newly signed metadata statement.
:param location: A URL to which the request is sent
:return: returns a dictionary with 'sms' and 'loc' as keys.
"""
response = requests.get(location, **self.req_args())
r... | [
"def",
"update_signature",
"(",
"self",
",",
"location",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"location",
",",
"*",
"*",
"self",
".",
"req_args",
"(",
")",
")",
"return",
"self",
".",
"parse_response",
"(",
"response",
")"
] | 38.555556 | 14.555556 |
def initialize(self):
"""initialize in base class"""
self._lb = [b[0] for b in self.bounds] # can be done more efficiently?
self._ub = [b[1] for b in self.bounds] | [
"def",
"initialize",
"(",
"self",
")",
":",
"self",
".",
"_lb",
"=",
"[",
"b",
"[",
"0",
"]",
"for",
"b",
"in",
"self",
".",
"bounds",
"]",
"# can be done more efficiently?",
"self",
".",
"_ub",
"=",
"[",
"b",
"[",
"1",
"]",
"for",
"b",
"in",
"se... | 46 | 16 |
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 | 9.428571 |
def output_paas(gandi, paas, datacenters, vhosts, output_keys, justify=11):
""" Helper to output a paas information."""
output_generic(gandi, paas, output_keys, justify)
if 'sftp_server' in output_keys:
output_line(gandi, 'sftp_server', paas['ftp_server'], justify)
if 'vhost' in output_keys:
... | [
"def",
"output_paas",
"(",
"gandi",
",",
"paas",
",",
"datacenters",
",",
"vhosts",
",",
"output_keys",
",",
"justify",
"=",
"11",
")",
":",
"output_generic",
"(",
"gandi",
",",
"paas",
",",
"output_keys",
",",
"justify",
")",
"if",
"'sftp_server'",
"in",
... | 37.162162 | 20.054054 |
def add_metpy_logo(fig, x=10, y=25, zorder=100, size='small', **kwargs):
"""Add the MetPy logo to a figure.
Adds an image of the MetPy logo to the figure.
Parameters
----------
fig : `matplotlib.figure`
The `figure` instance used for plotting
x : int
x position padding in pixels
... | [
"def",
"add_metpy_logo",
"(",
"fig",
",",
"x",
"=",
"10",
",",
"y",
"=",
"25",
",",
"zorder",
"=",
"100",
",",
"size",
"=",
"'small'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_add_logo",
"(",
"fig",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y... | 27.769231 | 22.423077 |
def encode(self, method, uri):
'''Called by the client to encode Authentication header.'''
if not self.username or not self.password:
return
o = self.options
qop = o.get('qop')
realm = o.get('realm')
nonce = o.get('nonce')
entdig = None
p_parse... | [
"def",
"encode",
"(",
"self",
",",
"method",
",",
"uri",
")",
":",
"if",
"not",
"self",
".",
"username",
"or",
"not",
"self",
".",
"password",
":",
"return",
"o",
"=",
"self",
".",
"options",
"qop",
"=",
"o",
".",
"get",
"(",
"'qop'",
")",
"realm... | 37.909091 | 13.636364 |
def create_global_steps():
"""Creates TF ops to track and increment global training step."""
global_step = tf.Variable(0, name="global_step", trainable=False, dtype=tf.int32)
increment_step = tf.assign(global_step, tf.add(global_step, 1))
return global_step, increment_step | [
"def",
"create_global_steps",
"(",
")",
":",
"global_step",
"=",
"tf",
".",
"Variable",
"(",
"0",
",",
"name",
"=",
"\"global_step\"",
",",
"trainable",
"=",
"False",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"increment_step",
"=",
"tf",
".",
"assign",... | 60.2 | 19.2 |
def mainloop(self):
""" The main loop.
"""
# Print usage if not enough args
if len(self.args) < 2:
self.parser.print_help()
self.parser.exit()
# TODO: Add mode to move tied metafiles, without losing the tie
# Target handling
target = self... | [
"def",
"mainloop",
"(",
"self",
")",
":",
"# Print usage if not enough args",
"if",
"len",
"(",
"self",
".",
"args",
")",
"<",
"2",
":",
"self",
".",
"parser",
".",
"print_help",
"(",
")",
"self",
".",
"parser",
".",
"exit",
"(",
")",
"# TODO: Add mode t... | 45.671756 | 26.183206 |
def find_consumers(self, var_def, simplified_graph=True):
"""
Find all consumers to the specified variable definition.
:param ProgramVariable var_def: The variable definition.
:param bool simplified_graph: True if we want to search in the simplified graph, False otherwise.
:retu... | [
"def",
"find_consumers",
"(",
"self",
",",
"var_def",
",",
"simplified_graph",
"=",
"True",
")",
":",
"if",
"simplified_graph",
":",
"graph",
"=",
"self",
".",
"simplified_data_graph",
"else",
":",
"graph",
"=",
"self",
".",
"data_graph",
"if",
"var_def",
"n... | 33.184211 | 18.921053 |
def schedule_snapshot(self):
"""Trigger snapshot to be uploaded to AWS.
Return success state."""
# Notes:
# - Snapshots are not immediate.
# - Snapshots will be cached for predefined amount
# of time.
# - Snapshots are not balanced. To get a better
#... | [
"def",
"schedule_snapshot",
"(",
"self",
")",
":",
"# Notes:",
"# - Snapshots are not immediate.",
"# - Snapshots will be cached for predefined amount",
"# of time.",
"# - Snapshots are not balanced. To get a better",
"# image, it must be taken from the stream, a few",
"# seconds... | 37.6875 | 15.8125 |
def get_collection(self, collection_id=None, nav="children", page=None):
""" Makes a call on the Collection API
:param collection_id: Id of the collection to retrieve
:param nav: Direction of the navigation
:param page: Page to retrieve
:return: Response
:rtype: requests... | [
"def",
"get_collection",
"(",
"self",
",",
"collection_id",
"=",
"None",
",",
"nav",
"=",
"\"children\"",
",",
"page",
"=",
"None",
")",
":",
"return",
"self",
".",
"call",
"(",
"\"collections\"",
",",
"{",
"\"id\"",
":",
"collection_id",
",",
"\"nav\"",
... | 28.727273 | 15.772727 |
def assess_quality(feed: "Feed") -> DataFrame:
"""
Return a DataFrame of various feed indicators and values,
e.g. number of trips missing shapes.
Parameters
----------
feed : Feed
Returns
-------
DataFrame
The columns are
- ``'indicator'``: string; name of an indic... | [
"def",
"assess_quality",
"(",
"feed",
":",
"\"Feed\"",
")",
"->",
"DataFrame",
":",
"d",
"=",
"OrderedDict",
"(",
")",
"# Count duplicate route short names",
"r",
"=",
"feed",
".",
"routes",
"dup",
"=",
"r",
".",
"duplicated",
"(",
"subset",
"=",
"[",
"\"r... | 31.14433 | 18.938144 |
def used(self, fieldname):
"""fieldname is used, remove from list of unused fields"""
if fieldname in self.unused:
self.unused.remove(fieldname) | [
"def",
"used",
"(",
"self",
",",
"fieldname",
")",
":",
"if",
"fieldname",
"in",
"self",
".",
"unused",
":",
"self",
".",
"unused",
".",
"remove",
"(",
"fieldname",
")"
] | 42.25 | 4.75 |
def get_max_bond_distance(self, el1_sym, el2_sym):
"""
Use Jmol algorithm to determine bond length from atomic parameters
Args:
el1_sym: (str) symbol of atom 1
el2_sym: (str) symbol of atom 2
Returns: (float) max bond length
"""
return sqrt(
... | [
"def",
"get_max_bond_distance",
"(",
"self",
",",
"el1_sym",
",",
"el2_sym",
")",
":",
"return",
"sqrt",
"(",
"(",
"self",
".",
"el_radius",
"[",
"el1_sym",
"]",
"+",
"self",
".",
"el_radius",
"[",
"el2_sym",
"]",
"+",
"self",
".",
"tol",
")",
"**",
... | 32.083333 | 18.083333 |
def _find_bad_meta(self):
'''Fill self._badmeta with meta datatypes that are invalid'''
self._badmeta = dict()
for datatype in self.meta:
for item in self.meta[datatype]:
if not Dap._meta_valid[datatype].match(item):
if datatype not in self._badme... | [
"def",
"_find_bad_meta",
"(",
"self",
")",
":",
"self",
".",
"_badmeta",
"=",
"dict",
"(",
")",
"for",
"datatype",
"in",
"self",
".",
"meta",
":",
"for",
"item",
"in",
"self",
".",
"meta",
"[",
"datatype",
"]",
":",
"if",
"not",
"Dap",
".",
"_meta_... | 42.4 | 16.6 |
def deregister(self, reg_data, retry=True, interval=1, timeout=3):
"""
Deregister model/view of this bundle
"""
Retry(target=self.publish.direct.delete,
args=("/controller/registration", reg_data,),
kwargs={"timeout": timeout},
options={"retry": ... | [
"def",
"deregister",
"(",
"self",
",",
"reg_data",
",",
"retry",
"=",
"True",
",",
"interval",
"=",
"1",
",",
"timeout",
"=",
"3",
")",
":",
"Retry",
"(",
"target",
"=",
"self",
".",
"publish",
".",
"direct",
".",
"delete",
",",
"args",
"=",
"(",
... | 46.363636 | 11.636364 |
def _decode8(self, offset):
"""
Decode an UTF-8 String at the given offset
:param offset: offset of the string inside the data
:return: str
"""
# UTF-8 Strings contain two lengths, as they might differ:
# 1) the UTF-16 length
str_len, skip = self._decode_... | [
"def",
"_decode8",
"(",
"self",
",",
"offset",
")",
":",
"# UTF-8 Strings contain two lengths, as they might differ:",
"# 1) the UTF-16 length",
"str_len",
",",
"skip",
"=",
"self",
".",
"_decode_length",
"(",
"offset",
",",
"1",
")",
"offset",
"+=",
"skip",
"# 2) t... | 33.045455 | 21.409091 |
def __preprocess_arguments(root):
"""Preprocesses occurrences of Argument within the root.
Argument XML values reference other values within the document by name. The
referenced value does not contain a switch. This function will add the
switch associated with the argument.
"""
# Set the flags ... | [
"def",
"__preprocess_arguments",
"(",
"root",
")",
":",
"# Set the flags to require a value",
"flags",
"=",
"','",
".",
"join",
"(",
"vsflags",
"(",
"VSFlags",
".",
"UserValueRequired",
")",
")",
"# Search through the arguments",
"arguments",
"=",
"root",
".",
"getE... | 36.697674 | 18.023256 |
def infer(self, **options):
"""https://github.com/frictionlessdata/datapackage-py#resource
"""
descriptor = deepcopy(self.__current_descriptor)
# Blank -> Stop
if self.__source_inspection.get('blank'):
return descriptor
# Name
if not descriptor.get('... | [
"def",
"infer",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"descriptor",
"=",
"deepcopy",
"(",
"self",
".",
"__current_descriptor",
")",
"# Blank -> Stop",
"if",
"self",
".",
"__source_inspection",
".",
"get",
"(",
"'blank'",
")",
":",
"return",
"des... | 34.058824 | 19.764706 |
def field_value(key, label, color, padding):
"""
Print a specific field's stats.
"""
if not clr.has_colors and padding > 0:
padding = 7
if color == "bright gray" or color == "dark gray":
bright_prefix = ""
else:
bright_prefix = "bright "
field = clr.stringc(key, "{0... | [
"def",
"field_value",
"(",
"key",
",",
"label",
",",
"color",
",",
"padding",
")",
":",
"if",
"not",
"clr",
".",
"has_colors",
"and",
"padding",
">",
"0",
":",
"padding",
"=",
"7",
"if",
"color",
"==",
"\"bright gray\"",
"or",
"color",
"==",
"\"dark gr... | 27.9375 | 16.8125 |
def to_css(self):
''' Generate the CSS representation of this RGB color.
Returns:
str, ``"rgb(...)"`` or ``"rgba(...)"``
'''
if self.a == 1.0:
return "rgb(%d, %d, %d)" % (self.r, self.g, self.b)
else:
return "rgba(%d, %d, %d, %s)" % (self.r, ... | [
"def",
"to_css",
"(",
"self",
")",
":",
"if",
"self",
".",
"a",
"==",
"1.0",
":",
"return",
"\"rgb(%d, %d, %d)\"",
"%",
"(",
"self",
".",
"r",
",",
"self",
".",
"g",
",",
"self",
".",
"b",
")",
"else",
":",
"return",
"\"rgba(%d, %d, %d, %s)\"",
"%",
... | 30.272727 | 26.272727 |
def downfile(self, remotefile, localpath = ''):
''' Usage: downfile <remotefile> [localpath] - \
download a remote file.
remotefile - remote file at Baidu Yun (after app root directory at Baidu Yun)
localpath - local path.
if it ends with '/' or '\\', it specifies the local directory
if it specifies an ex... | [
"def",
"downfile",
"(",
"self",
",",
"remotefile",
",",
"localpath",
"=",
"''",
")",
":",
"localfile",
"=",
"localpath",
"if",
"not",
"localpath",
":",
"localfile",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"remotefile",
")",
"elif",
"localpath",
"["... | 39.333333 | 19.407407 |
def _init_sub_groups(self, parent):
"""
Initialise sub-groups, and create any that do not already exist.
"""
if self._sub_groups:
for sub_group in self._sub_groups:
for component in split_path_components(sub_group):
fp = os.path.join(paren... | [
"def",
"_init_sub_groups",
"(",
"self",
",",
"parent",
")",
":",
"if",
"self",
".",
"_sub_groups",
":",
"for",
"sub_group",
"in",
"self",
".",
"_sub_groups",
":",
"for",
"component",
"in",
"split_path_components",
"(",
"sub_group",
")",
":",
"fp",
"=",
"os... | 39.333333 | 14.444444 |
def proof_type(self, proof_type):
"""
:param proof_type:
:return:
"""
if proof_type in CRYPTOCURRENCY_PROOF_TYPES:
self._proof_type = proof_type
else:
raise ValueError("Invalid input for proof type: %s" % proof_type) | [
"def",
"proof_type",
"(",
"self",
",",
"proof_type",
")",
":",
"if",
"proof_type",
"in",
"CRYPTOCURRENCY_PROOF_TYPES",
":",
"self",
".",
"_proof_type",
"=",
"proof_type",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid input for proof type: %s\"",
"%",
"proof_ty... | 31.111111 | 13.555556 |
def insert(self, objects, index=0):
"""
Insert an L{Element} content at the specified index.
@param objects: A (single|collection) of attribute(s) or element(s) to
be added as children.
@type objects: (L{Element}|L{Attribute})
@param index: The position in the list o... | [
"def",
"insert",
"(",
"self",
",",
"objects",
",",
"index",
"=",
"0",
")",
":",
"objects",
"=",
"(",
"objects",
",",
")",
"for",
"child",
"in",
"objects",
":",
"if",
"not",
"isinstance",
"(",
"child",
",",
"Element",
")",
":",
"raise",
"Exception",
... | 34.190476 | 15.428571 |
def median_low(data):
"""Return the low median of numeric data.
When the number of data points is odd, the middle value is returned.
When it is even, the smaller of the two middle values is returned.
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median f... | [
"def",
"median_low",
"(",
"data",
")",
":",
"data",
"=",
"sorted",
"(",
"data",
")",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"==",
"0",
":",
"raise",
"StatisticsError",
"(",
"\"no median for empty data\"",
")",
"if",
"n",
"%",
"2",
"==",
"1",
... | 29.357143 | 19.928571 |
def noisy_moment(self, moment: 'cirq.Moment',
system_qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
"""Adds noise to the operations from a moment.
Args:
moment: The moment to add noise to.
system_qubits: A list of all qubits in the system.
Returns... | [
"def",
"noisy_moment",
"(",
"self",
",",
"moment",
":",
"'cirq.Moment'",
",",
"system_qubits",
":",
"Sequence",
"[",
"'cirq.Qid'",
"]",
")",
"->",
"'cirq.OP_TREE'",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"noisy_moments",
",",
"'_not_overridden'",
")",
... | 38.666667 | 22.944444 |
def fit_tranform(self, raw_documents):
"""
Transform given list of raw_documents to document-term matrix in
sparse CSR format (see scipy)
"""
X = self.transform(raw_documents, new_document=True)
return X | [
"def",
"fit_tranform",
"(",
"self",
",",
"raw_documents",
")",
":",
"X",
"=",
"self",
".",
"transform",
"(",
"raw_documents",
",",
"new_document",
"=",
"True",
")",
"return",
"X"
] | 35 | 11.571429 |
def loads(s, *args, **kwargs):
"""Helper function that wraps :func:`json.loads`.
Automatically passes the object_hook for BSON type conversion.
Raises ``TypeError``, ``ValueError``, ``KeyError``, or
:exc:`~bson.errors.InvalidId` on invalid MongoDB Extended JSON.
:Parameters:
- `json_options... | [
"def",
"loads",
"(",
"s",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"json_options",
"=",
"kwargs",
".",
"pop",
"(",
"\"json_options\"",
",",
"DEFAULT_JSON_OPTIONS",
")",
"if",
"_HAS_OBJECT_PAIRS_HOOK",
":",
"kwargs",
"[",
"\"object_pairs_hook\"",
... | 40.785714 | 23.714286 |
def _set_items(self, a_iter):
"Clear and set the strings (and data if any) in the control from a list"
self._items_dict = {}
if not a_iter:
string_list = []
data_list = []
elif not isinstance(a_iter, (tuple, list, dict)):
raise ValueError("ite... | [
"def",
"_set_items",
"(",
"self",
",",
"a_iter",
")",
":",
"self",
".",
"_items_dict",
"=",
"{",
"}",
"if",
"not",
"a_iter",
":",
"string_list",
"=",
"[",
"]",
"data_list",
"=",
"[",
"]",
"elif",
"not",
"isinstance",
"(",
"a_iter",
",",
"(",
"tuple",... | 37.964286 | 13.107143 |
def disambiguate_ip_address(ip, location=None):
"""turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation of location is localhost)."""
if ip in ('0.0.0.0', '*'):
try:
external_ips = socket.gethostbyname_ex(socket.gethostname())[2]... | [
"def",
"disambiguate_ip_address",
"(",
"ip",
",",
"location",
"=",
"None",
")",
":",
"if",
"ip",
"in",
"(",
"'0.0.0.0'",
",",
"'*'",
")",
":",
"try",
":",
"external_ips",
"=",
"socket",
".",
"gethostbyname_ex",
"(",
"socket",
".",
"gethostname",
"(",
")"... | 46.2 | 17.6 |
def init(cls, site):
"""
put site settings in the header of the script
"""
bash_header = ""
for k,v in site.items():
bash_header += "%s=%s" % (k.upper(), v)
bash_header += '\n'
site['bash_header'] = bash_header
# TODO: execute before_deplo... | [
"def",
"init",
"(",
"cls",
",",
"site",
")",
":",
"bash_header",
"=",
"\"\"",
"for",
"k",
",",
"v",
"in",
"site",
".",
"items",
"(",
")",
":",
"bash_header",
"+=",
"\"%s=%s\"",
"%",
"(",
"k",
".",
"upper",
"(",
")",
",",
"v",
")",
"bash_header",
... | 41 | 14.931034 |
def get_dirs(self) -> List[str]:
"""
Get all effect directories for registered effects.
"""
for package in self.packages:
yield os.path.join(package.path, 'resources') | [
"def",
"get_dirs",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"for",
"package",
"in",
"self",
".",
"packages",
":",
"yield",
"os",
".",
"path",
".",
"join",
"(",
"package",
".",
"path",
",",
"'resources'",
")"
] | 34.333333 | 7.666667 |
def convert_like(item, like):
"""
Convert an item to have the dtype of another item
Parameters
----------
item: item to be converted
like: object with target dtype. If None, item is returned unmodified
Returns
--------
result: item, but in dtype of like
"""
if isinstance(li... | [
"def",
"convert_like",
"(",
"item",
",",
"like",
")",
":",
"if",
"isinstance",
"(",
"like",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"np",
".",
"asanyarray",
"(",
"item",
",",
"dtype",
"=",
"like",
".",
"dtype",
")",
"if",
"isinstance",
"(",
... | 23.961538 | 19.884615 |
def _linux_stp(br, state):
'''
Internal, sets STP state
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} stp {1} {2}'.format(brctl, br, state),
python_shell=False) | [
"def",
"_linux_stp",
"(",
"br",
",",
"state",
")",
":",
"brctl",
"=",
"_tool_path",
"(",
"'brctl'",
")",
"return",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'{0} stp {1} {2}'",
".",
"format",
"(",
"brctl",
",",
"br",
",",
"state",
")",
",",
"python_shell"... | 31.857143 | 20.714286 |
def _ntz(x):
"""
Get the number of consecutive zeros
:param x:
:return:
"""
if x == 0:
return 0
y = (~x) & (x - 1) # There is actually a bug in BAP until 0.8
def bits(y):
n = 0
while y != 0:
n += 1
... | [
"def",
"_ntz",
"(",
"x",
")",
":",
"if",
"x",
"==",
"0",
":",
"return",
"0",
"y",
"=",
"(",
"~",
"x",
")",
"&",
"(",
"x",
"-",
"1",
")",
"# There is actually a bug in BAP until 0.8",
"def",
"bits",
"(",
"y",
")",
":",
"n",
"=",
"0",
"while",
"y... | 21.705882 | 19 |
def confidence_interval(data, alpha):
"""
Computes the mean and alpha-confidence interval of the given sample set
Parameters
----------
data : ndarray
a 1D-array of samples
alpha : float in [0,1]
the confidence level, i.e. percentage of data included in the interval
... | [
"def",
"confidence_interval",
"(",
"data",
",",
"alpha",
")",
":",
"if",
"alpha",
"<",
"0",
"or",
"alpha",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'Not a meaningful confidence level: '",
"+",
"str",
"(",
"alpha",
")",
")",
"# compute mean",
"m",
"=",
"... | 29.809524 | 19.333333 |
def recognize(self, node: yaml.Node, expected_type: Type) -> RecResult:
"""Figure out how to interpret this node.
This is not quite a type check. This function makes a list of \
all types that match the expected type and also the node, and \
returns that list. The goal here is not to te... | [
"def",
"recognize",
"(",
"self",
",",
"node",
":",
"yaml",
".",
"Node",
",",
"expected_type",
":",
"Type",
")",
"->",
"RecResult",
":",
"logger",
".",
"debug",
"(",
"'Recognizing {} as a {}'",
".",
"format",
"(",
"node",
",",
"expected_type",
")",
")",
"... | 42.723404 | 18.638298 |
def _cancel_outstanding(self):
"""Cancel all of our outstanding requests"""
for d in list(self._outstanding):
d.addErrback(lambda _: None) # Eat any uncaught errors
d.cancel() | [
"def",
"_cancel_outstanding",
"(",
"self",
")",
":",
"for",
"d",
"in",
"list",
"(",
"self",
".",
"_outstanding",
")",
":",
"d",
".",
"addErrback",
"(",
"lambda",
"_",
":",
"None",
")",
"# Eat any uncaught errors",
"d",
".",
"cancel",
"(",
")"
] | 42.4 | 11.2 |
def get_required_fields(self):
"""Return the names of fields that are required according to the schema."""
return [m.name for m in self._ast_node.members if m.member_schema.required] | [
"def",
"get_required_fields",
"(",
"self",
")",
":",
"return",
"[",
"m",
".",
"name",
"for",
"m",
"in",
"self",
".",
"_ast_node",
".",
"members",
"if",
"m",
".",
"member_schema",
".",
"required",
"]"
] | 62.666667 | 16.333333 |
def read_xmile(xmile_file):
""" Construct a model object from `.xmile` file. """
from . import py_backend
from .py_backend.xmile.xmile2py import translate_xmile
py_model_file = translate_xmile(xmile_file)
model = load(py_model_file)
model.xmile_file = xmile_file
return model | [
"def",
"read_xmile",
"(",
"xmile_file",
")",
":",
"from",
".",
"import",
"py_backend",
"from",
".",
"py_backend",
".",
"xmile",
".",
"xmile2py",
"import",
"translate_xmile",
"py_model_file",
"=",
"translate_xmile",
"(",
"xmile_file",
")",
"model",
"=",
"load",
... | 37 | 11.25 |
def _decode_filename_to_unicode(f):
'''Get bytestring filename and return unicode.
First, try to decode from default file system encoding
If that fails, use ``chardet`` module to guess encoding.
As a last resort, try to decode as utf-8.
If the argument already is unicode, return as is'''
log.d... | [
"def",
"_decode_filename_to_unicode",
"(",
"f",
")",
":",
"log",
".",
"debug",
"(",
"'_decode_filename_to_unicode(%s)'",
",",
"repr",
"(",
"f",
")",
")",
"if",
"isinstance",
"(",
"f",
",",
"unicode",
")",
":",
"return",
"f",
"try",
":",
"return",
"f",
".... | 38.5 | 17.088235 |
def build(client, destination_args):
""" Build a SetupHandler object for client from destination parameters.
"""
# Have defined a remote job directory, lets do the setup locally.
if client.job_directory:
handler = LocalSetupHandler(client, destination_args)
else:
handler = RemoteSetu... | [
"def",
"build",
"(",
"client",
",",
"destination_args",
")",
":",
"# Have defined a remote job directory, lets do the setup locally.",
"if",
"client",
".",
"job_directory",
":",
"handler",
"=",
"LocalSetupHandler",
"(",
"client",
",",
"destination_args",
")",
"else",
":... | 38.555556 | 13.666667 |
def _handle_hr(self):
"""Handle a wiki-style horizontal rule (``----``) in the string."""
length = 4
self._head += 3
while self._read(1) == "-":
length += 1
self._head += 1
self._emit(tokens.TagOpenOpen(wiki_markup="-" * length))
self._emit_text("h... | [
"def",
"_handle_hr",
"(",
"self",
")",
":",
"length",
"=",
"4",
"self",
".",
"_head",
"+=",
"3",
"while",
"self",
".",
"_read",
"(",
"1",
")",
"==",
"\"-\"",
":",
"length",
"+=",
"1",
"self",
".",
"_head",
"+=",
"1",
"self",
".",
"_emit",
"(",
... | 36.1 | 13.4 |
def _parse_dependencies(string):
"""
This function actually parses the dependencies are sorts them into
the buildable and given dependencies
"""
contents = _get_contents_between(string, '(', ')')
unsorted_dependencies = contents.split(',')
_check_parameters(unsorted_dependencies, ('?',))
... | [
"def",
"_parse_dependencies",
"(",
"string",
")",
":",
"contents",
"=",
"_get_contents_between",
"(",
"string",
",",
"'('",
",",
"')'",
")",
"unsorted_dependencies",
"=",
"contents",
".",
"split",
"(",
"','",
")",
"_check_parameters",
"(",
"unsorted_dependencies",... | 35.052632 | 13.789474 |
def all(self):
" execute query, get all list of lists"
query,inputs = self._toedn()
return self.db.q(query,
inputs = inputs,
limit = self._limit,
offset = self._offset,
history = self._history) | [
"def",
"all",
"(",
"self",
")",
":",
"query",
",",
"inputs",
"=",
"self",
".",
"_toedn",
"(",
")",
"return",
"self",
".",
"db",
".",
"q",
"(",
"query",
",",
"inputs",
"=",
"inputs",
",",
"limit",
"=",
"self",
".",
"_limit",
",",
"offset",
"=",
... | 28.25 | 12.5 |
def ParseFlags(self, *flags):
"""
Parse the set of flags and return a dict with the flags placed
in the appropriate entry. The flags are treated as a typical
set of command-line flags for a GNU-like toolchain and used to
populate the entries in the dict immediately below. If on... | [
"def",
"ParseFlags",
"(",
"self",
",",
"*",
"flags",
")",
":",
"dict",
"=",
"{",
"'ASFLAGS'",
":",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"''",
")",
",",
"'CFLAGS'",
":",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"''",
")",
",",
"'CCFLAGS'",
":"... | 44.177914 | 14.018405 |
def export(self, hashVal, hashPath, tags=None, galleries=None):
"""
The export function needs to:
- Move source image to asset folder
- Rename to guid.ext
- Save thumbnail, video_thumbnail, and MP4 versions. If the source is already h264, then only transcode the thumbnails
... | [
"def",
"export",
"(",
"self",
",",
"hashVal",
",",
"hashPath",
",",
"tags",
"=",
"None",
",",
"galleries",
"=",
"None",
")",
":",
"self",
".",
"source",
"=",
"hashPath",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
".",
"replace",
"(",
"ROOT",
"... | 28.808511 | 19.361702 |
def proposal(self, proposer=None, proposal_expiration=None, proposal_review=None):
""" Return the default proposal buffer
... note:: If any parameter is set, the default proposal
parameters will be changed!
"""
if not self._propbuffer:
return self.new_prop... | [
"def",
"proposal",
"(",
"self",
",",
"proposer",
"=",
"None",
",",
"proposal_expiration",
"=",
"None",
",",
"proposal_review",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_propbuffer",
":",
"return",
"self",
".",
"new_proposal",
"(",
"self",
".",
"... | 40.941176 | 17.117647 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.