text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def isKeyboardShown(self):
'''
Whether the keyboard is displayed.
'''
self.__checkTransport()
dim = self.shell('dumpsys input_method')
if dim:
# FIXME: API >= 15 ?
return "mInputShown=true" in dim
return False | [
"def",
"isKeyboardShown",
"(",
"self",
")",
":",
"self",
".",
"__checkTransport",
"(",
")",
"dim",
"=",
"self",
".",
"shell",
"(",
"'dumpsys input_method'",
")",
"if",
"dim",
":",
"# FIXME: API >= 15 ?",
"return",
"\"mInputShown=true\"",
"in",
"dim",
"return",
... | 25.454545 | 17.090909 |
def scene_name(sequence_number, scene_id, name):
"""Create a scene.name message"""
return MessageWriter().string("scene.name").uint64(sequence_number).uint32(scene_id).string(name).get() | [
"def",
"scene_name",
"(",
"sequence_number",
",",
"scene_id",
",",
"name",
")",
":",
"return",
"MessageWriter",
"(",
")",
".",
"string",
"(",
"\"scene.name\"",
")",
".",
"uint64",
"(",
"sequence_number",
")",
".",
"uint32",
"(",
"scene_id",
")",
".",
"stri... | 66.666667 | 26.333333 |
def show_url(context, **kwargs):
"""Return the show feed URL with different protocol."""
if len(kwargs) != 2:
raise TemplateSyntaxError(_('"show_url" tag takes exactly two keyword arguments.'))
request = context['request']
current_site = get_current_site(request)
url = add_domain(current_sit... | [
"def",
"show_url",
"(",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
"!=",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"_",
"(",
"'\"show_url\" tag takes exactly two keyword arguments.'",
")",
")",
"request",
"=",
"context"... | 50.75 | 16.375 |
def sync(self):
"""
Syncs the information for this settings out to the file system.
"""
if self._customFormat:
self._customFormat.save(self.fileName())
else:
super(XSettings, self).sync() | [
"def",
"sync",
"(",
"self",
")",
":",
"if",
"self",
".",
"_customFormat",
":",
"self",
".",
"_customFormat",
".",
"save",
"(",
"self",
".",
"fileName",
"(",
")",
")",
"else",
":",
"super",
"(",
"XSettings",
",",
"self",
")",
".",
"sync",
"(",
")"
] | 31.375 | 13.125 |
def tshift(self, periods=1, freq=None, axis=0):
"""
Shift the time index, using the index's frequency if available.
Parameters
----------
periods : int
Number of periods to move, can be positive or negative
freq : DateOffset, timedelta, or time rule string, d... | [
"def",
"tshift",
"(",
"self",
",",
"periods",
"=",
"1",
",",
"freq",
"=",
"None",
",",
"axis",
"=",
"0",
")",
":",
"index",
"=",
"self",
".",
"_get_axis",
"(",
"axis",
")",
"if",
"freq",
"is",
"None",
":",
"freq",
"=",
"getattr",
"(",
"index",
... | 32.821429 | 21.25 |
def get_default_plugin(cls):
'''
Return a default plugin.
'''
from importlib import import_module
from django.conf import settings
default_plugin = getattr(settings, 'ACCESS_DEFAULT_PLUGIN', "access.plugins.DjangoAccessPlugin")
if default_plugin not in cls.default... | [
"def",
"get_default_plugin",
"(",
"cls",
")",
":",
"from",
"importlib",
"import",
"import_module",
"from",
"django",
".",
"conf",
"import",
"settings",
"default_plugin",
"=",
"getattr",
"(",
"settings",
",",
"'ACCESS_DEFAULT_PLUGIN'",
",",
"\"access.plugins.DjangoAcce... | 47.2 | 18.4 |
def domain_capabilities(emulator=None, arch=None, machine=None, domain=None, **kwargs):
'''
Return the domain capabilities given an emulator, architecture, machine or virtualization type.
.. versionadded:: 2019.2.0
:param emulator: return the capabilities for the given emulator binary
:param arch:... | [
"def",
"domain_capabilities",
"(",
"emulator",
"=",
"None",
",",
"arch",
"=",
"None",
",",
"machine",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__get_conn",
"(",
"*",
"*",
"kwargs",
")",
"result",
"=",
... | 36.371429 | 31.8 |
def node_dependencies(context: Context):
"""
Updates node.js dependencies
"""
args = ['--loglevel', {0: 'silent', 1: 'warn', 2: 'info'}[context.verbosity]]
if not context.use_colour:
args.append('--color false')
args.append('install')
return context.shell('npm', *args) | [
"def",
"node_dependencies",
"(",
"context",
":",
"Context",
")",
":",
"args",
"=",
"[",
"'--loglevel'",
",",
"{",
"0",
":",
"'silent'",
",",
"1",
":",
"'warn'",
",",
"2",
":",
"'info'",
"}",
"[",
"context",
".",
"verbosity",
"]",
"]",
"if",
"not",
... | 33 | 8.777778 |
def remove_lib(lib_name):
"""remove library.
:param lib_name: library name (e.g. 'PS2Keyboard')
:rtype: None
"""
targ_dlib = libraries_dir() / lib_name
log.debug('remove %s', targ_dlib)
targ_dlib.rmtree() | [
"def",
"remove_lib",
"(",
"lib_name",
")",
":",
"targ_dlib",
"=",
"libraries_dir",
"(",
")",
"/",
"lib_name",
"log",
".",
"debug",
"(",
"'remove %s'",
",",
"targ_dlib",
")",
"targ_dlib",
".",
"rmtree",
"(",
")"
] | 22.5 | 15.6 |
def getPk(self):
'''
getPk - @see ForeignLinkData.getPk
'''
if not self.pk or None in self.pk:
for i in range( len(self.pk) ):
if self.pk[i]:
continue
if self.obj[i] and self.obj[i]._id:
self.pk[i] = self.obj[i]._id
return self.pk | [
"def",
"getPk",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"pk",
"or",
"None",
"in",
"self",
".",
"pk",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"pk",
")",
")",
":",
"if",
"self",
".",
"pk",
"[",
"i",
"]",
":",
... | 19.384615 | 20.615385 |
def p_expr_assign(p):
'''expr : variable EQUALS expr
| variable EQUALS AND expr'''
if len(p) == 5:
p[0] = ast.Assignment(p[1], p[4], True, lineno=p.lineno(2))
else:
p[0] = ast.Assignment(p[1], p[3], False, lineno=p.lineno(2)) | [
"def",
"p_expr_assign",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"5",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Assignment",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"4",
"]",
",",
"True",
",",
"lineno",
"=",
"p",
".",
"linen... | 37 | 19 |
def get_breadcrumbs(url, request=None):
"""
Given a url returns a list of breadcrumbs, which are each a
tuple of (name, url).
"""
from wave.reverse import preserve_builtin_query_params
from wave.settings import api_settings
from wave.views import APIView
view_name_func = api_settings.VI... | [
"def",
"get_breadcrumbs",
"(",
"url",
",",
"request",
"=",
"None",
")",
":",
"from",
"wave",
".",
"reverse",
"import",
"preserve_builtin_query_params",
"from",
"wave",
".",
"settings",
"import",
"api_settings",
"from",
"wave",
".",
"views",
"import",
"APIView",
... | 37.377358 | 17.830189 |
def rise(self, crd, ev='5deg'):
"""This method will give the rise/set hour-angles of a source. It
needs the position in the frame, and a time. If the latter is not
set, the current time will be used.
:param crd: a direction measure
:param ev: the elevation limit as a quantity or... | [
"def",
"rise",
"(",
"self",
",",
"crd",
",",
"ev",
"=",
"'5deg'",
")",
":",
"if",
"not",
"is_measure",
"(",
"crd",
")",
":",
"raise",
"TypeError",
"(",
"'No rise/set coordinates specified'",
")",
"ps",
"=",
"self",
".",
"_getwhere",
"(",
")",
"self",
"... | 41.206897 | 13.827586 |
def run(self, graph, universe=None):
"""Run the contained protocol on a seed graph.
:param pybel.BELGraph graph: The seed BEL graph
:param pybel.BELGraph universe: Allows just-in-time setting of the universe in case it wasn't set before.
Defaults to the g... | [
"def",
"run",
"(",
"self",
",",
"graph",
",",
"universe",
"=",
"None",
")",
":",
"self",
".",
"universe",
"=",
"universe",
"or",
"graph",
".",
"copy",
"(",
")",
"return",
"self",
".",
"_run_helper",
"(",
"graph",
".",
"copy",
"(",
")",
",",
"self",... | 49.363636 | 20.545455 |
def get_ref_chain(self, ref_limit=100):
"""Get a chain of Dataset objects.
Starts with r, then goes to r.reference (if exists),
then to r.reference.reference, etc.
until we hit ``ref_limit`` or a reference loop.
Parameters
----------
ref_limit : int, optional (d... | [
"def",
"get_ref_chain",
"(",
"self",
",",
"ref_limit",
"=",
"100",
")",
":",
"head",
"=",
"self",
"ref_chain",
"=",
"set",
"(",
")",
"while",
"len",
"(",
"ref_chain",
")",
"<",
"ref_limit",
":",
"if",
"isinstance",
"(",
"head",
",",
"Dataset",
")",
"... | 30.482759 | 15.827586 |
def get_raw_query(self):
"""Returns the raw query to use for current search, based on the
base query + update query
"""
query = self.base_query.copy()
search_query = self.search_query.copy()
query.update(search_query)
# Add sorting criteria
sorting = self... | [
"def",
"get_raw_query",
"(",
"self",
")",
":",
"query",
"=",
"self",
".",
"base_query",
".",
"copy",
"(",
")",
"search_query",
"=",
"self",
".",
"search_query",
".",
"copy",
"(",
")",
"query",
".",
"update",
"(",
"search_query",
")",
"# Add sorting criteri... | 36.631579 | 13.210526 |
def getSiblings(self, textId: str, subreference: Union[str, BaseReference]) -> Tuple[BaseReference, BaseReference]:
""" Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage Reference
:type su... | [
"def",
"getSiblings",
"(",
"self",
",",
"textId",
":",
"str",
",",
"subreference",
":",
"Union",
"[",
"str",
",",
"BaseReference",
"]",
")",
"->",
"Tuple",
"[",
"BaseReference",
",",
"BaseReference",
"]",
":",
"raise",
"NotImplementedError",
"(",
")"
] | 39.727273 | 17.181818 |
def get_filter(self, name=constants.STRING_FILTER):
"""Get the filter on the source.
:param name: The name of the filter. This will be encoded as
an AMQP Symbol. By default this is set to b'apache.org:selector-filter:string'.
:type name: bytes
"""
try:
filte... | [
"def",
"get_filter",
"(",
"self",
",",
"name",
"=",
"constants",
".",
"STRING_FILTER",
")",
":",
"try",
":",
"filter_key",
"=",
"c_uamqp",
".",
"symbol_value",
"(",
"name",
")",
"return",
"self",
".",
"_address",
".",
"filter_set",
"[",
"filter_key",
"]",
... | 38.916667 | 18.5 |
def clear_assessment(self):
"""Clears the assessment.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm... | [
"def",
"clear_assessment",
"(",
"self",
")",
":",
"# Implemented from template for osid.resource.ResourceForm.clear_avatar_template",
"if",
"(",
"self",
".",
"get_assessment_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
"or",
"self",
".",
"get_assessment_metadata",
... | 42.615385 | 20.461538 |
def bisect_right(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e <= x, and all e in
a[i:] have e > x. So if x already appears in the list, a.insert(x) will
insert just after the rightmost x already ... | [
"def",
"bisect_right",
"(",
"a",
",",
"x",
",",
"lo",
"=",
"0",
",",
"hi",
"=",
"None",
")",
":",
"if",
"lo",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'lo must be non-negative'",
")",
"if",
"hi",
"is",
"None",
":",
"hi",
"=",
"len",
"(",
"a",
... | 31.8 | 20.6 |
def awaitAnyTermination(self, timeout=None):
"""Wait until any of the queries on the associated SQLContext has terminated since the
creation of the context, or since :func:`resetTerminated()` was called. If any query was
terminated with an exception, then the exception will be thrown.
If... | [
"def",
"awaitAnyTermination",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"timeout",
",",
"(",
"int",
",",
"float",
")",
")",
"or",
"timeout",
"<",
"0",
":",
"raise",
... | 63.884615 | 36 |
def get(self, key, failobj=None, exact=0):
"""Returns failobj if key is not found or is ambiguous"""
if not exact:
try:
key = self.getfullkey(key)
except KeyError:
return failobj
return self.data.get(key,failobj) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"failobj",
"=",
"None",
",",
"exact",
"=",
"0",
")",
":",
"if",
"not",
"exact",
":",
"try",
":",
"key",
"=",
"self",
".",
"getfullkey",
"(",
"key",
")",
"except",
"KeyError",
":",
"return",
"failobj",
"... | 28.5 | 15 |
def cleanup(self):
"""
Remove those pending exits if:
a) they are the return exits of non-returning SimProcedures
b) they are the return exits of non-returning syscalls
b) they are the return exits of non-returning functions
:return: None
"""
pending_exi... | [
"def",
"cleanup",
"(",
"self",
")",
":",
"pending_exits_to_remove",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"func_addr",
"in",
"self",
".",
"_updated_functions",
":",
"if",
"func_addr",
"not",
"in",
"self",
".",
"_jobs",
":",
"continue",
"jobs",
"=",
... | 38.363636 | 18.272727 |
def _dictify(self, doc):
"""Transforms the replies to a regular Python dict with
strings and datetimes.
Tested with BankID version 2.5 return data.
:param doc: The response as interpreted by :py:mod:`zeep`.
:returns: The response parsed to a dict.
:rtype: dict
... | [
"def",
"_dictify",
"(",
"self",
",",
"doc",
")",
":",
"return",
"{",
"k",
":",
"(",
"self",
".",
"_dictify",
"(",
"doc",
"[",
"k",
"]",
")",
"if",
"hasattr",
"(",
"doc",
"[",
"k",
"]",
",",
"\"_xsd_type\"",
")",
"else",
"doc",
"[",
"k",
"]",
... | 29.6 | 21.6 |
def fake_lens_path_set(lens_path, value, obj):
"""
Simulates R.set with a lens_path since we don't have lens functions
:param lens_path: Array of string paths
:param value: The value to set at the lens path
:param obj: Object containing the given path
:return: The value at the path or None
"... | [
"def",
"fake_lens_path_set",
"(",
"lens_path",
",",
"value",
",",
"obj",
")",
":",
"segment",
"=",
"head",
"(",
"lens_path",
")",
"obj_copy",
"=",
"copy",
".",
"copy",
"(",
"obj",
")",
"def",
"set_array_index",
"(",
"i",
",",
"v",
",",
"l",
")",
":",... | 30.906977 | 17.186047 |
def avail_locations(call=None):
'''
Return available Packet datacenter locations.
CLI Example:
.. code-block:: bash
salt-cloud --list-locations packet-provider
salt-cloud -f avail_locations packet-provider
'''
if call == 'action':
raise SaltCloudException(
... | [
"def",
"avail_locations",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudException",
"(",
"'The avail_locations function must be called with -f or --function.'",
")",
"vm_",
"=",
"get_configured_provider",
"(",
")",
"manager"... | 23.6 | 24.24 |
def scope(self, *args, **kwargs):
# type: (*Any, **Any) -> Scope
"""Return a single scope based on the provided name.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional que... | [
"def",
"scope",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (*Any, **Any) -> Scope",
"_scopes",
"=",
"self",
".",
"scopes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"_scopes",
")",
"==",
"0",
... | 40.631579 | 22.789474 |
def libvlc_video_set_format_callbacks(mp, setup, cleanup):
'''Set decoded video chroma and dimensions. This only works in combination with
L{libvlc_video_set_callbacks}().
@param mp: the media player.
@param setup: callback to select the video format (cannot be NULL).
@param cleanup: callback to rel... | [
"def",
"libvlc_video_set_format_callbacks",
"(",
"mp",
",",
"setup",
",",
"cleanup",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_video_set_format_callbacks'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_video_set_format_callbacks'",
",",
"("... | 54.25 | 23.75 |
def process(self):
"""
Call the function with the args/kwds and tell the ApplyResult
that its result is ready. Correctly handles the exceptions
happening during the execution of the function
"""
try:
result = self._func(*self._args, **self._kwds)
excep... | [
"def",
"process",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"_func",
"(",
"*",
"self",
".",
"_args",
",",
"*",
"*",
"self",
".",
"_kwds",
")",
"except",
":",
"self",
".",
"_result",
".",
"_set_exception",
"(",
")",
"else",
":... | 34.25 | 16.083333 |
def purge_old_logs(delete_before_days=7):
"""
Purges old logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = Log.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | [
"def",
"purge_old_logs",
"(",
"delete_before_days",
"=",
"7",
")",
":",
"delete_before_date",
"=",
"timezone",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"days",
"=",
"delete_before_days",
")",
"logs_deleted",
"=",
"Log",
".",
"objects",
".",
"filter",
"("... | 35.875 | 8.875 |
def delete(self, resource_id, **kwargs):
"""
Deletes a resource by ID.
"""
return self.client._delete(self._url(resource_id), **kwargs) | [
"def",
"delete",
"(",
"self",
",",
"resource_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"client",
".",
"_delete",
"(",
"self",
".",
"_url",
"(",
"resource_id",
")",
",",
"*",
"*",
"kwargs",
")"
] | 27.166667 | 12.5 |
def post_handler_err(self, function_arn, invocation_id, handler_err):
"""
Post the error message from executing the function handler for :code:`function_arn`
with specifid :code:`invocation_id`
:param function_arn: Arn of the Lambda function which has the handler error message.
... | [
"def",
"post_handler_err",
"(",
"self",
",",
"function_arn",
",",
"invocation_id",
",",
"handler_err",
")",
":",
"url",
"=",
"self",
".",
"_get_work_url",
"(",
"function_arn",
")",
"runtime_logger",
".",
"info",
"(",
"'Posting handler error for invocation id [{}] to {... | 37.419355 | 26.322581 |
def similarity_transformation(rot, mat):
""" R x M x R^-1 """
return np.dot(rot, np.dot(mat, np.linalg.inv(rot))) | [
"def",
"similarity_transformation",
"(",
"rot",
",",
"mat",
")",
":",
"return",
"np",
".",
"dot",
"(",
"rot",
",",
"np",
".",
"dot",
"(",
"mat",
",",
"np",
".",
"linalg",
".",
"inv",
"(",
"rot",
")",
")",
")"
] | 39.666667 | 5 |
def iter_causes(self):
"""Iterate over all causes."""
curr = self._cause
while curr is not None:
yield curr
curr = curr._cause | [
"def",
"iter_causes",
"(",
"self",
")",
":",
"curr",
"=",
"self",
".",
"_cause",
"while",
"curr",
"is",
"not",
"None",
":",
"yield",
"curr",
"curr",
"=",
"curr",
".",
"_cause"
] | 28.166667 | 11.5 |
def get_conductivity(self, output='eigs', doping_levels=True,
relaxation_time=1e-14):
"""
Gives the conductivity (1/Ohm*m) in either a full 3x3 tensor
form, as 3 eigenvalues, or as the average value
(trace/3.0) If doping_levels=True, the results are g... | [
"def",
"get_conductivity",
"(",
"self",
",",
"output",
"=",
"'eigs'",
",",
"doping_levels",
"=",
"True",
",",
"relaxation_time",
"=",
"1e-14",
")",
":",
"return",
"BoltztrapAnalyzer",
".",
"_format_to_output",
"(",
"self",
".",
"_cond",
",",
"self",
".",
"_c... | 50.918919 | 22.486486 |
def get_project(self) -> str:
"""Get the ihc project"""
xdoc = self.connection.soap_action('/ws/ControllerService',
'getIHCProject', "")
if xdoc:
base64data = xdoc.find(
'./SOAP-ENV:Body/ns1:getIHCProject1/ns1:data',
... | [
"def",
"get_project",
"(",
"self",
")",
"->",
"str",
":",
"xdoc",
"=",
"self",
".",
"connection",
".",
"soap_action",
"(",
"'/ws/ControllerService'",
",",
"'getIHCProject'",
",",
"\"\"",
")",
"if",
"xdoc",
":",
"base64data",
"=",
"xdoc",
".",
"find",
"(",
... | 42.928571 | 15.714286 |
def __flags(self):
"""
Internal method. Turns arguments into flags.
"""
flags = []
if self._capture:
flags.append("-capture")
if self._spy:
flags.append("-spy")
if self._dbpath:
flags += ["-db-path", self._dbpath]
fl... | [
"def",
"__flags",
"(",
"self",
")",
":",
"flags",
"=",
"[",
"]",
"if",
"self",
".",
"_capture",
":",
"flags",
".",
"append",
"(",
"\"-capture\"",
")",
"if",
"self",
".",
"_spy",
":",
"flags",
".",
"append",
"(",
"\"-spy\"",
")",
"if",
"self",
".",
... | 32.145455 | 11.563636 |
def add(self, num):
"""
Adds num to the current value
"""
try:
val = self.value() + num
except:
val = num
self.set(max(0, val)) | [
"def",
"add",
"(",
"self",
",",
"num",
")",
":",
"try",
":",
"val",
"=",
"self",
".",
"value",
"(",
")",
"+",
"num",
"except",
":",
"val",
"=",
"num",
"self",
".",
"set",
"(",
"max",
"(",
"0",
",",
"val",
")",
")"
] | 21.222222 | 12.333333 |
def kms_encrypt(value, key, aws_config=None):
"""Encrypt and value with KMS key.
Args:
value (str): value to encrypt
key (str): key id or alias
aws_config (optional[dict]): aws credentials
dict of arguments passed into boto3 session
example:
aws_c... | [
"def",
"kms_encrypt",
"(",
"value",
",",
"key",
",",
"aws_config",
"=",
"None",
")",
":",
"aws_config",
"=",
"aws_config",
"or",
"{",
"}",
"aws",
"=",
"boto3",
".",
"session",
".",
"Session",
"(",
"*",
"*",
"aws_config",
")",
"client",
"=",
"aws",
".... | 35.681818 | 14.727273 |
def create_for_rectangle(self, x, y, width, height):
"""
Create a new surface that is a rectangle within this surface.
All operations drawn to this surface are then clipped and translated
onto the target surface.
Nothing drawn via this sub-surface outside of its bounds
is... | [
"def",
"create_for_rectangle",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
":",
"return",
"Surface",
".",
"_from_pointer",
"(",
"cairo",
".",
"cairo_surface_create_for_rectangle",
"(",
"self",
".",
"_pointer",
",",
"x",
",",
"y",
","... | 38.272727 | 19.863636 |
def disconnect(self, callback=None):
""" Disconnect the callback from this group. See
:func:`connect() <vispy.event.EmitterGroup.connect>` and
:func:`EventEmitter.connect() <vispy.event.EventEmitter.connect>` for
more information.
"""
ret = EventEmitter.disconnect(self, c... | [
"def",
"disconnect",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"ret",
"=",
"EventEmitter",
".",
"disconnect",
"(",
"self",
",",
"callback",
")",
"if",
"len",
"(",
"self",
".",
"_callbacks",
")",
"==",
"0",
":",
"self",
".",
"_connect_emitter... | 41.8 | 11.9 |
def generate_files(path='', ext='', level=None, dirs=False, files=True, verbosity=0):
""" Recursively generate files (and thier stats) in the indicated directory
Filter by the indicated file name extension (ext)
Args:
path (str): Root/base path to search.
ext (str or list of str): File n... | [
"def",
"generate_files",
"(",
"path",
"=",
"''",
",",
"ext",
"=",
"''",
",",
"level",
"=",
"None",
",",
"dirs",
"=",
"False",
",",
"files",
"=",
"True",
",",
"verbosity",
"=",
"0",
")",
":",
"path",
"=",
"expand_path",
"(",
"path",
"or",
"'.'",
"... | 56.752809 | 32.123596 |
def fastrcnn_Xconv1fc_head(feature, num_convs, norm=None):
"""
Args:
feature (NCHW):
num_classes(int): num_category + 1
num_convs (int): number of conv layers
norm (str or None): either None or 'GN'
Returns:
2D head feature
"""
assert norm in [None, 'GN'], no... | [
"def",
"fastrcnn_Xconv1fc_head",
"(",
"feature",
",",
"num_convs",
",",
"norm",
"=",
"None",
")",
":",
"assert",
"norm",
"in",
"[",
"None",
",",
"'GN'",
"]",
",",
"norm",
"l",
"=",
"feature",
"with",
"argscope",
"(",
"Conv2D",
",",
"data_format",
"=",
... | 41.666667 | 21.333333 |
def _add_torus_extrude_lines(
self, irad, orad, lcar=None, R=numpy.eye(3), x0=numpy.array([0.0, 0.0, 0.0])
):
"""Create Gmsh code for the torus in the x-y plane under the coordinate
transformation
.. math::
\\hat{x} = R x + x_0.
:param irad: inner radius of the ... | [
"def",
"_add_torus_extrude_lines",
"(",
"self",
",",
"irad",
",",
"orad",
",",
"lcar",
"=",
"None",
",",
"R",
"=",
"numpy",
".",
"eye",
"(",
"3",
")",
",",
"x0",
"=",
"numpy",
".",
"array",
"(",
"[",
"0.0",
",",
"0.0",
",",
"0.0",
"]",
")",
")"... | 38.396552 | 20.017241 |
def say(
text = None,
preference_program = "festival",
background = False,
silent = True,
filepath = None
):
"""
Say specified text to speakers or to file, as specified. Determine the
program to use based on the specified program preference... | [
"def",
"say",
"(",
"text",
"=",
"None",
",",
"preference_program",
"=",
"\"festival\"",
",",
"background",
"=",
"False",
",",
"silent",
"=",
"True",
",",
"filepath",
"=",
"None",
")",
":",
"if",
"not",
"text",
":",
"if",
"not",
"silent",
":",
"print",
... | 36.928571 | 13.952381 |
def seq():
"""
Counts up sequentially from a number based on the current time
:rtype int:
"""
current_frame = inspect.currentframe().f_back
trace_string = ""
while current_frame.f_back:
trace_string = trace_string + current_frame.f_back.f_code.co_name
current_frame = cu... | [
"def",
"seq",
"(",
")",
":",
"current_frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"trace_string",
"=",
"\"\"",
"while",
"current_frame",
".",
"f_back",
":",
"trace_string",
"=",
"trace_string",
"+",
"current_frame",
".",
"f_back",
"... | 31.25 | 16.416667 |
def import_boundary_event_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN boundary event.
Boundary event inherits sequence of eventDefinitionRef from Event type.
Separate methods for each event type are required sin... | [
"def",
"import_boundary_event_to_graph",
"(",
"diagram_graph",
",",
"process_id",
",",
"process_attributes",
",",
"element",
")",
":",
"element_id",
"=",
"element",
".",
"getAttribute",
"(",
"consts",
".",
"Consts",
".",
"id",
")",
"boundary_event_definitions",
"=",... | 67.137931 | 38.172414 |
def _decode_v2(value):
"""
Decode ':' and '$' characters encoded by `_encode`.
"""
if re.search(r'(?<!\$):', value):
raise ValueError("Unescaped ':' in the encoded string")
decode_colons = value.replace('$:', ':')
if re.search(r'(?<!\$)(\$\$)*\$([^$]|\Z)', decode_colons):
raise... | [
"def",
"_decode_v2",
"(",
"value",
")",
":",
"if",
"re",
".",
"search",
"(",
"r'(?<!\\$):'",
",",
"value",
")",
":",
"raise",
"ValueError",
"(",
"\"Unescaped ':' in the encoded string\"",
")",
"decode_colons",
"=",
"value",
".",
"replace",
"(",
"'$:'",
",",
... | 33.25 | 15.583333 |
def get_tr(self):
"""Returns the top right border of the cell"""
cell_above = CellBorders(self.cell_attributes,
*self.cell.get_above_key_rect())
return cell_above.get_r() | [
"def",
"get_tr",
"(",
"self",
")",
":",
"cell_above",
"=",
"CellBorders",
"(",
"self",
".",
"cell_attributes",
",",
"*",
"self",
".",
"cell",
".",
"get_above_key_rect",
"(",
")",
")",
"return",
"cell_above",
".",
"get_r",
"(",
")"
] | 37.166667 | 18.166667 |
def find_birthdays(request):
"""Return information on user birthdays."""
today = date.today()
custom = False
yr_inc = 0
if "birthday_month" in request.GET and "birthday_day" in request.GET:
try:
mon = int(request.GET["birthday_month"])
day = int(request.GET["birthday_... | [
"def",
"find_birthdays",
"(",
"request",
")",
":",
"today",
"=",
"date",
".",
"today",
"(",
")",
"custom",
"=",
"False",
"yr_inc",
"=",
"0",
"if",
"\"birthday_month\"",
"in",
"request",
".",
"GET",
"and",
"\"birthday_day\"",
"in",
"request",
".",
"GET",
... | 36.085714 | 18.742857 |
def search(self, ngram):
'''
Parameters
----------
ngram str or unicode, string to search for
Returns
-------
pd.DataFrame, {'texts': <matching texts>, 'categories': <corresponding categories>}
'''
mask = self._document_index_mask(ngram)
return pd.DataFrame({
'text': self.get_texts()[mask],
... | [
"def",
"search",
"(",
"self",
",",
"ngram",
")",
":",
"mask",
"=",
"self",
".",
"_document_index_mask",
"(",
"ngram",
")",
"return",
"pd",
".",
"DataFrame",
"(",
"{",
"'text'",
":",
"self",
".",
"get_texts",
"(",
")",
"[",
"mask",
"]",
",",
"'categor... | 23.529412 | 23.882353 |
def partial_regardless(__fn, *a, **kw):
"""Wrap a note for injection of a partially applied function, or don't.
Use this instead of `partial` when binding a callable that may or may
not have annotations.
"""
return (PARTIAL_REGARDLESS, (__fn, a, tuple(kw.items()))) | [
"def",
"partial_regardless",
"(",
"__fn",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"return",
"(",
"PARTIAL_REGARDLESS",
",",
"(",
"__fn",
",",
"a",
",",
"tuple",
"(",
"kw",
".",
"items",
"(",
")",
")",
")",
")"
] | 42.857143 | 16.285714 |
def predict_mhci_binding(job, peptfile, allele, peplen, univ_options, mhci_options):
"""
Predict binding for each peptide in `peptfile` to `allele` using the IEDB mhci binding
prediction tool.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict bindin... | [
"def",
"predict_mhci_binding",
"(",
"job",
",",
"peptfile",
",",
"allele",
",",
"peplen",
",",
"univ_options",
",",
"mhci_options",
")",
":",
"work_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"input_files",
"=",
"{",
"'peptfile.faa'",
":",
"peptfile",
"}",
"... | 50.40625 | 23.59375 |
def getroot(self):
"""Build XML object, return the root"""
builder = ET.TreeBuilder()
self.build(builder)
return builder.close() | [
"def",
"getroot",
"(",
"self",
")",
":",
"builder",
"=",
"ET",
".",
"TreeBuilder",
"(",
")",
"self",
".",
"build",
"(",
"builder",
")",
"return",
"builder",
".",
"close",
"(",
")"
] | 31.2 | 10.2 |
def run(command, cwd=None, shell=False, raiseOnError=False):
"""
Executes a child process and waits for it to complete
"""
returncode = subprocess.call(command, cwd=cwd, shell=shell)
if raiseOnError == True and returncode != 0:
raise Exception('child process ' + str(command) + ' failed with exit code ' + s... | [
"def",
"run",
"(",
"command",
",",
"cwd",
"=",
"None",
",",
"shell",
"=",
"False",
",",
"raiseOnError",
"=",
"False",
")",
":",
"returncode",
"=",
"subprocess",
".",
"call",
"(",
"command",
",",
"cwd",
"=",
"cwd",
",",
"shell",
"=",
"shell",
")",
"... | 43.5 | 17.5 |
def _get_options(ret=None):
'''
Returns options used for the MySQL connection.
'''
defaults = {'host': 'salt',
'user': 'salt',
'pass': 'salt',
'db': 'salt',
'port': 3306,
'ssl_ca': None,
'ssl_cert': None,
... | [
"def",
"_get_options",
"(",
"ret",
"=",
"None",
")",
":",
"defaults",
"=",
"{",
"'host'",
":",
"'salt'",
",",
"'user'",
":",
"'salt'",
",",
"'pass'",
":",
"'salt'",
",",
"'db'",
":",
"'salt'",
",",
"'port'",
":",
"3306",
",",
"'ssl_ca'",
":",
"None",... | 33.578947 | 16.421053 |
def _find_valid_block(self, table, worksheet, flags, units, used_cells, start_pos, end_pos):
'''
Searches for the next location where a valid block could reside and constructs the block
object representing that location.
'''
for row_index in range(len(table)):
if row_... | [
"def",
"_find_valid_block",
"(",
"self",
",",
"table",
",",
"worksheet",
",",
"flags",
",",
"units",
",",
"used_cells",
",",
"start_pos",
",",
"end_pos",
")",
":",
"for",
"row_index",
"in",
"range",
"(",
"len",
"(",
"table",
")",
")",
":",
"if",
"row_i... | 55.730769 | 24.346154 |
def ReadMostRecentClientGraphSeries(self, client_label,
report_type
):
"""See db.Database."""
series_with_timestamps = self.ReadAllClientGraphSeries(
client_label, report_type)
if not series_with_timestamps:
return None... | [
"def",
"ReadMostRecentClientGraphSeries",
"(",
"self",
",",
"client_label",
",",
"report_type",
")",
":",
"series_with_timestamps",
"=",
"self",
".",
"ReadAllClientGraphSeries",
"(",
"client_label",
",",
"report_type",
")",
"if",
"not",
"series_with_timestamps",
":",
... | 41.1 | 12.9 |
def pinv(a, rcond=None, validate_args=False, name=None):
"""Compute the Moore-Penrose pseudo-inverse of a matrix.
Calculate the [generalized inverse of a matrix](
https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse) using its
singular-value decomposition (SVD) and including all large singular values.
... | [
"def",
"pinv",
"(",
"a",
",",
"rcond",
"=",
"None",
",",
"validate_args",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'pinv'",
",",
"[",
"a",
",",
"rcond",
"]",
... | 38.861789 | 22.821138 |
def _descendants(self):
"""
Scans full list of node descendants.
:return: Generator of nodes.
"""
children = self._children
if children is not None:
for child in children.values():
yield from child._descendants
yield child | [
"def",
"_descendants",
"(",
"self",
")",
":",
"children",
"=",
"self",
".",
"_children",
"if",
"children",
"is",
"not",
"None",
":",
"for",
"child",
"in",
"children",
".",
"values",
"(",
")",
":",
"yield",
"from",
"child",
".",
"_descendants",
"yield",
... | 27.727273 | 9.181818 |
def fixup_scipy_ndimage_result(whatever_it_returned):
"""Convert a result from scipy.ndimage to a numpy array
scipy.ndimage has the annoying habit of returning a single, bare
value instead of an array if the indexes passed in are of length 1.
For instance:
scind.maximum(image, labels, [1]) retu... | [
"def",
"fixup_scipy_ndimage_result",
"(",
"whatever_it_returned",
")",
":",
"if",
"getattr",
"(",
"whatever_it_returned",
",",
"\"__getitem__\"",
",",
"False",
")",
":",
"return",
"np",
".",
"array",
"(",
"whatever_it_returned",
")",
"else",
":",
"return",
"np",
... | 39.357143 | 17.928571 |
def get_formatter_by_name(_alias, **options):
"""Lookup and instantiate a formatter by alias.
Raises ClassNotFound if not found.
"""
cls = find_formatter_class(_alias)
if cls is None:
raise ClassNotFound("no formatter found for name %r" % _alias)
return cls(**options) | [
"def",
"get_formatter_by_name",
"(",
"_alias",
",",
"*",
"*",
"options",
")",
":",
"cls",
"=",
"find_formatter_class",
"(",
"_alias",
")",
"if",
"cls",
"is",
"None",
":",
"raise",
"ClassNotFound",
"(",
"\"no formatter found for name %r\"",
"%",
"_alias",
")",
... | 32.555556 | 12.777778 |
def device_unmounted(self, device):
"""Show unmount notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_unmounted',
_('Device unmounted'),
_('{0.ui_label} unmounted', devi... | [
"def",
"device_unmounted",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"self",
".",
"_show_notification",
"(",
"'device_unmounted'",
",",
"_",
"(",
"'Device unmounted'",
... | 38.444444 | 8.888889 |
def update_process_died_status(self):
""" Update the flag indicating whether any process exited and did not provide a result. """
# There is a result pending, the process is no longer alive, yet there is no result in the queue
# This means the decoder process has not succesfully produced metric... | [
"def",
"update_process_died_status",
"(",
"self",
")",
":",
"# There is a result pending, the process is no longer alive, yet there is no result in the queue",
"# This means the decoder process has not succesfully produced metrics",
"queue_should_hold_result",
"=",
"self",
".",
"_results_pen... | 70.625 | 34 |
def repo_is_dirty(self):
"""
Return true if repo is dirty
"""
try:
subprocess.check_call(['git', 'diff-files', '--quiet'], cwd=self.repo_dir)
# Return code is 0
return False
except subprocess.CalledProcessError:
return True | [
"def",
"repo_is_dirty",
"(",
"self",
")",
":",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"'git'",
",",
"'diff-files'",
",",
"'--quiet'",
"]",
",",
"cwd",
"=",
"self",
".",
"repo_dir",
")",
"# Return code is 0",
"return",
"False",
"except",
"su... | 30.2 | 14.2 |
def stop(self):
'''
Stop the auth proc.
'''
log.info('Stopping auth process')
self.__up = False
self.socket.close() | [
"def",
"stop",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Stopping auth process'",
")",
"self",
".",
"__up",
"=",
"False",
"self",
".",
"socket",
".",
"close",
"(",
")"
] | 22.428571 | 17.857143 |
def _merge_last(values, merge_after, merge_with=' '):
'''
Merge values all values after X into the last value
'''
if len(values) > merge_after:
values = values[0:(merge_after-1)] + [merge_with.join(values[(merge_after-1):])]
return values | [
"def",
"_merge_last",
"(",
"values",
",",
"merge_after",
",",
"merge_with",
"=",
"' '",
")",
":",
"if",
"len",
"(",
"values",
")",
">",
"merge_after",
":",
"values",
"=",
"values",
"[",
"0",
":",
"(",
"merge_after",
"-",
"1",
")",
"]",
"+",
"[",
"m... | 32.5 | 26.5 |
def unbuild_month(self, dt):
"""
Deletes the directory at self.get_build_path.
"""
self.year = str(dt.year)
self.month = str(dt.month)
logger.debug("Building %s-%s" % (self.year, self.month))
target_path = os.path.split(self.get_build_path())[0]
if self.fs... | [
"def",
"unbuild_month",
"(",
"self",
",",
"dt",
")",
":",
"self",
".",
"year",
"=",
"str",
"(",
"dt",
".",
"year",
")",
"self",
".",
"month",
"=",
"str",
"(",
"dt",
".",
"month",
")",
"logger",
".",
"debug",
"(",
"\"Building %s-%s\"",
"%",
"(",
"... | 39.545455 | 9.727273 |
def cycles_engine(**kwargs):
"""engine to extract cycles"""
logging.info("cycles_engine:")
logging.info("Not ready for production")
# raise NotImplementedError
experiments = kwargs["experiments"]
farms = []
barn = "raw_dir" # Its a murder in the red barn - murder in the red barn
for ... | [
"def",
"cycles_engine",
"(",
"*",
"*",
"kwargs",
")",
":",
"logging",
".",
"info",
"(",
"\"cycles_engine:\"",
")",
"logging",
".",
"info",
"(",
"\"Not ready for production\"",
")",
"# raise NotImplementedError",
"experiments",
"=",
"kwargs",
"[",
"\"experiments\"",
... | 34 | 19.043478 |
def get_edge_attr(self, n, m, attr):
'''
API: get_edge_attr(self, n, m, attr)
Description:
Returns attribute attr of edge (n,m).
Input:
n: Source node name.
m: Sink node name.
attr: Attribute of edge.
Pre:
Graph should have ... | [
"def",
"get_edge_attr",
"(",
"self",
",",
"n",
",",
"m",
",",
"attr",
")",
":",
"if",
"self",
".",
"graph_type",
"is",
"DIRECTED_GRAPH",
":",
"return",
"self",
".",
"edge_attr",
"[",
"(",
"n",
",",
"m",
")",
"]",
"[",
"attr",
"]",
"else",
":",
"t... | 30.238095 | 13.666667 |
def restore_version(self, symbol, as_of, prune_previous_version=True):
"""
Restore the specified 'symbol' data and metadata to the state of a given version/snapshot/date.
Returns a VersionedItem object only with a metadata element.
Fast operation: Zero data/segment read/write operations.... | [
"def",
"restore_version",
"(",
"self",
",",
"symbol",
",",
"as_of",
",",
"prune_previous_version",
"=",
"True",
")",
":",
"# TODO: This operation is tricky as it may create history branches and lead to corrupted symbols.",
"# To avoid this we do concat_rewrite (see Issue #579)",
... | 53.06383 | 31.702128 |
def update_transfer_config(
self,
transfer_config,
update_mask,
authorization_code=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates a data transfer configuration... | [
"def",
"update_transfer_config",
"(",
"self",
",",
"transfer_config",
",",
"update_mask",
",",
"authorization_code",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
... | 48.679612 | 28.718447 |
async def delete(self):
"""Delete this Bcache."""
await self._handler.delete(
system_id=self.node.system_id, id=self.id) | [
"async",
"def",
"delete",
"(",
"self",
")",
":",
"await",
"self",
".",
"_handler",
".",
"delete",
"(",
"system_id",
"=",
"self",
".",
"node",
".",
"system_id",
",",
"id",
"=",
"self",
".",
"id",
")"
] | 36.25 | 9 |
def setup_oauth(username, password, basemaps_token_uri, authcfg_id=AUTHCFG_ID, authcfg_name=AUTHCFG_NAME):
"""Setup oauth configuration to access the BCS API,
return authcfg_id on success, None on failure
"""
cfgjson = {
"accessMethod" : 0,
"apiKey" : "",
"clientId" : "",
"clientSecr... | [
"def",
"setup_oauth",
"(",
"username",
",",
"password",
",",
"basemaps_token_uri",
",",
"authcfg_id",
"=",
"AUTHCFG_ID",
",",
"authcfg_name",
"=",
"AUTHCFG_NAME",
")",
":",
"cfgjson",
"=",
"{",
"\"accessMethod\"",
":",
"0",
",",
"\"apiKey\"",
":",
"\"\"",
",",... | 34.25 | 17.9 |
def autoinc(self):
"""
Conditionally updates the stack version in the file associated with
this config.
This handles both official releases (i.e. QA configs), and release
candidates. Assumptions about version:
- Official release versions are MAJOR.minor, where MAJ... | [
"def",
"autoinc",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"get",
"(",
"'autoinc_version'",
")",
":",
"return",
"oldver",
"=",
"self",
"[",
"'version'",
"]",
"newver",
"=",
"bump_version_tail",
"(",
"oldver",
")",
"config_path",
"=",
"self",
".",... | 31.291667 | 20.541667 |
def delete_element(self, element):
"""Deletes an element (lazily).
:raises: ValueError -- No such element in the priority queue.
"""
if element not in self.element_finder:
raise ValueError("No such element in the priority queue.")
entry = self.element_finder[element... | [
"def",
"delete_element",
"(",
"self",
",",
"element",
")",
":",
"if",
"element",
"not",
"in",
"self",
".",
"element_finder",
":",
"raise",
"ValueError",
"(",
"\"No such element in the priority queue.\"",
")",
"entry",
"=",
"self",
".",
"element_finder",
"[",
"el... | 34.4 | 16.4 |
def split(txt, seps):
"""
Splits a text in a meaningful list of words based on a list of word
separators (define in pyqode.core.settings)
:param txt: Text to split
:param seps: List of words separators
:return: A **set** of words found in the document (excluding
... | [
"def",
"split",
"(",
"txt",
",",
"seps",
")",
":",
"# replace all possible separators with a default sep",
"default_sep",
"=",
"seps",
"[",
"0",
"]",
"for",
"sep",
"in",
"seps",
"[",
"1",
":",
"]",
":",
"if",
"sep",
":",
"txt",
"=",
"txt",
".",
"replace"... | 35.434783 | 13.086957 |
def forward(self, data_batch, is_train=None):
"""Split `data_batch` according to workload and run forward on each devices.
Parameters
----------
data_batch : DataBatch
Or could be any object implementing similar interface.
is_train : bool
The hint for the... | [
"def",
"forward",
"(",
"self",
",",
"data_batch",
",",
"is_train",
"=",
"None",
")",
":",
"_load_data",
"(",
"data_batch",
",",
"self",
".",
"data_arrays",
",",
"self",
".",
"data_layouts",
")",
"if",
"is_train",
"is",
"None",
":",
"is_train",
"=",
"self... | 39.703704 | 23.444444 |
def parameters(self):
"""The cell parameters (lengths and angles)"""
length_a = np.linalg.norm(self.matrix[:, 0])
length_b = np.linalg.norm(self.matrix[:, 1])
length_c = np.linalg.norm(self.matrix[:, 2])
alpha = np.arccos(np.dot(self.matrix[:, 1], self.matrix[:, 2]) / (length_b *... | [
"def",
"parameters",
"(",
"self",
")",
":",
"length_a",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"matrix",
"[",
":",
",",
"0",
"]",
")",
"length_b",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"matrix",
"[",
":",
",... | 54.083333 | 25.25 |
def cc(self, cc_emails, global_substitutions=None, is_multiple=False, p=0):
"""Adds Cc objects to the Personalization object
:param cc_emails: An Cc or list of Cc objects
:type cc_emails: Cc, list(Cc), tuple
:param global_substitutions: A dict of substitutions for all recipients
... | [
"def",
"cc",
"(",
"self",
",",
"cc_emails",
",",
"global_substitutions",
"=",
"None",
",",
"is_multiple",
"=",
"False",
",",
"p",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"cc_emails",
",",
"list",
")",
":",
"for",
"email",
"in",
"cc_emails",
":",
... | 46.692308 | 14.807692 |
def _psplit(self):
"""
Split `self` at both north and south poles.
:return: A list of split StridedIntervals
"""
nsplit_list = self._nsplit()
psplit_list = [ ]
for si in nsplit_list:
psplit_list.extend(si._ssplit())
return psplit_list | [
"def",
"_psplit",
"(",
"self",
")",
":",
"nsplit_list",
"=",
"self",
".",
"_nsplit",
"(",
")",
"psplit_list",
"=",
"[",
"]",
"for",
"si",
"in",
"nsplit_list",
":",
"psplit_list",
".",
"extend",
"(",
"si",
".",
"_ssplit",
"(",
")",
")",
"return",
"psp... | 21.5 | 17.785714 |
def bake_content(request):
"""Invoke the baking process - trigger post-publication"""
ident_hash = request.matchdict['ident_hash']
try:
id, version = split_ident_hash(ident_hash)
except IdentHashError:
raise httpexceptions.HTTPNotFound()
if not version:
raise httpexceptions.... | [
"def",
"bake_content",
"(",
"request",
")",
":",
"ident_hash",
"=",
"request",
".",
"matchdict",
"[",
"'ident_hash'",
"]",
"try",
":",
"id",
",",
"version",
"=",
"split_ident_hash",
"(",
"ident_hash",
")",
"except",
"IdentHashError",
":",
"raise",
"httpexcepti... | 34.105263 | 14.131579 |
def iter_used_addresses(
adapter, # type: BaseAdapter
seed, # type: Seed
start, # type: int
security_level=None, # type: Optional[int]
):
# type: (...) -> Generator[Tuple[Address, List[TransactionHash]], None, None]
"""
Scans the Tangle for used addresses.
This is ba... | [
"def",
"iter_used_addresses",
"(",
"adapter",
",",
"# type: BaseAdapter",
"seed",
",",
"# type: Seed",
"start",
",",
"# type: int",
"security_level",
"=",
"None",
",",
"# type: Optional[int]",
")",
":",
"# type: (...) -> Generator[Tuple[Address, List[TransactionHash]], None, No... | 30.5 | 20.428571 |
def textcontent(self, cls='current', correctionhandling=CorrectionHandling.CURRENT):
"""See :meth:`AbstractElement.textcontent`"""
if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility
if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandli... | [
"def",
"textcontent",
"(",
"self",
",",
"cls",
"=",
"'current'",
",",
"correctionhandling",
"=",
"CorrectionHandling",
".",
"CURRENT",
")",
":",
"if",
"cls",
"==",
"'original'",
":",
"correctionhandling",
"=",
"CorrectionHandling",
".",
"ORIGINAL",
"#backward comp... | 60.75 | 27 |
async def can_run(self, ctx):
"""|coro|
Checks if the command can be executed by checking all the predicates
inside the :attr:`.checks` attribute.
Parameters
-----------
ctx: :class:`.Context`
The ctx of the command currently being invoked.
Raises
... | [
"async",
"def",
"can_run",
"(",
"self",
",",
"ctx",
")",
":",
"original",
"=",
"ctx",
".",
"command",
"ctx",
".",
"command",
"=",
"self",
"try",
":",
"if",
"not",
"await",
"ctx",
".",
"bot",
".",
"can_run",
"(",
"ctx",
")",
":",
"raise",
"CheckFail... | 31.304348 | 23.304348 |
def save(cls,instance,filename):
"""Class method save for saving TracingVariable."""
filename = cls.correct_file_extension(filename)
try:
with open(filename,'wb') as f:
pickle.dump(instance,f,protocol=pickle.HIGHEST_PROTOCOL)
except MemoryError as e:
... | [
"def",
"save",
"(",
"cls",
",",
"instance",
",",
"filename",
")",
":",
"filename",
"=",
"cls",
".",
"correct_file_extension",
"(",
"filename",
")",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
... | 49.357143 | 14.285714 |
def cprint(string, fg=None, bg=None, end='\n', target=sys.stdout):
"""Print a colored string to the target handle.
fg and bg specify foreground- and background colors, respectively. The
remaining keyword arguments are the same as for Python's built-in print
function. Colors are returned to their defaul... | [
"def",
"cprint",
"(",
"string",
",",
"fg",
"=",
"None",
",",
"bg",
"=",
"None",
",",
"end",
"=",
"'\\n'",
",",
"target",
"=",
"sys",
".",
"stdout",
")",
":",
"_color_manager",
".",
"set_color",
"(",
"fg",
",",
"bg",
")",
"target",
".",
"write",
"... | 38.307692 | 19.846154 |
def get_ec2_info(connection,
instance_id,
region,
username=None):
""" queries EC2 for details about a particular instance_id
"""
instance = connection.get_only_instances(
filters={'instance_id': instance_id}
)[0]
data = instance.__dict_... | [
"def",
"get_ec2_info",
"(",
"connection",
",",
"instance_id",
",",
"region",
",",
"username",
"=",
"None",
")",
":",
"instance",
"=",
"connection",
".",
"get_only_instances",
"(",
"filters",
"=",
"{",
"'instance_id'",
":",
"instance_id",
"}",
")",
"[",
"0",
... | 26.590909 | 15.818182 |
def element_exists(self, element):
"""
Checks if given element exists.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.element_exists("String A")
True
... | [
"def",
"element_exists",
"(",
"self",
",",
"element",
")",
":",
"if",
"not",
"self",
".",
"__elements",
":",
"return",
"False",
"for",
"item",
"in",
"foundations",
".",
"walkers",
".",
"dictionaries_walker",
"(",
"self",
".",
"__elements",
")",
":",
"path"... | 29.548387 | 20.516129 |
def map_fit(interface, state, label, inp):
"""
Function counts occurrences of feature values for every row in given data chunk. For continuous features it returns
number of values and it calculates mean and variance for every feature.
For discrete features it counts occurrences of labels and values for ... | [
"def",
"map_fit",
"(",
"interface",
",",
"state",
",",
"label",
",",
"inp",
")",
":",
"import",
"numpy",
"as",
"np",
"combiner",
"=",
"{",
"}",
"# combiner used for joining of intermediate pairs",
"out",
"=",
"interface",
".",
"output",
"(",
"0",
")",
"# all... | 52.780488 | 26.292683 |
def _init_optional_attrs(self, optional_attrs):
"""Prepare to store data from user-desired optional fields.
Not loading these optional fields by default saves in space and speed.
But allow the possibility for saving these fields, if the user desires,
Including:
com... | [
"def",
"_init_optional_attrs",
"(",
"self",
",",
"optional_attrs",
")",
":",
"# Written by DV Klopfenstein",
"# Required attributes are always loaded. All others are optionally loaded.",
"self",
".",
"attrs_req",
"=",
"[",
"'id'",
",",
"'alt_id'",
",",
"'name'",
",",
"'name... | 57.428571 | 24.928571 |
def make_node(clss, node, *params):
''' This will return a node with a param_list
(declared in a function declaration)
Parameters:
-node: A SymbolPARAMLIST instance or None
-params: SymbolPARAMDECL insances
'''
if node is None:
node = clss()
... | [
"def",
"make_node",
"(",
"clss",
",",
"node",
",",
"*",
"params",
")",
":",
"if",
"node",
"is",
"None",
":",
"node",
"=",
"clss",
"(",
")",
"if",
"node",
".",
"token",
"!=",
"'PARAMLIST'",
":",
"return",
"clss",
".",
"make_node",
"(",
"None",
",",
... | 28.166667 | 17.277778 |
def disable_gen(self, idx):
"""
Disable a PV element for TDS
Parameters
----------
idx
Returns
-------
"""
self.u[self.uid[idx]] = 0
self.system.dae.factorize = True | [
"def",
"disable_gen",
"(",
"self",
",",
"idx",
")",
":",
"self",
".",
"u",
"[",
"self",
".",
"uid",
"[",
"idx",
"]",
"]",
"=",
"0",
"self",
".",
"system",
".",
"dae",
".",
"factorize",
"=",
"True"
] | 16.785714 | 19.071429 |
def _ObjectFactory(obj):
"""Parse a python ``{name: schema}`` dict as an :py:class:`Object` instance.
- A property name prepended by "+" is required
- A property name prepended by "?" is optional
- Any other property is required if :py:attr:`Object.REQUIRED_PROPERTIES`
is True else it's optional
... | [
"def",
"_ObjectFactory",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"optional",
",",
"required",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"obj",
")",
":",
"if",
"key",
"."... | 37.75 | 9.1 |
def check_dns_txt(domain, prefix, code):
"""
Validates a domain by checking that {prefix}={code} is present in the TXT DNS record
of the domain to check.
Returns true if verification suceeded.
"""
token = '{}={}'.format(prefix, code)
try:
for rr in dns.resolver.query(domain, 'TXT'):... | [
"def",
"check_dns_txt",
"(",
"domain",
",",
"prefix",
",",
"code",
")",
":",
"token",
"=",
"'{}={}'",
".",
"format",
"(",
"prefix",
",",
"code",
")",
"try",
":",
"for",
"rr",
"in",
"dns",
".",
"resolver",
".",
"query",
"(",
"domain",
",",
"'TXT'",
... | 29.4 | 14.466667 |
def envs():
'''
Each container configuration can have an environment setting, or defaults
to base
'''
saltenvs = []
for container in __opts__.get('azurefs', []):
saltenvs.append(container.get('saltenv', 'base'))
# Remove duplicates
return list(set(saltenvs)) | [
"def",
"envs",
"(",
")",
":",
"saltenvs",
"=",
"[",
"]",
"for",
"container",
"in",
"__opts__",
".",
"get",
"(",
"'azurefs'",
",",
"[",
"]",
")",
":",
"saltenvs",
".",
"append",
"(",
"container",
".",
"get",
"(",
"'saltenv'",
",",
"'base'",
")",
")"... | 28.9 | 23.7 |
def tmDiff2(tm1, tm2, verbosity = 0, relaxSegmentTests =True,
checkLearn = True, checkStates = True):
"""
Given two TM instances, list the difference between them and returns False
if there is a difference. This function checks the major parameters. If this
passes (and checkLearn is true) it checks ... | [
"def",
"tmDiff2",
"(",
"tm1",
",",
"tm2",
",",
"verbosity",
"=",
"0",
",",
"relaxSegmentTests",
"=",
"True",
",",
"checkLearn",
"=",
"True",
",",
"checkStates",
"=",
"True",
")",
":",
"# First check basic parameters. If we fail here, don't continue",
"if",
"sameTM... | 39.858491 | 25.235849 |
def get_order_container(self, quote_id):
"""Generate an order container from a quote object.
:param quote_id: ID number of target quote
"""
quote = self.client['Billing_Order_Quote']
container = quote.getRecalculatedOrderContainer(id=quote_id)
return container | [
"def",
"get_order_container",
"(",
"self",
",",
"quote_id",
")",
":",
"quote",
"=",
"self",
".",
"client",
"[",
"'Billing_Order_Quote'",
"]",
"container",
"=",
"quote",
".",
"getRecalculatedOrderContainer",
"(",
"id",
"=",
"quote_id",
")",
"return",
"container"
... | 33.555556 | 16 |
def finalize(self):
"""Closes socket and terminates context
NO-OP if already closed.
"""
if self._context is not None:
if self._socket is not None:
self._close_socket(confused=False)
self._context.term()
self._context = None
... | [
"def",
"finalize",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_socket",
"is",
"not",
"None",
":",
"self",
".",
"_close_socket",
"(",
"confused",
"=",
"False",
")",
"self",
".",
"_context",
".",... | 27.416667 | 12.416667 |
def checktype(self, val, kind, **kargs):
"""Raise TypeError if val does not satisfy kind."""
if not isinstance(val, kind):
raise TypeError('Expected {}; got {}'.format(
self.str_kind(kind), self.str_valtype(val))) | [
"def",
"checktype",
"(",
"self",
",",
"val",
",",
"kind",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"kind",
")",
":",
"raise",
"TypeError",
"(",
"'Expected {}; got {}'",
".",
"format",
"(",
"self",
".",
"str_kind",
... | 53 | 10.4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.