text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def create_manifest(self, cart_name, manifests):
"""
`cart_name` - Name of this release cart
`manifests` - a list of manifest files
"""
cart = juicer.common.Cart.Cart(cart_name)
for manifest in manifests:
cart.add_from_manifest(manifest, self.connectors)
... | [
"def",
"create_manifest",
"(",
"self",
",",
"cart_name",
",",
"manifests",
")",
":",
"cart",
"=",
"juicer",
".",
"common",
".",
"Cart",
".",
"Cart",
"(",
"cart_name",
")",
"for",
"manifest",
"in",
"manifests",
":",
"cart",
".",
"add_from_manifest",
"(",
... | 28.75 | 14.916667 |
def is_condition_met(self, hand, win_tile, melds, is_tsumo):
"""
Three closed pon sets, the other sets need not to be closed
:param hand: list of hand's sets
:param win_tile: 136 tiles format
:param melds: list Meld objects
:param is_tsumo:
:return: true|false
... | [
"def",
"is_condition_met",
"(",
"self",
",",
"hand",
",",
"win_tile",
",",
"melds",
",",
"is_tsumo",
")",
":",
"win_tile",
"//=",
"4",
"open_sets",
"=",
"[",
"x",
".",
"tiles_34",
"for",
"x",
"in",
"melds",
"if",
"x",
".",
"opened",
"]",
"chi_sets",
... | 32.689655 | 18.965517 |
def _support(self, caller):
"""Helper callback."""
markdown_content = caller()
html_content = markdown.markdown(
markdown_content,
extensions=[
"markdown.extensions.fenced_code",
CodeHiliteExtension(css_class="highlight"),
"... | [
"def",
"_support",
"(",
"self",
",",
"caller",
")",
":",
"markdown_content",
"=",
"caller",
"(",
")",
"html_content",
"=",
"markdown",
".",
"markdown",
"(",
"markdown_content",
",",
"extensions",
"=",
"[",
"\"markdown.extensions.fenced_code\"",
",",
"CodeHiliteExt... | 32.5 | 12.5 |
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:
"""Return the inner product between two tensors"""
# Note: Relying on fact that vdot flattens arrays
return np.vdot(tensor0, tensor1) | [
"def",
"inner",
"(",
"tensor0",
":",
"BKTensor",
",",
"tensor1",
":",
"BKTensor",
")",
"->",
"BKTensor",
":",
"# Note: Relying on fact that vdot flattens arrays",
"return",
"np",
".",
"vdot",
"(",
"tensor0",
",",
"tensor1",
")"
] | 50.75 | 9.25 |
def DOM_querySelector(self, nodeId, selector):
"""
Function path: DOM.querySelector
Domain: DOM
Method name: querySelector
Parameters:
Required arguments:
'nodeId' (type: NodeId) -> Id of the node to query upon.
'selector' (type: string) -> Selector string.
Returns:
'nodeId' (type: ... | [
"def",
"DOM_querySelector",
"(",
"self",
",",
"nodeId",
",",
"selector",
")",
":",
"assert",
"isinstance",
"(",
"selector",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'selector' must be of type '['str']'. Received type: '%s'\"",
"%",
"type",
"(",
"selector",
... | 32.190476 | 19.047619 |
def fastp_filtered_reads_chart(self):
""" Function to generate the fastp filtered reads bar plot """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['filtering_result_passed_filter_reads'] = { 'name': 'Passed Filter' }
keys['filtering_result_lo... | [
"def",
"fastp_filtered_reads_chart",
"(",
"self",
")",
":",
"# Specify the order of the different possible categories",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'filtering_result_passed_filter_reads'",
"]",
"=",
"{",
"'name'",
":",
"'Passed Filter'",
"}",
"keys... | 47.277778 | 20.277778 |
def _set_learning_mode(self, v, load=False):
"""
Setter method for learning_mode, mapped from YANG variable /mac_address_table/learning_mode (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_learning_mode is considered as a private
method. Backends lookin... | [
"def",
"_set_learning_mode",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | 95.375 | 46.625 |
def _detach_received(self, error):
"""Callback called when a link DETACH frame is received.
This callback will process the received DETACH error to determine if
the link is recoverable or whether it should be shutdown.
:param error: The error information from the detach
frame.
... | [
"def",
"_detach_received",
"(",
"self",
",",
"error",
")",
":",
"# pylint: disable=protected-access",
"if",
"error",
":",
"condition",
"=",
"error",
".",
"condition",
"description",
"=",
"error",
".",
"description",
"info",
"=",
"error",
".",
"info",
"else",
"... | 45.434783 | 19.565217 |
def called_with(self, *args, **kwargs):
"""
Before evaluating subsequent predicates, calls :attr:`subject` with given arguments (but unlike a direct call,
catches and transforms any exceptions that arise during the call).
"""
self._args = args
self._kwargs = kwargs
... | [
"def",
"called_with",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_args",
"=",
"args",
"self",
".",
"_kwargs",
"=",
"kwargs",
"self",
".",
"_call_subject",
"=",
"True",
"return",
"CallableInspector",
"(",
"self",
")"... | 42 | 16.444444 |
def inquire_property(name, doc=None):
"""Creates a property based on an inquire result
This method creates a property that calls the
:python:`_inquire` method, and return the value of the
requested information.
Args:
name (str): the name of the 'inquire' result information
Returns:
... | [
"def",
"inquire_property",
"(",
"name",
",",
"doc",
"=",
"None",
")",
":",
"def",
"inquire_property",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_started",
":",
"msg",
"=",
"(",
"\"Cannot read {0} from a security context whose \"",
"\"establishment has not ... | 29.652174 | 20.217391 |
def _perform_unbinds(self, binds):
"""
Unbinds queues from exchanges.
Parameters
----------
binds: list of dicts
A list of dicts with the following keys:
queue: string - name of the queue to bind
exchange: string - name of the exchange to bind
routing_key: string - routing key to use for this ... | [
"def",
"_perform_unbinds",
"(",
"self",
",",
"binds",
")",
":",
"for",
"bind",
"in",
"binds",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Unbinding queue {0} from exchange {1} with key {2}\"",
".",
"format",
"(",
"bind",
"[",
"'queue'",
"]",
",",
"bind",... | 34 | 18.933333 |
def to_spans(self):
"Convert the tree to a set of nonterms and spans."
s = set()
self._convert_to_spans(self.tree, 1, s)
return s | [
"def",
"to_spans",
"(",
"self",
")",
":",
"s",
"=",
"set",
"(",
")",
"self",
".",
"_convert_to_spans",
"(",
"self",
".",
"tree",
",",
"1",
",",
"s",
")",
"return",
"s"
] | 31.4 | 18.6 |
def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None):
"""save stock_min
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
stock_list = QA_fetch_get_stock_list().code.unique().tolist()
coll = client.stock_min
coll.create_index(
[
... | [
"def",
"QA_SU_save_stock_min",
"(",
"client",
"=",
"DATABASE",
",",
"ui_log",
"=",
"None",
",",
"ui_progress",
"=",
"None",
")",
":",
"stock_list",
"=",
"QA_fetch_get_stock_list",
"(",
")",
".",
"code",
".",
"unique",
"(",
")",
".",
"tolist",
"(",
")",
"... | 34.704918 | 14.655738 |
def _posify_mask_subindexer(index):
"""Convert masked indices in a flat array to the nearest unmasked index.
Parameters
----------
index : np.ndarray
One dimensional ndarray with dtype=int.
Returns
-------
np.ndarray
One dimensional ndarray with all values equal to -1 repla... | [
"def",
"_posify_mask_subindexer",
"(",
"index",
")",
":",
"masked",
"=",
"index",
"==",
"-",
"1",
"unmasked_locs",
"=",
"np",
".",
"flatnonzero",
"(",
"~",
"masked",
")",
"if",
"not",
"unmasked_locs",
".",
"size",
":",
"# indexing unmasked_locs is invalid",
"r... | 31.833333 | 17.208333 |
def do_alarm_definition_delete(mc, args):
'''Delete the alarm definition.'''
fields = {}
fields['alarm_id'] = args.id
try:
mc.alarm_definitions.delete(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
... | [
"def",
"do_alarm_definition_delete",
"(",
"mc",
",",
"args",
")",
":",
"fields",
"=",
"{",
"}",
"fields",
"[",
"'alarm_id'",
"]",
"=",
"args",
".",
"id",
"try",
":",
"mc",
".",
"alarm_definitions",
".",
"delete",
"(",
"*",
"*",
"fields",
")",
"except",... | 37.3 | 16.9 |
def date(f, *args, **kwargs):
"""Automatically log progress on function entry and exit with date- and
time- stamp. Default logging value: info.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted with parameters passed to
the... | [
"def",
"date",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'print_time'",
":",
"True",
"}",
")",
"return",
"_stump",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 38 | 22.086957 |
def read_seg(self, parc_type='aparc'):
"""Read the MRI segmentation.
Parameters
----------
parc_type : str
'aparc' or 'aparc.a2009s'
Returns
-------
numpy.ndarray
3d matrix with values
numpy.ndarray
4x4 affine matrix
... | [
"def",
"read_seg",
"(",
"self",
",",
"parc_type",
"=",
"'aparc'",
")",
":",
"seg_file",
"=",
"self",
".",
"dir",
"/",
"'mri'",
"/",
"(",
"parc_type",
"+",
"'+aseg.mgz'",
")",
"seg_mri",
"=",
"load",
"(",
"seg_file",
")",
"seg_aff",
"=",
"seg_mri",
".",... | 25.5 | 15.2 |
def check_recommended_files(data, vcs):
"""Do check for recommended files.
Returns True when all is fine.
"""
main_files = os.listdir(data['workingdir'])
if not 'setup.py' in main_files and not 'setup.cfg' in main_files:
# Not a python package. We have no recommendations.
return Tr... | [
"def",
"check_recommended_files",
"(",
"data",
",",
"vcs",
")",
":",
"main_files",
"=",
"os",
".",
"listdir",
"(",
"data",
"[",
"'workingdir'",
"]",
")",
"if",
"not",
"'setup.py'",
"in",
"main_files",
"and",
"not",
"'setup.cfg'",
"in",
"main_files",
":",
"... | 40.030303 | 16.606061 |
async def pendings(self, tasks=None):
"""Used for await in coroutines.
`await loop.pendings()`
`await loop.pendings(tasks)`
"""
tasks = tasks or self.todo_tasks
await asyncio.gather(*tasks, loop=self.loop) | [
"async",
"def",
"pendings",
"(",
"self",
",",
"tasks",
"=",
"None",
")",
":",
"tasks",
"=",
"tasks",
"or",
"self",
".",
"todo_tasks",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
",",
"loop",
"=",
"self",
".",
"loop",
")"
] | 35.285714 | 4 |
def get_repositories_by_genus_type(self, repository_genus_type=None):
"""Gets a ``RepositoryList`` corresponding to the given repository genus ``Type`` which
does not include repositories of types derived from the specified ``Type``.
In plenary mode, the returned list contains all known
... | [
"def",
"get_repositories_by_genus_type",
"(",
"self",
",",
"repository_genus_type",
"=",
"None",
")",
":",
"if",
"repository_genus_type",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"url_path",
"=",
"construct_url",
"(",
"'objective_banks'",
")",
"reposito... | 49.533333 | 21.6 |
def query(self):
"""A QueryDict object holding the query parameters (QUERY_STRING)."""
if self._query is None:
query_string = self.environ.get('QUERY_STRING')
self._query = QueryDict([
(k.decode('utf-8'), v.decode('utf-8'))
for k, v in urlparse.par... | [
"def",
"query",
"(",
"self",
")",
":",
"if",
"self",
".",
"_query",
"is",
"None",
":",
"query_string",
"=",
"self",
".",
"environ",
".",
"get",
"(",
"'QUERY_STRING'",
")",
"self",
".",
"_query",
"=",
"QueryDict",
"(",
"[",
"(",
"k",
".",
"decode",
... | 41.8 | 13.3 |
def default_middlewares(web3):
"""
List the default middlewares for the request manager.
Leaving ens unspecified will prevent the middleware from resolving names.
"""
return [
(request_parameter_normalizer, 'request_param_normalizer'),
(gas_price_strategy_... | [
"def",
"default_middlewares",
"(",
"web3",
")",
":",
"return",
"[",
"(",
"request_parameter_normalizer",
",",
"'request_param_normalizer'",
")",
",",
"(",
"gas_price_strategy_middleware",
",",
"'gas_price_strategy'",
")",
",",
"(",
"name_to_address_middleware",
"(",
"we... | 44.133333 | 17.2 |
def modify_process_property(self, key, value, pid=None):
'''
modify_process_property(self, key, value, pid=None)
Modify process output property.
Please note that the process property key provided must be declared as an output property in the relevant service specification.
:Par... | [
"def",
"modify_process_property",
"(",
"self",
",",
"key",
",",
"value",
",",
"pid",
"=",
"None",
")",
":",
"pid",
"=",
"self",
".",
"_get_pid",
"(",
"pid",
")",
"request_data",
"=",
"{",
"\"key\"",
":",
"key",
",",
"\"value\"",
":",
"value",
"}",
"r... | 44.363636 | 33.454545 |
def register_request(self, valid_responses):
"""Register a RPC request.
:param list valid_responses: List of possible Responses that
we should be waiting for.
:return:
"""
uuid = str(uuid4())
self._response[uuid] = []
for acti... | [
"def",
"register_request",
"(",
"self",
",",
"valid_responses",
")",
":",
"uuid",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"self",
".",
"_response",
"[",
"uuid",
"]",
"=",
"[",
"]",
"for",
"action",
"in",
"valid_responses",
":",
"self",
".",
"_request"... | 32.666667 | 13.416667 |
def calendar(type='holiday', direction='next', last=1, startDate=None, token='', version=''):
'''This call allows you to fetch a number of trade dates or holidays from a given date. For example, if you want the next trading day, you would call /ref-data/us/dates/trade/next/1.
https://iexcloud.io/docs/api/#u-s-... | [
"def",
"calendar",
"(",
"type",
"=",
"'holiday'",
",",
"direction",
"=",
"'next'",
",",
"last",
"=",
"1",
",",
"startDate",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"if",
"startDate",
":",
"startDate",
"=",
"_strOrDa... | 47.333333 | 32.952381 |
def efficient_frontier(self, points):
"""Get the efficient frontier"""
mu, sigma, weights = [], [], []
# remove the 1, to avoid duplications
a = np.linspace(0, 1, points / len(self.w))[:-1]
b = list(range(len(self.w) - 1))
for i in b:
w0, w1 = self.w[i], self.... | [
"def",
"efficient_frontier",
"(",
"self",
",",
"points",
")",
":",
"mu",
",",
"sigma",
",",
"weights",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"# remove the 1, to avoid duplications",
"a",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"po... | 43.235294 | 10.647059 |
def is_field_method(node):
"""Checks if a call to a field instance method is valid. A call is
valid if the call is a method of the underlying type. So, in a StringField
the methods from str are valid, in a ListField the methods from list are
valid and so on..."""
name = node.attrname
parent = no... | [
"def",
"is_field_method",
"(",
"node",
")",
":",
"name",
"=",
"node",
".",
"attrname",
"parent",
"=",
"node",
".",
"last_child",
"(",
")",
"inferred",
"=",
"safe_infer",
"(",
"parent",
")",
"if",
"not",
"inferred",
":",
"return",
"False",
"for",
"cls_nam... | 32.882353 | 21.176471 |
def _save_state(self):
"""
Helper context manager for :meth:`buffer` which saves the whole state.
This is broken out in a separate method for readability and tested
indirectly by testing :meth:`buffer`.
"""
ns_prefixes_floating_in = copy.copy(self._ns_prefixes_floating_i... | [
"def",
"_save_state",
"(",
"self",
")",
":",
"ns_prefixes_floating_in",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"_ns_prefixes_floating_in",
")",
"ns_prefixes_floating_out",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"_ns_prefixes_floating_out",
")",
"ns_decls... | 47.2 | 18.866667 |
def _update_usage_plan_apis(plan_id, apis, op, region=None, key=None, keyid=None, profile=None):
'''
Helper function that updates the usage plan identified by plan_id by adding or removing it to each of the stages, specified by apis parameter.
apis
a list of dictionaries, where each dictionary cont... | [
"def",
"_update_usage_plan_apis",
"(",
"plan_id",
",",
"apis",
",",
"op",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"patchOperations",
"=",
"[",
"]",
"for",
"api... | 38.794118 | 28.323529 |
def json(self, start=None):
"""
:param start: start key in dot notation
returns the dict in json format
:return: json string version
:rtype: string
"""
if start is not None:
data = self.data[start]
return json.dumps(self.data, indent=4) | [
"def",
"json",
"(",
"self",
",",
"start",
"=",
"None",
")",
":",
"if",
"start",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"data",
"[",
"start",
"]",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"data",
",",
"indent",
"=",
"4",
")... | 30.3 | 6.5 |
def save_credentials(self, profile):
"""
Saves credentials to a dotfile so you can open them grab them later.
Parameters
----------
profile: str
name for your profile (i.e. "dev", "prod")
"""
filename = profile_path(S3_PROFILE_ID, profile)
cre... | [
"def",
"save_credentials",
"(",
"self",
",",
"profile",
")",
":",
"filename",
"=",
"profile_path",
"(",
"S3_PROFILE_ID",
",",
"profile",
")",
"creds",
"=",
"{",
"\"access_key\"",
":",
"self",
".",
"access_key",
",",
"\"secret_key\"",
":",
"self",
".",
"secre... | 29.666667 | 15.533333 |
def notify(self, frame_type, headers=None, body=None):
"""
Utility function for notifying listeners of incoming and outgoing messages
:param str frame_type: the type of message
:param dict headers: the map of headers associated with the message
:param body: the content of the me... | [
"def",
"notify",
"(",
"self",
",",
"frame_type",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"if",
"frame_type",
"==",
"'receipt'",
":",
"# logic for wait-on-receipt notification",
"receipt",
"=",
"headers",
"[",
"'receipt-id'",
"]",
"rece... | 37.25 | 16.285714 |
def _checkpointLabelFromCheckpointDir(checkpointDir):
"""Returns a checkpoint label string for the given model checkpoint directory
checkpointDir: relative or absolute model checkpoint directory path
"""
assert checkpointDir.endswith(g_defaultCheckpointExtension)
lastSegment = os.path.split(checkpointDir)[1... | [
"def",
"_checkpointLabelFromCheckpointDir",
"(",
"checkpointDir",
")",
":",
"assert",
"checkpointDir",
".",
"endswith",
"(",
"g_defaultCheckpointExtension",
")",
"lastSegment",
"=",
"os",
".",
"path",
".",
"split",
"(",
"checkpointDir",
")",
"[",
"1",
"]",
"checkp... | 33.916667 | 22.916667 |
def _pdf(self, phi):
"""
Evaluate the _unnormalized_ flow PDF.
"""
pdf = np.inner(self._vn, np.cos(np.outer(phi, self._n)))
pdf *= 2.
pdf += 1.
return pdf | [
"def",
"_pdf",
"(",
"self",
",",
"phi",
")",
":",
"pdf",
"=",
"np",
".",
"inner",
"(",
"self",
".",
"_vn",
",",
"np",
".",
"cos",
"(",
"np",
".",
"outer",
"(",
"phi",
",",
"self",
".",
"_n",
")",
")",
")",
"pdf",
"*=",
"2.",
"pdf",
"+=",
... | 20.3 | 19.7 |
def _merge_and_bgzip(orig_files, out_file, base_file, ext=""):
"""Merge a group of gzipped input files into a final bgzipped output.
Also handles providing unique names for each input file to avoid
collisions on multi-region output. Handles renaming with awk magic from:
https://www.biostars.org/p/68477... | [
"def",
"_merge_and_bgzip",
"(",
"orig_files",
",",
"out_file",
",",
"base_file",
",",
"ext",
"=",
"\"\"",
")",
":",
"assert",
"out_file",
".",
"endswith",
"(",
"\".gz\"",
")",
"full_file",
"=",
"out_file",
".",
"replace",
"(",
"\".gz\"",
",",
"\"\"",
")",
... | 44.272727 | 16.727273 |
def fit(self, P):
"""Fit the diagonal matrices in Sinkhorn Knopp's algorithm
Parameters
----------
P : 2d array-like
Must be a square non-negative 2d array-like object, that
is convertible to a numpy array. The matrix must not be
equal to 0 and it must have total... | [
"def",
"fit",
"(",
"self",
",",
"P",
")",
":",
"P",
"=",
"np",
".",
"asarray",
"(",
"P",
")",
"assert",
"np",
".",
"all",
"(",
"P",
">=",
"0",
")",
"assert",
"P",
".",
"ndim",
"==",
"2",
"assert",
"P",
".",
"shape",
"[",
"0",
"]",
"==",
"... | 29.422535 | 19.15493 |
def respond(text=None, ssml=None, attributes=None, reprompt_text=None,
reprompt_ssml=None, end_session=True):
""" Build a dict containing a valid response to an Alexa request.
If speech output is desired, either of `text` or `ssml` should
be specified.
:param text: Plain text speech output... | [
"def",
"respond",
"(",
"text",
"=",
"None",
",",
"ssml",
"=",
"None",
",",
"attributes",
"=",
"None",
",",
"reprompt_text",
"=",
"None",
",",
"reprompt_ssml",
"=",
"None",
",",
"end_session",
"=",
"True",
")",
":",
"obj",
"=",
"{",
"'version'",
":",
... | 35.358974 | 25.102564 |
def encode(
self,
word,
language_arg=0,
name_mode='gen',
match_mode='approx',
concat=False,
filter_langs=False,
):
"""Return the Beider-Morse Phonetic Matching encoding(s) of a term.
Parameters
----------
word : str
... | [
"def",
"encode",
"(",
"self",
",",
"word",
",",
"language_arg",
"=",
"0",
",",
"name_mode",
"=",
"'gen'",
",",
"match_mode",
"=",
"'approx'",
",",
"concat",
"=",
"False",
",",
"filter_langs",
"=",
"False",
",",
")",
":",
"word",
"=",
"normalize",
"(",
... | 31.479452 | 19.246575 |
def mime_type(self, type_: Optional[MimeType] = None) -> str:
"""Get a random mime type from list.
:param type_: Enum object MimeType.
:return: Mime type.
"""
key = self._validate_enum(item=type_, enum=MimeType)
types = MIME_TYPES[key]
return self.random.choice(t... | [
"def",
"mime_type",
"(",
"self",
",",
"type_",
":",
"Optional",
"[",
"MimeType",
"]",
"=",
"None",
")",
"->",
"str",
":",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"item",
"=",
"type_",
",",
"enum",
"=",
"MimeType",
")",
"types",
"=",
"MIME_TYP... | 35.222222 | 11.777778 |
def rst_table(data, schema=None):
"""
Creates a reStructuredText simple table (list of strings) from a list of
lists.
"""
# Process multi-rows (replaced by rows with empty columns when needed)
pdata = []
for row in data:
prow = [el if isinstance(el, list) else [el] for el in row]
pdata.extend(pr f... | [
"def",
"rst_table",
"(",
"data",
",",
"schema",
"=",
"None",
")",
":",
"# Process multi-rows (replaced by rows with empty columns when needed)",
"pdata",
"=",
"[",
"]",
"for",
"row",
"in",
"data",
":",
"prow",
"=",
"[",
"el",
"if",
"isinstance",
"(",
"el",
","... | 32.870968 | 17.709677 |
def power(maf=0.5,beta=0.1, N=100, cutoff=5e-8):
"""
estimate power for a given allele frequency, effect size beta and sample size N
Assumption:
z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis
the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf)N) )... | [
"def",
"power",
"(",
"maf",
"=",
"0.5",
",",
"beta",
"=",
"0.1",
",",
"N",
"=",
"100",
",",
"cutoff",
"=",
"5e-8",
")",
":",
"\"\"\"\n\tstd(snp)=sqrt(2.0*maf*(1-maf)) \n\tpower = \\int \n\n\tbeta_ML = (snp^T*snp)^{-1}*snp^T*Y = cov(snp,Y)/var(snp) \n\tE[beta_ML]\t= (snp^T*s... | 31.244444 | 23.777778 |
def cli(out_fmt, input, output):
"""Converts text."""
_input = StringIO()
for l in input:
try:
_input.write(str(l))
except TypeError:
_input.write(bytes(l, 'utf-8'))
_input = seria.load(_input)
_out = (_input.dump(out_fmt))
output.write(_out) | [
"def",
"cli",
"(",
"out_fmt",
",",
"input",
",",
"output",
")",
":",
"_input",
"=",
"StringIO",
"(",
")",
"for",
"l",
"in",
"input",
":",
"try",
":",
"_input",
".",
"write",
"(",
"str",
"(",
"l",
")",
")",
"except",
"TypeError",
":",
"_input",
".... | 26.909091 | 12.181818 |
def fsn2text(path, strict=False):
"""
Args:
path (fsnative): The path to convert
strict (bool): Fail in case the conversion is not reversible
Returns:
`text`
Raises:
TypeError: In case no `fsnative` has been passed
ValueError: In case ``strict`` was True and the c... | [
"def",
"fsn2text",
"(",
"path",
",",
"strict",
"=",
"False",
")",
":",
"path",
"=",
"_fsn2native",
"(",
"path",
")",
"errors",
"=",
"\"strict\"",
"if",
"strict",
"else",
"\"replace\"",
"if",
"is_win",
":",
"return",
"path",
".",
"encode",
"(",
"\"utf-16-... | 32.09375 | 25.28125 |
def _partial_corr(self, x=None, y=None, covar=None, x_covar=None, y_covar=None,
tail='two-sided', method='pearson'):
"""Partial and semi-partial correlation."""
stats = partial_corr(data=self, x=x, y=y, covar=covar, x_covar=x_covar,
y_covar=y_covar, tail=tail, method=m... | [
"def",
"_partial_corr",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"covar",
"=",
"None",
",",
"x_covar",
"=",
"None",
",",
"y_covar",
"=",
"None",
",",
"tail",
"=",
"'two-sided'",
",",
"method",
"=",
"'pearson'",
")",
":",
"sta... | 56.333333 | 23.166667 |
def check_complete(task, out_queue):
"""
Checks if task is complete, puts the result to out_queue.
"""
logger.debug("Checking if %s is complete", task)
try:
is_complete = task.complete()
except Exception:
is_complete = TracebackWrapper(traceback.format_exc())
out_queue.put((t... | [
"def",
"check_complete",
"(",
"task",
",",
"out_queue",
")",
":",
"logger",
".",
"debug",
"(",
"\"Checking if %s is complete\"",
",",
"task",
")",
"try",
":",
"is_complete",
"=",
"task",
".",
"complete",
"(",
")",
"except",
"Exception",
":",
"is_complete",
"... | 32.9 | 11.5 |
def openconfig_interfaces(device_name=None):
'''
.. versionadded:: 2019.2.0
Return a dictionary structured as standardised in the
`openconfig-interfaces <http://ops.openconfig.net/branches/master/openconfig-interfaces.html>`_
YANG model, containing physical and configuration data available in Netbo... | [
"def",
"openconfig_interfaces",
"(",
"device_name",
"=",
"None",
")",
":",
"oc_if",
"=",
"{",
"}",
"interfaces",
"=",
"get_interfaces",
"(",
"device_name",
"=",
"device_name",
")",
"ipaddresses",
"=",
"get_ipaddresses",
"(",
"device_name",
"=",
"device_name",
")... | 39.44086 | 20.989247 |
def recursive_division(self, cells, min_size, width, height, x=0, y=0, depth=0):
"""
Recursive division:
1. Split room randomly
1a. Dodge towards larger half if in doorway
2. Place doorway randomly
3. Repeat for each half
"""
assert isi... | [
"def",
"recursive_division",
"(",
"self",
",",
"cells",
",",
"min_size",
",",
"width",
",",
"height",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"depth",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"cells",
",",
"list",
")",
"assert",
"isins... | 33.327869 | 17.196721 |
def teardown():
"""Remove integration"""
if not self._has_been_setup:
return
deregister_plugins()
deregister_host()
if self._has_menu:
remove_from_filemenu()
self._has_menu = False
self._has_been_setup = False
print("pyblish: Integration torn down successfully") | [
"def",
"teardown",
"(",
")",
":",
"if",
"not",
"self",
".",
"_has_been_setup",
":",
"return",
"deregister_plugins",
"(",
")",
"deregister_host",
"(",
")",
"if",
"self",
".",
"_has_menu",
":",
"remove_from_filemenu",
"(",
")",
"self",
".",
"_has_menu",
"=",
... | 21.714286 | 19.714286 |
def download(download_info):
"""Module method for downloading from S3
This public module method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the specified key to the dest_dir.
:para... | [
"def",
"download",
"(",
"download_info",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.download'",
")",
"# Ensure the passed arg is a dict",
"if",
"not",
"isinstance",
"(",
"download_info",
",",
"dict",
")",
":",
"msg",
"=",
"'d... | 39.885714 | 20.8 |
def get_serial_ports_list():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in rang... | [
"def",
"get_serial_ports_list",
"(",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
":",
"ports",
"=",
"[",
"'COM%s'",
"%",
"(",
"i",
"+",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"256",
")",
"]",
"elif",
"(",
"sys... | 34.294118 | 14.470588 |
def _vpcs_path(self):
"""
Returns the VPCS executable path.
:returns: path to VPCS
"""
search_path = self._manager.config.get_section_config("VPCS").get("vpcs_path", "vpcs")
path = shutil.which(search_path)
# shutil.which return None if the path doesn't exists
... | [
"def",
"_vpcs_path",
"(",
"self",
")",
":",
"search_path",
"=",
"self",
".",
"_manager",
".",
"config",
".",
"get_section_config",
"(",
"\"VPCS\"",
")",
".",
"get",
"(",
"\"vpcs_path\"",
",",
"\"vpcs\"",
")",
"path",
"=",
"shutil",
".",
"which",
"(",
"se... | 29.076923 | 18.153846 |
def process_event(self, event_name: str, data: dict) -> None:
"""
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
... | [
"def",
"process_event",
"(",
"self",
",",
"event_name",
":",
"str",
",",
"data",
":",
"dict",
")",
"->",
"None",
":",
"if",
"event_name",
"==",
"\"after_epoch\"",
":",
"self",
".",
"epochs_done",
"=",
"data",
"[",
"\"epochs_done\"",
"]",
"self",
".",
"ba... | 34.8125 | 17.0625 |
def user_absent(name, profile=None, **connection_args):
'''
Ensure that the keystone user is absent.
name
The name of the user that should not exist
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'User "{0}" is already absent'.format(name... | [
"def",
"user_absent",
"(",
"name",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"'User \"{0}\" is ... | 34.407407 | 21 |
def compute_overlayable_zorders(obj, path=[]):
"""
Traverses an overlayable composite container to determine which
objects are associated with specific (Nd)Overlay layers by
z-order, making sure to take DynamicMap Callables into
account. Returns a mapping between the zorders of each layer and a
... | [
"def",
"compute_overlayable_zorders",
"(",
"obj",
",",
"path",
"=",
"[",
"]",
")",
":",
"path",
"=",
"path",
"+",
"[",
"obj",
"]",
"zorder_map",
"=",
"defaultdict",
"(",
"list",
")",
"# Process non-dynamic layers",
"if",
"not",
"isinstance",
"(",
"obj",
",... | 42.824324 | 17.608108 |
def newline(self):
"""Effects a newline by moving the cursor down and clearing"""
self.write(self.term.move_down)
self.write(self.term.clear_bol) | [
"def",
"newline",
"(",
"self",
")",
":",
"self",
".",
"write",
"(",
"self",
".",
"term",
".",
"move_down",
")",
"self",
".",
"write",
"(",
"self",
".",
"term",
".",
"clear_bol",
")"
] | 41.5 | 6 |
def display_name(self):
"""Calculates the display name for a room."""
if self.name:
return self.name
elif self.canonical_alias:
return self.canonical_alias
# Member display names without me
members = [u.get_display_name(self) for u in self.get_joined_memb... | [
"def",
"display_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"name",
":",
"return",
"self",
".",
"name",
"elif",
"self",
".",
"canonical_alias",
":",
"return",
"self",
".",
"canonical_alias",
"# Member display names without me",
"members",
"=",
"[",
"u",
... | 36.095238 | 16.428571 |
def filter_matrix_columns(A, theta):
"""Filter each column of A with tol.
i.e., drop all entries in column k where
abs(A[i,k]) < tol max( abs(A[:,k]) )
Parameters
----------
A : sparse_matrix
theta : float
In range [0,1) and defines drop-tolerance used to filter the columns
... | [
"def",
"filter_matrix_columns",
"(",
"A",
",",
"theta",
")",
":",
"if",
"not",
"isspmatrix",
"(",
"A",
")",
":",
"raise",
"ValueError",
"(",
"\"Sparse matrix input needed\"",
")",
"if",
"isspmatrix_bsr",
"(",
"A",
")",
":",
"blocksize",
"=",
"A",
".",
"blo... | 31.506494 | 19.805195 |
def designPrimers(p3_args, input_log=None, output_log=None, err_log=None):
''' Return the raw primer3_core output for the provided primer3 args.
Returns an ordered dict of the boulderIO-format primer3 output file
'''
sp = subprocess.Popen([pjoin(PRIMER3_HOME, 'primer3_core')],
... | [
"def",
"designPrimers",
"(",
"p3_args",
",",
"input_log",
"=",
"None",
",",
"output_log",
"=",
"None",
",",
"err_log",
"=",
"None",
")",
":",
"sp",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"pjoin",
"(",
"PRIMER3_HOME",
",",
"'primer3_core'",
")",
"]",
... | 41 | 19 |
def filter_rep_set(inF, otuSet):
"""
Parse the rep set file and remove all sequences not associated with unique
OTUs.
:@type inF: file
:@param inF: The representative sequence set
:@rtype: list
:@return: The set of sequences associated with unique OTUs
"""
seqs = []
for record ... | [
"def",
"filter_rep_set",
"(",
"inF",
",",
"otuSet",
")",
":",
"seqs",
"=",
"[",
"]",
"for",
"record",
"in",
"SeqIO",
".",
"parse",
"(",
"inF",
",",
"\"fasta\"",
")",
":",
"if",
"record",
".",
"id",
"in",
"otuSet",
":",
"seqs",
".",
"append",
"(",
... | 25.875 | 19 |
def run_sorter(sorter_name_or_class, recording, output_folder=None, delete_output_folder=False,
grouping_property=None, parallel=False, debug=False, **params):
"""
Generic function to run a sorter via function approach.
2 Usage with name or class:
by name:
>>> sorting = run_sorte... | [
"def",
"run_sorter",
"(",
"sorter_name_or_class",
",",
"recording",
",",
"output_folder",
"=",
"None",
",",
"delete_output_folder",
"=",
"False",
",",
"grouping_property",
"=",
"None",
",",
"parallel",
"=",
"False",
",",
"debug",
"=",
"False",
",",
"*",
"*",
... | 34.137931 | 25.448276 |
def getWordList(ipFile, delim):
"""
extract a unique list of words and have line numbers that word appears
"""
indexedWords = {}
totWords = 0
totLines = 0
with codecs.open(ipFile, "r",encoding='utf-8', errors='replace') as f:
for line in f:
totLines = totLines + 1
... | [
"def",
"getWordList",
"(",
"ipFile",
",",
"delim",
")",
":",
"indexedWords",
"=",
"{",
"}",
"totWords",
"=",
"0",
"totLines",
"=",
"0",
"with",
"codecs",
".",
"open",
"(",
"ipFile",
",",
"\"r\"",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"... | 39.105263 | 16.052632 |
def parse_time_specification(units, dt=None, n_steps=None, nsteps=None, t1=None, t2=None, t=None):
"""
Return an array of times given a few combinations of kwargs that are
accepted -- see below.
Parameters
----------
dt, n_steps[, t1] : (numeric, int[, numeric])
A fixed timestep dt and ... | [
"def",
"parse_time_specification",
"(",
"units",
",",
"dt",
"=",
"None",
",",
"n_steps",
"=",
"None",
",",
"nsteps",
"=",
"None",
",",
"t1",
"=",
"None",
",",
"t2",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"if",
"nsteps",
"is",
"not",
"None",
... | 30.94898 | 21.214286 |
def public_ip_address_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific public IP address.
:param name: The name of the public IP address to query.
:param resource_group: The resource group name assigned to the
public IP address.
CLI Exa... | [
"def",
"public_ip_address_get",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"expand",
"=",
"kwargs",
".",
"get",
"(",
"'expand'",
")",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*... | 26.235294 | 25.058824 |
def create_joints(self):
'''Traverse the bone hierarchy and create physics joints.'''
stack = ['root']
while stack:
parent = stack.pop()
for child in self.hierarchy.get(parent, ()):
stack.append(child)
if parent not in self.bones:
... | [
"def",
"create_joints",
"(",
"self",
")",
":",
"stack",
"=",
"[",
"'root'",
"]",
"while",
"stack",
":",
"parent",
"=",
"stack",
".",
"pop",
"(",
")",
"for",
"child",
"in",
"self",
".",
"hierarchy",
".",
"get",
"(",
"parent",
",",
"(",
")",
")",
"... | 47.375 | 17.875 |
def clean(self, value):
"""
Convert the value's type and run validation. Validation errors from
to_python and validate are propagated. The correct value is returned if
no error is raised.
"""
value = self.to_python(value)
self.validate(value)
return value | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"to_python",
"(",
"value",
")",
"self",
".",
"validate",
"(",
"value",
")",
"return",
"value"
] | 34.555556 | 15.444444 |
def fun_inverse(fun=None, y=0, x0=None, args=(), disp=False, method='Nelder-Mead', **kwargs):
r"""Find the threshold level that accomplishes the desired specificity
Call indicated function repeatedly to find answer to the inverse function evaluation
Arguments:
fun (function): function to be calculate ... | [
"def",
"fun_inverse",
"(",
"fun",
"=",
"None",
",",
"y",
"=",
"0",
",",
"x0",
"=",
"None",
",",
"args",
"=",
"(",
")",
",",
"disp",
"=",
"False",
",",
"method",
"=",
"'Nelder-Mead'",
",",
"*",
"*",
"kwargs",
")",
":",
"fun_inverse",
".",
"fun",
... | 49.942857 | 26.371429 |
def min_value(self):
"""
The minimum pixel value of the ``data`` within the source
segment.
"""
if self._is_completely_masked:
return np.nan * self._data_unit
else:
return np.min(self.values) | [
"def",
"min_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_completely_masked",
":",
"return",
"np",
".",
"nan",
"*",
"self",
".",
"_data_unit",
"else",
":",
"return",
"np",
".",
"min",
"(",
"self",
".",
"values",
")"
] | 25.5 | 14.3 |
def _DiscoverElementTypeFromLocalname(self, type_localname):
"""Searches all namespaces for a type by name.
Args:
type_localname: The name of the type.
Returns:
A fully qualified SOAP type with the specified name.
Raises:
A zeep.exceptions.LookupError if the type cannot be found in ... | [
"def",
"_DiscoverElementTypeFromLocalname",
"(",
"self",
",",
"type_localname",
")",
":",
"elem_type",
"=",
"None",
"last_exception",
"=",
"None",
"for",
"ns_prefix",
"in",
"self",
".",
"zeep_client",
".",
"wsdl",
".",
"types",
".",
"prefix_map",
".",
"values",
... | 27.884615 | 20.692308 |
def delete_group(group_name, region=None, key=None,
keyid=None, profile=None):
'''
Delete a group policy.
CLI Example::
.. code-block:: bash
salt myminion boto_iam.delete_group mygroup
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
... | [
"def",
"delete_group",
"(",
"group_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"k... | 27.222222 | 22.333333 |
def wrapHeart(service):
"""Wrap a service in a MultiService with a heart"""
master = taservice.MultiService()
service.setServiceParent(master)
maybeAddHeart(master)
return master | [
"def",
"wrapHeart",
"(",
"service",
")",
":",
"master",
"=",
"taservice",
".",
"MultiService",
"(",
")",
"service",
".",
"setServiceParent",
"(",
"master",
")",
"maybeAddHeart",
"(",
"master",
")",
"return",
"master"
] | 32.166667 | 10.333333 |
def groupby_count(i, key=None, force_keys=None):
""" Aggregate iterator values into buckets based on how frequently the
values appear.
Example::
>>> list(groupby_count([1, 1, 1, 2, 3]))
[(1, 3), (2, 1), (3, 1)]
"""
counter = defaultdict(lambda: 0)
if not key:
key = lamb... | [
"def",
"groupby_count",
"(",
"i",
",",
"key",
"=",
"None",
",",
"force_keys",
"=",
"None",
")",
":",
"counter",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"if",
"not",
"key",
":",
"key",
"=",
"lambda",
"o",
":",
"o",
"for",
"k",
"in",
"i",... | 21.809524 | 19.761905 |
def get_status(app, repo_config, repo_name, sha):
"""Gets the status of a commit.
.. note::
``repo_name`` might not ever be anything other than
``repo_config['github_repo']``.
:param app: Flask app for leeroy
:param repo_config: configuration for the repo
:param repo_name: The name... | [
"def",
"get_status",
"(",
"app",
",",
"repo_config",
",",
"repo_name",
",",
"sha",
")",
":",
"url",
"=",
"get_api_url",
"(",
"app",
",",
"repo_config",
",",
"github_status_url",
")",
".",
"format",
"(",
"repo_name",
"=",
"repo_name",
",",
"sha",
"=",
"sh... | 37.619048 | 15.428571 |
def new_code_block(self, **kwargs):
"""Create a new code block."""
proto = {'content': '',
'type': self.code,
'IO': '',
'attributes': ''}
proto.update(**kwargs)
return proto | [
"def",
"new_code_block",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"proto",
"=",
"{",
"'content'",
":",
"''",
",",
"'type'",
":",
"self",
".",
"code",
",",
"'IO'",
":",
"''",
",",
"'attributes'",
":",
"''",
"}",
"proto",
".",
"update",
"(",
... | 31.125 | 8.625 |
def _upload_to_gcs(self, files_to_upload):
"""
Upload all of the file splits (and optionally the schema .json file) to
Google cloud storage.
"""
hook = GoogleCloudStorageHook(
google_cloud_storage_conn_id=self.google_cloud_storage_conn_id,
delegate_to=self... | [
"def",
"_upload_to_gcs",
"(",
"self",
",",
"files_to_upload",
")",
":",
"hook",
"=",
"GoogleCloudStorageHook",
"(",
"google_cloud_storage_conn_id",
"=",
"self",
".",
"google_cloud_storage_conn_id",
",",
"delegate_to",
"=",
"self",
".",
"delegate_to",
")",
"for",
"tm... | 45.916667 | 12.916667 |
def create(input, template, field, outdir, prefix, otype, command, index,
dpi, verbose, unicode_support):
"""Use docstamp to create documents from the content of a CSV file or
a Google Spreadsheet.
Examples: \n
docstamp create -i badge.csv -t badge_template.svg -o badges
docstamp create ... | [
"def",
"create",
"(",
"input",
",",
"template",
",",
"field",
",",
"outdir",
",",
"prefix",
",",
"otype",
",",
"command",
",",
"index",
",",
"dpi",
",",
"verbose",
",",
"unicode_support",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"LOG... | 33.897959 | 21.795918 |
def as_a_dict(self):
"""
Displays the index as a dictionary. This includes the design document
id, index name, index type, and index definition.
:returns: Dictionary representation of the index as a dictionary
"""
index_dict = {
'ddoc': self._ddoc_id,
... | [
"def",
"as_a_dict",
"(",
"self",
")",
":",
"index_dict",
"=",
"{",
"'ddoc'",
":",
"self",
".",
"_ddoc_id",
",",
"'name'",
":",
"self",
".",
"_name",
",",
"'type'",
":",
"self",
".",
"_type",
",",
"'def'",
":",
"self",
".",
"_def",
"}",
"if",
"self"... | 27.888889 | 19 |
def negotiate_sasl(transport, xmlstream,
sasl_providers,
negotiation_timeout,
jid, features):
"""
Perform SASL authentication on the given :class:`.protocol.XMLStream`
`stream`. `transport` must be the :class:`asyncio.Transport` over which the
`st... | [
"def",
"negotiate_sasl",
"(",
"transport",
",",
"xmlstream",
",",
"sasl_providers",
",",
"negotiation_timeout",
",",
"jid",
",",
"features",
")",
":",
"if",
"not",
"transport",
".",
"get_extra_info",
"(",
"\"sslcontext\"",
")",
":",
"transport",
"=",
"None",
"... | 36.761905 | 23.52381 |
def append(self, transitions, rows=None):
"""Append a batch of transitions to rows of the memory.
Args:
transitions: Tuple of transition quantities with batch dimension.
rows: Episodes to append to, defaults to all.
Returns:
Operation.
"""
rows = tf.range(self._capacity) if rows ... | [
"def",
"append",
"(",
"self",
",",
"transitions",
",",
"rows",
"=",
"None",
")",
":",
"rows",
"=",
"tf",
".",
"range",
"(",
"self",
".",
"_capacity",
")",
"if",
"rows",
"is",
"None",
"else",
"rows",
"assert",
"rows",
".",
"shape",
".",
"ndims",
"==... | 39.413793 | 13.206897 |
def color(self) -> str:
"""Get a random name of color.
:return: Color name.
:Example:
Red.
"""
colors = self._data['color']
return self.random.choice(colors) | [
"def",
"color",
"(",
"self",
")",
"->",
"str",
":",
"colors",
"=",
"self",
".",
"_data",
"[",
"'color'",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"colors",
")"
] | 21 | 16.1 |
def extractall(self, directory, auto_create_dir=False, patool_path=None):
'''
:param directory: directory to extract to
:param auto_create_dir: auto create directory
:param patool_path: the path to the patool backend
'''
log.debug('extracting %s into %s (backend=%s)', sel... | [
"def",
"extractall",
"(",
"self",
",",
"directory",
",",
"auto_create_dir",
"=",
"False",
",",
"patool_path",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'extracting %s into %s (backend=%s)'",
",",
"self",
".",
"filename",
",",
"directory",
",",
"self",
... | 40.806452 | 19.064516 |
def _get_indexable_sentences(document):
"""
Parameters
----------
document : Text
Article, book, paragraph, chapter, etc. Anything that is considered a document on its own.
Yields
------
str
json representation of elasticsearch type sentence
... | [
"def",
"_get_indexable_sentences",
"(",
"document",
")",
":",
"def",
"unroll_lists",
"(",
"list_of_lists",
")",
":",
"for",
"i",
"in",
"itertools",
".",
"product",
"(",
"*",
"[",
"set",
"(",
"j",
")",
"for",
"j",
"in",
"list_of_lists",
"]",
")",
":",
"... | 30.102564 | 18 |
def filter_scanline(type, line, fo, prev=None):
"""Apply a scanline filter to a scanline. `type` specifies the
filter type (0 to 4); `line` specifies the current (unfiltered)
scanline as a sequence of bytes; `prev` specifies the previous
(unfiltered) scanline as a sequence of bytes. `fo` specifies the
... | [
"def",
"filter_scanline",
"(",
"type",
",",
"line",
",",
"fo",
",",
"prev",
"=",
"None",
")",
":",
"assert",
"0",
"<=",
"type",
"<",
"5",
"# The output array. Which, pathetically, we extend one-byte at a",
"# time (fortunately this is linear).",
"out",
"=",
"array",
... | 29.164706 | 19.258824 |
def _compute_distance(cls, dists, coeffs):
"""
Compute third term of equation (1) on p. 1200:
``b3 * log(sqrt(Rjb ** 2 + b4 ** 2))``
"""
return coeffs['b3']*np.log10(np.sqrt(dists.rjb**2. + coeffs['b4']**2.)) | [
"def",
"_compute_distance",
"(",
"cls",
",",
"dists",
",",
"coeffs",
")",
":",
"return",
"coeffs",
"[",
"'b3'",
"]",
"*",
"np",
".",
"log10",
"(",
"np",
".",
"sqrt",
"(",
"dists",
".",
"rjb",
"**",
"2.",
"+",
"coeffs",
"[",
"'b4'",
"]",
"**",
"2.... | 34.714286 | 14.428571 |
def ask(message, options):
"""Ask the message interactively, with the given possible responses"""
while 1:
if os.environ.get('PIP_NO_INPUT'):
raise Exception('No input was expected ($PIP_NO_INPUT set); question: %s' % message)
response = raw_input(message)
response = response... | [
"def",
"ask",
"(",
"message",
",",
"options",
")",
":",
"while",
"1",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'PIP_NO_INPUT'",
")",
":",
"raise",
"Exception",
"(",
"'No input was expected ($PIP_NO_INPUT set); question: %s'",
"%",
"message",
")",
"re... | 44.583333 | 16.75 |
def com_google_fonts_check_name_license(ttFont, license):
"""Check copyright namerecords match license file."""
from fontbakery.constants import PLACEHOLDER_LICENSING_TEXT
failed = False
placeholder = PLACEHOLDER_LICENSING_TEXT[license]
entry_found = False
for i, nameRecord in enumerate(ttFont["name"].names... | [
"def",
"com_google_fonts_check_name_license",
"(",
"ttFont",
",",
"license",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"PLACEHOLDER_LICENSING_TEXT",
"failed",
"=",
"False",
"placeholder",
"=",
"PLACEHOLDER_LICENSING_TEXT",
"[",
"license",
"]",
"entry_f... | 48.59375 | 16.8125 |
def add_line_error(self, line_data, error_info, log_level=logging.ERROR):
"""Helper function to record and log an error message
:param line_data: dict
:param error_info: dict
:param logger:
:param log_level: int
:return:
"""
if not error_info: return
... | [
"def",
"add_line_error",
"(",
"self",
",",
"line_data",
",",
"error_info",
",",
"log_level",
"=",
"logging",
".",
"ERROR",
")",
":",
"if",
"not",
"error_info",
":",
"return",
"try",
":",
"line_data",
"[",
"'line_errors'",
"]",
".",
"append",
"(",
"error_in... | 39.45 | 23.75 |
def load_data_old(self):
"""
Loads time series of 2D data grids from each opened file. The code
handles loading a full time series from one file or individual time steps
from multiple files. Missing files are supported.
"""
units = ""
if len(self.file_objects) ==... | [
"def",
"load_data_old",
"(",
"self",
")",
":",
"units",
"=",
"\"\"",
"if",
"len",
"(",
"self",
".",
"file_objects",
")",
"==",
"1",
"and",
"self",
".",
"file_objects",
"[",
"0",
"]",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"file_objects",... | 53.225 | 23.925 |
def map_sid2sub(self, sid, sub):
"""
Store the connection between a Session ID and a subject ID.
:param sid: Session ID
:param sub: subject ID
"""
self.set('sid2sub', sid, sub)
self.set('sub2sid', sub, sid) | [
"def",
"map_sid2sub",
"(",
"self",
",",
"sid",
",",
"sub",
")",
":",
"self",
".",
"set",
"(",
"'sid2sub'",
",",
"sid",
",",
"sub",
")",
"self",
".",
"set",
"(",
"'sub2sid'",
",",
"sub",
",",
"sid",
")"
] | 28.333333 | 11.222222 |
def read(fname):
"""Quick way to read a file content."""
content = None
with open(os.path.join(here, fname)) as f:
content = f.read()
return content | [
"def",
"read",
"(",
"fname",
")",
":",
"content",
"=",
"None",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"here",
",",
"fname",
")",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
"return",
"content"
] | 27.833333 | 14.666667 |
def read_xdg_config_home(name, extension):
"""
Read from file found in XDG-specified configuration home directory,
expanding to ``${HOME}/.config/name.extension`` by default. Depends on
``XDG_CONFIG_HOME`` or ``HOME`` environment variables.
:param name: application or configuration set name
:pa... | [
"def",
"read_xdg_config_home",
"(",
"name",
",",
"extension",
")",
":",
"# find optional value of ${XDG_CONFIG_HOME}",
"config_home",
"=",
"environ",
".",
"get",
"(",
"'XDG_CONFIG_HOME'",
")",
"if",
"not",
"config_home",
":",
"# XDG spec: \"If $XDG_CONFIG_HOME is either not... | 50.25 | 23.35 |
def _check_load_paths(load_path):
'''
Checks the validity of the load_path, returns a sanitized version
with invalid paths removed.
'''
if load_path is None or not isinstance(load_path, six.string_types):
return None
_paths = []
for _path in load_path.split(':'):
if os.path... | [
"def",
"_check_load_paths",
"(",
"load_path",
")",
":",
"if",
"load_path",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"load_path",
",",
"six",
".",
"string_types",
")",
":",
"return",
"None",
"_paths",
"=",
"[",
"]",
"for",
"_path",
"in",
"load_path",
... | 26.7 | 24.8 |
def NewType(name, tp):
"""NewType creates simple unique types with almost zero
runtime overhead. NewType(name, tp) is considered a subtype of tp
by static type checkers. At runtime, NewType(name, tp) returns
a dummy function that simply returns its argument. Usage::
UserId = NewType('UserId', i... | [
"def",
"NewType",
"(",
"name",
",",
"tp",
")",
":",
"def",
"new_type",
"(",
"x",
")",
":",
"return",
"x",
"new_type",
".",
"__name__",
"=",
"name",
"new_type",
".",
"__supertype__",
"=",
"tp",
"return",
"new_type"
] | 27.16 | 20.84 |
def _tick(self):
"""Write progress info and move cursor to beginning of line."""
if (self.verbose >= 3 and not IS_REDIRECTED) or self.options.get("progress"):
stats = self.get_stats()
prefix = DRY_RUN_PREFIX if self.dry_run else ""
sys.stdout.write(
"{... | [
"def",
"_tick",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"verbose",
">=",
"3",
"and",
"not",
"IS_REDIRECTED",
")",
"or",
"self",
".",
"options",
".",
"get",
"(",
"\"progress\"",
")",
":",
"stats",
"=",
"self",
".",
"get_stats",
"(",
")",
"pre... | 39.466667 | 16.333333 |
def equivalent_sites(self, scaled_positions, ondublicates='error',
symprec=1e-3):
"""Returns the scaled positions and all their equivalent sites.
Parameters:
scaled_positions: list | array
List of non-equivalent sites given in unit cell coordinates.
... | [
"def",
"equivalent_sites",
"(",
"self",
",",
"scaled_positions",
",",
"ondublicates",
"=",
"'error'",
",",
"symprec",
"=",
"1e-3",
")",
":",
"kinds",
"=",
"[",
"]",
"sites",
"=",
"[",
"]",
"symprec2",
"=",
"symprec",
"**",
"2",
"scaled",
"=",
"np",
"."... | 37.395349 | 16.046512 |
def _get_value(self, node, scope, ctxt, stream):
"""Return the value of the node. It is expected to be
either an AST.ID instance or a constant
:node: TODO
:returns: TODO
"""
res = self._handle_node(node, scope, ctxt, stream)
if isinstance(res, fields.Field):
... | [
"def",
"_get_value",
"(",
"self",
",",
"node",
",",
"scope",
",",
"ctxt",
",",
"stream",
")",
":",
"res",
"=",
"self",
".",
"_handle_node",
"(",
"node",
",",
"scope",
",",
"ctxt",
",",
"stream",
")",
"if",
"isinstance",
"(",
"res",
",",
"fields",
"... | 24 | 19.529412 |
def standings(self):
'''Get standings from the community's account'''
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain","User-Agent": user_agent}
req = self.session.get('http://'+self.domain+'/standings.phtml',headers=headers).content
soup = BeautifulS... | [
"def",
"standings",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"\"Content-type\"",
":",
"\"application/x-www-form-urlencoded\"",
",",
"\"Accept\"",
":",
"\"text/plain\"",
",",
"\"User-Agent\"",
":",
"user_agent",
"}",
"req",
"=",
"self",
".",
"session",
".",
"g... | 72.555556 | 44.333333 |
def commit(cls, client=None):
"""Commit everything from datapoints via the client.
:param client: InfluxDBClient instance for writing points to InfluxDB.
:attention: any provided client will supersede the class client.
:return: result of client.write_points.
"""
if not c... | [
"def",
"commit",
"(",
"cls",
",",
"client",
"=",
"None",
")",
":",
"if",
"not",
"client",
":",
"client",
"=",
"cls",
".",
"_client",
"rtn",
"=",
"client",
".",
"write_points",
"(",
"cls",
".",
"_json_body_",
"(",
")",
")",
"cls",
".",
"_reset_",
"(... | 36.833333 | 17.25 |
def info(
self,
path="/", # type: Text
namespaces=None, # type: Optional[Collection[Text]]
**kwargs # type: Any
):
# type: (...) -> Iterator[Tuple[Text, Info]]
"""Walk a filesystem, yielding path and `Info` of resources.
Arguments:
path (str): ... | [
"def",
"info",
"(",
"self",
",",
"path",
"=",
"\"/\"",
",",
"# type: Text",
"namespaces",
"=",
"None",
",",
"# type: Optional[Collection[Text]]",
"*",
"*",
"kwargs",
"# type: Any",
")",
":",
"# type: (...) -> Iterator[Tuple[Text, Info]]",
"walker",
"=",
"self",
".",... | 47.897959 | 24.979592 |
def serialize(cls, obj, buf, lineLength, validate):
"""
Apple's Address Book is *really* weird with images, it expects
base64 data to have very specific whitespace. It seems Address Book
can handle PHOTO if it's not wrapped, so don't wrap it.
"""
if wacky_apple_photo_ser... | [
"def",
"serialize",
"(",
"cls",
",",
"obj",
",",
"buf",
",",
"lineLength",
",",
"validate",
")",
":",
"if",
"wacky_apple_photo_serialize",
":",
"lineLength",
"=",
"REALLY_LARGE",
"VCardTextBehavior",
".",
"serialize",
"(",
"obj",
",",
"buf",
",",
"lineLength",... | 47.222222 | 14.555556 |
def calculate_elem_per_kb(max_chunk_kb, matrix_dtype):
"""
Calculates the number of elem per kb depending on the max chunk size set.
Input:
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- matrix_dtype (numpy dtype, default=numpy.float32): Storage d... | [
"def",
"calculate_elem_per_kb",
"(",
"max_chunk_kb",
",",
"matrix_dtype",
")",
":",
"if",
"matrix_dtype",
"==",
"numpy",
".",
"float32",
":",
"return",
"(",
"max_chunk_kb",
"*",
"8",
")",
"/",
"32",
"elif",
"matrix_dtype",
"==",
"numpy",
".",
"float64",
":",... | 46.9 | 29.6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.