text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def v1(self):
"""Return voltage phasors at the "from buses" (bus1)"""
Vm = self.system.dae.y[self.v]
Va = self.system.dae.y[self.a]
return polar(Vm[self.a1], Va[self.a1]) | [
"def",
"v1",
"(",
"self",
")",
":",
"Vm",
"=",
"self",
".",
"system",
".",
"dae",
".",
"y",
"[",
"self",
".",
"v",
"]",
"Va",
"=",
"self",
".",
"system",
".",
"dae",
".",
"y",
"[",
"self",
".",
"a",
"]",
"return",
"polar",
"(",
"Vm",
"[",
... | 39.6 | 0.009901 |
def likelihood_table_to_probs(self, lktable):
"""
Calculates this formula (1), given the log of the numerator as input
p_k * f(x_i, a_k)
t_k(x_i) = -----------------------
---K
\ p_k * f(x_i, a_k)
... | [
"def",
"likelihood_table_to_probs",
"(",
"self",
",",
"lktable",
")",
":",
"m",
"=",
"lktable",
".",
"max",
"(",
"1",
")",
"# row max of lktable",
"shifted",
"=",
"lktable",
"-",
"m",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"# shift lktable of log-likeliho... | 47.52381 | 0.009823 |
def _check_daylong(tr):
"""
Check the data quality of the daylong file.
Check to see that the day isn't just zeros, with large steps, if it is
then the resampling will hate it.
:type tr: obspy.core.trace.Trace
:param tr: Trace to check if the data are daylong.
:return quality (simply good... | [
"def",
"_check_daylong",
"(",
"tr",
")",
":",
"if",
"len",
"(",
"np",
".",
"nonzero",
"(",
"tr",
".",
"data",
")",
"[",
"0",
"]",
")",
"<",
"0.5",
"*",
"len",
"(",
"tr",
".",
"data",
")",
":",
"qual",
"=",
"False",
"else",
":",
"qual",
"=",
... | 28.096774 | 0.00111 |
def __create_nlinks(self, data, inds=None, boundary_penalties_fcn=None):
"""
Compute nlinks grid from data shape information. For boundary penalties
are data (intensities) values are used.
ins: Default is None. Used for multiscale GC. This are indexes of
multiscale pixels. Next ... | [
"def",
"__create_nlinks",
"(",
"self",
",",
"data",
",",
"inds",
"=",
"None",
",",
"boundary_penalties_fcn",
"=",
"None",
")",
":",
"# use the gerneral graph algorithm",
"# first, we construct the grid graph",
"start",
"=",
"time",
".",
"time",
"(",
")",
"if",
"in... | 36.884058 | 0.000765 |
def recommended_overlap(name, nfft=None):
"""Returns the recommended fractional overlap for the given window
If ``nfft`` is given, the return is in samples
Parameters
----------
name : `str`
the name of the window you are using
nfft : `int`, optional
the length of the window
... | [
"def",
"recommended_overlap",
"(",
"name",
",",
"nfft",
"=",
"None",
")",
":",
"try",
":",
"name",
"=",
"canonical_name",
"(",
"name",
")",
"except",
"KeyError",
"as",
"exc",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"exc",
")",
")",
"try",
":",
"... | 25.526316 | 0.000993 |
def make_argparser():
"""Argument parsing. Keep this together with main()"""
if PY2:
def unicode_arg(val):
return val.decode(sys.getfilesystemencoding() or 'utf8')
else:
unicode_arg = str
# Generic options
p_main = ArgumentParser()
generic = p_main.add_argument_grou... | [
"def",
"make_argparser",
"(",
")",
":",
"if",
"PY2",
":",
"def",
"unicode_arg",
"(",
"val",
")",
":",
"return",
"val",
".",
"decode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
"or",
"'utf8'",
")",
"else",
":",
"unicode_arg",
"=",
"str",
"# Ge... | 49.6 | 0.001797 |
def add_element(self, name, ns_uri=None, attributes=None,
text=None, before_this_element=False):
"""
Add a new child element to this element, with an optional namespace
definition. If no namespace is provided the child will be assigned
to the default namespace.
:para... | [
"def",
"add_element",
"(",
"self",
",",
"name",
",",
"ns_uri",
"=",
"None",
",",
"attributes",
"=",
"None",
",",
"text",
"=",
"None",
",",
"before_this_element",
"=",
"False",
")",
":",
"# Determine local name, namespace and prefix info from tag name",
"prefix",
"... | 49.736111 | 0.001369 |
def from_array(self, array, grid='DH', copy=True):
"""
Initialize the class instance from an input array.
Usage
-----
x = SHGrid.from_array(array, [grid, copy])
Returns
-------
x : SHGrid class instance
Parameters
----------
arra... | [
"def",
"from_array",
"(",
"self",
",",
"array",
",",
"grid",
"=",
"'DH'",
",",
"copy",
"=",
"True",
")",
":",
"if",
"_np",
".",
"iscomplexobj",
"(",
"array",
")",
":",
"kind",
"=",
"'complex'",
"else",
":",
"kind",
"=",
"'real'",
"if",
"type",
"(",... | 34.159091 | 0.001294 |
def service(self):
"""Retrieve the `Service` object to which this execution is associated."""
if not self._service:
self._service = self._client.service(id=self.service_id)
return self._service | [
"def",
"service",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_service",
":",
"self",
".",
"_service",
"=",
"self",
".",
"_client",
".",
"service",
"(",
"id",
"=",
"self",
".",
"service_id",
")",
"return",
"self",
".",
"_service"
] | 45 | 0.0131 |
def get_files_changed(repository, review_id):
"""
Get a list of files changed compared to the given review.
Compares against current directory.
:param repository: Git repository. Used to get remote.
- By default uses first remote in list.
:param review_id: Gerrit review ID.
:return: List ... | [
"def",
"get_files_changed",
"(",
"repository",
",",
"review_id",
")",
":",
"repository",
".",
"git",
".",
"fetch",
"(",
"[",
"next",
"(",
"iter",
"(",
"repository",
".",
"remotes",
")",
")",
",",
"review_id",
"]",
")",
"files_changed",
"=",
"repository",
... | 45 | 0.00128 |
def handle(app):
# TODO: for this to work properly we need a generator registry
# generator, lifecycle etc.
# list of tuples (label, value)
# TODO customize & use own style
default_choices = [
{
'name': 'Install a generator',
'value': 'install'
},
{
... | [
"def",
"handle",
"(",
"app",
")",
":",
"# TODO: for this to work properly we need a generator registry",
"# generator, lifecycle etc.",
"# list of tuples (label, value)",
"# TODO customize & use own style",
"default_choices",
"=",
"[",
"{",
"'name'",
":",
"'Install a generator'",
... | 25.177778 | 0.001274 |
def validate(self, arg=None):
"""Check that inputted path is valid - set validator accordingly"""
if os.path.isdir(self.path):
self.validator.object = None
else:
self.validator.object = ICONS['error'] | [
"def",
"validate",
"(",
"self",
",",
"arg",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"path",
")",
":",
"self",
".",
"validator",
".",
"object",
"=",
"None",
"else",
":",
"self",
".",
"validator",
".",
"objec... | 40.5 | 0.008065 |
def get_token(authed_user: hug.directives.user):
"""
Get Job details
:param authed_user:
:return:
"""
user_model = Query()
user = db.search(user_model.username == authed_user)[0]
if user:
out = {
'user': user['username'],
'api_key': user['api_key']
... | [
"def",
"get_token",
"(",
"authed_user",
":",
"hug",
".",
"directives",
".",
"user",
")",
":",
"user_model",
"=",
"Query",
"(",
")",
"user",
"=",
"db",
".",
"search",
"(",
"user_model",
".",
"username",
"==",
"authed_user",
")",
"[",
"0",
"]",
"if",
"... | 21.761905 | 0.002096 |
def complete_hit(self, text, line, begidx, endidx):
''' Tab-complete hit command. '''
return [i for i in PsiturkNetworkShell.hit_commands if \
i.startswith(text)] | [
"def",
"complete_hit",
"(",
"self",
",",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
")",
":",
"return",
"[",
"i",
"for",
"i",
"in",
"PsiturkNetworkShell",
".",
"hit_commands",
"if",
"i",
".",
"startswith",
"(",
"text",
")",
"]"
] | 48.25 | 0.020408 |
def wait_instances_running(ec2, instances):
"""
Wait until no instance in the given iterable is 'pending'. Yield every instance that
entered the running state as soon as it does.
:param boto.ec2.connection.EC2Connection ec2: the EC2 connection to use for making requests
:param Iterator[Instance] in... | [
"def",
"wait_instances_running",
"(",
"ec2",
",",
"instances",
")",
":",
"running_ids",
"=",
"set",
"(",
")",
"other_ids",
"=",
"set",
"(",
")",
"while",
"True",
":",
"pending_ids",
"=",
"set",
"(",
")",
"for",
"i",
"in",
"instances",
":",
"if",
"i",
... | 37.823529 | 0.002274 |
def _open_sheet(self, dtypes_dict=None):
"""Opens sheets and returns it"""
table_name = self.db_sheet_table
header_row = self.db_header_row
nrows = self.nrows
if dtypes_dict is None:
dtypes_dict = self.dtypes_dict
rows_to_skip = self.skiprows
logging... | [
"def",
"_open_sheet",
"(",
"self",
",",
"dtypes_dict",
"=",
"None",
")",
":",
"table_name",
"=",
"self",
".",
"db_sheet_table",
"header_row",
"=",
"self",
".",
"db_header_row",
"nrows",
"=",
"self",
".",
"nrows",
"if",
"dtypes_dict",
"is",
"None",
":",
"dt... | 38.133333 | 0.001705 |
def _canonical_type(name): # pylint: disable=too-many-return-statements
""" Replace aliases to the corresponding type to compute the ids. """
if name == 'int':
return 'int256'
if name == 'uint':
return 'uint256'
if name == 'fixed':
return 'fixed128x128'
if name == 'ufixe... | [
"def",
"_canonical_type",
"(",
"name",
")",
":",
"# pylint: disable=too-many-return-statements",
"if",
"name",
"==",
"'int'",
":",
"return",
"'int256'",
"if",
"name",
"==",
"'uint'",
":",
"return",
"'uint256'",
"if",
"name",
"==",
"'fixed'",
":",
"return",
"'fix... | 22.714286 | 0.001508 |
def createFolder(self, name):
"""
Creates a folder in which items can be placed. Folders are only
visible to a user and solely used for organizing content within
that user's content space.
"""
url = "%s/createFolder" % self.root
params = {
"f" : "json"... | [
"def",
"createFolder",
"(",
"self",
",",
"name",
")",
":",
"url",
"=",
"\"%s/createFolder\"",
"%",
"self",
".",
"root",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"title\"",
":",
"name",
"}",
"self",
".",
"_folders",
"=",
"None",
"return",
"s... | 37.411765 | 0.01227 |
def check(self):
"""
Determine how long until the next scheduled time for a Task.
Returns the number of seconds until the next scheduled time or zero
if the task needs to be run immediately.
If it's an hourly task and it's never been run, run it now.
If it's a daily task ... | [
"def",
"check",
"(",
"self",
")",
":",
"boto",
".",
"log",
".",
"info",
"(",
"'checking Task[%s]-now=%s, last=%s'",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"now",
",",
"self",
".",
"last_executed",
")",
")",
"if",
"self",
".",
"hourly",
"and",... | 39.757576 | 0.008929 |
def _check_compound_minions(self,
expr,
delimiter,
greedy,
pillar_exact=False): # pylint: disable=unused-argument
'''
Return the minions found by looking via compound matcher
... | [
"def",
"_check_compound_minions",
"(",
"self",
",",
"expr",
",",
"delimiter",
",",
"greedy",
",",
"pillar_exact",
"=",
"False",
")",
":",
"# pylint: disable=unused-argument",
"if",
"not",
"isinstance",
"(",
"expr",
",",
"six",
".",
"string_types",
")",
"and",
... | 46.032258 | 0.001646 |
def pdist(objects, dmeasure, diagval = numpy.inf):
"""
Compute the pair-wise distances between arbitrary objects.
Notes
-----
``dmeasure`` is assumed to be *symmetry* i.e. between object *a* and object *b* the
function will be called only ones.
Parameters
----------
objects... | [
"def",
"pdist",
"(",
"objects",
",",
"dmeasure",
",",
"diagval",
"=",
"numpy",
".",
"inf",
")",
":",
"out",
"=",
"numpy",
".",
"zeros",
"(",
"[",
"len",
"(",
"objects",
")",
"]",
"*",
"2",
",",
"numpy",
".",
"float",
")",
"numpy",
".",
"fill_diag... | 32.535714 | 0.008529 |
def remove_user_from_group(self, username, groupname, raise_on_error=False):
"""Remove a user from a group
Attempts to remove a user from a group
Args
username: The username to remove from the group.
groupname: The group name to be removed from the user.
Returns:
... | [
"def",
"remove_user_from_group",
"(",
"self",
",",
"username",
",",
"groupname",
",",
"raise_on_error",
"=",
"False",
")",
":",
"response",
"=",
"self",
".",
"_delete",
"(",
"self",
".",
"rest_url",
"+",
"\"/group/user/direct\"",
",",
"params",
"=",
"{",
"\"... | 28.782609 | 0.011696 |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
comp_file = args.get('comp', None)
if comp_file is not None:
comp_dict = yaml.safe_load(open(comp_file))
coordsys = comp_dict.pop('coordsys')
for v in ... | [
"def",
"build_job_configs",
"(",
"self",
",",
"args",
")",
":",
"job_configs",
"=",
"{",
"}",
"comp_file",
"=",
"args",
".",
"get",
"(",
"'comp'",
",",
"None",
")",
"if",
"comp_file",
"is",
"not",
"None",
":",
"comp_dict",
"=",
"yaml",
".",
"safe_load"... | 39.565217 | 0.002145 |
def expand_effect_repertoire(self, new_purview=None):
"""See |Subsystem.expand_repertoire()|."""
return self.subsystem.expand_effect_repertoire(
self.effect.repertoire, new_purview) | [
"def",
"expand_effect_repertoire",
"(",
"self",
",",
"new_purview",
"=",
"None",
")",
":",
"return",
"self",
".",
"subsystem",
".",
"expand_effect_repertoire",
"(",
"self",
".",
"effect",
".",
"repertoire",
",",
"new_purview",
")"
] | 51.5 | 0.009569 |
def detect_function_style(self, test_record):
"""Returns the index for the function declaration style detected in the given string
or None if no function declarations are detected."""
index = 0
# IMPORTANT: apply regex sequentially and stop on the first match:
for regex in FUN... | [
"def",
"detect_function_style",
"(",
"self",
",",
"test_record",
")",
":",
"index",
"=",
"0",
"# IMPORTANT: apply regex sequentially and stop on the first match:",
"for",
"regex",
"in",
"FUNCTION_STYLE_REGEX",
":",
"if",
"re",
".",
"search",
"(",
"regex",
",",
"test_r... | 44.5 | 0.008811 |
def option_list_all(self):
"""Get a list of all options, including those in option groups."""
res = self.option_list[:]
for i in self.option_groups:
res.extend(i.option_list)
return res | [
"def",
"option_list_all",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"option_list",
"[",
":",
"]",
"for",
"i",
"in",
"self",
".",
"option_groups",
":",
"res",
".",
"extend",
"(",
"i",
".",
"option_list",
")",
"return",
"res"
] | 32 | 0.008696 |
def new_session_callback(fuzzer, edge, resp):
'''
:param fuzzer: the fuzzer object
:param edge: the edge in the graph we currently at.
edge.src is the get_session template
edge.dst is the send_data template
:param resp: the response from the target
'''
fuzzer.lo... | [
"def",
"new_session_callback",
"(",
"fuzzer",
",",
"edge",
",",
"resp",
")",
":",
"fuzzer",
".",
"logger",
".",
"info",
"(",
"'session is: %s'",
"%",
"hexlify",
"(",
"resp",
"[",
"1",
":",
"3",
"]",
")",
".",
"decode",
"(",
")",
")",
"fuzzer",
".",
... | 42.5 | 0.002304 |
def write_plain(self, text, attr=None):
u'''write text at current cursor position.'''
log(u'write("%s", %s)' %(text, attr))
if attr is None:
attr = self.attr
n = c_int(0)
self.SetConsoleTextAttribute(self.hout, attr)
self.WriteConsoleA(self.hout, text, ... | [
"def",
"write_plain",
"(",
"self",
",",
"text",
",",
"attr",
"=",
"None",
")",
":",
"log",
"(",
"u'write(\"%s\", %s)'",
"%",
"(",
"text",
",",
"attr",
")",
")",
"if",
"attr",
"is",
"None",
":",
"attr",
"=",
"self",
".",
"attr",
"n",
"=",
"c_int",
... | 40.444444 | 0.008065 |
def block_username(username):
""" given the username block it. """
if not username:
# no reason to continue when there is no username
return
if config.DISABLE_USERNAME_LOCKOUT:
# no need to block, we disabled it.
return
key = get_username_blocked_cache_key(username)
i... | [
"def",
"block_username",
"(",
"username",
")",
":",
"if",
"not",
"username",
":",
"# no reason to continue when there is no username",
"return",
"if",
"config",
".",
"DISABLE_USERNAME_LOCKOUT",
":",
"# no need to block, we disabled it.",
"return",
"key",
"=",
"get_username_... | 34.5 | 0.002016 |
def toDict(datastorage_obj, recursive=True):
""" convert a DataStorage object to a dictionary (useful for saving); it should work for other objects too
"""
# if not a DataStorage, convert to it first
if "items" not in dir(datastorage_obj): datastorage_obj = DataStorage(datastorage_obj)
return _toDi... | [
"def",
"toDict",
"(",
"datastorage_obj",
",",
"recursive",
"=",
"True",
")",
":",
"# if not a DataStorage, convert to it first",
"if",
"\"items\"",
"not",
"in",
"dir",
"(",
"datastorage_obj",
")",
":",
"datastorage_obj",
"=",
"DataStorage",
"(",
"datastorage_obj",
"... | 55.666667 | 0.014749 |
def store_object(self, container, obj_name, data, content_type=None,
etag=None, content_encoding=None, ttl=None, return_none=False,
chunk_size=None, headers=None, metadata=None, extra_info=None):
"""
Creates a new object in the specified container, and populates it with
t... | [
"def",
"store_object",
"(",
"self",
",",
"container",
",",
"obj_name",
",",
"data",
",",
"content_type",
"=",
"None",
",",
"etag",
"=",
"None",
",",
"content_encoding",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
"return_none",
"=",
"False",
",",
"chunk_s... | 56.176471 | 0.008239 |
def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
... | [
"def",
"set_member_roles",
"(",
"self",
",",
"guild_id",
":",
"int",
",",
"member_id",
":",
"int",
",",
"roles",
":",
"List",
"[",
"int",
"]",
")",
":",
"self",
".",
"_query",
"(",
"f'guilds/{guild_id}/members/{member_id}'",
",",
"'PATCH'",
",",
"{",
"'rol... | 49.888889 | 0.008743 |
def DataIsInteger(self):
"""Determines, based on the data type, if the data is an integer.
The data types considered strings are: REG_DWORD (REG_DWORD_LITTLE_ENDIAN),
REG_DWORD_BIG_ENDIAN and REG_QWORD.
Returns:
bool: True if the data is an integer, False otherwise.
"""
return self.data_... | [
"def",
"DataIsInteger",
"(",
"self",
")",
":",
"return",
"self",
".",
"data_type",
"in",
"(",
"definitions",
".",
"REG_DWORD",
",",
"definitions",
".",
"REG_DWORD_BIG_ENDIAN",
",",
"definitions",
".",
"REG_QWORD",
")"
] | 34.5 | 0.002353 |
def add_fields(store_name, field_names):
"""
A class-decorator that creates layout managers with a set of named
fields.
"""
def decorate(cls):
def _add(index, name):
def _set_dir(self, value): getattr(self, store_name)[index] = value
def _get_dir(self): return getattr... | [
"def",
"add_fields",
"(",
"store_name",
",",
"field_names",
")",
":",
"def",
"decorate",
"(",
"cls",
")",
":",
"def",
"_add",
"(",
"index",
",",
"name",
")",
":",
"def",
"_set_dir",
"(",
"self",
",",
"value",
")",
":",
"getattr",
"(",
"self",
",",
... | 30.882353 | 0.001848 |
async def packages(
self, package_state: Union[int, str] = '',
show_archived: bool = False) -> list:
"""Get the list of packages associated with the account."""
packages_resp = await self._request(
'post',
API_URL_BUYER,
json={
... | [
"async",
"def",
"packages",
"(",
"self",
",",
"package_state",
":",
"Union",
"[",
"int",
",",
"str",
"]",
"=",
"''",
",",
"show_archived",
":",
"bool",
"=",
"False",
")",
"->",
"list",
":",
"packages_resp",
"=",
"await",
"self",
".",
"_request",
"(",
... | 36.190476 | 0.001281 |
def to_dict_no_content(fields, row):
"""
Convert a SQLAlchemy row that does not contain a 'content' field to a dict.
If row is None, return None.
Raises AssertionError if there is a field named 'content' in ``fields``.
"""
assert(len(fields) == len(row))
field_names = list(map(_get_name, ... | [
"def",
"to_dict_no_content",
"(",
"fields",
",",
"row",
")",
":",
"assert",
"(",
"len",
"(",
"fields",
")",
"==",
"len",
"(",
"row",
")",
")",
"field_names",
"=",
"list",
"(",
"map",
"(",
"_get_name",
",",
"fields",
")",
")",
"assert",
"'content'",
"... | 30.285714 | 0.002288 |
def adjust_brightness(img, brightness_factor):
"""Adjust brightness of an Image.
Args:
img (PIL Image): PIL Image to be adjusted.
brightness_factor (float): How much to adjust the brightness. Can be
any non negative number. 0 gives a black image, 1 gives the
original im... | [
"def",
"adjust_brightness",
"(",
"img",
",",
"brightness_factor",
")",
":",
"if",
"not",
"_is_pil_image",
"(",
"img",
")",
":",
"raise",
"TypeError",
"(",
"'img should be PIL Image. Got {}'",
".",
"format",
"(",
"type",
"(",
"img",
")",
")",
")",
"enhancer",
... | 35.5 | 0.001524 |
def get_parser():
"""Return the parser object for this script."""
project_root = utils.get_project_root()
# Get latest (raw) dataset
dataset_folder = os.path.join(project_root, "raw-datasets")
latest_dataset = utils.get_latest_in_folder(dataset_folder, "raw.pickle")
from argparse import Argume... | [
"def",
"get_parser",
"(",
")",
":",
"project_root",
"=",
"utils",
".",
"get_project_root",
"(",
")",
"# Get latest (raw) dataset",
"dataset_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"project_root",
",",
"\"raw-datasets\"",
")",
"latest_dataset",
"=",
"u... | 45.608696 | 0.000934 |
def simxGetObjectIntParameter(clientID, objectHandle, parameterID, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
parameterValue = ct.c_int()
return c_GetObjectIntParameter(clientID, objectHandle, parameterID, ct.byref(parameterValue),... | [
"def",
"simxGetObjectIntParameter",
"(",
"clientID",
",",
"objectHandle",
",",
"parameterID",
",",
"operationMode",
")",
":",
"parameterValue",
"=",
"ct",
".",
"c_int",
"(",
")",
"return",
"c_GetObjectIntParameter",
"(",
"clientID",
",",
"objectHandle",
",",
"para... | 50.142857 | 0.014006 |
def get_median_lat_lon_of_stops(gtfs):
"""
Get median latitude AND longitude of stops
Parameters
----------
gtfs: GTFS
Returns
-------
median_lat : float
median_lon : float
"""
stops = gtfs.get_table("stops")
median_lat = numpy.percentile(stops['lat'].values, 50)
me... | [
"def",
"get_median_lat_lon_of_stops",
"(",
"gtfs",
")",
":",
"stops",
"=",
"gtfs",
".",
"get_table",
"(",
"\"stops\"",
")",
"median_lat",
"=",
"numpy",
".",
"percentile",
"(",
"stops",
"[",
"'lat'",
"]",
".",
"values",
",",
"50",
")",
"median_lon",
"=",
... | 22.941176 | 0.002463 |
def generate(module):
"""
Generates a new interface from the inputted module.
:param module | <module>
:return <Interface>
"""
inter = Interface(PROGRAM_NAME)
inter.register(module, True)
return inter | [
"def",
"generate",
"(",
"module",
")",
":",
"inter",
"=",
"Interface",
"(",
"PROGRAM_NAME",
")",
"inter",
".",
"register",
"(",
"module",
",",
"True",
")",
"return",
"inter"
] | 21.909091 | 0.011952 |
def patch_requests():
""" Customize the cacerts.pem file that requests uses.
Automatically updates the cert file if the contents are different.
"""
config.create_config_directory()
ca_certs_file = config.CERT_FILE
ca_certs_contents = requests.__loader__.get_data('requests/cacert.pem')
shoul... | [
"def",
"patch_requests",
"(",
")",
":",
"config",
".",
"create_config_directory",
"(",
")",
"ca_certs_file",
"=",
"config",
".",
"CERT_FILE",
"ca_certs_contents",
"=",
"requests",
".",
"__loader__",
".",
"get_data",
"(",
"'requests/cacert.pem'",
")",
"should_write_c... | 34.041667 | 0.00119 |
def split(self, X, y=None, groups=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like, of length n_samples
Training data, includes reaction's containers
y : array-like, of length n_samples
The target va... | [
"def",
"split",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"groups",
"=",
"None",
")",
":",
"X",
",",
"y",
",",
"groups",
"=",
"indexable",
"(",
"X",
",",
"y",
",",
"groups",
")",
"cgrs",
"=",
"[",
"~",
"r",
"for",
"r",
"in",
"X",
... | 38.692308 | 0.001939 |
def __SetBody(self, http_request, method_config, request, upload):
"""Fill in the body on http_request."""
if not method_config.request_field:
return
request_type = _LoadClass(
method_config.request_type_name, self.__client.MESSAGES_MODULE)
if method_config.reque... | [
"def",
"__SetBody",
"(",
"self",
",",
"http_request",
",",
"method_config",
",",
"request",
",",
"upload",
")",
":",
"if",
"not",
"method_config",
".",
"request_field",
":",
"return",
"request_type",
"=",
"_LoadClass",
"(",
"method_config",
".",
"request_type_na... | 43.038462 | 0.001748 |
def slow_highlight(img1, img2, opts):
"""Try to find similar areas between two images.
Produces two masks for img1 and img2.
The algorithm works by comparing every possible alignment of the images,
smoothing it a bit to reduce spurious matches in areas that are
perceptibly different (e.g. text), a... | [
"def",
"slow_highlight",
"(",
"img1",
",",
"img2",
",",
"opts",
")",
":",
"w1",
",",
"h1",
"=",
"img1",
".",
"size",
"w2",
",",
"h2",
"=",
"img2",
".",
"size",
"W",
",",
"H",
"=",
"max",
"(",
"w1",
",",
"w2",
")",
",",
"max",
"(",
"h1",
","... | 34.666667 | 0.00039 |
def to_csvf(self, fpath: str, fieldnames: Sequence[str], encoding: str='utf8',
with_header: bool=False, crlf: bool=False, tsv: bool=False) -> str:
"""From instance to yaml file
:param fpath: Csv file path
:param fieldnames: Order of columns by property name
:param encodi... | [
"def",
"to_csvf",
"(",
"self",
",",
"fpath",
":",
"str",
",",
"fieldnames",
":",
"Sequence",
"[",
"str",
"]",
",",
"encoding",
":",
"str",
"=",
"'utf8'",
",",
"with_header",
":",
"bool",
"=",
"False",
",",
"crlf",
":",
"bool",
"=",
"False",
",",
"t... | 54 | 0.019608 |
def delete_all_events(self, calendar_ids=()):
"""Deletes all events managed through Cronofy from the all of the user's calendars.
:param tuple calendar_ids: List of calendar ids to delete events for. (Optional. Default empty tuple)
"""
params = {'delete_all': True}
if calendar_i... | [
"def",
"delete_all_events",
"(",
"self",
",",
"calendar_ids",
"=",
"(",
")",
")",
":",
"params",
"=",
"{",
"'delete_all'",
":",
"True",
"}",
"if",
"calendar_ids",
":",
"params",
"=",
"{",
"'calendar_ids[]'",
":",
"calendar_ids",
"}",
"self",
".",
"request_... | 43.9 | 0.008929 |
def simulate(self, data, mime=None):
"""Simulate the arrival of feeddata into the feed. Useful if the remote Thing doesn't publish
very often.
`data` (mandatory) (as applicable) The data you want to use to simulate the arrival of remote feed data
`mime` (optional) (string) The mime ty... | [
"def",
"simulate",
"(",
"self",
",",
"data",
",",
"mime",
"=",
"None",
")",
":",
"self",
".",
"_client",
".",
"simulate_feeddata",
"(",
"self",
".",
"__pointid",
",",
"data",
",",
"mime",
")"
] | 47.8 | 0.008214 |
def imported_classifiers_package(p: ecore.EPackage):
"""Determines which classifiers have to be imported into given package."""
classes = {c for c in p.eClassifiers if isinstance(c, ecore.EClass)}
references = itertools.chain(*(c.eAllReferences() for c in classes))
references_types = (r... | [
"def",
"imported_classifiers_package",
"(",
"p",
":",
"ecore",
".",
"EPackage",
")",
":",
"classes",
"=",
"{",
"c",
"for",
"c",
"in",
"p",
".",
"eClassifiers",
"if",
"isinstance",
"(",
"c",
",",
"ecore",
".",
"EClass",
")",
"}",
"references",
"=",
"ite... | 45.923077 | 0.00821 |
def parse_by_sections(self, issues, pull_requests):
"""
This method sort issues by types (bugs, features, etc. or
just closed issues) by labels.
:param list(dict) issues: List of issues in this tag section.
:param list(dict) pull_requests: List of PR's in this tag section.
... | [
"def",
"parse_by_sections",
"(",
"self",
",",
"issues",
",",
"pull_requests",
")",
":",
"issues_a",
"=",
"[",
"]",
"sections_a",
"=",
"OrderedDict",
"(",
")",
"if",
"not",
"self",
".",
"options",
".",
"sections",
":",
"return",
"[",
"sections_a",
",",
"i... | 38.142857 | 0.002436 |
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
for key in JOYENT_L... | [
"def",
"avail_locations",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_locations function must be called with '",
"'-f or --function, or with the --list-locations option'",
")",
"ret",
"=",
"{",
... | 29.83871 | 0.001047 |
def create(quiet, name, base_uri, symlink_path):
"""Create a proto dataset."""
_validate_name(name)
admin_metadata = dtoolcore.generate_admin_metadata(name)
parsed_base_uri = dtoolcore.utils.generous_parse_uri(base_uri)
if parsed_base_uri.scheme == "symlink":
if symlink_path is None:
... | [
"def",
"create",
"(",
"quiet",
",",
"name",
",",
"base_uri",
",",
"symlink_path",
")",
":",
"_validate_name",
"(",
"name",
")",
"admin_metadata",
"=",
"dtoolcore",
".",
"generate_admin_metadata",
"(",
"name",
")",
"parsed_base_uri",
"=",
"dtoolcore",
".",
"uti... | 36.338028 | 0.000377 |
def parse_glyphs_filter(filter_str, is_pre=False):
"""Parses glyphs custom filter string into a dict object that
ufo2ft can consume.
Reference:
ufo2ft: https://github.com/googlei18n/ufo2ft
Glyphs 2.3 Handbook July 2016, p184
Args:
filter_str - a string of... | [
"def",
"parse_glyphs_filter",
"(",
"filter_str",
",",
"is_pre",
"=",
"False",
")",
":",
"elements",
"=",
"filter_str",
".",
"split",
"(",
"\";\"",
")",
"if",
"elements",
"[",
"0",
"]",
"==",
"\"\"",
":",
"logger",
".",
"error",
"(",
"\"Failed to parse glyp... | 32.192308 | 0.001159 |
def _gen_unzip(it, elem_len):
"""Helper for unzip which checks the lengths of each element in it.
Parameters
----------
it : iterable[tuple]
An iterable of tuples. ``unzip`` should map ensure that these are
already tuples.
elem_len : int or None
The expected element length. I... | [
"def",
"_gen_unzip",
"(",
"it",
",",
"elem_len",
")",
":",
"elem",
"=",
"next",
"(",
"it",
")",
"first_elem_len",
"=",
"len",
"(",
"elem",
")",
"if",
"elem_len",
"is",
"not",
"None",
"and",
"elem_len",
"!=",
"first_elem_len",
":",
"raise",
"ValueError",
... | 27.465116 | 0.000818 |
def _resolve(self, spec):
"""Attempt resolving cache URIs when a remote spec is provided. """
if not spec.remote:
return spec
try:
resolved_urls = self._resolver.resolve(spec.remote)
if resolved_urls:
# keep the bar separated list of URLs convention
return CacheSpec(local=... | [
"def",
"_resolve",
"(",
"self",
",",
"spec",
")",
":",
"if",
"not",
"spec",
".",
"remote",
":",
"return",
"spec",
"try",
":",
"resolved_urls",
"=",
"self",
".",
"_resolver",
".",
"resolve",
"(",
"spec",
".",
"remote",
")",
"if",
"resolved_urls",
":",
... | 38.105263 | 0.016173 |
def timestamp(args):
"""
%prog timestamp path > timestamp.info
Record the timestamps for all files in the current folder.
filename atime mtime
This file can be used later to recover previous timestamps through touch().
"""
p = OptionParser(timestamp.__doc__)
opts, args = p.parse_args(a... | [
"def",
"timestamp",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"timestamp",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"("... | 27.619048 | 0.001667 |
def delay(self, positions):
'''Delay one or more audio channels such that they start at the given
positions.
Parameters
----------
positions: list of floats
List of times (in seconds) to delay each audio channel.
If fewer positions are given than the numb... | [
"def",
"delay",
"(",
"self",
",",
"positions",
")",
":",
"if",
"not",
"isinstance",
"(",
"positions",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"positions must be a a list of numbers\"",
")",
"if",
"not",
"all",
"(",
"(",
"is_number",
"(",
"p",
... | 34.583333 | 0.002345 |
def fetch(cert, use_deltas=True, user_agent=None, timeout=10):
"""
Fetches the CRLs for a certificate
:param cert:
An asn1cyrpto.x509.Certificate object to get the CRL for
:param use_deltas:
A boolean indicating if delta CRLs should be fetched
:param user_agent:
The HTTP u... | [
"def",
"fetch",
"(",
"cert",
",",
"use_deltas",
"=",
"True",
",",
"user_agent",
"=",
"None",
",",
"timeout",
"=",
"10",
")",
":",
"if",
"not",
"isinstance",
"(",
"cert",
",",
"x509",
".",
"Certificate",
")",
":",
"raise",
"TypeError",
"(",
"'cert must ... | 31.295455 | 0.002113 |
def impersonate(self, name=None, lifetime=None, mechs=None,
usage='initiate'):
"""Impersonate a name using the current credentials
This method acquires credentials by impersonating another
name using the current credentials.
:requires-ext:`s4u`
Args:
... | [
"def",
"impersonate",
"(",
"self",
",",
"name",
"=",
"None",
",",
"lifetime",
"=",
"None",
",",
"mechs",
"=",
"None",
",",
"usage",
"=",
"'initiate'",
")",
":",
"if",
"rcred_s4u",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"Your GSSAPI imple... | 39.3125 | 0.002327 |
def stochastic_from_data(name, data, lower=-np.inf, upper=np.inf,
value=None, observed=False, trace=True, verbose=-1, debug=False):
"""
Return a Stochastic subclass made from arbitrary data.
The histogram for the data is fitted with Kernel Density Estimation.
:Parameters:
... | [
"def",
"stochastic_from_data",
"(",
"name",
",",
"data",
",",
"lower",
"=",
"-",
"np",
".",
"inf",
",",
"upper",
"=",
"np",
".",
"inf",
",",
"value",
"=",
"None",
",",
"observed",
"=",
"False",
",",
"trace",
"=",
"True",
",",
"verbose",
"=",
"-",
... | 31.448276 | 0.001063 |
def cublasZsymv(handle, uplo, n, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for complex symmetric matrix.
"""
status = _libcublas.cublasZsymv_v2(handle,
_CUBLAS_FILL_MODE[uplo], n,
ctypes.byref(cud... | [
"def",
"cublasZsymv",
"(",
"handle",
",",
"uplo",
",",
"n",
",",
"alpha",
",",
"A",
",",
"lda",
",",
"x",
",",
"incx",
",",
"beta",
",",
"y",
",",
"incy",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasZsymv_v2",
"(",
"handle",
",",
"_CUBLAS_FI... | 50.2 | 0.022164 |
def extract_from_stack(stack, template, length, pre_pick, pre_pad,
Z_include=False, pre_processed=True, samp_rate=None,
lowcut=None, highcut=None, filt_order=3):
"""
Extract a multiplexed template from a stack of detections.
Function to extract a new template f... | [
"def",
"extract_from_stack",
"(",
"stack",
",",
"template",
",",
"length",
",",
"pre_pick",
",",
"pre_pad",
",",
"Z_include",
"=",
"False",
",",
"pre_processed",
"=",
"True",
",",
"samp_rate",
"=",
"None",
",",
"lowcut",
"=",
"None",
",",
"highcut",
"=",
... | 46.129412 | 0.00025 |
def bipartition(seq):
"""Return a list of bipartitions for a sequence.
Args:
a (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
partitions.
Example:
>>> bipartition((1,2,3))
[((), (1, 2, 3)), ((1,),... | [
"def",
"bipartition",
"(",
"seq",
")",
":",
"return",
"[",
"(",
"tuple",
"(",
"seq",
"[",
"i",
"]",
"for",
"i",
"in",
"part0_idx",
")",
",",
"tuple",
"(",
"seq",
"[",
"j",
"]",
"for",
"j",
"in",
"part1_idx",
")",
")",
"for",
"part0_idx",
",",
"... | 30.470588 | 0.001873 |
def memory_data():
"""Returns memory data.
"""
vm = psutil.virtual_memory()
sw = psutil.swap_memory()
return {
'virtual': {
'total': mark(vm.total, 'bytes'),
'free': mark(vm.free, 'bytes'),
'percent': mark(vm.percent, 'percentage')
},
'swa... | [
"def",
"memory_data",
"(",
")",
":",
"vm",
"=",
"psutil",
".",
"virtual_memory",
"(",
")",
"sw",
"=",
"psutil",
".",
"swap_memory",
"(",
")",
"return",
"{",
"'virtual'",
":",
"{",
"'total'",
":",
"mark",
"(",
"vm",
".",
"total",
",",
"'bytes'",
")",
... | 26.055556 | 0.002058 |
def is_valid_key(key):
"""Return true if a string is a valid Vorbis comment key.
Valid Vorbis comment keys are printable ASCII between 0x20 (space)
and 0x7D ('}'), excluding '='.
Takes str/unicode in Python 2, unicode in Python 3
"""
if PY3 and isinstance(key, bytes):
raise TypeError(... | [
"def",
"is_valid_key",
"(",
"key",
")",
":",
"if",
"PY3",
"and",
"isinstance",
"(",
"key",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"needs to be str not bytes\"",
")",
"for",
"c",
"in",
"key",
":",
"if",
"c",
"<",
"\" \"",
"or",
"c",
">",
... | 26.705882 | 0.002128 |
def _prepare_retry(self, state, failure, original_list):
'''
Here we prepare to ask another brother to resolve our problem.
The failure here is always ProtocolFailed. If contract finished
without getting a bid (resolver is not there) we are removing the guy
from our local list. I... | [
"def",
"_prepare_retry",
"(",
"self",
",",
"state",
",",
"failure",
",",
"original_list",
")",
":",
"failed_recipient",
"=",
"failure",
".",
"value",
".",
"args",
"[",
"0",
"]",
"new_list",
"=",
"copy",
".",
"deepcopy",
"(",
"original_list",
")",
"if",
"... | 45.944444 | 0.00237 |
def _encode_dict(self, obj):
"""Returns a JSON representation of a Python dict"""
self._increment_nested_level()
buffer = []
for key in obj:
buffer.append(self._encode_key(key) + ':' + self._encode(obj[key]))
self._decrement_nested_level()
return '{'+ ','.... | [
"def",
"_encode_dict",
"(",
"self",
",",
"obj",
")",
":",
"self",
".",
"_increment_nested_level",
"(",
")",
"buffer",
"=",
"[",
"]",
"for",
"key",
"in",
"obj",
":",
"buffer",
".",
"append",
"(",
"self",
".",
"_encode_key",
"(",
"key",
")",
"+",
"':'"... | 27.25 | 0.008876 |
def to_dict(self):
"""
Create a JSON-serializable representation of the device Specs.
The dictionary representation is of the form::
{
'1Q': {
"0": {
"f1QRB": 0.99,
"T1": 20e-6,
... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'1Q'",
":",
"{",
"\"{}\"",
".",
"format",
"(",
"qs",
".",
"id",
")",
":",
"{",
"'f1QRB'",
":",
"qs",
".",
"f1QRB",
",",
"'fRO'",
":",
"qs",
".",
"fRO",
",",
"'T1'",
":",
"qs",
".",
"T1"... | 29.383333 | 0.001098 |
def from_file(cls, filename, source):
"""
Load a theme from the specified configuration file.
Parameters:
filename: The name of the filename to load.
source: A description of where the theme was loaded from.
"""
_logger.info('Loading theme %s', filename)
... | [
"def",
"from_file",
"(",
"cls",
",",
"filename",
",",
"source",
")",
":",
"_logger",
".",
"info",
"(",
"'Loading theme %s'",
",",
"filename",
")",
"try",
":",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"optionxform",
"=",
... | 37.333333 | 0.00145 |
def indent_line(zerolevel, bracket_list, line, in_comment, in_symbol_region,
options=None):
""" indent_line(zerolevel : int, bracket_list : list, line : str, in_comment : bool,
in_symbol_region : bool, options : string|list)
Most important function in the indentation process... | [
"def",
"indent_line",
"(",
"zerolevel",
",",
"bracket_list",
",",
"line",
",",
"in_comment",
",",
"in_symbol_region",
",",
"options",
"=",
"None",
")",
":",
"opts",
"=",
"parse_options",
"(",
"options",
")",
"comment_line",
"=",
"re",
".",
"search",
"(",
"... | 46.076923 | 0.00218 |
def rfc2426(self):
"""RFC2426-encode the field content.
:return: the field in the RFC 2426 format.
:returntype: `str`"""
if self.unit:
return rfc2425encode("org",u';'.join(quote_semicolon(val) for val in
(self.name,self.unit)))
e... | [
"def",
"rfc2426",
"(",
"self",
")",
":",
"if",
"self",
".",
"unit",
":",
"return",
"rfc2425encode",
"(",
"\"org\"",
",",
"u';'",
".",
"join",
"(",
"quote_semicolon",
"(",
"val",
")",
"for",
"val",
"in",
"(",
"self",
".",
"name",
",",
"self",
".",
"... | 39.1 | 0.0175 |
def calculate_error(self):
"""Estimate the numerical error based on the fluxes calculated
by the current and the last method.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> model.numvars.idx_method = 2
>>> results = numpy.asarray(fluxes.fastaccess._q_resu... | [
"def",
"calculate_error",
"(",
"self",
")",
":",
"self",
".",
"numvars",
".",
"error",
"=",
"0.",
"fluxes",
"=",
"self",
".",
"sequences",
".",
"fluxes",
"for",
"flux",
"in",
"fluxes",
".",
"numerics",
":",
"results",
"=",
"getattr",
"(",
"fluxes",
"."... | 40.818182 | 0.002176 |
def _get_status(self):
"""utility method to get the status of a slicing job resource, but also used to initialize slice
objects by location"""
if self._state in ["processed", "error"]:
return self._state
get_resp = requests.get(self.location, cookies={"session": ... | [
"def",
"_get_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"in",
"[",
"\"processed\"",
",",
"\"error\"",
"]",
":",
"return",
"self",
".",
"_state",
"get_resp",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"location",
",",
"cookies",
"=... | 38.666667 | 0.012632 |
def download_database(connection, container: str, target: str=""):
"""
Download database dump
"""
meta_data = objectstore.get_full_container_list(
connection, container, prefix='database')
options = return_file_objects(connection, container)
for o_info in meta_data:
expected_f... | [
"def",
"download_database",
"(",
"connection",
",",
"container",
":",
"str",
",",
"target",
":",
"str",
"=",
"\"\"",
")",
":",
"meta_data",
"=",
"objectstore",
".",
"get_full_container_list",
"(",
"connection",
",",
"container",
",",
"prefix",
"=",
"'database'... | 26.478261 | 0.002375 |
def Java(env, target, source, *args, **kw):
"""
A pseudo-Builder wrapper around the separate JavaClass{File,Dir}
Builders.
"""
if not SCons.Util.is_List(target):
target = [target]
if not SCons.Util.is_List(source):
source = [source]
# Pad the target list with repetitions of ... | [
"def",
"Java",
"(",
"env",
",",
"target",
",",
"source",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"target",
")",
":",
"target",
"=",
"[",
"target",
"]",
"if",
"not",
"SCons",
".",
... | 31.114286 | 0.00089 |
def is_published(self):
""" Return true if this resource has published date in the past """
now = datetime.now()
published = self.props.published
if published:
return published < now
return False | [
"def",
"is_published",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"published",
"=",
"self",
".",
"props",
".",
"published",
"if",
"published",
":",
"return",
"published",
"<",
"now",
"return",
"False"
] | 30.125 | 0.008065 |
def cached(func):
"""
Cache decorator for a function without keyword arguments
You can access the cache contents using the ``cache`` attribute in the
resulting function, which is a dictionary mapping the arguments tuple to
the previously returned function result.
"""
class Cache(dict):
def __missing_... | [
"def",
"cached",
"(",
"func",
")",
":",
"class",
"Cache",
"(",
"dict",
")",
":",
"def",
"__missing__",
"(",
"self",
",",
"key",
")",
":",
"result",
"=",
"self",
"[",
"key",
"]",
"=",
"func",
"(",
"*",
"key",
")",
"return",
"result",
"cache",
"=",... | 29.125 | 0.018711 |
def __cleanup_process(self, event):
"""
Auxiliary method for L{_notify_exit_process}.
"""
pid = event.get_pid()
process = event.get_process()
# Cleanup code breakpoints
for (bp_pid, bp_address) in compat.keys(self.__codeBP):
if bp_pid == pid:
... | [
"def",
"__cleanup_process",
"(",
"self",
",",
"event",
")",
":",
"pid",
"=",
"event",
".",
"get_pid",
"(",
")",
"process",
"=",
"event",
".",
"get_process",
"(",
")",
"# Cleanup code breakpoints",
"for",
"(",
"bp_pid",
",",
"bp_address",
")",
"in",
"compat... | 34.576923 | 0.011905 |
def _find_dot_net_versions(self, bits):
"""
Find Microsoft .NET Framework versions.
Parameters
----------
bits: int
Platform number of bits: 32 or 64.
"""
# Find actual .NET version in registry
reg_ver = self.ri.lookup(self.ri.vc, 'frameworkve... | [
"def",
"_find_dot_net_versions",
"(",
"self",
",",
"bits",
")",
":",
"# Find actual .NET version in registry",
"reg_ver",
"=",
"self",
".",
"ri",
".",
"lookup",
"(",
"self",
".",
"ri",
".",
"vc",
",",
"'frameworkver%d'",
"%",
"bits",
")",
"dot_net_dir",
"=",
... | 36.52 | 0.002134 |
def addable(Class, parent, set=None, raiseexceptions=True):
"""Tests whether a new element of this class can be added to the parent.
This method is mostly for internal use.
This will use the ``OCCURRENCES`` property, but may be overidden by subclasses for more customised behaviour.
Par... | [
"def",
"addable",
"(",
"Class",
",",
"parent",
",",
"set",
"=",
"None",
",",
"raiseexceptions",
"=",
"True",
")",
":",
"if",
"not",
"parent",
".",
"__class__",
".",
"accepts",
"(",
"Class",
",",
"raiseexceptions",
",",
"parent",
")",
":",
"return",
"Fa... | 44.96 | 0.009142 |
def allDecisions(self, result, **values):
"""
Joust like self.decision but for multiple finded values.
Returns:
Arrays of arrays of finded elements or if finds only one mach, array of strings.
"""
data = self.__getDecision(result, multiple=True, **values)
data = [data[value] for value in result]
if le... | [
"def",
"allDecisions",
"(",
"self",
",",
"result",
",",
"*",
"*",
"values",
")",
":",
"data",
"=",
"self",
".",
"__getDecision",
"(",
"result",
",",
"multiple",
"=",
"True",
",",
"*",
"*",
"values",
")",
"data",
"=",
"[",
"data",
"[",
"value",
"]",... | 27.846154 | 0.037433 |
def main():
"""
Run the appropriate main function according to the output of the parser.
"""
parser = make_parser()
args = parser.parse_args()
if not hasattr(args, 'action'):
parser.print_help()
exit(1)
if args.action == 'sheet':
from bernard.misc.sheet_sync import... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"make_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"not",
"hasattr",
"(",
"args",
",",
"'action'",
")",
":",
"parser",
".",
"print_help",
"(",
")",
"exit",
"(",
"1",
")",
... | 27.095238 | 0.001698 |
def _check_grain_minions(self, expr, delimiter, greedy):
'''
Return the minions found by looking via grains
'''
return self._check_cache_minions(expr, delimiter, greedy, 'grains') | [
"def",
"_check_grain_minions",
"(",
"self",
",",
"expr",
",",
"delimiter",
",",
"greedy",
")",
":",
"return",
"self",
".",
"_check_cache_minions",
"(",
"expr",
",",
"delimiter",
",",
"greedy",
",",
"'grains'",
")"
] | 41.4 | 0.009479 |
def resolve_path(file_path, calling_function):
"""
Conditionally set a path to a CSV file.
Option 1 - Join working directory and calling function name (file_name)
Option 2 - Join working directory and provided file_path string
Option 3 - Return provided file_path
:param file_path: None, filena... | [
"def",
"resolve_path",
"(",
"file_path",
",",
"calling_function",
")",
":",
"# No file_path is provided",
"if",
"not",
"file_path",
":",
"resolved",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"calling_function",
")",
"# Str... | 32.5 | 0.002134 |
def _delete_advanced_config(config_spec, advanced_config, vm_extra_config):
'''
Removes configuration parameters for the vm
config_spec
vm.ConfigSpec object
advanced_config
List of advanced config keys to be deleted
vm_extra_config
Virtual machine vm_ref.config.extraConfig... | [
"def",
"_delete_advanced_config",
"(",
"config_spec",
",",
"advanced_config",
",",
"vm_extra_config",
")",
":",
"log",
".",
"trace",
"(",
"'Removing advanced configuration '",
"'parameters %s'",
",",
"advanced_config",
")",
"if",
"isinstance",
"(",
"advanced_config",
",... | 35.259259 | 0.001022 |
def from_config(config, **options):
"""Instantiate an `SyncedRotationEventStores` from config.
Parameters:
config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this even... | [
"def",
"from_config",
"(",
"config",
",",
"*",
"*",
"options",
")",
":",
"required_args",
"=",
"(",
"'storage-backends'",
",",
")",
"optional_args",
"=",
"{",
"'events_per_batch'",
":",
"25000",
"}",
"rconfig",
".",
"check_config_options",
"(",
"\"SyncedRotation... | 40.972973 | 0.001289 |
def read_units(self, fid):
"""Read units from an acclaim skeleton file stream."""
lin = self.read_line(fid)
while lin[0] != ':':
parts = lin.split()
if parts[0]=='mass':
self.mass = float(parts[1])
elif parts[0]=='length':
... | [
"def",
"read_units",
"(",
"self",
",",
"fid",
")",
":",
"lin",
"=",
"self",
".",
"read_line",
"(",
"fid",
")",
"while",
"lin",
"[",
"0",
"]",
"!=",
"':'",
":",
"parts",
"=",
"lin",
".",
"split",
"(",
")",
"if",
"parts",
"[",
"0",
"]",
"==",
"... | 37.076923 | 0.012146 |
def _convert_entity_to_json(source):
''' Converts an entity object to json to send.
The entity format is:
{
"Address":"Mountain View",
"Age":23,
"AmountDue":200.23,
"CustomerCode@odata.type":"Edm.Guid",
"CustomerCode":"c9da6455-213d-42c9-9a79-3e9149a57833",
"Custome... | [
"def",
"_convert_entity_to_json",
"(",
"source",
")",
":",
"properties",
"=",
"{",
"}",
"# set properties type for types we know if value has no type info.",
"# if value has type info, then set the type to value.type",
"for",
"name",
",",
"value",
"in",
"source",
".",
"items",
... | 33.489796 | 0.000592 |
def set_attribute(self, attribute, attribute_state):
"""Get an attribute from the session.
:param attribute:
:return: attribute value, status code
:rtype: object, constants.StatusCode
"""
# Check that the attribute exists.
try:
attr = attributes.Attr... | [
"def",
"set_attribute",
"(",
"self",
",",
"attribute",
",",
"attribute_state",
")",
":",
"# Check that the attribute exists.",
"try",
":",
"attr",
"=",
"attributes",
".",
"AttributesByID",
"[",
"attribute",
"]",
"except",
"KeyError",
":",
"return",
"constants",
".... | 34 | 0.002043 |
def p_edgesigs(self, p):
'edgesigs : edgesigs SENS_OR edgesig'
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_edgesigs",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"(",
"p",
"[",
"3",
"]",
",",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 33.5 | 0.014599 |
def _analytical_forbild_phantom(resolution, ear):
"""Analytical description of FORBILD phantom.
Parameters
----------
resolution : bool
If ``True``, insert a small resolution test pattern to the left.
ear : bool
If ``True``, insert an ear-like structure to the right.
"""
sha... | [
"def",
"_analytical_forbild_phantom",
"(",
"resolution",
",",
"ear",
")",
":",
"sha",
"=",
"0.2",
"*",
"np",
".",
"sqrt",
"(",
"3",
")",
"y016b",
"=",
"-",
"14.294530834372887",
"a16b",
"=",
"0.443194085308632",
"b16b",
"=",
"3.892760834372886",
"E",
"=",
... | 34.838384 | 0.000282 |
def convert_values(self):
"""Convert datetimes to a comparable value in an expression.
"""
def stringify(value):
if self.encoding is not None:
encoder = partial(pprint_thing_encoded,
encoding=self.encoding)
else:
... | [
"def",
"convert_values",
"(",
"self",
")",
":",
"def",
"stringify",
"(",
"value",
")",
":",
"if",
"self",
".",
"encoding",
"is",
"not",
"None",
":",
"encoder",
"=",
"partial",
"(",
"pprint_thing_encoded",
",",
"encoding",
"=",
"self",
".",
"encoding",
")... | 35.366667 | 0.001835 |
def new_transfer_from_transaction(self, asset: str, b58_send_address: str, b58_from_address: str,
b58_recv_address: str, amount: int, b58_payer_address: str, gas_limit: int,
gas_price: int) -> Transaction:
"""
This interface is ... | [
"def",
"new_transfer_from_transaction",
"(",
"self",
",",
"asset",
":",
"str",
",",
"b58_send_address",
":",
"str",
",",
"b58_from_address",
":",
"str",
",",
"b58_recv_address",
":",
"str",
",",
"amount",
":",
"int",
",",
"b58_payer_address",
":",
"str",
",",
... | 76.48 | 0.008781 |
def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
... | [
"def",
"create_unsigned_transaction",
"(",
"cls",
",",
"*",
",",
"nonce",
":",
"int",
",",
"gas_price",
":",
"int",
",",
"gas",
":",
"int",
",",
"to",
":",
"Address",
",",
"value",
":",
"int",
",",
"data",
":",
"bytes",
")",
"->",
"'BaseUnsignedTransac... | 43.416667 | 0.016917 |
def get_result_as_array(self):
"""
Returns the float values converted into strings using
the parameters given at initialisation, as a numpy array
"""
if self.formatter is not None:
return np.array([self.formatter(x) for x in self.values])
if self.fixed_width... | [
"def",
"get_result_as_array",
"(",
"self",
")",
":",
"if",
"self",
".",
"formatter",
"is",
"not",
"None",
":",
"return",
"np",
".",
"array",
"(",
"[",
"self",
".",
"formatter",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"values",
"]",
")",
"if",... | 38.418605 | 0.000885 |
def hasChannelType(self, chan):
"""Returns True if chan is among the supported channel types.
@param app: Module name.
@return: Boolean
"""
if self._chantypes is None:
self._initChannelTypesList()
return chan in self._chantypes | [
"def",
"hasChannelType",
"(",
"self",
",",
"chan",
")",
":",
"if",
"self",
".",
"_chantypes",
"is",
"None",
":",
"self",
".",
"_initChannelTypesList",
"(",
")",
"return",
"chan",
"in",
"self",
".",
"_chantypes"
] | 30 | 0.016181 |
def diff_flux_threshold(self, skydir, fn, ts_thresh, min_counts):
"""Compute the differential flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinate... | [
"def",
"diff_flux_threshold",
"(",
"self",
",",
"skydir",
",",
"fn",
",",
"ts_thresh",
",",
"min_counts",
")",
":",
"sig",
",",
"bkg",
",",
"bkg_fit",
"=",
"self",
".",
"compute_counts",
"(",
"skydir",
",",
"fn",
")",
"norms",
"=",
"irfs",
".",
"comput... | 37.135135 | 0.001418 |
def extract_random_video_patch(videos, num_frames=-1):
"""For every video, extract a random consecutive patch of num_frames.
Args:
videos: 5-D Tensor, (NTHWC)
num_frames: Integer, if -1 then the entire video is returned.
Returns:
video_patch: 5-D Tensor, (NTHWC) with T = num_frames.
Raises:
Val... | [
"def",
"extract_random_video_patch",
"(",
"videos",
",",
"num_frames",
"=",
"-",
"1",
")",
":",
"if",
"num_frames",
"==",
"-",
"1",
":",
"return",
"videos",
"batch_size",
",",
"num_total_frames",
",",
"h",
",",
"w",
",",
"c",
"=",
"common_layers",
".",
"... | 40.578947 | 0.012033 |
def block_sep0(self, Y):
r"""Separate variable into component corresponding to
:math:`\mathbf{y}_0` in :math:`\mathbf{y}\;\;`.
"""
return Y[(slice(None),)*self.blkaxis + (slice(0, self.blkidx),)] | [
"def",
"block_sep0",
"(",
"self",
",",
"Y",
")",
":",
"return",
"Y",
"[",
"(",
"slice",
"(",
"None",
")",
",",
")",
"*",
"self",
".",
"blkaxis",
"+",
"(",
"slice",
"(",
"0",
",",
"self",
".",
"blkidx",
")",
",",
")",
"]"
] | 37.166667 | 0.008772 |
def system_find_executions(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /system/findExecutions API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method%3A-%2Fsystem%2FfindExecutions
"""
return DXHTTPRequest('/system/findExecutions', inpu... | [
"def",
"system_find_executions",
"(",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/system/findExecutions'",
",",
"input_params",
",",
"always_retry",
"=",
"always_retry",
"... | 51.428571 | 0.008197 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.