text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret):
"""S = (A * v^u) ^ b % N
:param int password_verifier:
:param int server_private:
:param int client_public:
:param int common_secret:
:rtype: int
"""
r... | [
"def",
"get_server_premaster_secret",
"(",
"self",
",",
"password_verifier",
",",
"server_private",
",",
"client_public",
",",
"common_secret",
")",
":",
"return",
"pow",
"(",
"(",
"client_public",
"*",
"pow",
"(",
"password_verifier",
",",
"common_secret",
",",
"... | 41.9 | 0.009346 |
def sessions(self):
"""
Access the sessions
:returns: twilio.rest.proxy.v1.service.session.SessionList
:rtype: twilio.rest.proxy.v1.service.session.SessionList
"""
if self._sessions is None:
self._sessions = SessionList(self._version, service_sid=self._soluti... | [
"def",
"sessions",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sessions",
"is",
"None",
":",
"self",
".",
"_sessions",
"=",
"SessionList",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
")",
"... | 35.3 | 0.008287 |
def erase_in_display(self, how=0, *args, **kwargs):
"""Overloaded to reset history state."""
super(HistoryScreen, self).erase_in_display(how, *args, **kwargs)
if how == 3:
self._reset_history() | [
"def",
"erase_in_display",
"(",
"self",
",",
"how",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"HistoryScreen",
",",
"self",
")",
".",
"erase_in_display",
"(",
"how",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",... | 37.5 | 0.008696 |
def get_sequence(self,chr=None,start=None,end=None,dir=None,rng=None):
"""get a sequence
:param chr:
:param start:
:param end:
:param dir: charcter +/-
:parma rng:
:type chr: string
:type start: int
:type end: int
:type dir: char
:type rng: GenomicRange
:return: sequence... | [
"def",
"get_sequence",
"(",
"self",
",",
"chr",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"dir",
"=",
"None",
",",
"rng",
"=",
"None",
")",
":",
"if",
"rng",
":",
"chr",
"=",
"rng",
".",
"chr",
"start",
"=",
"rng",
... | 24 | 0.023739 |
def extract_ctcp(self, spin, nick, user, host, target, msg):
"""
it is used to extract ctcp requests into pieces.
"""
# The ctcp delimiter token.
DELIM = '\001'
if not msg.startswith(DELIM) or not msg.endswith(DELIM):
return
ctcp_args =... | [
"def",
"extract_ctcp",
"(",
"self",
",",
"spin",
",",
"nick",
",",
"user",
",",
"host",
",",
"target",
",",
"msg",
")",
":",
"# The ctcp delimiter token.",
"DELIM",
"=",
"'\\001'",
"if",
"not",
"msg",
".",
"startswith",
"(",
"DELIM",
")",
"or",
"not",
... | 30.642857 | 0.020362 |
def _process_vetoes(self, results, veto_info):
"""Calculate signal based vetoes"""
chisq = numpy.array(numpy.zeros(len(veto_info)), numpy.float32, ndmin=1)
dof = numpy.array(numpy.zeros(len(veto_info)), numpy.uint32, ndmin=1)
sg_chisq = numpy.array(numpy.zeros(len(veto_info)), numpy.floa... | [
"def",
"_process_vetoes",
"(",
"self",
",",
"results",
",",
"veto_info",
")",
":",
"chisq",
"=",
"numpy",
".",
"array",
"(",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"veto_info",
")",
")",
",",
"numpy",
".",
"float32",
",",
"ndmin",
"=",
"1",
")",
"... | 40.264706 | 0.00214 |
def under_variable_scope():
"""
Returns:
A decorator which makes the function happen under a variable scope,
which is named by the function itself.
Example:
.. code-block:: python
@under_variable_scope()
def mid_level(x):
with argscope(Conv2D, kernel_shape=... | [
"def",
"under_variable_scope",
"(",
")",
":",
"def",
"_impl",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"wit... | 25.814815 | 0.001383 |
def from_xml(self, doc):
"""Load this domain based on an XML document"""
import xml.sax
handler = DomainDumpParser(self)
xml.sax.parse(doc, handler)
return handler | [
"def",
"from_xml",
"(",
"self",
",",
"doc",
")",
":",
"import",
"xml",
".",
"sax",
"handler",
"=",
"DomainDumpParser",
"(",
"self",
")",
"xml",
".",
"sax",
".",
"parse",
"(",
"doc",
",",
"handler",
")",
"return",
"handler"
] | 33 | 0.009852 |
def use_config_file(self):
"""Find and apply the config file"""
self.config_file = self.find_config_file()
if self.config_file:
self.apply_config_file(self.config_file) | [
"def",
"use_config_file",
"(",
"self",
")",
":",
"self",
".",
"config_file",
"=",
"self",
".",
"find_config_file",
"(",
")",
"if",
"self",
".",
"config_file",
":",
"self",
".",
"apply_config_file",
"(",
"self",
".",
"config_file",
")"
] | 40 | 0.009804 |
async def wait_stream(aiterable):
"""Wait for an asynchronous iterable to finish and return the last item.
The iterable is executed within a safe stream context.
A StreamEmpty exception is raised if the sequence is empty.
"""
async with streamcontext(aiterable) as streamer:
async for item i... | [
"async",
"def",
"wait_stream",
"(",
"aiterable",
")",
":",
"async",
"with",
"streamcontext",
"(",
"aiterable",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",
"streamer",
":",
"item",
"try",
":",
"return",
"item",
"except",
"NameError",
":",
"rai... | 33.153846 | 0.002257 |
def spawn(self, url, force_spawn=False):
"""use the url for creation of domain and fetch cookies
- init cache dir by the url domain as ``<base>/domain``
- save the cookies to file ``<base>/domain/cookie.txt``
- init ``headers.get/post/json`` with response info
- init ``site_dir/... | [
"def",
"spawn",
"(",
"self",
",",
"url",
",",
"force_spawn",
"=",
"False",
")",
":",
"_url",
",",
"domain",
"=",
"self",
".",
"get_domain_home_from_url",
"(",
"url",
")",
"if",
"not",
"_url",
":",
"return",
"False",
"self",
".",
"cache",
"[",
"'site_di... | 33.469388 | 0.001185 |
def find_local_uuid(tw, keys, issue, legacy_matching=False):
""" For a given issue issue, find its local UUID.
Assembles a list of task IDs existing in taskwarrior
matching the supplied issue (`issue`) on the combination of any
set of supplied unique identifiers (`keys`) or, optionally,
the task's ... | [
"def",
"find_local_uuid",
"(",
"tw",
",",
"keys",
",",
"issue",
",",
"legacy_matching",
"=",
"False",
")",
":",
"if",
"not",
"issue",
"[",
"'description'",
"]",
":",
"raise",
"ValueError",
"(",
"'Issue %s has no description.'",
"%",
"issue",
")",
"possibilitie... | 35.22619 | 0.000329 |
def make_importfrom_alias(queue, body, context, name):
"""
Make an ast.alias node for the names list of an ast.ImportFrom.
Parameters
----------
queue : deque
Instruction Queue
body : list
Current body.
context : DecompilationContext
name : str
Expected name of t... | [
"def",
"make_importfrom_alias",
"(",
"queue",
",",
"body",
",",
"context",
",",
"name",
")",
":",
"import_from",
",",
"store",
"=",
"queue",
".",
"popleft",
"(",
")",
",",
"queue",
".",
"popleft",
"(",
")",
"expect",
"(",
"import_from",
",",
"instrs",
... | 25.742857 | 0.00107 |
def singular(plural):
"""
Take a plural English word and turn it into singular
Obviously, this doesn't work in general. It know just enough words to
generate XML tag names for list items. For example, if we have an element
called 'tracks' in the response, it will be serialized as a list without
... | [
"def",
"singular",
"(",
"plural",
")",
":",
"if",
"plural",
".",
"endswith",
"(",
"'ies'",
")",
":",
"return",
"plural",
"[",
":",
"-",
"3",
"]",
"+",
"'y'",
"if",
"plural",
".",
"endswith",
"(",
"'s'",
")",
":",
"return",
"plural",
"[",
":",
"-"... | 39.133333 | 0.001664 |
def preserve_cwd(func: Callable) -> Callable:
"""
Decorator to preserve the current working directory in calls to the
decorated function.
Example:
.. code-block:: python
@preserve_cwd
def myfunc():
os.chdir("/faraway")
os.chdir("/home")
myfunc()
... | [
"def",
"preserve_cwd",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"# http://stackoverflow.com/questions/169070/python-how-do-i-write-a-decorator-that-restores-the-cwd # noqa",
"def",
"decorator",
"(",
"*",
"args_",
",",
"*",
"*",
"kwargs",
")",
"->",
"Any"... | 25.958333 | 0.001548 |
def from_string(date_str):
"""
construction from the following string patterns
'%Y-%m-%d'
'%d.%m.%Y'
'%m/%d/%Y'
'%Y%m%d'
:param str date_str:
:return BusinessDate:
"""
if date_str.count('-'):
str_format = '%Y-%m-%d'
eli... | [
"def",
"from_string",
"(",
"date_str",
")",
":",
"if",
"date_str",
".",
"count",
"(",
"'-'",
")",
":",
"str_format",
"=",
"'%Y-%m-%d'",
"elif",
"date_str",
".",
"count",
"(",
"'.'",
")",
":",
"str_format",
"=",
"'%d.%m.%Y'",
"elif",
"date_str",
".",
"cou... | 30.677419 | 0.002039 |
def open(path, mode=None, ac_parser=None, **options):
"""
Open given configuration file with appropriate open flag.
:param path: Configuration file path
:param mode:
Can be 'r' and 'rb' for reading (default) or 'w', 'wb' for writing.
Please note that even if you specify 'r' or 'w', it w... | [
"def",
"open",
"(",
"path",
",",
"mode",
"=",
"None",
",",
"ac_parser",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"psr",
"=",
"find",
"(",
"path",
",",
"forced_type",
"=",
"ac_parser",
")",
"if",
"mode",
"is",
"not",
"None",
"and",
"mode",
... | 39.25 | 0.001036 |
def remove_total_size(apps, schema_editor):
"""Remove ``total_size`` field from all file/dir-type outputs."""
Data = apps.get_model('flow', 'Data')
for data in Data.objects.all():
for field_schema, fields in iterate_fields(data.output, data.process.output_schema):
name = field_schema['na... | [
"def",
"remove_total_size",
"(",
"apps",
",",
"schema_editor",
")",
":",
"Data",
"=",
"apps",
".",
"get_model",
"(",
"'flow'",
",",
"'Data'",
")",
"for",
"data",
"in",
"Data",
".",
"objects",
".",
"all",
"(",
")",
":",
"for",
"field_schema",
",",
"fiel... | 49.263158 | 0.002096 |
def data(self, rows=None):
"""Access a batch of episodes from the memory.
Padding elements after the length of each episode are unspecified and might
contain old data.
Args:
rows: Episodes to select, defaults to all.
Returns:
Tuple containing a tuple of transition quantities with batc... | [
"def",
"data",
"(",
"self",
",",
"rows",
"=",
"None",
")",
":",
"rows",
"=",
"tf",
".",
"range",
"(",
"self",
".",
"_capacity",
")",
"if",
"rows",
"is",
"None",
"else",
"rows",
"assert",
"rows",
".",
"shape",
".",
"ndims",
"==",
"1",
"episode",
"... | 34.277778 | 0.001577 |
def delete_item(self, payload, last_modified=None):
"""
Delete Items from a Zotero library
Accepts a single argument:
a dict containing item data
OR a list of dicts containing item data
"""
params = None
if isinstance(payload, list):
pa... | [
"def",
"delete_item",
"(",
"self",
",",
"payload",
",",
"last_modified",
"=",
"None",
")",
":",
"params",
"=",
"None",
"if",
"isinstance",
"(",
"payload",
",",
"list",
")",
":",
"params",
"=",
"{",
"\"itemKey\"",
":",
"\",\"",
".",
"join",
"(",
"[",
... | 37.514286 | 0.001485 |
def _parse_tree_dump(text_dump):
# type: (str) -> Optional[Dict[str, Any]]
""" Parse text tree dump (one item of a list returned by Booster.get_dump())
into json format that will be used by next XGBoost release.
"""
result = None
stack = [] # type: List[Dict]
for line in text_dump.split('\n... | [
"def",
"_parse_tree_dump",
"(",
"text_dump",
")",
":",
"# type: (str) -> Optional[Dict[str, Any]]",
"result",
"=",
"None",
"stack",
"=",
"[",
"]",
"# type: List[Dict]",
"for",
"line",
"in",
"text_dump",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"line",
":",
... | 36.818182 | 0.002407 |
def start(self):
"Start the project on the directory"
bookname = self.args.get('--bookname', None)
if not bookname:
bookname = 'book.md'
project_dir = self.args.get('<name>', None)
if not project_dir:
project_dir = join(self.cwd, 'Book')
project_di... | [
"def",
"start",
"(",
"self",
")",
":",
"bookname",
"=",
"self",
".",
"args",
".",
"get",
"(",
"'--bookname'",
",",
"None",
")",
"if",
"not",
"bookname",
":",
"bookname",
"=",
"'book.md'",
"project_dir",
"=",
"self",
".",
"args",
".",
"get",
"(",
"'<n... | 42.230769 | 0.000712 |
def following_siblings(elem):
'''
Yields elements and text which have the same parent as elem, but come afterward in document order
'''
it = itertools.dropwhile(lambda x: x != elem, elem.xml_parent.xml_children)
next(it) #Skip the element itself
return it | [
"def",
"following_siblings",
"(",
"elem",
")",
":",
"it",
"=",
"itertools",
".",
"dropwhile",
"(",
"lambda",
"x",
":",
"x",
"!=",
"elem",
",",
"elem",
".",
"xml_parent",
".",
"xml_children",
")",
"next",
"(",
"it",
")",
"#Skip the element itself",
"return"... | 39 | 0.014337 |
def delete_relationship(cls, id, related_collection_name, related_resource=None):
"""
Deprecated for version 1.1.0. Please use update_relationship
"""
try:
this_resource = cls.nodes.get(id=id, active=True)
if not related_resource:
r = this_resourc... | [
"def",
"delete_relationship",
"(",
"cls",
",",
"id",
",",
"related_collection_name",
",",
"related_resource",
"=",
"None",
")",
":",
"try",
":",
"this_resource",
"=",
"cls",
".",
"nodes",
".",
"get",
"(",
"id",
"=",
"id",
",",
"active",
"=",
"True",
")",... | 48.153846 | 0.009404 |
def _hz_to_semitones(self, hz):
"""
Convert hertz into a number of semitones above or below some reference
value, in this case, A440
"""
return np.log(hz / self._a440) / np.log(self._a) | [
"def",
"_hz_to_semitones",
"(",
"self",
",",
"hz",
")",
":",
"return",
"np",
".",
"log",
"(",
"hz",
"/",
"self",
".",
"_a440",
")",
"/",
"np",
".",
"log",
"(",
"self",
".",
"_a",
")"
] | 36.666667 | 0.008889 |
def verify_sig(signed_request, secret, issuer=None, algorithms=None,
expected_aud=None):
"""
Verify the JWT signature.
Given a raw JWT, this verifies it was signed with
*secret*, decodes it, and returns the JSON dict.
"""
if not issuer:
issuer = _get_issuer(signed_request... | [
"def",
"verify_sig",
"(",
"signed_request",
",",
"secret",
",",
"issuer",
"=",
"None",
",",
"algorithms",
"=",
"None",
",",
"expected_aud",
"=",
"None",
")",
":",
"if",
"not",
"issuer",
":",
"issuer",
"=",
"_get_issuer",
"(",
"signed_request",
"=",
"signed... | 35.5 | 0.001143 |
def piGenGosper():
"""A generator function that yields the digits of Pi
"""
z = ((1,0,0,1),1)
while True:
lft = __lfts(z[1])
n = int(__next(z))
if __safe(z,n):
z = __prod(z,n)
yield n
else:
z = __cons(z,lft) | [
"def",
"piGenGosper",
"(",
")",
":",
"z",
"=",
"(",
"(",
"1",
",",
"0",
",",
"0",
",",
"1",
")",
",",
"1",
")",
"while",
"True",
":",
"lft",
"=",
"__lfts",
"(",
"z",
"[",
"1",
"]",
")",
"n",
"=",
"int",
"(",
"__next",
"(",
"z",
")",
")"... | 23.333333 | 0.027491 |
def add_collection(collection,
cache_size=1000,
cache_cls=LRUCache,
**cache_args):
"""Add a collection named ``collection``."""
assert collection not in _db
cache = cache_cls(maxsize=cache_size,
missing=lambda id: load_object(col... | [
"def",
"add_collection",
"(",
"collection",
",",
"cache_size",
"=",
"1000",
",",
"cache_cls",
"=",
"LRUCache",
",",
"*",
"*",
"cache_args",
")",
":",
"assert",
"collection",
"not",
"in",
"_db",
"cache",
"=",
"cache_cls",
"(",
"maxsize",
"=",
"cache_size",
... | 41.4 | 0.002364 |
def unlink(client, name, include, exclude, yes):
"""Remove matching files from a dataset."""
dataset = client.load_dataset(name=name)
records = _filter(
client, names=[dataset.name], include=include, exclude=exclude
)
if not yes and records:
prompt_text = (
'You are abou... | [
"def",
"unlink",
"(",
"client",
",",
"name",
",",
"include",
",",
"exclude",
",",
"yes",
")",
":",
"dataset",
"=",
"client",
".",
"load_dataset",
"(",
"name",
"=",
"name",
")",
"records",
"=",
"_filter",
"(",
"client",
",",
"names",
"=",
"[",
"datase... | 32.954545 | 0.00134 |
def abbrev(self,dev_suffix=""):
"""
Abbreviated string representation, optionally declaring whether it is
a development version.
"""
return '.'.join(str(el) for el in self.release) + \
(dev_suffix if self.commit_count > 0 or self.dirty else "") | [
"def",
"abbrev",
"(",
"self",
",",
"dev_suffix",
"=",
"\"\"",
")",
":",
"return",
"'.'",
".",
"join",
"(",
"str",
"(",
"el",
")",
"for",
"el",
"in",
"self",
".",
"release",
")",
"+",
"(",
"dev_suffix",
"if",
"self",
".",
"commit_count",
">",
"0",
... | 41.428571 | 0.010135 |
def username_password_authn(environ, start_response, reference, key,
redirect_uri):
"""
Display the login form
"""
logger.info("The login page")
headers = []
resp = Response(mako_template="login.mako", template_lookup=LOOKUP,
headers=headers)
... | [
"def",
"username_password_authn",
"(",
"environ",
",",
"start_response",
",",
"reference",
",",
"key",
",",
"redirect_uri",
")",
":",
"logger",
".",
"info",
"(",
"\"The login page\"",
")",
"headers",
"=",
"[",
"]",
"resp",
"=",
"Response",
"(",
"mako_template"... | 27.857143 | 0.001653 |
def _shellcomplete(cli, prog_name, complete_var=None):
"""Internal handler for the bash completion support.
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
complete_var : str
The environ... | [
"def",
"_shellcomplete",
"(",
"cli",
",",
"prog_name",
",",
"complete_var",
"=",
"None",
")",
":",
"if",
"complete_var",
"is",
"None",
":",
"complete_var",
"=",
"'_%s_COMPLETE'",
"%",
"(",
"prog_name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
".... | 46.943396 | 0.002362 |
def grounded_monomer_patterns(model, agent, ignore_activities=False):
"""Get monomer patterns for the agent accounting for grounding information.
Parameters
----------
model : pysb.core.Model
The model to search for MonomerPatterns matching the given Agent.
agent : indra.statements.Agent
... | [
"def",
"grounded_monomer_patterns",
"(",
"model",
",",
"agent",
",",
"ignore_activities",
"=",
"False",
")",
":",
"# If it's not a molecular agent",
"if",
"not",
"isinstance",
"(",
"agent",
",",
"ist",
".",
"Agent",
")",
":",
"monomer",
"=",
"model",
".",
"mon... | 44.946154 | 0.00067 |
def set_device_name(self, new_name):
"""Sets a new BLE device name for this SK8.
Args:
new_name (str): the new device name as an ASCII string, max 20 characters.
Returns:
True if the name was updated successfully, False otherwise.
"""
device_name = self... | [
"def",
"set_device_name",
"(",
"self",
",",
"new_name",
")",
":",
"device_name",
"=",
"self",
".",
"get_characteristic_handle_from_uuid",
"(",
"UUID_DEVICE_NAME",
")",
"if",
"device_name",
"is",
"None",
":",
"logger",
".",
"warn",
"(",
"'Failed to find handle for de... | 35.375 | 0.008028 |
def compare(left: Union[str, pathlib.Path, _Entity],
right: Union[str, pathlib.Path, _Entity]) -> Comparison:
"""
Compare two paths.
:param left: The left side or "before" entity.
:param right: The right side or "after" entity.
:return: A comparison details what has changed from the lef... | [
"def",
"compare",
"(",
"left",
":",
"Union",
"[",
"str",
",",
"pathlib",
".",
"Path",
",",
"_Entity",
"]",
",",
"right",
":",
"Union",
"[",
"str",
",",
"pathlib",
".",
"Path",
",",
"_Entity",
"]",
")",
"->",
"Comparison",
":",
"def",
"normalise",
"... | 35.461538 | 0.001056 |
def call_filter(self, name, value, args=None, kwargs=None,
context=None, eval_ctx=None):
"""Invokes a filter on a value the same way the compiler does it.
Note that on Python 3 this might return a coroutine in case the
filter is running from an environment in async mode and ... | [
"def",
"call_filter",
"(",
"self",
",",
"name",
",",
"value",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"context",
"=",
"None",
",",
"eval_ctx",
"=",
"None",
")",
":",
"func",
"=",
"self",
".",
"filters",
".",
"get",
"(",
"name",
... | 42.933333 | 0.002278 |
def unregister(self, matchers, runnable):
'''
Unregister an iterator(runnable) and stop waiting for events
:param matchers: sequence of EventMatchers
:param runnable: an iterator that accept send method
'''
for m in matchers:
self.matchtree.r... | [
"def",
"unregister",
"(",
"self",
",",
"matchers",
",",
"runnable",
")",
":",
"for",
"m",
"in",
"matchers",
":",
"self",
".",
"matchtree",
".",
"remove",
"(",
"m",
",",
"runnable",
")",
"if",
"m",
".",
"indices",
"[",
"0",
"]",
"==",
"PollEvent",
"... | 45.538462 | 0.009934 |
def get_band_qpoints_by_seekpath(primitive, npoints, is_const_interval=False):
"""q-points along BZ high symmetry paths are generated using seekpath.
Parameters
----------
primitive : PhonopyAtoms
Primitive cell.
npoints : int
Number of q-points sampled along a path including end po... | [
"def",
"get_band_qpoints_by_seekpath",
"(",
"primitive",
",",
"npoints",
",",
"is_const_interval",
"=",
"False",
")",
":",
"try",
":",
"import",
"seekpath",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"You need to install seekpath.\"",
")",
"band_path... | 36.490196 | 0.000523 |
def get_peer_id(peer, add_mark=True):
"""
Finds the ID of the given peer, and converts it to the "bot api" format
so it the peer can be identified back. User ID is left unmodified,
chat ID is negated, and channel ID is prefixed with -100.
The original ID and the peer type class can be returned with... | [
"def",
"get_peer_id",
"(",
"peer",
",",
"add_mark",
"=",
"True",
")",
":",
"# First we assert it's a Peer TLObject, or early return for integers",
"if",
"isinstance",
"(",
"peer",
",",
"int",
")",
":",
"return",
"peer",
"if",
"add_mark",
"else",
"resolve_id",
"(",
... | 39.761905 | 0.001169 |
def _GenNetflowRecordV9(cls, lengths_list):
"""Internal function used to generate the Records from
their template.
"""
_fields_desc = []
for j, k in lengths_list:
_f_data = NetflowV9TemplateFieldDecoders.get(k, None)
_f_type, _f_args = (
_f_data if isinstance(_f_data, tup... | [
"def",
"_GenNetflowRecordV9",
"(",
"cls",
",",
"lengths_list",
")",
":",
"_fields_desc",
"=",
"[",
"]",
"for",
"j",
",",
"k",
"in",
"lengths_list",
":",
"_f_data",
"=",
"NetflowV9TemplateFieldDecoders",
".",
"get",
"(",
"k",
",",
"None",
")",
"_f_type",
",... | 33.771429 | 0.000822 |
def from_long(self, number):
"""Make PCI address from long.
in number of type int
"""
if not isinstance(number, baseinteger):
raise TypeError("number can only be an instance of type baseinteger")
self._call("fromLong",
in_p=[number]) | [
"def",
"from_long",
"(",
"self",
",",
"number",
")",
":",
"if",
"not",
"isinstance",
"(",
"number",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"number can only be an instance of type baseinteger\"",
")",
"self",
".",
"_call",
"(",
"\"fromLong\"",
... | 29.9 | 0.012987 |
def pool(builder, size, timeout=None):
"""Create a pool that imposes a limit on the number of stored
instances.
Args:
builder: a function to build an instance.
size: the size of the pool.
timeout(Optional[float]): the seconds to wait before raising
a ``queue.Empty`` exce... | [
"def",
"pool",
"(",
"builder",
",",
"size",
",",
"timeout",
"=",
"None",
")",
":",
"lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"local_pool",
"=",
"queue",
".",
"Queue",
"(",
")",
"current_size",
"=",
"0",
"@",
"contextlib",
".",
"contextmanager",
... | 30.705882 | 0.000619 |
def _render_context(self, template, block, **context):
"""
Render a block to a string with its context
"""
return u''.join(block(template.new_context(context))) | [
"def",
"_render_context",
"(",
"self",
",",
"template",
",",
"block",
",",
"*",
"*",
"context",
")",
":",
"return",
"u''",
".",
"join",
"(",
"block",
"(",
"template",
".",
"new_context",
"(",
"context",
")",
")",
")"
] | 37.6 | 0.010417 |
def reverse(self):
"reverse *IN PLACE*"
leftblock = self.left
rightblock = self.right
leftindex = self.leftndx
rightindex = self.rightndx
for i in range(self.length // 2):
# Validate that pointers haven't met in the middle
assert leftblock != right... | [
"def",
"reverse",
"(",
"self",
")",
":",
"leftblock",
"=",
"self",
".",
"left",
"rightblock",
"=",
"self",
".",
"right",
"leftindex",
"=",
"self",
".",
"leftndx",
"rightindex",
"=",
"self",
".",
"rightndx",
"for",
"i",
"in",
"range",
"(",
"self",
".",
... | 35.037037 | 0.002058 |
async def _start_plugins(self) -> None:
"""
Start the plugins by priority
Start the plugins based on the priority and wait for them to be fully
started before starting the next one. This ensure plugins can use
a previously started one during startup.
"""
logger.d... | [
"async",
"def",
"_start_plugins",
"(",
"self",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"'Starting plugins'",
")",
"for",
"priority",
"in",
"sorted",
"(",
"self",
".",
"_start_priority",
",",
"reverse",
"=",
"True",
")",
":",
"logger",
".",
"... | 37.03125 | 0.001645 |
def detwingle(cls, in_bytes, main_encoding="utf8",
embedded_encoding="windows-1252"):
"""Fix characters from one encoding embedded in some other encoding.
Currently the only situation supported is Windows-1252 (or its
subset ISO-8859-1), embedded in UTF-8.
The input m... | [
"def",
"detwingle",
"(",
"cls",
",",
"in_bytes",
",",
"main_encoding",
"=",
"\"utf8\"",
",",
"embedded_encoding",
"=",
"\"windows-1252\"",
")",
":",
"if",
"embedded_encoding",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
".",
"lower",
"(",
")",
"not",
"in"... | 39.819672 | 0.002009 |
def unitResponse(self,band):
"""This is used internally for :ref:`pysynphot-formula-effstim`
calculations."""
#sumfilt(wave,1,band)
# SUMFILT = Sum [ FILT(I) * WAVE(I) ** NPOW * DWAVE(I) ]
wave=band.wave
total = band.trapezoidIntegration(wave,band.throughput*wave)
... | [
"def",
"unitResponse",
"(",
"self",
",",
"band",
")",
":",
"#sumfilt(wave,1,band)",
"# SUMFILT = Sum [ FILT(I) * WAVE(I) ** NPOW * DWAVE(I) ]",
"wave",
"=",
"band",
".",
"wave",
"total",
"=",
"band",
".",
"trapezoidIntegration",
"(",
"wave",
",",
"band",
".",
"throu... | 42.222222 | 0.015464 |
def any_soco():
"""Return any visible soco device, for when it doesn't matter which.
Try to obtain an existing instance, or use `discover` if necessary.
Note that this assumes that the existing instance has not left
the network.
Returns:
SoCo: A `SoCo` instance (or subclass if `config.SOCO... | [
"def",
"any_soco",
"(",
")",
":",
"cls",
"=",
"config",
".",
"SOCO_CLASS",
"# pylint: disable=no-member, protected-access",
"try",
":",
"# Try to get the first pre-existing soco instance we know about,",
"# as long as it is visible (i.e. not a bridge etc). Otherwise,",
"# perform disco... | 36.461538 | 0.001028 |
def lookup(alias):
""" Tries to find a matcher callable associated to the given alias. If
an exact match does not exists it will try normalizing it and even
removing underscores to find one.
"""
if alias in matchers:
return matchers[alias]
else:
norm = normalize(alias)
... | [
"def",
"lookup",
"(",
"alias",
")",
":",
"if",
"alias",
"in",
"matchers",
":",
"return",
"matchers",
"[",
"alias",
"]",
"else",
":",
"norm",
"=",
"normalize",
"(",
"alias",
")",
"if",
"norm",
"in",
"normalized",
":",
"alias",
"=",
"normalized",
"[",
... | 27.9 | 0.001733 |
def order_fmap(ncoef):
"""Compute order corresponding to a given number of coefficients.
Parameters
----------
ncoef : int
Number of coefficients.
Returns
-------
order : int
Order corresponding to the provided number of coefficients.
"""
loop = True
order = 1... | [
"def",
"order_fmap",
"(",
"ncoef",
")",
":",
"loop",
"=",
"True",
"order",
"=",
"1",
"while",
"loop",
":",
"loop",
"=",
"not",
"(",
"ncoef",
"==",
"ncoef_fmap",
"(",
"order",
")",
")",
"if",
"loop",
":",
"order",
"+=",
"1",
"if",
"order",
">",
"N... | 23.923077 | 0.001546 |
def transform_annotation(self, ann, duration):
'''Transform an annotation to the beat-position encoding
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
Returns
-------... | [
"def",
"transform_annotation",
"(",
"self",
",",
"ann",
",",
"duration",
")",
":",
"# 1. get all the events",
"# 2. find all the downbeats",
"# 3. map each downbeat to a subdivision counter",
"# number of beats until the next downbeat",
"# 4. pad out events to intervals",
"# 5. e... | 39.56 | 0.000987 |
def to_jd(year, month, day):
'''Obtain Julian day for Indian Civil date'''
gyear = year + 78
leap = isleap(gyear)
# // Is this a leap year ?
# 22 - leap = 21 if leap, 22 non-leap
start = gregorian.to_jd(gyear, 3, 22 - leap)
if leap:
Caitra = 31
else:
Caitra = 30
if... | [
"def",
"to_jd",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"gyear",
"=",
"year",
"+",
"78",
"leap",
"=",
"isleap",
"(",
"gyear",
")",
"# // Is this a leap year ?",
"# 22 - leap = 21 if leap, 22 non-leap",
"start",
"=",
"gregorian",
".",
"to_jd",
"(",
"... | 19.678571 | 0.00173 |
def write_single_coil(self, starting_address, value):
"""
Write single Coil to Master device (Function code 5)
starting_address: Coil to be written
value: Coil Value to be written
"""
self.__transactionIdentifier+=1
if (self.__ser is not None):
if (se... | [
"def",
"write_single_coil",
"(",
"self",
",",
"starting_address",
",",
"value",
")",
":",
"self",
".",
"__transactionIdentifier",
"+=",
"1",
"if",
"(",
"self",
".",
"__ser",
"is",
"not",
"None",
")",
":",
"if",
"(",
"self",
".",
"__ser",
".",
"closed",
... | 48.625 | 0.009574 |
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub =... | [
"def",
"get_version",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"VERSION",
"assert",
"len",
"(",
"version",
")",
"==",
"5",
"assert",
"version",
"[",
"3",
"]",
"in",
"(",
"'alpha'",
",",
"'beta'",
",",... | 33.785714 | 0.001028 |
def add_transformer(self, transformer):
"""Adds a transformer to _transformers if not already existing
Args
----
transformer : StationDing0
Description #TODO
"""
if transformer not in self.transformers() and isinstance(transformer, TransformerDing0):
... | [
"def",
"add_transformer",
"(",
"self",
",",
"transformer",
")",
":",
"if",
"transformer",
"not",
"in",
"self",
".",
"transformers",
"(",
")",
"and",
"isinstance",
"(",
"transformer",
",",
"TransformerDing0",
")",
":",
"self",
".",
"_transformers",
".",
"appe... | 36.1 | 0.010811 |
def generate_report(
self,
components,
output_folder=None,
iface=None,
ordered_layers_uri=None,
legend_layers_uri=None,
use_template_extent=False):
"""Generate Impact Report independently by the Impact Function.
:param ... | [
"def",
"generate_report",
"(",
"self",
",",
"components",
",",
"output_folder",
"=",
"None",
",",
"iface",
"=",
"None",
",",
"ordered_layers_uri",
"=",
"None",
",",
"legend_layers_uri",
"=",
"None",
",",
"use_template_extent",
"=",
"False",
")",
":",
"# iface ... | 35.52381 | 0.000373 |
def make_k8s_lando_router(config, obj, queue_name):
"""
Makes MessageRouter which can listen to queue_name sending messages to the k8s version of lando.
:param config: WorkerConfig/ServerConfig: settings for connecting to the queue
:param obj: object: implements lando specific methods
... | [
"def",
"make_k8s_lando_router",
"(",
"config",
",",
"obj",
",",
"queue_name",
")",
":",
"return",
"MessageRouter",
"(",
"config",
",",
"obj",
",",
"queue_name",
",",
"K8S_LANDO_INCOMING_MESSAGES",
",",
"processor_constructor",
"=",
"WorkQueueProcessor",
")"
] | 57.3 | 0.008591 |
def acquire(self, timeout=None):
'''
acquire - Acquire given lock. Can be blocking or nonblocking by providing a timeout.
Returns "True" if you got the lock, otherwise "False"
@param timeout <None/float> - Max number of seconds to wait, or None to block until we can acquir... | [
"def",
"acquire",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"held",
"is",
"True",
":",
"# NOTE: Without some type of in-directory marker (like a uuid) we cannot",
"# refresh an expired lock accurately",
"if",
"os",
".",
"path",
".",
... | 36.981132 | 0.009443 |
def main(**kwargs):
"""
\b
Starts a countdown to or from TIME. Example values for TIME:
10, '1h 5m 30s', '12:00', '2020-01-01', '2020-01-01 14:00 UTC'.
\b
If TIME is not given, termdown will operate in stopwatch mode
and count forward.
\b
Hotkeys:
\tL\tLap (stopwatch mode only)
... | [
"def",
"main",
"(",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
"[",
"'time_format'",
"]",
"is",
"None",
":",
"kwargs",
"[",
"'time_format'",
"]",
"=",
"DEFAULT_TIME_FORMAT",
"[",
":",
"-",
"3",
"]",
"if",
"kwargs",
"[",
"'no_seconds'",
"]",
"else",
... | 32.148148 | 0.001118 |
def list(self, request, project):
"""
GET method implementation for list view
Optional parameters (default):
- offset (0)
- count (10)
- return_type (dict)
"""
MAX_JOBS_COUNT = 2000
# make a mutable copy of these params
filter_params = req... | [
"def",
"list",
"(",
"self",
",",
"request",
",",
"project",
")",
":",
"MAX_JOBS_COUNT",
"=",
"2000",
"# make a mutable copy of these params",
"filter_params",
"=",
"request",
".",
"query_params",
".",
"copy",
"(",
")",
"# various hacks to ensure API backwards compatibil... | 43.567164 | 0.00134 |
def copy(self):
""" Create a copy, and return it."""
new_cursor = self.__class__(self.x, self.y)
new_cursor.set_bounds(self.xmin, self.ymin, self.xmax, self.ymax, self.ymaxmax)
new_cursor.set_deltas(self.dx, self.dy)
return new_cursor | [
"def",
"copy",
"(",
"self",
")",
":",
"new_cursor",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
")",
"new_cursor",
".",
"set_bounds",
"(",
"self",
".",
"xmin",
",",
"self",
".",
"ymin",
",",
"self",
".",
"xmax",
"... | 45.666667 | 0.010753 |
def import_job(db, calc_id, calc_mode, description, user_name, status,
hc_id, datadir):
"""
Insert a calculation inside the database, if calc_id is not taken
"""
job = dict(id=calc_id,
calculation_mode=calc_mode,
description=description,
user_n... | [
"def",
"import_job",
"(",
"db",
",",
"calc_id",
",",
"calc_mode",
",",
"description",
",",
"user_name",
",",
"status",
",",
"hc_id",
",",
"datadir",
")",
":",
"job",
"=",
"dict",
"(",
"id",
"=",
"calc_id",
",",
"calculation_mode",
"=",
"calc_mode",
",",
... | 40.642857 | 0.001718 |
def save_minions(jid, minions, syndic_id=None):
'''
Save/update the serialized list of minions for a given job
'''
# Ensure we have a list for Python 3 compatability
minions = list(minions)
log.debug(
'Adding minions for job %s%s: %s',
jid,
' from syndic master \'{0}\''.... | [
"def",
"save_minions",
"(",
"jid",
",",
"minions",
",",
"syndic_id",
"=",
"None",
")",
":",
"# Ensure we have a list for Python 3 compatability",
"minions",
"=",
"list",
"(",
"minions",
")",
"log",
".",
"debug",
"(",
"'Adding minions for job %s%s: %s'",
",",
"jid",
... | 29.183673 | 0.000677 |
def pp(el,preString=''):
"""
Formats (prettyprint) a concatenated dictionary
"""
tab=' '*4
if isinstance(el,dict):
keys=list(el.keys())
keys.sort()
for key in keys:
val=el[key]
if isinstance(val,dict) or isinstance(val,list):
print('%s%s :' % (preString,key))
pp(val,preString+tab)
else:
... | [
"def",
"pp",
"(",
"el",
",",
"preString",
"=",
"''",
")",
":",
"tab",
"=",
"' '",
"*",
"4",
"if",
"isinstance",
"(",
"el",
",",
"dict",
")",
":",
"keys",
"=",
"list",
"(",
"el",
".",
"keys",
"(",
")",
")",
"keys",
".",
"sort",
"(",
")",
"fo... | 23.058824 | 0.073439 |
def plotBrightLimitInV(gBright, pdf=False, png=False):
"""
Plot the bright limit of Gaia in V as a function of (V-I).
Parameters
----------
gBright - The bright limit of Gaia in G
"""
vmini=np.linspace(0.0,6.0,1001)
gminv=gminvFromVmini(vmini)
vBright=gBright-gminv
fig=plt.figure(figsize=(10,6.5)... | [
"def",
"plotBrightLimitInV",
"(",
"gBright",
",",
"pdf",
"=",
"False",
",",
"png",
"=",
"False",
")",
":",
"vmini",
"=",
"np",
".",
"linspace",
"(",
"0.0",
",",
"6.0",
",",
"1001",
")",
"gminv",
"=",
"gminvFromVmini",
"(",
"vmini",
")",
"vBright",
"=... | 22.75 | 0.040663 |
def pid(sig):
'''
Return the PID or an empty string if the process is running or not.
Pass a signature to use to find the process via ps. Note you can pass
a Python-compatible regular expression to return all pids of
processes matching the regexp.
.. versionchanged:: 2016.11.4
Added su... | [
"def",
"pid",
"(",
"sig",
")",
":",
"cmd",
"=",
"__grains__",
"[",
"'ps'",
"]",
"output",
"=",
"__salt__",
"[",
"'cmd.run_stdout'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"True",
")",
"pids",
"=",
"''",
"for",
"line",
"in",
"output",
".",
"splitl... | 24.166667 | 0.001326 |
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or an... | [
"def",
"_set_account_policy",
"(",
"name",
",",
"policy",
")",
":",
"cmd",
"=",
"'pwpolicy -u {0} -setpolicy \"{1}\"'",
".",
"format",
"(",
"name",
",",
"policy",
")",
"try",
":",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
... | 36.85 | 0.001323 |
def newDevice(deviceJson, lupusec):
"""Create new device object for the given type."""
type_tag = deviceJson.get('type')
if not type_tag:
_LOGGER.info('Device has no type')
if type_tag in CONST.TYPE_OPENING:
return LupusecBinarySensor(deviceJson, lupusec)
elif type_tag in CONST.TYP... | [
"def",
"newDevice",
"(",
"deviceJson",
",",
"lupusec",
")",
":",
"type_tag",
"=",
"deviceJson",
".",
"get",
"(",
"'type'",
")",
"if",
"not",
"type_tag",
":",
"_LOGGER",
".",
"info",
"(",
"'Device has no type'",
")",
"if",
"type_tag",
"in",
"CONST",
".",
... | 33.125 | 0.001835 |
def autodoc_basemodel(module):
"""Add an exhaustive docstring to the given module of a basemodel.
Works onlye when all modules of the basemodel are named in the
standard way, e.g. `lland_model`, `lland_control`, `lland_inputs`.
"""
autodoc_tuple2doc(module)
namespace = module.__dict__
doc =... | [
"def",
"autodoc_basemodel",
"(",
"module",
")",
":",
"autodoc_tuple2doc",
"(",
"module",
")",
"namespace",
"=",
"module",
".",
"__dict__",
"doc",
"=",
"namespace",
".",
"get",
"(",
"'__doc__'",
")",
"if",
"doc",
"is",
"None",
":",
"doc",
"=",
"''",
"base... | 41.933333 | 0.000518 |
def normal_cdf(x, mu=0, sigma=1):
"""Cumulative Normal Distribution Function.
:param x: scalar or array of real numbers.
:type x: numpy.ndarray, float
:param mu: Mean value. Default 0.
:type mu: float, numpy.ndarray
:param sigma: Standard deviation. Default 1.
:type sigma: float
:ret... | [
"def",
"normal_cdf",
"(",
"x",
",",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
")",
":",
"arg",
"=",
"(",
"x",
"-",
"mu",
")",
"/",
"(",
"sigma",
"*",
"numpy",
".",
"sqrt",
"(",
"2",
")",
")",
"res",
"=",
"(",
"1",
"+",
"erf",
"(",
"arg",
... | 27.791667 | 0.008696 |
def deliver(self, sender, receiver, packet):
"deliver on edge of timeout_window"
to = ConsensusManager.round_timeout
assert to > 0
print "in slow transport deliver"
super(SlowTransport, self).deliver(sender, receiver, packet, add_delay=to) | [
"def",
"deliver",
"(",
"self",
",",
"sender",
",",
"receiver",
",",
"packet",
")",
":",
"to",
"=",
"ConsensusManager",
".",
"round_timeout",
"assert",
"to",
">",
"0",
"print",
"\"in slow transport deliver\"",
"super",
"(",
"SlowTransport",
",",
"self",
")",
... | 45.666667 | 0.010753 |
def split_in_blocks(sequence, hint, weight=lambda item: 1, key=nokey):
"""
Split the `sequence` in a number of WeightedSequences close to `hint`.
:param sequence: a finite sequence of items
:param hint: an integer suggesting the number of subsequences to generate
:param weight: a function returning... | [
"def",
"split_in_blocks",
"(",
"sequence",
",",
"hint",
",",
"weight",
"=",
"lambda",
"item",
":",
"1",
",",
"key",
"=",
"nokey",
")",
":",
"if",
"isinstance",
"(",
"sequence",
",",
"int",
")",
":",
"return",
"split_in_slices",
"(",
"sequence",
",",
"h... | 41.870968 | 0.001506 |
def cost(self, t_node, branch_length, multiplicity=2.0):
'''
returns the cost associated with a branch starting at t_node
t_node is time before present, the branch goes back in time
Args:
- t_node: time of the node
- branch_length: branch length, det... | [
"def",
"cost",
"(",
"self",
",",
"t_node",
",",
"branch_length",
",",
"multiplicity",
"=",
"2.0",
")",
":",
"merger_time",
"=",
"t_node",
"+",
"branch_length",
"return",
"self",
".",
"integral_merger_rate",
"(",
"merger_time",
")",
"-",
"self",
".",
"integra... | 52 | 0.010174 |
def get_source_kernel(gta, name, kernel=None):
"""Get the PDF for the given source."""
sm = []
zs = 0
for c in gta.components:
z = c.model_counts_map(name).data.astype('float')
if kernel is not None:
shape = (z.shape[0],) + kernel.shape
z = np.apply_over_axes(np.... | [
"def",
"get_source_kernel",
"(",
"gta",
",",
"name",
",",
"kernel",
"=",
"None",
")",
":",
"sm",
"=",
"[",
"]",
"zs",
"=",
"0",
"for",
"c",
"in",
"gta",
".",
"components",
":",
"z",
"=",
"c",
".",
"model_counts_map",
"(",
"name",
")",
".",
"data"... | 24.384615 | 0.001517 |
def redshift_from_comoving_volume(vc, **kwargs):
r"""Returns the redshift from the given comoving volume.
Parameters
----------
vc : float
The comoving volume, in units of cubed Mpc.
\**kwargs :
All other keyword args are passed to :py:func:`get_cosmology` to
select a cosmol... | [
"def",
"redshift_from_comoving_volume",
"(",
"vc",
",",
"*",
"*",
"kwargs",
")",
":",
"cosmology",
"=",
"get_cosmology",
"(",
"*",
"*",
"kwargs",
")",
"return",
"z_at_value",
"(",
"cosmology",
".",
"comoving_volume",
",",
"vc",
",",
"units",
".",
"Mpc",
"*... | 30.210526 | 0.001689 |
def get_all_monomials(variables, extramonomials, substitutions, degree,
removesubstitutions=True):
"""Return the monomials of a certain degree.
"""
monomials = get_monomials(variables, degree)
if extramonomials is not None:
monomials.extend(extramonomials)
if removesubs... | [
"def",
"get_all_monomials",
"(",
"variables",
",",
"extramonomials",
",",
"substitutions",
",",
"degree",
",",
"removesubstitutions",
"=",
"True",
")",
":",
"monomials",
"=",
"get_monomials",
"(",
"variables",
",",
"degree",
")",
"if",
"extramonomials",
"is",
"n... | 47.333333 | 0.001381 |
def diseases(context):
"""Show all diseases in the database"""
LOG.info("Running scout view diseases")
adapter = context.obj['adapter']
disease_objs = adapter.disease_terms()
nr_diseases = disease_objs.count()
if nr_diseases == 0:
click.echo("No diseases found")
else:
click... | [
"def",
"diseases",
"(",
"context",
")",
":",
"LOG",
".",
"info",
"(",
"\"Running scout view diseases\"",
")",
"adapter",
"=",
"context",
".",
"obj",
"[",
"'adapter'",
"]",
"disease_objs",
"=",
"adapter",
".",
"disease_terms",
"(",
")",
"nr_diseases",
"=",
"d... | 32.666667 | 0.001984 |
def edge_label(s, edge, alpha=1.0):
""" Visualization of the label accompanying an edge.
"""
if s.text and edge.label != "":
s._ctx.nostroke()
s._ctx.fill(
s.text.r,
s.text.g,
s.text.b,
s.text.a * alpha*0.75
)
s._ctx... | [
"def",
"edge_label",
"(",
"s",
",",
"edge",
",",
"alpha",
"=",
"1.0",
")",
":",
"if",
"s",
".",
"text",
"and",
"edge",
".",
"label",
"!=",
"\"\"",
":",
"s",
".",
"_ctx",
".",
"nostroke",
"(",
")",
"s",
".",
"_ctx",
".",
"fill",
"(",
"s",
".",... | 33.54 | 0.015643 |
def detectBlackBerryTouch(self):
"""Return detection of a Blackberry touchscreen device
Detects if the current browser is a BlackBerry Touch
device, such as the Storm, Torch, and Bold Touch. Excludes the Playbook.
"""
return UAgentInfo.deviceBBStorm in self.__userAgent \
... | [
"def",
"detectBlackBerryTouch",
"(",
"self",
")",
":",
"return",
"UAgentInfo",
".",
"deviceBBStorm",
"in",
"self",
".",
"__userAgent",
"or",
"UAgentInfo",
".",
"deviceBBTorch",
"in",
"self",
".",
"__userAgent",
"or",
"UAgentInfo",
".",
"deviceBBBoldTouch",
"in",
... | 50.8 | 0.011605 |
def get_connection_cls(cls):
"""Return connection class.
:rtype: :class:`type`
"""
if cls.__connection_cls is None:
cls.__connection_cls, _ = cls.from_settings()
return cls.__connection_cls | [
"def",
"get_connection_cls",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__connection_cls",
"is",
"None",
":",
"cls",
".",
"__connection_cls",
",",
"_",
"=",
"cls",
".",
"from_settings",
"(",
")",
"return",
"cls",
".",
"__connection_cls"
] | 29.375 | 0.008264 |
def get_stream_handler(stream=sys.stderr, level=logging.INFO,
log_format=log_formats.easy_read):
"""
Returns a set up stream handler to add to a logger.
:param stream: which stream to use, defaults to sys.stderr
:param level: logging level to set handler at
:param log_format:... | [
"def",
"get_stream_handler",
"(",
"stream",
"=",
"sys",
".",
"stderr",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"log_format",
"=",
"log_formats",
".",
"easy_read",
")",
":",
"sh",
"=",
"logging",
".",
"StreamHandler",
"(",
"stream",
")",
"sh",
"."... | 34.785714 | 0.002 |
def all_coarse_grains_for_blackbox(blackbox):
"""Generator over all |CoarseGrains| for the given blackbox.
If a box has multiple outputs, those outputs are partitioned into the same
coarse-grain macro-element.
"""
for partition in all_partitions(blackbox.output_indices):
for grouping in all... | [
"def",
"all_coarse_grains_for_blackbox",
"(",
"blackbox",
")",
":",
"for",
"partition",
"in",
"all_partitions",
"(",
"blackbox",
".",
"output_indices",
")",
":",
"for",
"grouping",
"in",
"all_groupings",
"(",
"partition",
")",
":",
"coarse_grain",
"=",
"CoarseGrai... | 40.571429 | 0.001721 |
def diff(old_html, new_html, cutoff=0.0, plaintext=False, pretty=False):
"""Show the differences between the old and new html document, as html.
Return the document html with extra tags added to show changes. Add <ins>
tags around newly added sections, and <del> tags to show sections that have
been del... | [
"def",
"diff",
"(",
"old_html",
",",
"new_html",
",",
"cutoff",
"=",
"0.0",
",",
"plaintext",
"=",
"False",
",",
"pretty",
"=",
"False",
")",
":",
"if",
"plaintext",
":",
"old_dom",
"=",
"parse_text",
"(",
"old_html",
")",
"new_dom",
"=",
"parse_text",
... | 35.096774 | 0.001789 |
def srem(self, key, member, *members):
"""Remove one or more members from a set."""
return self.execute(b'SREM', key, member, *members) | [
"def",
"srem",
"(",
"self",
",",
"key",
",",
"member",
",",
"*",
"members",
")",
":",
"return",
"self",
".",
"execute",
"(",
"b'SREM'",
",",
"key",
",",
"member",
",",
"*",
"members",
")"
] | 49.666667 | 0.013245 |
def summarize(self, rows):
"""Return summary rows for `rows`.
Parameters
----------
rows : list of dicts
Normalized rows to summarize.
Returns
-------
A list of summary rows. Each row is a tuple where the first item is
the data and the secon... | [
"def",
"summarize",
"(",
"self",
",",
"rows",
")",
":",
"columns",
"=",
"list",
"(",
"rows",
"[",
"0",
"]",
".",
"keys",
"(",
")",
")",
"agg_styles",
"=",
"{",
"c",
":",
"self",
".",
"style",
"[",
"c",
"]",
"[",
"\"aggregate\"",
"]",
"for",
"c"... | 38.5 | 0.001013 |
def RemoveFromQueue(self, addr):
"""
Remove an address from the connection queue
Args:
addr:
Returns:
"""
if addr in self.connection_queue:
self.connection_queue.remove(addr) | [
"def",
"RemoveFromQueue",
"(",
"self",
",",
"addr",
")",
":",
"if",
"addr",
"in",
"self",
".",
"connection_queue",
":",
"self",
".",
"connection_queue",
".",
"remove",
"(",
"addr",
")"
] | 21.636364 | 0.008065 |
def get_session(username, password, pin, cookie_path=COOKIE_PATH):
"""Get a new session."""
class MoparAuth(AuthBase): # pylint: disable=too-few-public-methods
"""Authentication wrapper."""
def __init__(self, username, password, pin, cookie_path):
"""Init."""
self.usern... | [
"def",
"get_session",
"(",
"username",
",",
"password",
",",
"pin",
",",
"cookie_path",
"=",
"COOKIE_PATH",
")",
":",
"class",
"MoparAuth",
"(",
"AuthBase",
")",
":",
"# pylint: disable=too-few-public-methods",
"\"\"\"Authentication wrapper.\"\"\"",
"def",
"__init__",
... | 34 | 0.001144 |
def parse_list_or_docstring(options, sps):
"""
Handle py3-cmd list and docstring options.
"""
import py3status.docstrings as docstrings
# HARDCODE: make include path to search for user modules
home_path = os.path.expanduser("~")
xdg_home_path = os.environ.get("XDG_CONFIG_HOME", "{}/.config"... | [
"def",
"parse_list_or_docstring",
"(",
"options",
",",
"sps",
")",
":",
"import",
"py3status",
".",
"docstrings",
"as",
"docstrings",
"# HARDCODE: make include path to search for user modules",
"home_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",... | 37.254902 | 0.001026 |
def history_view(self, request, object_id, extra_context=None):
"The 'history' admin view for this model."
from django.contrib.admin.models import LogEntry
# First check if the user can see this history.
model = self.model
obj = get_object_or_404(self.get_queryset(request),
... | [
"def",
"history_view",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"extra_context",
"=",
"None",
")",
":",
"from",
"django",
".",
"contrib",
".",
"admin",
".",
"models",
"import",
"LogEntry",
"# First check if the user can see this history.",
"model",
"=",... | 45.485714 | 0.00123 |
def _dev_api(cls):
"""Get a developer instance for GitHub API access."""
gh = github3.GitHub()
gh.set_client_id(cls.remote.consumer_key, cls.remote.consumer_secret)
return gh | [
"def",
"_dev_api",
"(",
"cls",
")",
":",
"gh",
"=",
"github3",
".",
"GitHub",
"(",
")",
"gh",
".",
"set_client_id",
"(",
"cls",
".",
"remote",
".",
"consumer_key",
",",
"cls",
".",
"remote",
".",
"consumer_secret",
")",
"return",
"gh"
] | 40.4 | 0.009709 |
def _from_docstring_md(doc):
"""
format from docstring to Markdown
"""
def format_fn(line, status):
""" format function """
def fix_tags(line):
# In markdown we need to escape < > and & for display
# but we don't want to do this is the value is quoted
... | [
"def",
"_from_docstring_md",
"(",
"doc",
")",
":",
"def",
"format_fn",
"(",
"line",
",",
"status",
")",
":",
"\"\"\" format function \"\"\"",
"def",
"fix_tags",
"(",
"line",
")",
":",
"# In markdown we need to escape < > and & for display",
"# but we don't want to do this... | 32.941176 | 0.000578 |
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
translation parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
An... | [
"def",
"transform",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"# convert to radians and unpack",
"translation_x",
",",
"translation_y",
"=",
"self",
".",
"translation",
"translation_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
... | 34.275 | 0.002128 |
def fcontext_policy_present(name, sel_type, filetype='a', sel_user=None, sel_level=None):
'''
.. versionadded:: 2017.7.0
Makes sure a SELinux policy for a given filespec (name), filetype
and SELinux context type is present.
name
filespec of the file or directory. Regex syntax is allowed.
... | [
"def",
"fcontext_policy_present",
"(",
"name",
",",
"sel_type",
",",
"filetype",
"=",
"'a'",
",",
"sel_user",
"=",
"None",
",",
"sel_level",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
... | 37.848101 | 0.002282 |
def askretrycancel(title=None, message=None, **options):
"""Original doc: Ask if operation should be retried; return true if the answer is yes"""
return psidialogs.ask_ok_cancel(title=title, message=message, ok='Retry') | [
"def",
"askretrycancel",
"(",
"title",
"=",
"None",
",",
"message",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"return",
"psidialogs",
".",
"ask_ok_cancel",
"(",
"title",
"=",
"title",
",",
"message",
"=",
"message",
",",
"ok",
"=",
"'Retry'",
")... | 75 | 0.008811 |
def _set_bulk_size(self, bulk_size):
"""
Set the bulk size
:param bulk_size the bulker size
"""
self._bulk_size = bulk_size
self.bulker.bulk_size = bulk_size | [
"def",
"_set_bulk_size",
"(",
"self",
",",
"bulk_size",
")",
":",
"self",
".",
"_bulk_size",
"=",
"bulk_size",
"self",
".",
"bulker",
".",
"bulk_size",
"=",
"bulk_size"
] | 24.875 | 0.009709 |
def parse_python_file(filepath):
"""
Retrieves the AST of the specified file.
This function performs simple caching so that the same file isn't read or
parsed more than once per process.
:param filepath: the file to parse
:type filepath: str
:returns: ast.AST
"""
with _AST_CACHE_L... | [
"def",
"parse_python_file",
"(",
"filepath",
")",
":",
"with",
"_AST_CACHE_LOCK",
":",
"if",
"filepath",
"not",
"in",
"_AST_CACHE",
":",
"source",
"=",
"read_file",
"(",
"filepath",
")",
"_AST_CACHE",
"[",
"filepath",
"]",
"=",
"ast",
".",
"parse",
"(",
"s... | 28.941176 | 0.001969 |
def histogram_hour_counts(
df,
variable
):
"""
Create a day-long histogram of counts of the variable for each hour. It is
assumed that the DataFrame index is datetime and that the variable
`hour` exists.
"""
if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]:
l... | [
"def",
"histogram_hour_counts",
"(",
"df",
",",
"variable",
")",
":",
"if",
"not",
"df",
".",
"index",
".",
"dtype",
"in",
"[",
"\"datetime64[ns]\"",
",",
"\"<M8[ns]\"",
",",
"\">M8[ns]\"",
"]",
":",
"log",
".",
"error",
"(",
"\"index is not datetime\"",
")"... | 34.357143 | 0.022267 |
def readQuotes(self, start, end):
''' read quotes '''
rows = self.__hbase.scanTable(self.tableName(HBaseDAM.QUOTE), [HBaseDAM.QUOTE], start, end)
return [self.__rowResultToQuote(row) for row in rows] | [
"def",
"readQuotes",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"rows",
"=",
"self",
".",
"__hbase",
".",
"scanTable",
"(",
"self",
".",
"tableName",
"(",
"HBaseDAM",
".",
"QUOTE",
")",
",",
"[",
"HBaseDAM",
".",
"QUOTE",
"]",
",",
"start",
"... | 44.8 | 0.013158 |
def sign(self, issuer_cert, issuer_key, digest):
"""
Sign the CRL.
Signing a CRL enables clients to associate the CRL itself with an
issuer. Before a CRL is meaningful to other OpenSSL functions, it must
be signed by an issuer.
This method implicitly sets the issuer's n... | [
"def",
"sign",
"(",
"self",
",",
"issuer_cert",
",",
"issuer_key",
",",
"digest",
")",
":",
"digest_obj",
"=",
"_lib",
".",
"EVP_get_digestbyname",
"(",
"digest",
")",
"_openssl_assert",
"(",
"digest_obj",
"!=",
"_ffi",
".",
"NULL",
")",
"_lib",
".",
"X509... | 40.666667 | 0.002002 |
def get_http_body(req, content_type=URL_ENCODED):
"""
Get the message into the format that should be places in the body part
of a HTTP request.
:param req: The service request as a :py:class:`oidcmsg.message.Message`
instance
:param content_type: The format of the body part.
:return: T... | [
"def",
"get_http_body",
"(",
"req",
",",
"content_type",
"=",
"URL_ENCODED",
")",
":",
"if",
"URL_ENCODED",
"in",
"content_type",
":",
"return",
"req",
".",
"to_urlencoded",
"(",
")",
"elif",
"JSON_ENCODED",
"in",
"content_type",
":",
"return",
"req",
".",
"... | 34.894737 | 0.001468 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.