text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def tostr(object, encoding=None):
""" get a unicode safe string representation of an object """
if isinstance(object, basestring):
if encoding is None:
return object
else:
return object.encode(encoding)
if isinstance(object, tuple):
s = ['(']
for item ... | [
"def",
"tostr",
"(",
"object",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"object",
",",
"basestring",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"return",
"object",
"else",
":",
"return",
"object",
".",
"encode",
"(",
"encodi... | 28.891304 | 0.001456 |
def get_perm_prompt(cls, package_list):
"""
Return text for prompt (do you want to install...), to install given packages.
"""
if cls == PackageManager:
raise NotImplementedError()
ln = len(package_list)
plural = 's' if ln > 1 else ''
return cls.permis... | [
"def",
"get_perm_prompt",
"(",
"cls",
",",
"package_list",
")",
":",
"if",
"cls",
"==",
"PackageManager",
":",
"raise",
"NotImplementedError",
"(",
")",
"ln",
"=",
"len",
"(",
"package_list",
")",
"plural",
"=",
"'s'",
"if",
"ln",
">",
"1",
"else",
"''",... | 39.222222 | 0.00831 |
def search(api_key, query, offset=0, type='personal'):
"""Get a list of email addresses for the provided domain.
The type of search executed will vary depending on the query provided.
Currently this query is restricted to either domain searches, in which
the email addresses (and other bits) for the dom... | [
"def",
"search",
"(",
"api_key",
",",
"query",
",",
"offset",
"=",
"0",
",",
"type",
"=",
"'personal'",
")",
":",
"if",
"not",
"isinstance",
"(",
"api_key",
",",
"str",
")",
":",
"raise",
"InvalidAPIKeyException",
"(",
"'API key must be a string'",
")",
"i... | 40.206897 | 0.000838 |
def idx_sequence(self):
"""Indices of sentences when enumerating data set from batches.
Useful when retrieving the correct order of sentences
Returns
-------
list
List of ids ranging from 0 to #sent -1
"""
return [x[1] for x in sorted(zip(self._record... | [
"def",
"idx_sequence",
"(",
"self",
")",
":",
"return",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"sorted",
"(",
"zip",
"(",
"self",
".",
"_record",
",",
"list",
"(",
"range",
"(",
"len",
"(",
"self",
".",
"_record",
")",
")",
")",
")",
")",
... | 34.6 | 0.008451 |
def parse_title(self, title):
"""
split of the last parenthesis operator==,!=,<,<=(std::vector)
tested with
```
operator==,!=,<,<=,>,>=(std::vector)
operator==,!=,<,<=,>,>=(std::vector)
operator==,!=,<,<=,>,>=
operator... | [
"def",
"parse_title",
"(",
"self",
",",
"title",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'^\\s*((?:\\(size_type\\)|(?:.|\\(\\))*?)*)((?:\\([^)]+\\))?)\\s*$'",
",",
"title",
")",
"postfix",
"=",
"m",
".",
"group",
"(",
"2",
")",
"t_names",
"=",
"m",
".... | 37.088235 | 0.008501 |
def _isReactiveMarket(self):
""" Returns a flag indicating the existance of offers/bids for reactive
power.
"""
vLoads = [g for g in self.case.generators if g.is_load]
if [offbid for offbid in self.offers + self.bids if offbid.reactive]:
haveQ = True
... | [
"def",
"_isReactiveMarket",
"(",
"self",
")",
":",
"vLoads",
"=",
"[",
"g",
"for",
"g",
"in",
"self",
".",
"case",
".",
"generators",
"if",
"g",
".",
"is_load",
"]",
"if",
"[",
"offbid",
"for",
"offbid",
"in",
"self",
".",
"offers",
"+",
"self",
".... | 38.304348 | 0.009967 |
def _findOptionValueAdvAudit(option):
'''
Get the Advanced Auditing policy as configured in
``C:\\Windows\\Security\\Audit\\audit.csv``
Args:
option (str): The name of the setting as it appears in audit.csv
Returns:
bool: ``True`` if successful, otherwise ``False``
'''
if '... | [
"def",
"_findOptionValueAdvAudit",
"(",
"option",
")",
":",
"if",
"'lgpo.adv_audit_data'",
"not",
"in",
"__context__",
":",
"system_root",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SystemRoot'",
",",
"'C:\\\\Windows'",
")",
"f_audit",
"=",
"os",
".",
"path... | 41.292683 | 0.000577 |
def update_license(license_id, **kwargs):
"""
Replace the License with given ID with a new License
"""
updated_license = pnc_api.licenses.get_specific(id=license_id).content
for key, value in iteritems(kwargs):
if value:
setattr(updated_license, key, value)
response = utils... | [
"def",
"update_license",
"(",
"license_id",
",",
"*",
"*",
"kwargs",
")",
":",
"updated_license",
"=",
"pnc_api",
".",
"licenses",
".",
"get_specific",
"(",
"id",
"=",
"license_id",
")",
".",
"content",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
... | 28.941176 | 0.001969 |
def all(self):
"""
Return all entries
:rtype: list(dict)
"""
attribute = self._attr[0]
return self.profile.data.get(attribute, []) | [
"def",
"all",
"(",
"self",
")",
":",
"attribute",
"=",
"self",
".",
"_attr",
"[",
"0",
"]",
"return",
"self",
".",
"profile",
".",
"data",
".",
"get",
"(",
"attribute",
",",
"[",
"]",
")"
] | 22.5 | 0.016043 |
def PROFILE_SDVOIGT(sg0,GamD,Gam0,Gam2,Shift0,Shift2,sg):
"""
# Speed dependent Voigt profile based on HTP.
# Input parameters:
# sg0 : Unperturbed line position in cm-1 (Input).
# GamD : Doppler HWHM in cm-1 (Input)
# Gam0 : Speed-averaged line-width in cm-1 (Input). ... | [
"def",
"PROFILE_SDVOIGT",
"(",
"sg0",
",",
"GamD",
",",
"Gam0",
",",
"Gam2",
",",
"Shift0",
",",
"Shift2",
",",
"sg",
")",
":",
"return",
"pcqsdhc",
"(",
"sg0",
",",
"GamD",
",",
"Gam0",
",",
"Gam2",
",",
"Shift0",
",",
"Shift2",
",",
"cZero",
",",... | 52.307692 | 0.024566 |
def installed(name,
composer=None,
php=None,
user=None,
prefer_source=None,
prefer_dist=None,
no_scripts=None,
no_plugins=None,
optimize=None,
no_dev=None,
quiet=False,
... | [
"def",
"installed",
"(",
"name",
",",
"composer",
"=",
"None",
",",
"php",
"=",
"None",
",",
"user",
"=",
"None",
",",
"prefer_source",
"=",
"None",
",",
"prefer_dist",
"=",
"None",
",",
"no_scripts",
"=",
"None",
",",
"no_plugins",
"=",
"None",
",",
... | 29.646154 | 0.00226 |
def _enum_lines(self):
"""Enumerate lines from the attached file."""
with _open_table(self.path, self.encoding) as lines:
for i, line in enumerate(lines):
yield i, line | [
"def",
"_enum_lines",
"(",
"self",
")",
":",
"with",
"_open_table",
"(",
"self",
".",
"path",
",",
"self",
".",
"encoding",
")",
"as",
"lines",
":",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"yield",
"i",
",",
"line"
] | 41.6 | 0.009434 |
def ma_fitpoly(bma, order=1, gt=None, perc=(2,98), origmask=True):
"""Fit a plane to values in input array
"""
if gt is None:
gt = [0, 1, 0, 0, 0, -1]
#Filter, can be useful to remove outliers
if perc is not None:
from pygeotools.lib import filtlib
bma_f = filtlib.perc_fltr(... | [
"def",
"ma_fitpoly",
"(",
"bma",
",",
"order",
"=",
"1",
",",
"gt",
"=",
"None",
",",
"perc",
"=",
"(",
"2",
",",
"98",
")",
",",
"origmask",
"=",
"True",
")",
":",
"if",
"gt",
"is",
"None",
":",
"gt",
"=",
"[",
"0",
",",
"1",
",",
"0",
"... | 35.409091 | 0.01375 |
def gblocks(self,
new_path = None,
seq_type = 'nucl' or 'prot'):
"""Apply the gblocks filtering algorithm to the alignment.
See http://molevol.cmima.csic.es/castresana/Gblocks/Gblocks_documentation.html
Need to rename all sequences, because it will complain with l... | [
"def",
"gblocks",
"(",
"self",
",",
"new_path",
"=",
"None",
",",
"seq_type",
"=",
"'nucl'",
"or",
"'prot'",
")",
":",
"# Temporary path #",
"if",
"new_path",
"is",
"None",
":",
"final",
"=",
"self",
".",
"__class__",
"(",
"new_temp_path",
"(",
")",
")",... | 51.074074 | 0.014235 |
def calculate_sunrise_sunset_from_datetime(self, datetime, depression=0.833,
is_solar_time=False):
"""Calculate sunrise, sunset and noon for a day of year."""
# TODO(mostapha): This should be more generic and based on a method
if datetime.year != 20... | [
"def",
"calculate_sunrise_sunset_from_datetime",
"(",
"self",
",",
"datetime",
",",
"depression",
"=",
"0.833",
",",
"is_solar_time",
"=",
"False",
")",
":",
"# TODO(mostapha): This should be more generic and based on a method",
"if",
"datetime",
".",
"year",
"!=",
"2016"... | 44.897959 | 0.001335 |
def parse_datetime(value: Union[datetime, StrIntFloat]) -> datetime:
"""
Parse a datetime/int/float/string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raise ValueError if the input i... | [
"def",
"parse_datetime",
"(",
"value",
":",
"Union",
"[",
"datetime",
",",
"StrIntFloat",
"]",
")",
"->",
"datetime",
":",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
")",
":",
"return",
"value",
"number",
"=",
"get_numeric",
"(",
"value",
")",
"i... | 32.809524 | 0.001409 |
def is_empty(self):
"""Asserts that val is empty."""
if len(self.val) != 0:
if isinstance(self.val, str_types):
self._err('Expected <%s> to be empty string, but was not.' % self.val)
else:
self._err('Expected <%s> to be empty, but was not.' % self.... | [
"def",
"is_empty",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"val",
")",
"!=",
"0",
":",
"if",
"isinstance",
"(",
"self",
".",
"val",
",",
"str_types",
")",
":",
"self",
".",
"_err",
"(",
"'Expected <%s> to be empty string, but was not.'",
"%... | 42.125 | 0.008721 |
def _get_filekey(self):
"""This method creates a key from a keyfile."""
if not os.path.exists(self.keyfile):
raise KPError('Keyfile not exists.')
try:
with open(self.keyfile, 'rb') as handler:
handler.seek(0, os.SEEK_END)
size = handler.te... | [
"def",
"_get_filekey",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"keyfile",
")",
":",
"raise",
"KPError",
"(",
"'Keyfile not exists.'",
")",
"try",
":",
"with",
"open",
"(",
"self",
".",
"keyfile",
",",
"... | 35.357143 | 0.001967 |
def add_member(self, address, **kwargs):
"""
Add a member to a group.
All Fiesta membership options can be passed in as keyword
arguments. Some valid options include:
- `group_name`: Since each member can access a group using
their own name, you can override the `grou... | [
"def",
"add_member",
"(",
"self",
",",
"address",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"'membership/%s'",
"%",
"self",
".",
"id",
"kwargs",
"[",
"\"address\"",
"]",
"=",
"address",
"if",
"\"group_name\"",
"not",
"in",
"kwargs",
"and",
"self",
... | 40.147059 | 0.002146 |
def visit_FunctionCall(self, node):
"""Visitor for `FunctionCall` AST node."""
call = self.memory[node.identifier.name]._node
args = [self.visit(parameter) for parameter in node.parameters]
if isinstance(call, AST):
current_scope = self.memory.stack.current.current
... | [
"def",
"visit_FunctionCall",
"(",
"self",
",",
"node",
")",
":",
"call",
"=",
"self",
".",
"memory",
"[",
"node",
".",
"identifier",
".",
"name",
"]",
".",
"_node",
"args",
"=",
"[",
"self",
".",
"visit",
"(",
"parameter",
")",
"for",
"parameter",
"i... | 33.961538 | 0.002203 |
def _glob_to_re(self, pattern):
"""Translate a shell-like glob pattern to a regular expression.
Return a string containing the regex. Differs from
'fnmatch.translate()' in that '*' does not match "special characters"
(which are platform-specific).
"""
pattern_re = fnmat... | [
"def",
"_glob_to_re",
"(",
"self",
",",
"pattern",
")",
":",
"pattern_re",
"=",
"fnmatch",
".",
"translate",
"(",
"pattern",
")",
"# '?' and '*' in the glob pattern become '.' and '.*' in the RE, which",
"# IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,",
"#... | 46.681818 | 0.001908 |
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsse... | [
"def",
"init",
"(",
"name",
",",
"config",
"=",
"None",
",",
"cpuset",
"=",
"None",
",",
"cpushare",
"=",
"None",
",",
"memory",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"network_profile",
"=",
"None",
",",
"nic_opts",
"=",
"None",
",",
"cpu",
... | 36.586873 | 0.000154 |
def getVariances(self):
"""
Returns the estimated variances as a n_terms x P matrix
each row of the output represents a term and its P values represent the variance corresponding variance in each trait
"""
if self.P>1:
RV=SP.zeros((self.n_terms,self.P))
fo... | [
"def",
"getVariances",
"(",
"self",
")",
":",
"if",
"self",
".",
"P",
">",
"1",
":",
"RV",
"=",
"SP",
".",
"zeros",
"(",
"(",
"self",
".",
"n_terms",
",",
"self",
".",
"P",
")",
")",
"for",
"term_i",
"in",
"range",
"(",
"self",
".",
"n_terms",
... | 41 | 0.019881 |
def execution_environment():
"""A convenient bundling of the current execution context"""
context = {}
context['conf'] = config()
if relation_id():
context['reltype'] = relation_type()
context['relid'] = relation_id()
context['rel'] = relation_get()
context['unit'] = local_un... | [
"def",
"execution_environment",
"(",
")",
":",
"context",
"=",
"{",
"}",
"context",
"[",
"'conf'",
"]",
"=",
"config",
"(",
")",
"if",
"relation_id",
"(",
")",
":",
"context",
"[",
"'reltype'",
"]",
"=",
"relation_type",
"(",
")",
"context",
"[",
"'rel... | 33.166667 | 0.002445 |
def draw_cross(self, position, color=(255, 0, 0), radius=4):
"""Draw a cross on the canvas.
:param position: (row, col) tuple
:param color: RGB tuple
:param radius: radius of the cross (int)
"""
y, x = position
for xmod in np.arange(-radius, radius+1, 1):
... | [
"def",
"draw_cross",
"(",
"self",
",",
"position",
",",
"color",
"=",
"(",
"255",
",",
"0",
",",
"0",
")",
",",
"radius",
"=",
"4",
")",
":",
"y",
",",
"x",
"=",
"position",
"for",
"xmod",
"in",
"np",
".",
"arange",
"(",
"-",
"radius",
",",
"... | 38.818182 | 0.002286 |
def securitygroupid(vm_):
'''
Returns the SecurityGroupId
'''
securitygroupid_set = set()
securitygroupid_list = config.get_cloud_config_value(
'securitygroupid',
vm_,
__opts__,
search_global=False
)
# If the list is None, then the set will remain empty
# ... | [
"def",
"securitygroupid",
"(",
"vm_",
")",
":",
"securitygroupid_set",
"=",
"set",
"(",
")",
"securitygroupid_list",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'securitygroupid'",
",",
"vm_",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
"# ... | 40.205882 | 0.002143 |
def generate_reports(self):
"""close the whole package /module, it's time to make reports !
if persistent run, pickle results for later comparison
"""
# Display whatever messages are left on the reporter.
self.reporter.display_messages(report_nodes.Section())
if self.fi... | [
"def",
"generate_reports",
"(",
"self",
")",
":",
"# Display whatever messages are left on the reporter.",
"self",
".",
"reporter",
".",
"display_messages",
"(",
"report_nodes",
".",
"Section",
"(",
")",
")",
"if",
"self",
".",
"file_state",
".",
"base_name",
"is",
... | 42.461538 | 0.001771 |
def verify_state(self):
"""Verify if session was not yet opened. If it is, open it and call connections `on_open`"""
if self.state == CONNECTING:
self.state = OPEN
self.conn.on_open(self.conn_info) | [
"def",
"verify_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"CONNECTING",
":",
"self",
".",
"state",
"=",
"OPEN",
"self",
".",
"conn",
".",
"on_open",
"(",
"self",
".",
"conn_info",
")"
] | 38.833333 | 0.012605 |
def _splitGenoGeneWindow(self,annotation_file=None,cis=1e4,funct='protein_coding',minSnps=1.,maxSnps=SP.inf):
"""
split into windows based on genes
"""
#1. load annotation
assert annotation_file is not None, 'Splitter:: specify annotation file'
try:
f = h5py.... | [
"def",
"_splitGenoGeneWindow",
"(",
"self",
",",
"annotation_file",
"=",
"None",
",",
"cis",
"=",
"1e4",
",",
"funct",
"=",
"'protein_coding'",
",",
"minSnps",
"=",
"1.",
",",
"maxSnps",
"=",
"SP",
".",
"inf",
")",
":",
"#1. load annotation",
"assert",
"an... | 39.106383 | 0.017516 |
def err(self) -> Option[E]:
"""
Converts from :class:`Result` [T, E] to :class:`option.option_.Option` [E].
Returns:
:class:`Option` containing the error value if `self` is
:meth:`Result.Err`, otherwise :data:`option.option_.NONE`.
Examples:
>>> Ok(1... | [
"def",
"err",
"(",
"self",
")",
"->",
"Option",
"[",
"E",
"]",
":",
"return",
"cast",
"(",
"Option",
"[",
"E",
"]",
",",
"NONE",
")",
"if",
"self",
".",
"_is_ok",
"else",
"Option",
".",
"Some",
"(",
"cast",
"(",
"E",
",",
"self",
".",
"_val",
... | 32 | 0.008097 |
def handle_cookies(response, exc=None):
'''Handle response cookies.
'''
if exc:
return
headers = response.headers
request = response.request
client = request.client
response._cookies = c = SimpleCookie()
if 'set-cookie' in headers or 'set-cookie2' in headers:
for cookie i... | [
"def",
"handle_cookies",
"(",
"response",
",",
"exc",
"=",
"None",
")",
":",
"if",
"exc",
":",
"return",
"headers",
"=",
"response",
".",
"headers",
"request",
"=",
"response",
".",
"request",
"client",
"=",
"request",
".",
"client",
"response",
".",
"_c... | 33.4375 | 0.001818 |
def log_every_x_times(logger, counter, x, msg, *args, **kwargs):
'''
Works like logdebug, but only prints first and
and every xth message.
'''
if counter==1 or counter % x == 0:
#msg = msg + (' (counter %i)' % counter)
logdebug(logger, msg, *args, **kwargs) | [
"def",
"log_every_x_times",
"(",
"logger",
",",
"counter",
",",
"x",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"counter",
"==",
"1",
"or",
"counter",
"%",
"x",
"==",
"0",
":",
"#msg = msg + (' (counter %i)' % counter)",
"logd... | 35.75 | 0.010239 |
def get_levels(dict_, n=0, levels=None):
r"""
DEPCIRATE
Args:
dict_ (dict_): a dictionary
n (int): (default = 0)
levels (None): (default = None)
CommandLine:
python -m utool.util_graph --test-get_levels --show
python3 -m utool.util_graph --test-get_levels --sho... | [
"def",
"get_levels",
"(",
"dict_",
",",
"n",
"=",
"0",
",",
"levels",
"=",
"None",
")",
":",
"if",
"levels",
"is",
"None",
":",
"levels_",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"dict_depth",
"(",
"dict_",
")",
")",
"]",
"else",
":... | 27.283019 | 0.000668 |
def handle_error(self):
"""
Handles an error log record that should be shown
Returns:
None
"""
if not self.tasks:
return
# All the parents inherit the failure
self.mark_parent_tasks_as_failed(
self.cur_task,
flush_... | [
"def",
"handle_error",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"tasks",
":",
"return",
"# All the parents inherit the failure",
"self",
".",
"mark_parent_tasks_as_failed",
"(",
"self",
".",
"cur_task",
",",
"flush_logs",
"=",
"True",
",",
")",
"# Show t... | 29.292683 | 0.001612 |
def is_orderable(cls):
"""
Checks if the provided class is specified as an orderable in
settings.ORDERABLE_MODELS. If it is return its settings.
"""
if not getattr(settings, 'ORDERABLE_MODELS', None):
return False
labels = resolve_labels(cls)
if labels['app_model'] in settings.ORDER... | [
"def",
"is_orderable",
"(",
"cls",
")",
":",
"if",
"not",
"getattr",
"(",
"settings",
",",
"'ORDERABLE_MODELS'",
",",
"None",
")",
":",
"return",
"False",
"labels",
"=",
"resolve_labels",
"(",
"cls",
")",
"if",
"labels",
"[",
"'app_model'",
"]",
"in",
"s... | 33.333333 | 0.002433 |
def get_user_info(tokens, uk):
'''获取用户的部分信息.
比如头像, 用户名, 自我介绍, 粉丝数等.
这个接口可用于查询任何用户的信息, 只要知道他/她的uk.
'''
url = ''.join([
const.PAN_URL,
'pcloud/user/getinfo?channel=chunlei&clienttype=0&web=1',
'&bdstoken=', tokens['bdstoken'],
'&query_uk=', uk,
'&t=', util.time... | [
"def",
"get_user_info",
"(",
"tokens",
",",
"uk",
")",
":",
"url",
"=",
"''",
".",
"join",
"(",
"[",
"const",
".",
"PAN_URL",
",",
"'pcloud/user/getinfo?channel=chunlei&clienttype=0&web=1'",
",",
"'&bdstoken='",
",",
"tokens",
"[",
"'bdstoken'",
"]",
",",
"'&q... | 26 | 0.001953 |
def getfilename(package, relativeTo=None):
"""Find the python source file for a package, relative to a
particular directory (defaults to current working directory if not
given).
"""
if relativeTo is None:
relativeTo = os.getcwd()
path = os.path.join(relativeTo, os.sep.join(package.split(... | [
"def",
"getfilename",
"(",
"package",
",",
"relativeTo",
"=",
"None",
")",
":",
"if",
"relativeTo",
"is",
"None",
":",
"relativeTo",
"=",
"os",
".",
"getcwd",
"(",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"relativeTo",
",",
"os",
".",
... | 35.285714 | 0.001972 |
def ended(self):
"""We call this method when the function is finished."""
self._end_time = time.time()
if setting(key='memory_profile', expected_type=bool):
self._end_memory = get_free_memory() | [
"def",
"ended",
"(",
"self",
")",
":",
"self",
".",
"_end_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"setting",
"(",
"key",
"=",
"'memory_profile'",
",",
"expected_type",
"=",
"bool",
")",
":",
"self",
".",
"_end_memory",
"=",
"get_free_memory",
... | 37.5 | 0.008696 |
def estimate_mass_range(numPoints, massRangeParams, metricParams, fUpper,\
covary=True):
"""
This function will generate a large set of points with random masses and
spins (using pycbc.tmpltbank.get_random_mass) and translate these points
into the xi_i coordinate system for the g... | [
"def",
"estimate_mass_range",
"(",
"numPoints",
",",
"massRangeParams",
",",
"metricParams",
",",
"fUpper",
",",
"covary",
"=",
"True",
")",
":",
"vals_set",
"=",
"get_random_mass",
"(",
"numPoints",
",",
"massRangeParams",
")",
"mass1",
"=",
"vals_set",
"[",
... | 41.020833 | 0.000992 |
def delete(self, event):
"delete all of the selected objects"
# get the selected objects (if any)
for obj in self.selection:
if obj:
if DEBUG: print "deleting", obj.name
obj.destroy()
self.selection = [] # clean selectio... | [
"def",
"delete",
"(",
"self",
",",
"event",
")",
":",
"# get the selected objects (if any)",
"for",
"obj",
"in",
"self",
".",
"selection",
":",
"if",
"obj",
":",
"if",
"DEBUG",
":",
"print",
"\"deleting\"",
",",
"obj",
".",
"name",
"obj",
".",
"destroy",
... | 38.888889 | 0.00838 |
def mixin(self):
"""
Add the annotations to the ODM Element (if defined)
:return:
"""
if self.milestones:
from rwslib.builders.clinicaldata import Annotation, Flag, FlagValue
annotation = Annotation()
for codelist, milestones in self.milestone... | [
"def",
"mixin",
"(",
"self",
")",
":",
"if",
"self",
".",
"milestones",
":",
"from",
"rwslib",
".",
"builders",
".",
"clinicaldata",
"import",
"Annotation",
",",
"Flag",
",",
"FlagValue",
"annotation",
"=",
"Annotation",
"(",
")",
"for",
"codelist",
",",
... | 41.666667 | 0.009785 |
def substitute_ref_with_url(self, txt):
"""
In the string `txt`, replace sphinx references with
corresponding links to online docs.
"""
# Find sphinx cross-references
mi = re.finditer(r':([^:]+):`([^`]+)`', txt)
if mi:
# Iterate over match objects in ... | [
"def",
"substitute_ref_with_url",
"(",
"self",
",",
"txt",
")",
":",
"# Find sphinx cross-references",
"mi",
"=",
"re",
".",
"finditer",
"(",
"r':([^:]+):`([^`]+)`'",
",",
"txt",
")",
"if",
"mi",
":",
"# Iterate over match objects in iterator returned by re.finditer",
"... | 40.586957 | 0.001046 |
def delete_repository(self, namespace, repository):
"""DELETE /v1/repositories/(namespace)/(repository)/"""
return self._http_call(self.REPO, delete,
namespace=namespace, repository=repository) | [
"def",
"delete_repository",
"(",
"self",
",",
"namespace",
",",
"repository",
")",
":",
"return",
"self",
".",
"_http_call",
"(",
"self",
".",
"REPO",
",",
"delete",
",",
"namespace",
"=",
"namespace",
",",
"repository",
"=",
"repository",
")"
] | 59.25 | 0.008333 |
def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all):
"""Forward computation."""
sampled_candidates, expected_count_sampled, expected_count_true = sampled_values
# (num_sampled, in_unit)
w_sampled = w_all.slice(begin=(0, 0), end=(self._num_sampled, None))
w_true = ... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"x",
",",
"sampled_values",
",",
"label",
",",
"w_all",
",",
"b_all",
")",
":",
"sampled_candidates",
",",
"expected_count_sampled",
",",
"expected_count_true",
"=",
"sampled_values",
"# (num_sampled, in_unit)",
... | 47.272727 | 0.001884 |
def _consume(iterator, n=None):
"""Advance the iterator n-steps ahead. If n is none, consume entirely."""
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to ... | [
"def",
"_consume",
"(",
"iterator",
",",
"n",
"=",
"None",
")",
":",
"# Use functions that consume iterators at C speed.",
"if",
"n",
"is",
"None",
":",
"# feed the entire iterator into a zero-length deque",
"collections",
".",
"deque",
"(",
"iterator",
",",
"maxlen",
... | 44.777778 | 0.002433 |
def print_colors(palette, outfile="Palette.png"):
"""
print color palette (a tuple) to a PNG file for quick check
"""
fig = plt.figure()
ax = fig.add_subplot(111)
xmax = 20 * (len(palette) + 1)
x1s = np.arange(0, xmax, 20)
xintervals = [10] * len(palette)
xx = zip(x1s, xintervals)
... | [
"def",
"print_colors",
"(",
"palette",
",",
"outfile",
"=",
"\"Palette.png\"",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"111",
")",
"xmax",
"=",
"20",
"*",
"(",
"len",
"(",
"palette",
")",
"+"... | 24.777778 | 0.00216 |
def getMetadata(self, remote, address, key):
"""Get metadata of device"""
if self._server is not None:
# pylint: disable=E1121
return self._server.getAllMetadata(remote, address, key) | [
"def",
"getMetadata",
"(",
"self",
",",
"remote",
",",
"address",
",",
"key",
")",
":",
"if",
"self",
".",
"_server",
"is",
"not",
"None",
":",
"# pylint: disable=E1121",
"return",
"self",
".",
"_server",
".",
"getAllMetadata",
"(",
"remote",
",",
"address... | 43.8 | 0.008969 |
def error_message(e, message=None, cause=None):
"""
Formats exception message + cause
:param e:
:param message:
:param cause:
:return: formatted message, includes cause if any is set
"""
if message is None and cause is None:
return None
elif message is None:
return '%... | [
"def",
"error_message",
"(",
"e",
",",
"message",
"=",
"None",
",",
"cause",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
"and",
"cause",
"is",
"None",
":",
"return",
"None",
"elif",
"message",
"is",
"None",
":",
"return",
"'%s, caused by %r'",
... | 28.375 | 0.002132 |
def stops(self):
"""Return all stops visited by trips for this agency."""
stops = set()
for stop_time in self.stop_times():
stops |= stop_time.stops()
return stops | [
"def",
"stops",
"(",
"self",
")",
":",
"stops",
"=",
"set",
"(",
")",
"for",
"stop_time",
"in",
"self",
".",
"stop_times",
"(",
")",
":",
"stops",
"|=",
"stop_time",
".",
"stops",
"(",
")",
"return",
"stops"
] | 30 | 0.010811 |
def get_status(dev, recipient = None):
r"""Return the status for the specified recipient.
dev is the Device object to which the request will be
sent to.
The recipient can be None (on which the status will be queried
from the device), an Interface or Endpoint descriptors.
The status value is r... | [
"def",
"get_status",
"(",
"dev",
",",
"recipient",
"=",
"None",
")",
":",
"bmRequestType",
",",
"wIndex",
"=",
"_parse_recipient",
"(",
"recipient",
",",
"util",
".",
"CTRL_IN",
")",
"ret",
"=",
"dev",
".",
"ctrl_transfer",
"(",
"bmRequestType",
"=",
"bmRe... | 38.444444 | 0.015515 |
def validate(self, value) :
"""checks the validity of 'value' given the lits of validators"""
for v in self.validators :
v.validate(value)
return True | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"for",
"v",
"in",
"self",
".",
"validators",
":",
"v",
".",
"validate",
"(",
"value",
")",
"return",
"True"
] | 36.4 | 0.021505 |
def fancy_modeladmin(*args):
"""Returns a new copy of a :class:`FancyModelAdmin` class (a class, not
an instance!). This can then be inherited from when declaring a model
admin class. The :class:`FancyModelAdmin` class has additional methods
for managing the ``list_display`` attribute.
:param ``*ar... | [
"def",
"fancy_modeladmin",
"(",
"*",
"args",
")",
":",
"global",
"klass_count",
"klass_count",
"+=",
"1",
"name",
"=",
"'DynamicAdminClass%d'",
"%",
"klass_count",
"# clone the admin class",
"klass",
"=",
"type",
"(",
"name",
",",
"(",
"FancyModelAdmin",
",",
")... | 33.581081 | 0.000391 |
def dirpath_int(self):
"""Absolute path of the directory of the internal data file.
Normally, each sequence queries its current "internal" directory
path from the |SequenceManager| object stored in module |pub|:
>>> from hydpy import pub, repr_, TestIO
>>> from hydpy.core.filet... | [
"def",
"dirpath_int",
"(",
"self",
")",
":",
"try",
":",
"return",
"hydpy",
".",
"pub",
".",
"sequencemanager",
".",
"tempdirpath",
"except",
"RuntimeError",
":",
"raise",
"RuntimeError",
"(",
"f'For sequence {objecttools.devicephrase(self)} '",
"f'the directory of the ... | 35.306452 | 0.000889 |
def register_ddk_task(self, *args, **kwargs):
"""Register a ddk task."""
kwargs["task_class"] = DdkTask
return self.register_task(*args, **kwargs) | [
"def",
"register_ddk_task",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"task_class\"",
"]",
"=",
"DdkTask",
"return",
"self",
".",
"register_task",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 41.75 | 0.011765 |
def request_length(self):
"""
Return length of next chunk upload.
"""
remainder = self.stop_at - self.offset
return self.chunk_size if remainder > self.chunk_size else remainder | [
"def",
"request_length",
"(",
"self",
")",
":",
"remainder",
"=",
"self",
".",
"stop_at",
"-",
"self",
".",
"offset",
"return",
"self",
".",
"chunk_size",
"if",
"remainder",
">",
"self",
".",
"chunk_size",
"else",
"remainder"
] | 35.333333 | 0.009217 |
def quantiles(self, quantiles,
axis=0, strict=False,
recompute_integral=False):
"""
Calculate the quantiles of this histogram.
Parameters
----------
quantiles : list or int
A list of cumulative probabilities or an integer used to ... | [
"def",
"quantiles",
"(",
"self",
",",
"quantiles",
",",
"axis",
"=",
"0",
",",
"strict",
"=",
"False",
",",
"recompute_integral",
"=",
"False",
")",
":",
"if",
"axis",
">=",
"self",
".",
"GetDimension",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"axi... | 39.055556 | 0.000991 |
def first_instr(self, start, end, instr, target=None, exact=True):
"""
Find the first <instr> in the block from start to end.
<instr> is any python bytecode instruction or a list of opcodes
If <instr> is an opcode with a target (like a jump), a target
destination can be specified... | [
"def",
"first_instr",
"(",
"self",
",",
"start",
",",
"end",
",",
"instr",
",",
"target",
"=",
"None",
",",
"exact",
"=",
"True",
")",
":",
"code",
"=",
"self",
".",
"code",
"assert",
"(",
"start",
">=",
"0",
"and",
"end",
"<=",
"len",
"(",
"code... | 36.971429 | 0.002259 |
def cli(ctx, data, verbose, color, format, editor):
"""Query a meetup database.
"""
ctx.obj['verbose'] = verbose
if verbose:
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
ctx.obj['datadir'] = os.path.abspath(data)
if 'db' no... | [
"def",
"cli",
"(",
"ctx",
",",
"data",
",",
"verbose",
",",
"color",
",",
"format",
",",
"editor",
")",
":",
"ctx",
".",
"obj",
"[",
"'verbose'",
"]",
"=",
"verbose",
"if",
"verbose",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
... | 38.583333 | 0.001054 |
def _marginal_loglike(self, x):
"""Internal function to calculate and cache the marginal likelihood
"""
yedge = self._nuis_pdf.marginalization_bins()
yw = yedge[1:] - yedge[:-1]
yc = 0.5 * (yedge[1:] + yedge[:-1])
s = self.like(x[:, np.newaxis], yc[np.newaxis, :])
... | [
"def",
"_marginal_loglike",
"(",
"self",
",",
"x",
")",
":",
"yedge",
"=",
"self",
".",
"_nuis_pdf",
".",
"marginalization_bins",
"(",
")",
"yw",
"=",
"yedge",
"[",
"1",
":",
"]",
"-",
"yedge",
"[",
":",
"-",
"1",
"]",
"yc",
"=",
"0.5",
"*",
"(",... | 38.826087 | 0.002186 |
def format_output(data, fmt='table'): # pylint: disable=R0911,R0912
"""Given some data, will format it for console output.
:param data: One of: String, Table, FormattedItem, List, Tuple,
SequentialOutput
:param string fmt (optional): One of: table, raw, json, python
"""
if isinsta... | [
"def",
"format_output",
"(",
"data",
",",
"fmt",
"=",
"'table'",
")",
":",
"# pylint: disable=R0911,R0912",
"if",
"isinstance",
"(",
"data",
",",
"utils",
".",
"string_types",
")",
":",
"if",
"fmt",
"in",
"(",
"'json'",
",",
"'jsonraw'",
")",
":",
"return"... | 33.431373 | 0.00057 |
def pose2mat(pose):
"""
Converts pose to homogeneous matrix.
Args:
pose: a (pos, orn) tuple where pos is vec3 float cartesian, and
orn is vec4 float quaternion.
Returns:
4x4 homogeneous matrix
"""
homo_pose_mat = np.zeros((4, 4), dtype=np.float32)
homo_pose_mat[... | [
"def",
"pose2mat",
"(",
"pose",
")",
":",
"homo_pose_mat",
"=",
"np",
".",
"zeros",
"(",
"(",
"4",
",",
"4",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"homo_pose_mat",
"[",
":",
"3",
",",
":",
"3",
"]",
"=",
"quat2mat",
"(",
"pose",
"[... | 28.0625 | 0.002155 |
def start(self, tag, attrib):
"""On start of element tag"""
if tag == E_CLINICAL_DATA:
self.ref_state = AUDIT_REF_STATE
self.context = Context(attrib[A_STUDY_OID],
attrib[A_AUDIT_SUBCATEGORY_NAME],
int(attrib[A... | [
"def",
"start",
"(",
"self",
",",
"tag",
",",
"attrib",
")",
":",
"if",
"tag",
"==",
"E_CLINICAL_DATA",
":",
"self",
".",
"ref_state",
"=",
"AUDIT_REF_STATE",
"self",
".",
"context",
"=",
"Context",
"(",
"attrib",
"[",
"A_STUDY_OID",
"]",
",",
"attrib",
... | 36.828571 | 0.000504 |
def populate_sites( self, number_of_atoms, selected_sites=None ):
"""
Populate the lattice sites with a specific number of atoms.
Args:
number_of_atoms (Int): The number of atoms to populate the lattice sites with.
selected_sites (:obj:List, optional): List of site label... | [
"def",
"populate_sites",
"(",
"self",
",",
"number_of_atoms",
",",
"selected_sites",
"=",
"None",
")",
":",
"if",
"number_of_atoms",
">",
"self",
".",
"number_of_sites",
":",
"raise",
"ValueError",
"if",
"selected_sites",
":",
"atoms",
"=",
"[",
"atom",
".",
... | 46.157895 | 0.02905 |
def _gen_header(self, sequence, payloadtype):
""" Create packet header. """
protocol = bytearray.fromhex("00 34")
source = bytearray.fromhex("42 52 4b 52")
target = bytearray.fromhex("00 00 00 00 00 00 00 00")
reserved1 = bytearray.fromhex("00 00 00 00 00 00")
sequence = ... | [
"def",
"_gen_header",
"(",
"self",
",",
"sequence",
",",
"payloadtype",
")",
":",
"protocol",
"=",
"bytearray",
".",
"fromhex",
"(",
"\"00 34\"",
")",
"source",
"=",
"bytearray",
".",
"fromhex",
"(",
"\"42 52 4b 52\"",
")",
"target",
"=",
"bytearray",
".",
... | 35.125 | 0.002309 |
def get_claims_for(self, user_id, requested_claims):
# type: (str, Mapping[str, Optional[Mapping[str, Union[str, List[str]]]]) -> Dict[str, Union[str, List[str]]]
"""
Filter the userinfo based on which claims where requested.
:param user_id: user identifier
:param requested_claim... | [
"def",
"get_claims_for",
"(",
"self",
",",
"user_id",
",",
"requested_claims",
")",
":",
"# type: (str, Mapping[str, Optional[Mapping[str, Union[str, List[str]]]]) -> Dict[str, Union[str, List[str]]]",
"userinfo",
"=",
"self",
".",
"_db",
"[",
"user_id",
"]",
"claims",
"=",
... | 53.461538 | 0.008487 |
def dev_moments(self):
"""Sum of the absolute deviations between the central moments of the
instantaneous unit hydrograph and the ARMA approximation."""
return numpy.sum(numpy.abs(self.moments-self.ma.moments)) | [
"def",
"dev_moments",
"(",
"self",
")",
":",
"return",
"numpy",
".",
"sum",
"(",
"numpy",
".",
"abs",
"(",
"self",
".",
"moments",
"-",
"self",
".",
"ma",
".",
"moments",
")",
")"
] | 57.75 | 0.008547 |
def get_artist(self, id_):
"""Data for a specific artist."""
endpoint = "artists/{id}".format(id=id_)
return self._make_request(endpoint) | [
"def",
"get_artist",
"(",
"self",
",",
"id_",
")",
":",
"endpoint",
"=",
"\"artists/{id}\"",
".",
"format",
"(",
"id",
"=",
"id_",
")",
"return",
"self",
".",
"_make_request",
"(",
"endpoint",
")"
] | 39.5 | 0.012422 |
def __indent(self, lines, indent, initial=2):
"""This will indent the given set of lines by normal HTML layout.
An initial indent of `2*indent` will be used to account for the
`<html><head>` or `<html><body>` levels."""
tagempty = re.compile(r"""<\w+(\s+[^>]*?)*/>""")
tagopen = re.compile(r"""<\w+(\s+[^>]*?)*... | [
"def",
"__indent",
"(",
"self",
",",
"lines",
",",
"indent",
",",
"initial",
"=",
"2",
")",
":",
"tagempty",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"<\\w+(\\s+[^>]*?)*/>\"\"\"",
")",
"tagopen",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"<\\w+(\\s+[^>]*?)*>\"\"\""... | 34.75 | 0.030338 |
def centroid_refine_triangulation_by_vertices(self, vertices):
"""
return points defining a refined triangulation obtained by bisection of all edges
in the triangulation connected to any of the vertices in the list provided
"""
triangles = self.identify_vertex_triangles(vertices... | [
"def",
"centroid_refine_triangulation_by_vertices",
"(",
"self",
",",
"vertices",
")",
":",
"triangles",
"=",
"self",
".",
"identify_vertex_triangles",
"(",
"vertices",
")",
"return",
"self",
".",
"centroid_refine_triangulation_by_triangles",
"(",
"triangles",
")"
] | 43.111111 | 0.010101 |
def reference(self, tkn: str):
""" Return the element that tkn represents"""
return self.grammarelts[tkn] if tkn in self.grammarelts else UndefinedElement(tkn) | [
"def",
"reference",
"(",
"self",
",",
"tkn",
":",
"str",
")",
":",
"return",
"self",
".",
"grammarelts",
"[",
"tkn",
"]",
"if",
"tkn",
"in",
"self",
".",
"grammarelts",
"else",
"UndefinedElement",
"(",
"tkn",
")"
] | 57.666667 | 0.017143 |
def potential_from_grid(self, grid):
"""
Calculate the potential at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
"""
poten... | [
"def",
"potential_from_grid",
"(",
"self",
",",
"grid",
")",
":",
"potential_grid",
"=",
"quad_grid",
"(",
"self",
".",
"potential_func",
",",
"0.0",
",",
"1.0",
",",
"grid",
",",
"args",
"=",
"(",
"self",
".",
"axis_ratio",
",",
"self",
".",
"kappa_s",
... | 38.714286 | 0.009009 |
def iterweekdays(self, d1, d2):
"""
Date iterator returning dates in d1 <= x < d2, excluding weekends
"""
for dt in self.iterdays(d1, d2):
if not self.isweekend(dt):
yield dt | [
"def",
"iterweekdays",
"(",
"self",
",",
"d1",
",",
"d2",
")",
":",
"for",
"dt",
"in",
"self",
".",
"iterdays",
"(",
"d1",
",",
"d2",
")",
":",
"if",
"not",
"self",
".",
"isweekend",
"(",
"dt",
")",
":",
"yield",
"dt"
] | 32.571429 | 0.008547 |
def needsattached(func):
"""Decorator to prevent commands from being used when not attached."""
@functools.wraps(func)
def wrap(self, *args, **kwargs):
if not self.attached:
raise PositionError('Not attached to any process.')
return func(self, *args, **kwargs)
return wrap | [
"def",
"needsattached",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrap",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"attached",
":",
"raise",
"PositionError",
"... | 33.444444 | 0.009709 |
def query(self):
"""
Returns the query instance for this widget.
:return <orb.Query> || <orb.QueryCompound>
"""
queryWidget = self.queryWidget()
# check to see if there is an active container for this widget
container = queryWidget.c... | [
"def",
"query",
"(",
"self",
")",
":",
"queryWidget",
"=",
"self",
".",
"queryWidget",
"(",
")",
"# check to see if there is an active container for this widget\r",
"container",
"=",
"queryWidget",
".",
"containerFor",
"(",
"self",
")",
"if",
"container",
":",
"retu... | 31.964286 | 0.008677 |
def export(group, bucket, prefix, start, end, role, poll_period=120,
session=None, name="", region=None):
"""export a given log group to s3"""
start = start and isinstance(start, six.string_types) and parse(start) or start
end = (end and isinstance(start, six.string_types) and
parse(en... | [
"def",
"export",
"(",
"group",
",",
"bucket",
",",
"prefix",
",",
"start",
",",
"end",
",",
"role",
",",
"poll_period",
"=",
"120",
",",
"session",
"=",
"None",
",",
"name",
"=",
"\"\"",
",",
"region",
"=",
"None",
")",
":",
"start",
"=",
"start",
... | 34.395522 | 0.001054 |
def p_data(p):
""" statement : DATA arguments
"""
label_ = make_label(gl.DATA_PTR_CURRENT, lineno=p.lineno(1))
datas_ = []
funcs = []
if p[2] is None:
p[0] = None
return
for d in p[2].children:
value = d.value
if is_static(value):
datas_.append(d... | [
"def",
"p_data",
"(",
"p",
")",
":",
"label_",
"=",
"make_label",
"(",
"gl",
".",
"DATA_PTR_CURRENT",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"datas_",
"=",
"[",
"]",
"funcs",
"=",
"[",
"]",
"if",
"p",
"[",
"2",
"]",
"is",
... | 28.324324 | 0.001845 |
def getCurrentFadeColor(self, bBackground):
"""Get current fade color value."""
fn = self.function_table.getCurrentFadeColor
result = fn(bBackground)
return result | [
"def",
"getCurrentFadeColor",
"(",
"self",
",",
"bBackground",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getCurrentFadeColor",
"result",
"=",
"fn",
"(",
"bBackground",
")",
"return",
"result"
] | 31.833333 | 0.010204 |
def earthquake_fatality_rate(hazard_level):
"""Earthquake fatality ratio for a given hazard level.
It reads the QGIS QSettings to know what is the default earthquake
function.
:param hazard_level: The hazard level.
:type hazard_level: int
:return: The fatality rate.
:rtype: float
"""
... | [
"def",
"earthquake_fatality_rate",
"(",
"hazard_level",
")",
":",
"earthquake_function",
"=",
"setting",
"(",
"'earthquake_function'",
",",
"EARTHQUAKE_FUNCTIONS",
"[",
"0",
"]",
"[",
"'key'",
"]",
",",
"str",
")",
"ratio",
"=",
"0",
"for",
"model",
"in",
"EAR... | 31.15 | 0.001558 |
def GE(classical_reg1, classical_reg2, classical_reg3):
"""
Produce an GE instruction.
:param classical_reg1: Memory address to which to store the comparison result.
:param classical_reg2: Left comparison operand.
:param classical_reg3: Right comparison operand.
:return: A ClassicalGreaterEqual... | [
"def",
"GE",
"(",
"classical_reg1",
",",
"classical_reg2",
",",
"classical_reg3",
")",
":",
"classical_reg1",
",",
"classical_reg2",
",",
"classical_reg3",
"=",
"prepare_ternary_operands",
"(",
"classical_reg1",
",",
"classical_reg2",
",",
"classical_reg3",
")",
"retu... | 53 | 0.008559 |
def replace_project(self, project_key, **kwargs):
"""Replace an existing Project
*Create a project with a given id or completely rewrite the project,
including any previously added files or linked datasets, if one already
exists with the given id.*
:param project_key: Username ... | [
"def",
"replace_project",
"(",
"self",
",",
"project_key",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"self",
".",
"__build_project_obj",
"(",
"lambda",
":",
"_swagger",
".",
"ProjectCreateRequest",
"(",
"title",
"=",
"kwargs",
".",
"get",
"(",
"'t... | 42 | 0.00075 |
def _get_type(cls, ptr):
"""Get the subtype class for a pointer"""
# fall back to the base class if unknown
return cls.__types.get(lib.g_base_info_get_type(ptr), cls) | [
"def",
"_get_type",
"(",
"cls",
",",
"ptr",
")",
":",
"# fall back to the base class if unknown",
"return",
"cls",
".",
"__types",
".",
"get",
"(",
"lib",
".",
"g_base_info_get_type",
"(",
"ptr",
")",
",",
"cls",
")"
] | 37.4 | 0.010471 |
def _partialParseDateStd(self, s, sourceTime):
"""
test if giving C{s} matched CRE_DATE, used by L{parse()}
@type s: string
@param s: date/time text to evaluate
@type sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base
... | [
"def",
"_partialParseDateStd",
"(",
"self",
",",
"s",
",",
"sourceTime",
")",
":",
"parseStr",
"=",
"None",
"chunk1",
"=",
"chunk2",
"=",
"''",
"# Standard date format",
"m",
"=",
"self",
".",
"ptc",
".",
"CRE_DATE",
".",
"search",
"(",
"s",
")",
"if",
... | 31.675676 | 0.001656 |
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _con... | [
"def",
"alter_db",
"(",
"name",
",",
"character_set",
"=",
"None",
",",
"collate",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"dbc",
"=",
"_connect",
"(",
"*",
"*",
"connection_args",
")",
"if",
"dbc",
"is",
"None",
":",
"return",
"[",
... | 31.772727 | 0.001389 |
def get_nodes(graph: BELGraph, node_predicates: NodePredicates) -> Set[BaseEntity]:
"""Get the set of all nodes that pass the predicates."""
return set(filter_nodes(graph, node_predicates=node_predicates)) | [
"def",
"get_nodes",
"(",
"graph",
":",
"BELGraph",
",",
"node_predicates",
":",
"NodePredicates",
")",
"->",
"Set",
"[",
"BaseEntity",
"]",
":",
"return",
"set",
"(",
"filter_nodes",
"(",
"graph",
",",
"node_predicates",
"=",
"node_predicates",
")",
")"
] | 70.333333 | 0.00939 |
def laplacian_reordering(G):
'''Reorder vertices using the eigenvector of the graph Laplacian corresponding
to the first positive eigenvalue.'''
L = G.laplacian()
vals, vecs = np.linalg.eigh(L)
min_positive_idx = np.argmax(vals == vals[vals>0].min())
vec = vecs[:, min_positive_idx]
return permute_graph(G,... | [
"def",
"laplacian_reordering",
"(",
"G",
")",
":",
"L",
"=",
"G",
".",
"laplacian",
"(",
")",
"vals",
",",
"vecs",
"=",
"np",
".",
"linalg",
".",
"eigh",
"(",
"L",
")",
"min_positive_idx",
"=",
"np",
".",
"argmax",
"(",
"vals",
"==",
"vals",
"[",
... | 41.25 | 0.026706 |
def replaceall(table, a, b, **kwargs):
"""
Convenience function to replace all instances of `a` with `b` under all
fields. See also :func:`convertall`.
The ``where`` keyword argument can be given with a callable or expression
which is evaluated on each row and which should return True if the
co... | [
"def",
"replaceall",
"(",
"table",
",",
"a",
",",
"b",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"convertall",
"(",
"table",
",",
"{",
"a",
":",
"b",
"}",
",",
"*",
"*",
"kwargs",
")"
] | 34.75 | 0.002336 |
def pad(self, *args, **kwargs):
"""Apply a padding to each segment in this `DataQualityFlag`
This method either takes no arguments, in which case the value of
the :attr:`~DataQualityFlag.padding` attribute will be used,
or two values representing the padding for the start and end of
... | [
"def",
"pad",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"start",
",",
"end",
"=",
"self",
".",
"padding",
"else",
":",
"start",
",",
"end",
"=",
"args",
"if",
"kwargs",
".",
"pop",
"(",
"'inplac... | 37 | 0.00112 |
def preprocess(pipeline, args):
"""Transfrom csv data into transfromed tf.example files.
Outline:
1) read the input data (as csv or bigquery) into a dict format
2) replace image paths with base64 encoded image files
3) build a csv input string with images paths replaced with base64. This
matche... | [
"def",
"preprocess",
"(",
"pipeline",
",",
"args",
")",
":",
"from",
"tensorflow",
".",
"python",
".",
"lib",
".",
"io",
"import",
"file_io",
"from",
"trainer",
"import",
"feature_transforms",
"schema",
"=",
"json",
".",
"loads",
"(",
"file_io",
".",
"read... | 39.776316 | 0.010006 |
def read(self, primary_key):
'''
a method to retrieve the details for a record in the table
:param primary_key: string with primary key of record
:return: dictionary with record fields
'''
title = '%s.read' % self.__class__.__name__
... | [
"def",
"read",
"(",
"self",
",",
"primary_key",
")",
":",
"title",
"=",
"'%s.read'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# retrieve record object",
"# record_object = self.session.query(self.record).filter_by(id=primary_key).first()",
"select_statement",
"=",
"... | 38.545455 | 0.017261 |
def _find_url_name(self, index_url, url_name, req):
"""
Finds the true URL name of a package, when the given name isn't quite
correct.
This is usually used to implement case-insensitivity.
"""
if not index_url.url.endswith('/'):
# Vaguely part of the PyPI API.... | [
"def",
"_find_url_name",
"(",
"self",
",",
"index_url",
",",
"url_name",
",",
"req",
")",
":",
"if",
"not",
"index_url",
".",
"url",
".",
"endswith",
"(",
"'/'",
")",
":",
"# Vaguely part of the PyPI API... weird but true.",
"# FIXME: bad to modify this?",
"index_ur... | 39.73913 | 0.002137 |
def div( txt, *args, **kwargs ):
"""
Create & return an HTML <div> element by wrapping the passed text buffer.
@param txt (basestring): the text buffer to use
@param *args (list): if present, \c txt is considered a Python format
string, and the arguments are formatted into it
@param kw... | [
"def",
"div",
"(",
"txt",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
":",
"txt",
"=",
"txt",
".",
"format",
"(",
"*",
"args",
")",
"css",
"=",
"kwargs",
".",
"get",
"(",
"'css'",
",",
"HTML_DIV_CLASS",
")",
"return",
"u'... | 42.384615 | 0.017762 |
def compute_samples_displays_sweep(
self,
program: Union[circuits.Circuit, schedules.Schedule],
params: Optional[study.Sweepable] = None
) -> List[study.ComputeDisplaysResult]:
"""Computes SamplesDisplays in the supplied Circuit or Schedule.
In contrast to `compu... | [
"def",
"compute_samples_displays_sweep",
"(",
"self",
",",
"program",
":",
"Union",
"[",
"circuits",
".",
"Circuit",
",",
"schedules",
".",
"Schedule",
"]",
",",
"params",
":",
"Optional",
"[",
"study",
".",
"Sweepable",
"]",
"=",
"None",
")",
"->",
"List"... | 44.877551 | 0.00178 |
def sjuncChunk(key, chunk):
"""
Parse Super Junction (SJUNC) Chunk Method
"""
schunk = chunk[0].strip().split()
result = {'sjuncNumber': schunk[1],
'groundSurfaceElev': schunk[2],
'invertElev': schunk[3],
'manholeSA': schunk[4],
'inletCode': s... | [
"def",
"sjuncChunk",
"(",
"key",
",",
"chunk",
")",
":",
"schunk",
"=",
"chunk",
"[",
"0",
"]",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"result",
"=",
"{",
"'sjuncNumber'",
":",
"schunk",
"[",
"1",
"]",
",",
"'groundSurfaceElev'",
":",
"sch... | 29.352941 | 0.001942 |
def _download_http_url(link, session, temp_dir):
"""Download link url into temp_dir using provided session"""
target_url = link.url.split('#', 1)[0]
try:
resp = session.get(
target_url,
# We use Accept-Encoding: identity here because requests
# defaults to accepti... | [
"def",
"_download_http_url",
"(",
"link",
",",
"session",
",",
"temp_dir",
")",
":",
"target_url",
"=",
"link",
".",
"url",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"[",
"0",
"]",
"try",
":",
"resp",
"=",
"session",
".",
"get",
"(",
"target_url",
"... | 46.385965 | 0.00037 |
def galcenrect_to_XYZ_jac(*args,**kwargs):
"""
NAME:
galcenrect_to_XYZ_jac
PURPOSE:
calculate the Jacobian of the Galactocentric rectangular to Galactic coordinates
INPUT:
X,Y,Z- Galactocentric rectangular coordinates
vX, vY, vZ- Galactocentric rectangular velocities
... | [
"def",
"galcenrect_to_XYZ_jac",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"Xsun",
"=",
"kwargs",
".",
"get",
"(",
"'Xsun'",
",",
"1.",
")",
"dgc",
"=",
"nu",
".",
"sqrt",
"(",
"Xsun",
"**",
"2.",
"+",
"kwargs",
".",
"get",
"(",
"'Zsun'... | 21.854167 | 0.031022 |
def deterministic_from_funcs(
name, eval, jacobians={}, jacobian_formats={}, dtype=np.float, mv=False):
"""
Return a Stochastic subclass made from a particular distribution.
:Parameters:
name : string
The name of the new class.
jacobians : function
The log-probability fu... | [
"def",
"deterministic_from_funcs",
"(",
"name",
",",
"eval",
",",
"jacobians",
"=",
"{",
"}",
",",
"jacobian_formats",
"=",
"{",
"}",
",",
"dtype",
"=",
"np",
".",
"float",
",",
"mv",
"=",
"False",
")",
":",
"(",
"args",
",",
"defaults",
")",
"=",
... | 33.472222 | 0.002419 |
def group_to_gid(group):
'''
Convert the group to the gid on this system
Under Windows, because groups are just another ACL entity, this function
behaves the same as user_to_uid, except if None is given, '' is returned.
For maintaining Windows systems, this function is superfluous and only
exi... | [
"def",
"group_to_gid",
"(",
"group",
")",
":",
"func_name",
"=",
"'{0}.group_to_gid'",
".",
"format",
"(",
"__virtualname__",
")",
"if",
"__opts__",
".",
"get",
"(",
"'fun'",
",",
"''",
")",
"==",
"func_name",
":",
"log",
".",
"info",
"(",
"'The function %... | 29.939394 | 0.00098 |
def log_request(self, handler):
"""Writes a completed HTTP request to the logs.
By default writes to the tinman.application LOGGER. To change
this behavior either subclass Application and override this method,
or pass a function in the application settings dictionary as
'log_fu... | [
"def",
"log_request",
"(",
"self",
",",
"handler",
")",
":",
"if",
"config",
".",
"LOG_FUNCTION",
"in",
"self",
".",
"settings",
":",
"self",
".",
"settings",
"[",
"config",
".",
"LOG_FUNCTION",
"]",
"(",
"handler",
")",
"return",
"if",
"handler",
".",
... | 39.521739 | 0.002148 |
def load(cls, path, fmt=None, backend=None):
r"""Load a graph from a file.
Edge weights are retrieved as an edge attribute named "weight".
Signals are retrieved from node attributes,
and stored in the :attr:`signals` dictionary under the attribute name.
`N`-dimensional signals ... | [
"def",
"load",
"(",
"cls",
",",
"path",
",",
"fmt",
"=",
"None",
",",
"backend",
"=",
"None",
")",
":",
"if",
"fmt",
"is",
"None",
":",
"fmt",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
"if... | 33.95 | 0.000716 |
def migrate(self, host, port, keys, destination_db, timeout,
copy=False, replace=False, auth=None):
"""
Migrate 1 or more keys from the current Redis server to a different
server specified by the ``host``, ``port`` and ``destination_db``.
The ``timeout``, specified in mi... | [
"def",
"migrate",
"(",
"self",
",",
"host",
",",
"port",
",",
"keys",
",",
"destination_db",
",",
"timeout",
",",
"copy",
"=",
"False",
",",
"replace",
"=",
"False",
",",
"auth",
"=",
"None",
")",
":",
"keys",
"=",
"list_or_args",
"(",
"keys",
",",
... | 40.147059 | 0.002146 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.