text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def jc(result, reference):
"""
Jaccard coefficient
Computes the Jaccard coefficient between the binary objects in two images.
Parameters
----------
result: array_like
Input data containing objects. Can be any type but will be converted
into binary: background wh... | [
"def",
"jc",
"(",
"result",
",",
"reference",
")",
":",
"result",
"=",
"numpy",
".",
"atleast_1d",
"(",
"result",
".",
"astype",
"(",
"numpy",
".",
"bool",
")",
")",
"reference",
"=",
"numpy",
".",
"atleast_1d",
"(",
"reference",
".",
"astype",
"(",
... | 32.823529 | 0.009574 |
def hkeys(self, key, *, encoding=_NOTSET):
"""Get all the fields in a hash."""
return self.execute(b'HKEYS', key, encoding=encoding) | [
"def",
"hkeys",
"(",
"self",
",",
"key",
",",
"*",
",",
"encoding",
"=",
"_NOTSET",
")",
":",
"return",
"self",
".",
"execute",
"(",
"b'HKEYS'",
",",
"key",
",",
"encoding",
"=",
"encoding",
")"
] | 48.666667 | 0.013514 |
def _install_hiero(use_threaded_wrapper):
"""Helper function to The Foundry Hiero support"""
import hiero
import nuke
if "--hiero" not in nuke.rawArgs:
raise ImportError
def threaded_wrapper(func, *args, **kwargs):
return hiero.core.executeInMainThreadWithResult(
func, ... | [
"def",
"_install_hiero",
"(",
"use_threaded_wrapper",
")",
":",
"import",
"hiero",
"import",
"nuke",
"if",
"\"--hiero\"",
"not",
"in",
"nuke",
".",
"rawArgs",
":",
"raise",
"ImportError",
"def",
"threaded_wrapper",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*... | 29.923077 | 0.002494 |
def diags2(symmat):
"""
Diagonalize a symmetric 2x2 matrix.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/diags2_c.html
:param symmat: A symmetric 2x2 matrix.
:type symmat: 2x2-Element Array of floats
:return:
A diagonal matrix similar to symmat,
A rotation us... | [
"def",
"diags2",
"(",
"symmat",
")",
":",
"symmat",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"symmat",
")",
"diag",
"=",
"stypes",
".",
"emptyDoubleMatrix",
"(",
"x",
"=",
"2",
",",
"y",
"=",
"2",
")",
"rotateout",
"=",
"stypes",
".",
"emptyDoubleMat... | 34.722222 | 0.001558 |
def serialize_task_spec(self, spec, elem):
"""
Serializes common attributes of :meth:`SpiffWorkflow.specs.TaskSpec`.
"""
if spec.id is not None:
SubElement(elem, 'id').text = str(spec.id)
SubElement(elem, 'name').text = spec.name
if spec.description:
... | [
"def",
"serialize_task_spec",
"(",
"self",
",",
"spec",
",",
"elem",
")",
":",
"if",
"spec",
".",
"id",
"is",
"not",
"None",
":",
"SubElement",
"(",
"elem",
",",
"'id'",
")",
".",
"text",
"=",
"str",
"(",
"spec",
".",
"id",
")",
"SubElement",
"(",
... | 44.310345 | 0.001523 |
def remove_all(self, item):
# type: (Any) -> None
"""
Remove all occurrence of the parameter.
:param item: Value to delete from the WeakList.
"""
item = self.ref(item)
while list.__contains__(self, item):
list.remove(self, item) | [
"def",
"remove_all",
"(",
"self",
",",
"item",
")",
":",
"# type: (Any) -> None",
"item",
"=",
"self",
".",
"ref",
"(",
"item",
")",
"while",
"list",
".",
"__contains__",
"(",
"self",
",",
"item",
")",
":",
"list",
".",
"remove",
"(",
"self",
",",
"i... | 32 | 0.010135 |
def build_groetzch_graph():
"""Makes a new Groetzsch graph.
Ref: http://mathworld.wolfram.com/GroetzschGraph.html"""
# Because the graph is so complicated, we want to
# build it via adjacency matrix specification
# -- Initialize the matrix to all zeros
adj = [[0 for _ in range(11)] for _... | [
"def",
"build_groetzch_graph",
"(",
")",
":",
"# Because the graph is so complicated, we want to",
"# build it via adjacency matrix specification",
"# -- Initialize the matrix to all zeros",
"adj",
"=",
"[",
"[",
"0",
"for",
"_",
"in",
"range",
"(",
"11",
")",
"]",
"for",
... | 30.027778 | 0.049283 |
def pathFromIndex(self, index):
"""
Returns the joined path from the given model index. This will
join together the full path with periods.
:param index | <QModelIndex>
:return <str>
"""
out = []
while index and index... | [
"def",
"pathFromIndex",
"(",
"self",
",",
"index",
")",
":",
"out",
"=",
"[",
"]",
"while",
"index",
"and",
"index",
".",
"isValid",
"(",
")",
":",
"out",
".",
"append",
"(",
"nativestring",
"(",
"unwrapVariant",
"(",
"index",
".",
"data",
"(",
")",
... | 32.733333 | 0.011881 |
def to_string(self, endpoints):
"""
Converts the given endpoint description beans into a string
:param endpoints: A list of EndpointDescription beans
:return: A string containing an XML document
"""
# Make the ElementTree
root = self._make_xml(endpoints)
... | [
"def",
"to_string",
"(",
"self",
",",
"endpoints",
")",
":",
"# Make the ElementTree",
"root",
"=",
"self",
".",
"_make_xml",
"(",
"endpoints",
")",
"tree",
"=",
"ElementTree",
".",
"ElementTree",
"(",
"root",
")",
"# Force the default name space",
"ElementTree",
... | 29.513514 | 0.001773 |
def concat_vectors(*args):
"""Concatenates input vectors, statically if possible."""
args_ = [tf.get_static_value(x) for x in args]
if any(vec is None for vec in args_):
return tf.concat(args, axis=0)
return [val for vec in args_ for val in vec] | [
"def",
"concat_vectors",
"(",
"*",
"args",
")",
":",
"args_",
"=",
"[",
"tf",
".",
"get_static_value",
"(",
"x",
")",
"for",
"x",
"in",
"args",
"]",
"if",
"any",
"(",
"vec",
"is",
"None",
"for",
"vec",
"in",
"args_",
")",
":",
"return",
"tf",
"."... | 42 | 0.019455 |
def delete_deployment(self, service_name, deployment_name,delete_vhd=False):
'''
Deletes the specified deployment.
service_name:
Name of the hosted service.
deployment_name:
The name of the deployment.
'''
_validate_not_none('service_name', servic... | [
"def",
"delete_deployment",
"(",
"self",
",",
"service_name",
",",
"deployment_name",
",",
"delete_vhd",
"=",
"False",
")",
":",
"_validate_not_none",
"(",
"'service_name'",
",",
"service_name",
")",
"_validate_not_none",
"(",
"'deployment_name'",
",",
"deployment_nam... | 35.235294 | 0.009756 |
def get_owned_subscriptions(self, server_id):
"""
Return the indication subscriptions in a WBEM server owned by this
subscription manager.
This function accesses only the local list of owned subscriptions; it
does not contact the WBEM server. The local list of owned subscription... | [
"def",
"get_owned_subscriptions",
"(",
"self",
",",
"server_id",
")",
":",
"# Validate server_id",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"return",
"list",
"(",
"self",
".",
"_owned_subscriptions",
"[",
"server_id",
"]",
")"
] | 35.185185 | 0.002049 |
def clear(self):
''' Clear the undo list. '''
self._undos.clear()
self._redos.clear()
self._savepoint = None
self._receiver = self._undos | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_undos",
".",
"clear",
"(",
")",
"self",
".",
"_redos",
".",
"clear",
"(",
")",
"self",
".",
"_savepoint",
"=",
"None",
"self",
".",
"_receiver",
"=",
"self",
".",
"_undos"
] | 29.5 | 0.010989 |
def git_branch(repo_dir, branch_name, start_point='HEAD',
force=True, verbose=True, checkout=False):
"""Create a new branch like `git branch <branch_name> <start_point>`."""
command = ['git', 'branch']
if verbose:
command.append('--verbose')
if force:
command.append('--for... | [
"def",
"git_branch",
"(",
"repo_dir",
",",
"branch_name",
",",
"start_point",
"=",
"'HEAD'",
",",
"force",
"=",
"True",
",",
"verbose",
"=",
"True",
",",
"checkout",
"=",
"False",
")",
":",
"command",
"=",
"[",
"'git'",
",",
"'branch'",
"]",
"if",
"ver... | 38.071429 | 0.001832 |
def session_end(self):
"""
End a session. Se session_begin for an in depth description of TREZOR sessions.
"""
self.session_depth -= 1
self.session_depth = max(0, self.session_depth)
if self.session_depth == 0:
self._session_end() | [
"def",
"session_end",
"(",
"self",
")",
":",
"self",
".",
"session_depth",
"-=",
"1",
"self",
".",
"session_depth",
"=",
"max",
"(",
"0",
",",
"self",
".",
"session_depth",
")",
"if",
"self",
".",
"session_depth",
"==",
"0",
":",
"self",
".",
"_session... | 35.5 | 0.010309 |
def steady_connection(self):
"""Get a steady, unpooled PostgreSQL connection."""
return SteadyPgConnection(self._maxusage, self._setsession, True,
*self._args, **self._kwargs) | [
"def",
"steady_connection",
"(",
"self",
")",
":",
"return",
"SteadyPgConnection",
"(",
"self",
".",
"_maxusage",
",",
"self",
".",
"_setsession",
",",
"True",
",",
"*",
"self",
".",
"_args",
",",
"*",
"*",
"self",
".",
"_kwargs",
")"
] | 55.5 | 0.008889 |
def edit_shares(self, id, user_ids): # pylint: disable=invalid-name,redefined-builtin
"""Edit shares for a config.
:param id: Config ID as an int.
:param user_ids: User IDs as int list.
:return: :class:`cdrouter.Share <cdrouter.Share>` list
"""
return self.service.edit_s... | [
"def",
"edit_shares",
"(",
"self",
",",
"id",
",",
"user_ids",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"return",
"self",
".",
"service",
".",
"edit_shares",
"(",
"self",
".",
"base",
",",
"id",
",",
"user_ids",
")"
] | 42.875 | 0.011429 |
def _distributeCells(numCellsPop):
''' distribute cells across compute nodes using round-robin'''
from .. import sim
hostCells = {}
for i in range(sim.nhosts):
hostCells[i] = []
for i in range(numCellsPop):
hostCells[sim.nextHost].append(i)
sim.next... | [
"def",
"_distributeCells",
"(",
"numCellsPop",
")",
":",
"from",
".",
".",
"import",
"sim",
"hostCells",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"sim",
".",
"nhosts",
")",
":",
"hostCells",
"[",
"i",
"]",
"=",
"[",
"]",
"for",
"i",
"in",
"... | 30.722222 | 0.024561 |
def create_template(self):
"""Create template (main function called by Stacker)."""
template = self.template
# variables = self.get_variables()
template.add_version('2010-09-09')
template.add_description('Static Website - Dependencies')
# Resources
awslogbucket =... | [
"def",
"create_template",
"(",
"self",
")",
":",
"template",
"=",
"self",
".",
"template",
"# variables = self.get_variables()",
"template",
".",
"add_version",
"(",
"'2010-09-09'",
")",
"template",
".",
"add_description",
"(",
"'Static Website - Dependencies'",
")",
... | 35.594203 | 0.000792 |
def render_template(template):
"""
takes a template to render to and returns a function that
takes an object to render the data for this template.
If callable_or_dict is callable, it will be called with
the request and any additional arguments to produce the
template paramaters. This is useful ... | [
"def",
"render_template",
"(",
"template",
")",
":",
"def",
"outer_wrapper",
"(",
"callable_or_dict",
"=",
"None",
",",
"statuscode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"wr... | 36.117647 | 0.000793 |
def help_center_user_user_segments(self, user_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/user_segments#list-user-segments"
api_path = "/api/v2/help_center/users/{user_id}/user_segments.json"
api_path = api_path.format(user_id=user_id)
return self.call(api_pat... | [
"def",
"help_center_user_user_segments",
"(",
"self",
",",
"user_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/users/{user_id}/user_segments.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"user_id",
"=",
"user_id",
")",
"... | 65.6 | 0.009036 |
def rmvsuffix(subject):
"""
Remove the suffix from *subject*.
"""
index = subject.rfind('.')
if index > subject.replace('\\', '/').rfind('/'):
subject = subject[:index]
return subject | [
"def",
"rmvsuffix",
"(",
"subject",
")",
":",
"index",
"=",
"subject",
".",
"rfind",
"(",
"'.'",
")",
"if",
"index",
">",
"subject",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
".",
"rfind",
"(",
"'/'",
")",
":",
"subject",
"=",
"subject",
"[",... | 21.333333 | 0.025 |
def member_status():
'''
Get cluster member status
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.member_status
'''
ret = {'membership': {},
'summary': {'Valid': 0,
'Leaving': 0,
'Exiting': 0,
... | [
"def",
"member_status",
"(",
")",
":",
"ret",
"=",
"{",
"'membership'",
":",
"{",
"}",
",",
"'summary'",
":",
"{",
"'Valid'",
":",
"0",
",",
"'Leaving'",
":",
"0",
",",
"'Exiting'",
":",
"0",
",",
"'Joining'",
":",
"0",
",",
"'Down'",
":",
"0",
"... | 25.190476 | 0.00091 |
def create_key_manager(self):
"""Create the :class:`KeyManager`.
The inputs to KeyManager are expected to be callable, so we can't
use the standard @property and @attrib.setter for these attributes.
Lambdas cannot contain assignments so we're forced to define setters.
:rtype: :... | [
"def",
"create_key_manager",
"(",
"self",
")",
":",
"def",
"set_match_fuzzy",
"(",
"match_fuzzy",
")",
":",
"\"\"\"Setter for fuzzy matching mode.\n\n :type match_fuzzy: bool\n :param match_fuzzy: The match fuzzy flag.\n\n \"\"\"",
"self",
".",
"model_c... | 35.745763 | 0.000923 |
def request(self, session_id):
"""Force the termination of a NETCONF session (not the current one!)
*session_id* is the session identifier of the NETCONF session to be terminated as a string
"""
node = new_ele("kill-session")
sub_ele(node, "session-id").text = session_id
... | [
"def",
"request",
"(",
"self",
",",
"session_id",
")",
":",
"node",
"=",
"new_ele",
"(",
"\"kill-session\"",
")",
"sub_ele",
"(",
"node",
",",
"\"session-id\"",
")",
".",
"text",
"=",
"session_id",
"return",
"self",
".",
"_request",
"(",
"node",
")"
] | 42.5 | 0.008646 |
def set_access_control(self, mode, onerror = None):
"""Enable use of access control lists at connection setup if mode
is X.EnableAccess, disable if it is X.DisableAccess."""
request.SetAccessControl(display = self.display,
onerror = onerror,
... | [
"def",
"set_access_control",
"(",
"self",
",",
"mode",
",",
"onerror",
"=",
"None",
")",
":",
"request",
".",
"SetAccessControl",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
",",
"mode",
"=",
"mode",
")"
] | 56.5 | 0.02907 |
def is_contradictory(self, other):
""" Two beliefstates are incompatible if the other beliefstates's entities
are not consistent with or accessible from the caller.
Note: this only compares the items in the DictCell, not `pos`,
`environment_variables` or `deferred_effects`.
... | [
"def",
"is_contradictory",
"(",
"self",
",",
"other",
")",
":",
"for",
"(",
"s_key",
",",
"s_val",
")",
"in",
"self",
":",
"if",
"s_key",
"in",
"other",
"and",
"s_val",
".",
"is_contradictory",
"(",
"other",
"[",
"s_key",
"]",
")",
":",
"return",
"Tr... | 43.454545 | 0.012295 |
def parameterized_codec(raw, b64):
"""Parameterize a string, possibly encoding it as Base64 afterwards
Args:
raw (`str` | `bytes`): String to be processed. Byte strings will be
interpreted as UTF-8.
b64 (`bool`): Whether to wrap the output in a Base64 CloudFormation
call... | [
"def",
"parameterized_codec",
"(",
"raw",
",",
"b64",
")",
":",
"if",
"isinstance",
"(",
"raw",
",",
"bytes",
")",
":",
"raw",
"=",
"raw",
".",
"decode",
"(",
"'utf-8'",
")",
"result",
"=",
"_parameterize_string",
"(",
"raw",
")",
"# Note, since we want a ... | 32.478261 | 0.0013 |
def _check_email_changed(cls, username, email):
"""Compares email to one set on SeAT"""
ret = cls.exec_request('user/{}'.format(username), 'get', raise_for_status=True)
return ret['email'] != email | [
"def",
"_check_email_changed",
"(",
"cls",
",",
"username",
",",
"email",
")",
":",
"ret",
"=",
"cls",
".",
"exec_request",
"(",
"'user/{}'",
".",
"format",
"(",
"username",
")",
",",
"'get'",
",",
"raise_for_status",
"=",
"True",
")",
"return",
"ret",
"... | 54.5 | 0.013575 |
def clear(self, key):
# type: (Hashable) -> DataLoader
"""
Clears the value at `key` from the cache, if it exists. Returns itself for
method chaining.
"""
cache_key = self.get_cache_key(key)
self._promise_cache.pop(cache_key, None)
return self | [
"def",
"clear",
"(",
"self",
",",
"key",
")",
":",
"# type: (Hashable) -> DataLoader",
"cache_key",
"=",
"self",
".",
"get_cache_key",
"(",
"key",
")",
"self",
".",
"_promise_cache",
".",
"pop",
"(",
"cache_key",
",",
"None",
")",
"return",
"self"
] | 33.222222 | 0.013029 |
def refine_peaks(arr, ipeaks, window_width):
"""Refine the peak location previously found by find_peaks_indexes
Parameters
----------
arr : 1d numpy array, float
Input 1D spectrum.
ipeaks : 1d numpy array (int)
Indices of the input array arr in which the peaks were initially found.
... | [
"def",
"refine_peaks",
"(",
"arr",
",",
"ipeaks",
",",
"window_width",
")",
":",
"_check_window_width",
"(",
"window_width",
")",
"step",
"=",
"window_width",
"//",
"2",
"ipeaks",
"=",
"filter_array_margins",
"(",
"arr",
",",
"ipeaks",
",",
"window_width",
")"... | 26.421053 | 0.000961 |
def now(cls, Name = None):
"""
Instantiate a Time element initialized to the current UTC
time in the default format (ISO-8601). The Name attribute
will be set to the value of the Name parameter if given.
"""
self = cls()
if Name is not None:
self.Name = Name
self.pcdata = datetime.datetime.utcnow()
... | [
"def",
"now",
"(",
"cls",
",",
"Name",
"=",
"None",
")",
":",
"self",
"=",
"cls",
"(",
")",
"if",
"Name",
"is",
"not",
"None",
":",
"self",
".",
"Name",
"=",
"Name",
"self",
".",
"pcdata",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
"... | 29.363636 | 0.042042 |
def getRGBData(self):
"Return byte array of RGB data as string"
if self._data is None:
self._dataA = None
if sys.platform[0:4] == 'java':
import jarray # TODO: Move to top.
from java.awt.image import PixelGrabber
width, height = s... | [
"def",
"getRGBData",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data",
"is",
"None",
":",
"self",
".",
"_dataA",
"=",
"None",
"if",
"sys",
".",
"platform",
"[",
"0",
":",
"4",
"]",
"==",
"'java'",
":",
"import",
"jarray",
"# TODO: Move to top.",
"fr... | 40.435897 | 0.002477 |
def break_sandbox():
"""Patches sandbox to add match-all regex to sandbox whitelist
"""
class EvilCM(object):
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
import re
tb.tb_next.tb_next.tb_next.tb_frame.f_locals[
'... | [
"def",
"break_sandbox",
"(",
")",
":",
"class",
"EvilCM",
"(",
"object",
")",
":",
"def",
"__enter__",
"(",
"self",
")",
":",
"return",
"self",
"def",
"__exit__",
"(",
"self",
",",
"exc_type",
",",
"exc",
",",
"tb",
")",
":",
"import",
"re",
"tb",
... | 29.235294 | 0.001949 |
def update_extent(self, extent):
# type: (int) -> None
'''
Update the extent for this CE record.
Parameters:
extent - The new extent for this CE record.
Returns:
Nothing.
'''
if not self._initialized:
raise pycdlibexception.PyCdlibIn... | [
"def",
"update_extent",
"(",
"self",
",",
"extent",
")",
":",
"# type: (int) -> None",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'CE record not yet initialized!'",
")",
"self",
".",
"bl_cont_area",
... | 27.714286 | 0.009975 |
def image_get(fingerprint,
remote_addr=None,
cert=None,
key=None,
verify_cert=True,
_raw=False):
''' Get an image by its fingerprint
fingerprint :
The fingerprint of the image to retrieve
remote_addr :
An... | [
"def",
"image_get",
"(",
"fingerprint",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
",",
"_raw",
"=",
"False",
")",
":",
"client",
"=",
"pylxd_client_get",
"(",
"remote_addr",
",",
... | 25.491525 | 0.00064 |
def _get_root(self):
"""get root user password."""
_DEFAULT_USER_DETAILS = {"level": 20, "password": "", "sshkeys": []}
root = {}
root_table = junos_views.junos_root_table(self.device)
root_table.get()
root_items = root_table.items()
for user_entry in root_items:
... | [
"def",
"_get_root",
"(",
"self",
")",
":",
"_DEFAULT_USER_DETAILS",
"=",
"{",
"\"level\"",
":",
"20",
",",
"\"password\"",
":",
"\"\"",
",",
"\"sshkeys\"",
":",
"[",
"]",
"}",
"root",
"=",
"{",
"}",
"root_table",
"=",
"junos_views",
".",
"junos_root_table"... | 40.73913 | 0.002086 |
def process_params(request, standard_params=STANDARD_QUERY_PARAMS,
filter_fields=None, defaults=None):
"""Parse query params.
Parses, validates, and converts query into a consistent format.
:keyword request: the bottle request
:keyword standard_params: query params that are present ... | [
"def",
"process_params",
"(",
"request",
",",
"standard_params",
"=",
"STANDARD_QUERY_PARAMS",
",",
"filter_fields",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"if",
"not",
"filter_fields",
":",
"filter_fields",
"=",
"[",
"]",
"unfilterable",
"=",
"(... | 42.391304 | 0.000501 |
def list_namespaced_daemon_set(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_daemon_set # noqa: E501
list or watch objects of kind DaemonSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req... | [
"def",
"list_namespaced_daemon_set",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".... | 162.733333 | 0.000407 |
def to_string(input_):
"""Format an input for representation as text
This method is just a convenience that handles default LaTeX formatting
"""
usetex = rcParams['text.usetex']
if isinstance(input_, units.UnitBase):
return input_.to_string('latex_inline')
if isinstance(input_, (float, ... | [
"def",
"to_string",
"(",
"input_",
")",
":",
"usetex",
"=",
"rcParams",
"[",
"'text.usetex'",
"]",
"if",
"isinstance",
"(",
"input_",
",",
"units",
".",
"UnitBase",
")",
":",
"return",
"input_",
".",
"to_string",
"(",
"'latex_inline'",
")",
"if",
"isinstan... | 34.384615 | 0.002179 |
def _batchify(self, batch_data, batch_label, start=0):
"""Override the helper function for batchifying data"""
i = start
batch_size = self.batch_size
try:
while i < batch_size:
label, s = self.next_sample()
data = self.imdecode(s)
... | [
"def",
"_batchify",
"(",
"self",
",",
"batch_data",
",",
"batch_label",
",",
"start",
"=",
"0",
")",
":",
"i",
"=",
"start",
"batch_size",
"=",
"self",
".",
"batch_size",
"try",
":",
"while",
"i",
"<",
"batch_size",
":",
"label",
",",
"s",
"=",
"self... | 42.862069 | 0.00236 |
def _replace_bm(self):
"""Replace ``_block_matcher`` with current values."""
self._block_matcher = cv2.StereoSGBM(minDisparity=self._min_disparity,
numDisparities=self._num_disp,
SADWindowSize=self._sad_window_size,
uniquenessRatio=... | [
"def",
"_replace_bm",
"(",
"self",
")",
":",
"self",
".",
"_block_matcher",
"=",
"cv2",
".",
"StereoSGBM",
"(",
"minDisparity",
"=",
"self",
".",
"_min_disparity",
",",
"numDisparities",
"=",
"self",
".",
"_num_disp",
",",
"SADWindowSize",
"=",
"self",
".",
... | 52.666667 | 0.017107 |
def draw_markers(self):
"""Draw all created markers on the TimeLine Canvas"""
self._canvas_markers.clear()
for marker in self._markers.values():
self.create_marker(marker["category"], marker["start"], marker["finish"], marker) | [
"def",
"draw_markers",
"(",
"self",
")",
":",
"self",
".",
"_canvas_markers",
".",
"clear",
"(",
")",
"for",
"marker",
"in",
"self",
".",
"_markers",
".",
"values",
"(",
")",
":",
"self",
".",
"create_marker",
"(",
"marker",
"[",
"\"category\"",
"]",
"... | 51.6 | 0.01145 |
def query(query_string, secure=False, container='namedtuple', verbose=False,
user_agent=api.USER_AGENT, no_redirect=False, no_html=False,
skip_disambig=False):
"""
Generates and sends a query to DuckDuckGo API.
Args:
query_string: Query to be passed to DuckDuckGo API.
se... | [
"def",
"query",
"(",
"query_string",
",",
"secure",
"=",
"False",
",",
"container",
"=",
"'namedtuple'",
",",
"verbose",
"=",
"False",
",",
"user_agent",
"=",
"api",
".",
"USER_AGENT",
",",
"no_redirect",
"=",
"False",
",",
"no_html",
"=",
"False",
",",
... | 37.741935 | 0.000278 |
def score_wu(CIJ, s):
'''
The s-core is the largest subnetwork comprising nodes of strength at
least s. This function computes the s-core for a given weighted
undirected connection matrix. Computation is analogous to the more
widely used k-core, but is based on node strengths instead of node
deg... | [
"def",
"score_wu",
"(",
"CIJ",
",",
"s",
")",
":",
"CIJscore",
"=",
"CIJ",
".",
"copy",
"(",
")",
"while",
"True",
":",
"str",
"=",
"strengths_und",
"(",
"CIJscore",
")",
"# get strengths of matrix",
"# find nodes with strength <s",
"ff",
",",
"=",
"np",
"... | 28.179487 | 0.00088 |
def later_than(after, before):
""" True if then is later or equal to that """
if isinstance(after, six.string_types):
after = str_to_time(after)
elif isinstance(after, int):
after = time.gmtime(after)
if isinstance(before, six.string_types):
before = str_to_time(before)
elif... | [
"def",
"later_than",
"(",
"after",
",",
"before",
")",
":",
"if",
"isinstance",
"(",
"after",
",",
"six",
".",
"string_types",
")",
":",
"after",
"=",
"str_to_time",
"(",
"after",
")",
"elif",
"isinstance",
"(",
"after",
",",
"int",
")",
":",
"after",
... | 28.235294 | 0.002016 |
def _parse_nick(client, command, actor, args):
"""Parse a NICK response, update state, and dispatch events.
Note: this function dispatches both a NICK event and also one or more
MEMBERS events for each channel the user that changed nick was in.
"""
old_nick, _, _ = actor.partition('!')
new_nick... | [
"def",
"_parse_nick",
"(",
"client",
",",
"command",
",",
"actor",
",",
"args",
")",
":",
"old_nick",
",",
"_",
",",
"_",
"=",
"actor",
".",
"partition",
"(",
"'!'",
")",
"new_nick",
"=",
"args",
"if",
"old_nick",
"==",
"client",
".",
"user",
".",
... | 34.916667 | 0.001161 |
def save_otfs(
self,
ufos,
ttf=False,
is_instance=False,
interpolatable=False,
use_afdko=False,
autohint=None,
subset=None,
use_production_names=None,
subroutinize=None, # deprecated
optimize_cff=CFFOptimization.NONE,
cff_r... | [
"def",
"save_otfs",
"(",
"self",
",",
"ufos",
",",
"ttf",
"=",
"False",
",",
"is_instance",
"=",
"False",
",",
"interpolatable",
"=",
"False",
",",
"use_afdko",
"=",
"False",
",",
"autohint",
"=",
"None",
",",
"subset",
"=",
"None",
",",
"use_production_... | 43.74 | 0.001788 |
def rewrite(
filepath: Union[str, Path], mode: str = "w", **kw: Any
) -> Generator[IO, None, None]:
"""Rewrite an existing file atomically to avoid programs running in
parallel to have race conditions while reading."""
if isinstance(filepath, str):
base_dir = os.path.dirname(filepath)
fi... | [
"def",
"rewrite",
"(",
"filepath",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"mode",
":",
"str",
"=",
"\"w\"",
",",
"*",
"*",
"kw",
":",
"Any",
")",
"->",
"Generator",
"[",
"IO",
",",
"None",
",",
"None",
"]",
":",
"if",
"isinstance",
"(... | 39.777778 | 0.000909 |
def ctimes(*args):
'''
ctimes(a, b...) returns the product of all the values as a numpy array object. Like numpy's
multiply function or a*b syntax, times will thread over the latest dimension possible; thus
if a.shape is (4,2) and b.shape is 2, times(a,b) is a equivalent to a * b.
Unlike numpy'... | [
"def",
"ctimes",
"(",
"*",
"args",
")",
":",
"n",
"=",
"len",
"(",
"args",
")",
"if",
"n",
"==",
"0",
":",
"return",
"np",
".",
"asarray",
"(",
"0",
")",
"elif",
"n",
"==",
"1",
":",
"return",
"np",
".",
"asarray",
"(",
"args",
"[",
"0",
"]... | 43.3125 | 0.022599 |
def alias(self, annotationtype, set, fallback=False):
"""Return the alias for a set (if applicable, returns the unaltered set otherwise iff fallback is enabled)"""
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
if annotationtype in self.set_alias and set in se... | [
"def",
"alias",
"(",
"self",
",",
"annotationtype",
",",
"set",
",",
"fallback",
"=",
"False",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"annotationtype",
")",
":",
"annotationtype",
"=",
"annotationtype",
".",
"ANNOTATIONTYPE",
"if",
"annotationtype",
... | 56.666667 | 0.011583 |
def console_from_file(filename: str) -> tcod.console.Console:
"""Return a new console object from a filename.
The file format is automactially determined. This can load REXPaint `.xp`,
ASCII Paint `.apf`, or Non-delimited ASCII `.asc` files.
Args:
filename (Text): The path to the file, as a s... | [
"def",
"console_from_file",
"(",
"filename",
":",
"str",
")",
"->",
"tcod",
".",
"console",
".",
"Console",
":",
"return",
"tcod",
".",
"console",
".",
"Console",
".",
"_from_cdata",
"(",
"lib",
".",
"TCOD_console_from_file",
"(",
"filename",
".",
"encode",
... | 34.071429 | 0.002041 |
def calc_geo_branches_in_polygon(mv_grid, polygon, mode, proj):
""" Calculate geographical branches in polygon.
For a given `mv_grid` all branches (edges in the graph of the grid) are
tested if they are in the given `polygon`. You can choose different modes
and projections for this operation.
Para... | [
"def",
"calc_geo_branches_in_polygon",
"(",
"mv_grid",
",",
"polygon",
",",
"mode",
",",
"proj",
")",
":",
"branches",
"=",
"[",
"]",
"polygon_shp",
"=",
"transform",
"(",
"proj",
",",
"polygon",
")",
"for",
"branch",
"in",
"mv_grid",
".",
"graph_edges",
"... | 33.045455 | 0.001336 |
def calc_common_dist(df):
'''
calculate a common distribution (for col qn only) that will be used to qn
'''
# axis is col
tmp_arr = np.array([])
col_names = df.columns.tolist()
for inst_col in col_names:
# sort column
tmp_vect = df[inst_col].sort_values(ascending=False).values
# stacking ... | [
"def",
"calc_common_dist",
"(",
"df",
")",
":",
"# axis is col",
"tmp_arr",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"col_names",
"=",
"df",
".",
"columns",
".",
"tolist",
"(",
")",
"for",
"inst_col",
"in",
"col_names",
":",
"# sort column",
"tmp_vec... | 20.461538 | 0.019749 |
def add_star(G, nodes, t, **attr):
"""Add a star at time t.
The first node in nodes is the middle of the star. It is connected
to all other nodes.
Parameters
----------
G : graph
A DyNetx graph
nodes : iterable container
... | [
"def",
"add_star",
"(",
"G",
",",
"nodes",
",",
"t",
",",
"*",
"*",
"attr",
")",
":",
"nlist",
"=",
"iter",
"(",
"nodes",
")",
"v",
"=",
"next",
"(",
"nlist",
")",
"edges",
"=",
"(",
"(",
"v",
",",
"n",
")",
"for",
"n",
"in",
"nlist",
")",
... | 24.333333 | 0.001318 |
def get_file(hash):
"""Return the contents of the file as a ``memoryview``."""
stmt = _get_sql('get-file.sql')
args = dict(hash=hash)
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
cursor.execute(stmt, args)
try:
file, _ = cursor.fetchone(... | [
"def",
"get_file",
"(",
"hash",
")",
":",
"stmt",
"=",
"_get_sql",
"(",
"'get-file.sql'",
")",
"args",
"=",
"dict",
"(",
"hash",
"=",
"hash",
")",
"with",
"db_connect",
"(",
")",
"as",
"db_conn",
":",
"with",
"db_conn",
".",
"cursor",
"(",
")",
"as",... | 31.615385 | 0.002364 |
def dynamodb_connection_factory():
"""
Since SessionStore is called for every single page view, we'd be
establishing new connections so frequently that performance would be
hugely impacted. We'll lazy-load this here on a per-worker basis. Since
boto3.resource.('dynamodb')objects are state-less (asid... | [
"def",
"dynamodb_connection_factory",
"(",
")",
":",
"global",
"_DYNAMODB_CONN",
"global",
"_BOTO_SESSION",
"if",
"not",
"_DYNAMODB_CONN",
":",
"logger",
".",
"debug",
"(",
"\"Creating a DynamoDB connection.\"",
")",
"if",
"not",
"_BOTO_SESSION",
":",
"_BOTO_SESSION",
... | 42.05 | 0.001163 |
def stringify(*args):
"""
Joins args to build a string, unless there's one arg and it's a
function, then acts a decorator.
"""
if (len(args) == 1) and callable(args[0]):
func = args[0]
@wraps(func)
def _inner(*args, **kwargs):
return "".join([str(i) for i in func... | [
"def",
"stringify",
"(",
"*",
"args",
")",
":",
"if",
"(",
"len",
"(",
"args",
")",
"==",
"1",
")",
"and",
"callable",
"(",
"args",
"[",
"0",
"]",
")",
":",
"func",
"=",
"args",
"[",
"0",
"]",
"@",
"wraps",
"(",
"func",
")",
"def",
"_inner",
... | 28.928571 | 0.002392 |
def _stop_index(self, stop_point, inclusive):
"""
Determine index of stage of stopping point for run().
:param str | pypiper.Stage | function stop_point: Stopping point itself
or name of it.
:param bool inclusive: Whether the stopping point is to be regarded as
i... | [
"def",
"_stop_index",
"(",
"self",
",",
"stop_point",
",",
"inclusive",
")",
":",
"if",
"not",
"stop_point",
":",
"# Null case, no stopping point",
"return",
"len",
"(",
"self",
".",
"_stages",
")",
"stop_name",
"=",
"parse_stage_name",
"(",
"stop_point",
")",
... | 47.75 | 0.001711 |
def first(iterable, default=_marker):
"""Return the first item of *iterable*, or *default* if *iterable* is
empty.
>>> first([0, 1, 2, 3])
0
>>> first([], 'some default')
'some default'
If *default* is not provided and there are no items in the iterable,
raise ``ValueEr... | [
"def",
"first",
"(",
"iterable",
",",
"default",
"=",
"_marker",
")",
":",
"try",
":",
"return",
"next",
"(",
"iter",
"(",
"iterable",
")",
")",
"except",
"StopIteration",
":",
"# I'm on the edge about raising ValueError instead of StopIteration. At",
"# the moment, V... | 38 | 0.000917 |
def to_xml(self, opts = defaultdict(lambda: None)):
'''
Generate XML from the current settings.
'''
if not self.launch_url or not self.secure_launch_url:
raise InvalidLTIConfigError('Invalid LTI configuration')
root = etree.Element('cartridge_basiclti_link', attrib ... | [
"def",
"to_xml",
"(",
"self",
",",
"opts",
"=",
"defaultdict",
"(",
"lambda",
":",
"None",
")",
")",
":",
"if",
"not",
"self",
".",
"launch_url",
"or",
"not",
"self",
".",
"secure_launch_url",
":",
"raise",
"InvalidLTIConfigError",
"(",
"'Invalid LTI configu... | 54.47619 | 0.011734 |
def get_hostname(config, method=None):
"""
Returns a hostname as configured by the user
"""
method = method or config.get('hostname_method', 'smart')
# case insensitive method
method = method.lower()
if 'hostname' in config and method != 'shell':
return config['hostname']
if m... | [
"def",
"get_hostname",
"(",
"config",
",",
"method",
"=",
"None",
")",
":",
"method",
"=",
"method",
"or",
"config",
".",
"get",
"(",
"'hostname_method'",
",",
"'smart'",
")",
"# case insensitive method",
"method",
"=",
"method",
".",
"lower",
"(",
")",
"i... | 34.056075 | 0.000267 |
def get_issue_link_type(self, issue_link_type_id):
"""Returns for a given issue link type id all information about this issue link type.
"""
url = 'rest/api/2/issueLinkType/{issueLinkTypeId}'.format(issueLinkTypeId=issue_link_type_id)
return self.get(url) | [
"def",
"get_issue_link_type",
"(",
"self",
",",
"issue_link_type_id",
")",
":",
"url",
"=",
"'rest/api/2/issueLinkType/{issueLinkTypeId}'",
".",
"format",
"(",
"issueLinkTypeId",
"=",
"issue_link_type_id",
")",
"return",
"self",
".",
"get",
"(",
"url",
")"
] | 56.6 | 0.013937 |
def filter(self, **kwargs):
"""
Returns a new QuerySet instance with the args ANDed to the existing
set.
"""
if kwargs:
assert self.query.can_filter(), "Cannot filter a query once a slice has been taken."
clone = self._clone()
clone.query.add_filters(... | [
"def",
"filter",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
":",
"assert",
"self",
".",
"query",
".",
"can_filter",
"(",
")",
",",
"\"Cannot filter a query once a slice has been taken.\"",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
... | 28.333333 | 0.008547 |
def show_loadbalancer(self, lbaas_loadbalancer, **_params):
"""Fetches information for a load balancer."""
return self.get(self.lbaas_loadbalancer_path % (lbaas_loadbalancer),
params=_params) | [
"def",
"show_loadbalancer",
"(",
"self",
",",
"lbaas_loadbalancer",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"lbaas_loadbalancer_path",
"%",
"(",
"lbaas_loadbalancer",
")",
",",
"params",
"=",
"_params",
")"
] | 57 | 0.008658 |
def get_num_names( self, include_expired=False ):
"""
Get the number of names that exist.
"""
cur = self.db.cursor()
return namedb_get_num_names( cur, self.lastblock, include_expired=include_expired ) | [
"def",
"get_num_names",
"(",
"self",
",",
"include_expired",
"=",
"False",
")",
":",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"return",
"namedb_get_num_names",
"(",
"cur",
",",
"self",
".",
"lastblock",
",",
"include_expired",
"=",
"include_... | 39.166667 | 0.029167 |
def get_nodes(self):
"""
Get the list of all nodes.
"""
return self.fold_up(lambda n, fl, fg: [n] + fl + fg, lambda leaf: [leaf]) | [
"def",
"get_nodes",
"(",
"self",
")",
":",
"return",
"self",
".",
"fold_up",
"(",
"lambda",
"n",
",",
"fl",
",",
"fg",
":",
"[",
"n",
"]",
"+",
"fl",
"+",
"fg",
",",
"lambda",
"leaf",
":",
"[",
"leaf",
"]",
")"
] | 27.5 | 0.023529 |
def request_verification(self, user, identity):
"""
Sends the user a verification email with a link to verify ownership of the email address.
:param user: User id or object
:param identity: Identity id or object
:return: requests Response object
"""
return UserId... | [
"def",
"request_verification",
"(",
"self",
",",
"user",
",",
"identity",
")",
":",
"return",
"UserIdentityRequest",
"(",
"self",
")",
".",
"put",
"(",
"self",
".",
"endpoint",
".",
"request_verification",
",",
"user",
",",
"identity",
")"
] | 43 | 0.010127 |
def post_events(self, events):
"""
Posts a single event to the Keen IO API. The write key must be set first.
:param events: an Event to upload
"""
url = "{0}/{1}/projects/{2}/events".format(self.base_url, self.api_version,
sel... | [
"def",
"post_events",
"(",
"self",
",",
"events",
")",
":",
"url",
"=",
"\"{0}/{1}/projects/{2}/events\"",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"self",
".",
"api_version",
",",
"self",
".",
"project_id",
")",
"headers",
"=",
"utilities",
".",
... | 40.6 | 0.008026 |
def cudaMemcpy_dtoh(dst, src, count):
"""
Copy memory from device to host.
Copy data from device memory to host memory.
Parameters
----------
dst : ctypes pointer
Host memory pointer.
src : ctypes pointer
Device memory pointer.
count : int
Number of bytes to cop... | [
"def",
"cudaMemcpy_dtoh",
"(",
"dst",
",",
"src",
",",
"count",
")",
":",
"status",
"=",
"_libcudart",
".",
"cudaMemcpy",
"(",
"dst",
",",
"src",
",",
"ctypes",
".",
"c_size_t",
"(",
"count",
")",
",",
"cudaMemcpyDeviceToHost",
")",
"cudaCheckStatus",
"(",... | 23.952381 | 0.001912 |
def rdfs_properties(rdf):
"""Perform RDFS subproperty inference.
Add superproperties where subproperties have been used."""
# find out the subproperty mappings
superprops = {} # key: property val: set([superprop1, superprop2..])
for s, o in rdf.subject_objects(RDFS.subPropertyOf):
superpr... | [
"def",
"rdfs_properties",
"(",
"rdf",
")",
":",
"# find out the subproperty mappings",
"superprops",
"=",
"{",
"}",
"# key: property val: set([superprop1, superprop2..])",
"for",
"s",
",",
"o",
"in",
"rdf",
".",
"subject_objects",
"(",
"RDFS",
".",
"subPropertyOf",
")... | 37.526316 | 0.001368 |
def mangle_unicode_to_ascii(s: Any) -> str:
"""
Mangle unicode to ASCII, losing accents etc. in the process.
"""
# http://stackoverflow.com/questions/1207457
if s is None:
return ""
if not isinstance(s, str):
s = str(s)
return (
unicodedata.normalize('NFKD', s)
... | [
"def",
"mangle_unicode_to_ascii",
"(",
"s",
":",
"Any",
")",
"->",
"str",
":",
"# http://stackoverflow.com/questions/1207457",
"if",
"s",
"is",
"None",
":",
"return",
"\"\"",
"if",
"not",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"s",
"=",
"str",
"(",
... | 30.785714 | 0.002252 |
def update_address_scope(self, address_scope, body=None):
"""Updates a address scope."""
return self.put(self.address_scope_path % (address_scope), body=body) | [
"def",
"update_address_scope",
"(",
"self",
",",
"address_scope",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"put",
"(",
"self",
".",
"address_scope_path",
"%",
"(",
"address_scope",
")",
",",
"body",
"=",
"body",
")"
] | 57.333333 | 0.011494 |
def dist(src, tar, method=sim_levenshtein):
"""Return a distance between two strings.
This is a generalized function for calling other distance functions.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
method : function
... | [
"def",
"dist",
"(",
"src",
",",
"tar",
",",
"method",
"=",
"sim_levenshtein",
")",
":",
"if",
"callable",
"(",
"method",
")",
":",
"return",
"1",
"-",
"method",
"(",
"src",
",",
"tar",
")",
"else",
":",
"raise",
"AttributeError",
"(",
"'Unknown distanc... | 23.666667 | 0.000966 |
def from_Bar(bar, width=40, tuning=None, collapse=True):
"""Convert a mingus.containers.Bar object to ASCII tablature.
Throw a FingerError if no playable fingering can be found.
'tuning' should be a StringTuning object or None for the default tuning.
If 'collapse' is False this will return a list of l... | [
"def",
"from_Bar",
"(",
"bar",
",",
"width",
"=",
"40",
",",
"tuning",
"=",
"None",
",",
"collapse",
"=",
"True",
")",
":",
"if",
"tuning",
"is",
"None",
":",
"tuning",
"=",
"default_tuning",
"# Size of a quarter note",
"qsize",
"=",
"_get_qsize",
"(",
"... | 34.351648 | 0.000933 |
def _parse_species_references(self, name):
"""Yield species id and parsed value for a speciesReference list"""
for species in self._root.iterfind('./{}/{}'.format(
self._reader._sbml_tag(name),
self._reader._sbml_tag('speciesReference'))):
species_id = specie... | [
"def",
"_parse_species_references",
"(",
"self",
",",
"name",
")",
":",
"for",
"species",
"in",
"self",
".",
"_root",
".",
"iterfind",
"(",
"'./{}/{}'",
".",
"format",
"(",
"self",
".",
"_reader",
".",
"_sbml_tag",
"(",
"name",
")",
",",
"self",
".",
"... | 49.25 | 0.00083 |
def get_cartesian(self):
"""Return the molecule in cartesian coordinates.
Raises an :class:`~exceptions.InvalidReference` exception,
if the reference of the i-th atom is undefined.
Args:
None
Returns:
Cartesian: Reindexed version of the zmatrix.
... | [
"def",
"get_cartesian",
"(",
"self",
")",
":",
"def",
"create_cartesian",
"(",
"positions",
",",
"row",
")",
":",
"xyz_frame",
"=",
"pd",
".",
"DataFrame",
"(",
"columns",
"=",
"[",
"'atom'",
",",
"'x'",
",",
"'y'",
",",
"'z'",
"]",
",",
"index",
"="... | 40.214286 | 0.001156 |
def predict(self, structure, ref_structure):
"""
Given a structure, returns the predicted volume.
Args:
structure (Structure): structure w/unknown volume
ref_structure (Structure): A reference structure with a similar
structure but different species.
... | [
"def",
"predict",
"(",
"self",
",",
"structure",
",",
"ref_structure",
")",
":",
"if",
"self",
".",
"check_isostructural",
":",
"m",
"=",
"StructureMatcher",
"(",
")",
"mapping",
"=",
"m",
".",
"get_best_electronegativity_anonymous_mapping",
"(",
"structure",
",... | 44.732394 | 0.000924 |
def search_reads(
self, read_group_ids, reference_id=None, start=None, end=None):
"""
Returns an iterator over the Reads fulfilling the specified
conditions from the specified read_group_ids.
:param str read_group_ids: The IDs of the
:class:`ga4gh.protocol.ReadGr... | [
"def",
"search_reads",
"(",
"self",
",",
"read_group_ids",
",",
"reference_id",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"request",
"=",
"protocol",
".",
"SearchReadsRequest",
"(",
")",
"request",
".",
"read_group_ids",
".... | 48 | 0.001276 |
def fasta_cmd_get_seqs(acc_list,
blast_db=None,
is_protein=None,
out_filename=None,
params={},
WorkingDir=tempfile.gettempdir(),
SuppressStderr=None,
SuppressStdout=None):
"""Retrieve sequences for... | [
"def",
"fasta_cmd_get_seqs",
"(",
"acc_list",
",",
"blast_db",
"=",
"None",
",",
"is_protein",
"=",
"None",
",",
"out_filename",
"=",
"None",
",",
"params",
"=",
"{",
"}",
",",
"WorkingDir",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"SuppressStder... | 27.571429 | 0.012012 |
def remove_listener(self, registration_id):
"""
Removes the specified item listener. Returns silently if the specified listener was not added before.
:param registration_id: (str), id of the listener to be deleted.
:return: (bool), ``true`` if the item listener is removed, ``false`` oth... | [
"def",
"remove_listener",
"(",
"self",
",",
"registration_id",
")",
":",
"return",
"self",
".",
"_stop_listening",
"(",
"registration_id",
",",
"lambda",
"i",
":",
"queue_remove_listener_codec",
".",
"encode_request",
"(",
"self",
".",
"name",
",",
"i",
")",
"... | 56.625 | 0.01087 |
def is_negated(self):
"""A negated query is one in which every clause has a presence of
prohibited. These queries require some special processing to return
the expected results.
"""
return all(
clause.presence == QueryPresence.PROHIBITED for clause in self.clauses
... | [
"def",
"is_negated",
"(",
"self",
")",
":",
"return",
"all",
"(",
"clause",
".",
"presence",
"==",
"QueryPresence",
".",
"PROHIBITED",
"for",
"clause",
"in",
"self",
".",
"clauses",
")"
] | 39.875 | 0.009202 |
def from_json(cls, json):
"""Inherit doc."""
num_ranges = int(json["num_ranges"])
query_spec = json["query_spec"]
item_name = json["item_name"]
p_range_iters = []
for i in xrange(num_ranges):
json_item = json[str(i)]
# Place query_spec, name back into each iterator
json_item["... | [
"def",
"from_json",
"(",
"cls",
",",
"json",
")",
":",
"num_ranges",
"=",
"int",
"(",
"json",
"[",
"\"num_ranges\"",
"]",
")",
"query_spec",
"=",
"json",
"[",
"\"query_spec\"",
"]",
"item_name",
"=",
"json",
"[",
"\"item_name\"",
"]",
"p_range_iters",
"=",... | 30.5 | 0.011928 |
def zip(self, *others):
"""
Zip the items of this collection with one or more
other sequences, and wrap the result.
Unlike Python's zip, all sequences must be the same length.
Parameters:
others: One or more iterables or Collections
Returns:
A... | [
"def",
"zip",
"(",
"self",
",",
"*",
"others",
")",
":",
"args",
"=",
"[",
"_unwrap",
"(",
"item",
")",
"for",
"item",
"in",
"(",
"self",
",",
")",
"+",
"others",
"]",
"ct",
"=",
"self",
".",
"count",
"(",
")",
"if",
"not",
"all",
"(",
"len",... | 28.925926 | 0.002478 |
def one(func, n=0):
"""
Create a callable that applies ``func`` to a value in a sequence.
If the value is not a sequence or is an empty sequence then ``None`` is
returned.
:type func: `callable`
:param func: Callable to be applied to each result.
:type n: `int`
:param n: Index of th... | [
"def",
"one",
"(",
"func",
",",
"n",
"=",
"0",
")",
":",
"def",
"_one",
"(",
"result",
")",
":",
"if",
"_isSequenceTypeNotText",
"(",
"result",
")",
"and",
"len",
"(",
"result",
")",
">",
"n",
":",
"return",
"func",
"(",
"result",
"[",
"n",
"]",
... | 27.944444 | 0.001923 |
def get_host_domainname(name, domains=None, **api_opts):
'''
Get host domain name
If no domains are passed, the hostname is checked for a zone in infoblox,
if no zone split on first dot.
If domains are provided, the best match out of the list is returned.
If none are found the return is None
... | [
"def",
"get_host_domainname",
"(",
"name",
",",
"domains",
"=",
"None",
",",
"*",
"*",
"api_opts",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
".",
"rstrip",
"(",
"'.'",
")",
"if",
"not",
"domains",
":",
"data",
"=",
"get_host",
"(",
"na... | 27.405405 | 0.000952 |
def optimize(objective_function, domain,
stopping_condition, parameters=None,
position_update=functions.std_position,
velocity_update=functions.std_velocity,
parameter_update=functions.std_parameter_update,
measurements=(),
measurer=dictionar... | [
"def",
"optimize",
"(",
"objective_function",
",",
"domain",
",",
"stopping_condition",
",",
"parameters",
"=",
"None",
",",
"position_update",
"=",
"functions",
".",
"std_position",
",",
"velocity_update",
"=",
"functions",
".",
"std_velocity",
",",
"parameter_upda... | 41.9375 | 0.000485 |
def get_books_containing_page(cursor, uuid, version,
context_uuid=None, context_version=None):
"""Return a list of book names and UUIDs
that contain a given module UUID."""
with db_connect() as db_connection:
# Uses a RealDictCursor instead of the regular cursor
... | [
"def",
"get_books_containing_page",
"(",
"cursor",
",",
"uuid",
",",
"version",
",",
"context_uuid",
"=",
"None",
",",
"context_version",
"=",
"None",
")",
":",
"with",
"db_connect",
"(",
")",
"as",
"db_connection",
":",
"# Uses a RealDictCursor instead of the regul... | 54.083333 | 0.000757 |
def formfield(self, **kwargs):
"""Return a formfield."""
# This is a fairly standard way to set up some defaults
# while letting the caller override them.
defaults = {}
if self.ppoi_field:
defaults['form_class'] = SizedImageCenterpointClickDjangoAdminField
if ... | [
"def",
"formfield",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# This is a fairly standard way to set up some defaults",
"# while letting the caller override them.",
"defaults",
"=",
"{",
"}",
"if",
"self",
".",
"ppoi_field",
":",
"defaults",
"[",
"'form_class'",
... | 56.846154 | 0.001331 |
def create(self, check, notification_plan, criteria=None,
disabled=False, label=None, name=None, metadata=None):
"""
Creates an alarm that binds the check on the given entity with a
notification plan.
Note that the 'criteria' parameter, if supplied, should be a string
... | [
"def",
"create",
"(",
"self",
",",
"check",
",",
"notification_plan",
",",
"criteria",
"=",
"None",
",",
"disabled",
"=",
"False",
",",
"label",
"=",
"None",
",",
"name",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"uri",
"=",
"\"/%s\"",
"%"... | 44.433333 | 0.002203 |
def get_queryset(self):
"""
Returns a queryset of all states holding a non-special election on
a date.
"""
try:
date = ElectionDay.objects.get(date=self.kwargs["date"])
except Exception:
raise APIException(
"No elections on {}.".for... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"try",
":",
"date",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"kwargs",
"[",
"\"date\"",
"]",
")",
"except",
"Exception",
":",
"raise",
"APIException",
"(",
"\"No election... | 36.826087 | 0.002301 |
def _do_resumable_upload(
self, client, stream, content_type, size, num_retries, predefined_acl
):
"""Perform a resumable upload.
Assumes ``chunk_size`` is not :data:`None` on the current blob.
The content type of the upload will be determined in order
of precedence:
... | [
"def",
"_do_resumable_upload",
"(",
"self",
",",
"client",
",",
"stream",
",",
"content_type",
",",
"size",
",",
"num_retries",
",",
"predefined_acl",
")",
":",
"upload",
",",
"transport",
"=",
"self",
".",
"_initiate_resumable_upload",
"(",
"client",
",",
"st... | 36 | 0.001531 |
def strip_praw_message(cls, msg):
"""
Parse through a message and return a dict with data ready to be
displayed through the terminal. Messages can be of either type
praw.objects.Message or praw.object.Comment. The comments returned will
contain special fields unique to messages a... | [
"def",
"strip_praw_message",
"(",
"cls",
",",
"msg",
")",
":",
"author",
"=",
"getattr",
"(",
"msg",
",",
"'author'",
",",
"None",
")",
"data",
"=",
"{",
"}",
"data",
"[",
"'object'",
"]",
"=",
"msg",
"if",
"isinstance",
"(",
"msg",
",",
"praw",
".... | 40.295455 | 0.001652 |
def write_source(self, filename):
'''
Save source to file by calling `write` on the root element.
'''
with open(filename, 'w') as fp:
return json.dump(self.message._elem, fp, indent=4, sort_keys=True) | [
"def",
"write_source",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fp",
":",
"return",
"json",
".",
"dump",
"(",
"self",
".",
"message",
".",
"_elem",
",",
"fp",
",",
"indent",
"=",
"4",
",",
"... | 40.666667 | 0.008032 |
def _handle_ansi_color_codes(self, s):
"""Replace ansi escape sequences with spans of appropriately named css classes."""
parts = HtmlReporter._ANSI_COLOR_CODE_RE.split(s)
ret = []
span_depth = 0
# Note that len(parts) is always odd: text, code, text, code, ..., text.
for i in range(0, len(parts... | [
"def",
"_handle_ansi_color_codes",
"(",
"self",
",",
"s",
")",
":",
"parts",
"=",
"HtmlReporter",
".",
"_ANSI_COLOR_CODE_RE",
".",
"split",
"(",
"s",
")",
"ret",
"=",
"[",
"]",
"span_depth",
"=",
"0",
"# Note that len(parts) is always odd: text, code, text, code, ..... | 33.954545 | 0.013021 |
def apply_groups(cls, obj, options=None, backend=None, clone=True, **kwargs):
"""Applies nested options definition grouped by type.
Applies options on an object or nested group of objects,
returning a new object with the options applied. This method
accepts the separate option namespace... | [
"def",
"apply_groups",
"(",
"cls",
",",
"obj",
",",
"options",
"=",
"None",
",",
"backend",
"=",
"None",
",",
"clone",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"options",
",",
"basestring",
")",
":",
"from",
".",
"."... | 43.54717 | 0.001695 |
def get_blockcypher_walletname_from_mpub(mpub, subchain_indices=[]):
'''
Blockcypher limits wallet names to 25 chars.
Hash the master pubkey (with subchain indexes) and take the first 25 chars.
Hackey determinstic method for naming.
'''
# http://stackoverflow.com/a/19877309/1754586
mpub ... | [
"def",
"get_blockcypher_walletname_from_mpub",
"(",
"mpub",
",",
"subchain_indices",
"=",
"[",
"]",
")",
":",
"# http://stackoverflow.com/a/19877309/1754586",
"mpub",
"=",
"mpub",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"subchain_indices",
":",
"mpub",
"+=",
"','... | 32 | 0.002024 |
def _apply_user_agent(headers, user_agent):
"""Adds a user-agent to the headers.
Args:
headers: dict, request headers to add / modify user
agent within.
user_agent: str, the user agent to add.
Returns:
dict, the original headers passed in, but modified if the
... | [
"def",
"_apply_user_agent",
"(",
"headers",
",",
"user_agent",
")",
":",
"if",
"user_agent",
"is",
"not",
"None",
":",
"if",
"'user-agent'",
"in",
"headers",
":",
"headers",
"[",
"'user-agent'",
"]",
"=",
"(",
"user_agent",
"+",
"' '",
"+",
"headers",
"[",... | 29.631579 | 0.001721 |
def fanqie2mch(fanqie, debug=False):
"""
Convert a Fǎnqiè reading to it's MCH counterpart.
Important: we need to identify the medials in the xia-syllable. We also
need to make additional background-checks, since in the current form, the
approach is not error-prone and does not what it is suppos... | [
"def",
"fanqie2mch",
"(",
"fanqie",
",",
"debug",
"=",
"False",
")",
":",
"# check for gbk",
"fanqie",
"=",
"gbk2big5",
"(",
"fanqie",
")",
"# get normal vals",
"shangxia",
"=",
"chars2baxter",
"(",
"fanqie",
")",
"# check for good fixed solutions in our dictionary",
... | 27.098039 | 0.016061 |
def find_version(include_dev_version=True, root='%(pwd)s',
version_file='%(root)s/version.txt', version_module_paths=(),
git_args=None, vcs_args=None, decrement_dev_version=None,
strip_prefix='v',
Popen=subprocess.Popen, open=open):
"""Find an appr... | [
"def",
"find_version",
"(",
"include_dev_version",
"=",
"True",
",",
"root",
"=",
"'%(pwd)s'",
",",
"version_file",
"=",
"'%(root)s/version.txt'",
",",
"version_module_paths",
"=",
"(",
")",
",",
"git_args",
"=",
"None",
",",
"vcs_args",
"=",
"None",
",",
"dec... | 38.357513 | 0.000658 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.