text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def validate(self, formats_dir="../formats/"):
"""checks if the document is valid"""
#TODO: download XSD from web
if self.inline:
xmlschema = ElementTree.XMLSchema(ElementTree.parse(StringIO("\n".join(open(formats_dir+"dcoi-dsc.xsd").readlines()))))
xmlschema.assertValid(... | [
"def",
"validate",
"(",
"self",
",",
"formats_dir",
"=",
"\"../formats/\"",
")",
":",
"#TODO: download XSD from web",
"if",
"self",
".",
"inline",
":",
"xmlschema",
"=",
"ElementTree",
".",
"XMLSchema",
"(",
"ElementTree",
".",
"parse",
"(",
"StringIO",
"(",
"... | 57.1 | 0.010345 |
def main(args):
of = sys.stdout
if args.output and args.output[-4:] == '.bam':
cmd = 'samtools view -Sb - -o '+args.output
pof = Popen(cmd.split(),stdin=PIPE)
of = pof.stdin
elif args.output:
of = open(args.output,'w')
"""Use the valid input file to get the header information."""
header = Non... | [
"def",
"main",
"(",
"args",
")",
":",
"of",
"=",
"sys",
".",
"stdout",
"if",
"args",
".",
"output",
"and",
"args",
".",
"output",
"[",
"-",
"4",
":",
"]",
"==",
"'.bam'",
":",
"cmd",
"=",
"'samtools view -Sb - -o '",
"+",
"args",
".",
"output",
"po... | 36.272727 | 0.019034 |
def absolute_distance(cls, q0, q1):
"""Quaternion absolute distance.
Find the distance between two quaternions accounting for the sign ambiguity.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive scalar corresponding to t... | [
"def",
"absolute_distance",
"(",
"cls",
",",
"q0",
",",
"q1",
")",
":",
"q0_minus_q1",
"=",
"q0",
"-",
"q1",
"q0_plus_q1",
"=",
"q0",
"+",
"q1",
"d_minus",
"=",
"q0_minus_q1",
".",
"norm",
"d_plus",
"=",
"q0_plus_q1",
".",
"norm",
"if",
"(",
"d_minus",... | 32.461538 | 0.008055 |
def add_ago_to_since(since: str) -> str:
"""
Backwards compatibility hack. Without this slices with since: 7 days will
be treated as 7 days in the future.
:param str since:
:returns: Since with ago added if necessary
:rtype: str
"""
since_words = since.split(' ')
grains = ['days', '... | [
"def",
"add_ago_to_since",
"(",
"since",
":",
"str",
")",
"->",
"str",
":",
"since_words",
"=",
"since",
".",
"split",
"(",
"' '",
")",
"grains",
"=",
"[",
"'days'",
",",
"'years'",
",",
"'hours'",
",",
"'day'",
",",
"'year'",
",",
"'weeks'",
"]",
"i... | 32.071429 | 0.002165 |
def encode_network(root):
"""Yield ref-containing obj table entries from object network"""
orig_objects = []
objects = []
def get_ref(value, objects=objects):
"""Returns the index of the given object in the object table,
adding it if needed.
"""
value = PythonicAdapter(... | [
"def",
"encode_network",
"(",
"root",
")",
":",
"orig_objects",
"=",
"[",
"]",
"objects",
"=",
"[",
"]",
"def",
"get_ref",
"(",
"value",
",",
"objects",
"=",
"objects",
")",
":",
"\"\"\"Returns the index of the given object in the object table,\n adding it if n... | 30.719512 | 0.002308 |
def start_tls(
self,
server_side: bool,
ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None,
server_hostname: str = None,
) -> Awaitable["SSLIOStream"]:
"""Convert this `IOStream` to an `SSLIOStream`.
This enables protocols that begin in clear-text mode and
... | [
"def",
"start_tls",
"(",
"self",
",",
"server_side",
":",
"bool",
",",
"ssl_options",
":",
"Union",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"ssl",
".",
"SSLContext",
"]",
"=",
"None",
",",
"server_hostname",
":",
"str",
"=",
"None",
",",
")",
... | 38.626667 | 0.00101 |
def save(self, inplace=True):
"""
Saves all modification to the marker on the server.
:param inplace Apply edits on the current instance or get a new one.
:return: Marker instance.
"""
modified_data = self._modified_data()
if bool(modified_data):
extra... | [
"def",
"save",
"(",
"self",
",",
"inplace",
"=",
"True",
")",
":",
"modified_data",
"=",
"self",
".",
"_modified_data",
"(",
")",
"if",
"bool",
"(",
"modified_data",
")",
":",
"extra",
"=",
"{",
"'resource'",
":",
"self",
".",
"__class__",
".",
"__name... | 37.454545 | 0.002367 |
def _build_message(self, message):
"""A helper method to convert a PMEmailMessage to a PMMail"""
if not message.recipients():
return False
recipients = ','.join(message.to)
recipients_cc = ','.join(message.cc)
recipients_bcc = ','.join(message.bcc)
text_body ... | [
"def",
"_build_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"message",
".",
"recipients",
"(",
")",
":",
"return",
"False",
"recipients",
"=",
"','",
".",
"join",
"(",
"message",
".",
"to",
")",
"recipients_cc",
"=",
"','",
".",
"join"... | 44.616667 | 0.000731 |
def link_contentkey_authorization_policy(access_token, ckap_id, options_id, \
ams_redirected_rest_endpoint):
'''Link Media Service Content Key Authorization Policy.
Args:
access_token (str): A valid Azure authentication token.
ckap_id (str): A Media Service Asset Content Key Authorization Polic... | [
"def",
"link_contentkey_authorization_policy",
"(",
"access_token",
",",
"ckap_id",
",",
"options_id",
",",
"ams_redirected_rest_endpoint",
")",
":",
"path",
"=",
"'/ContentKeyAuthorizationPolicies'",
"full_path",
"=",
"''",
".",
"join",
"(",
"[",
"path",
",",
"\"('\"... | 48.809524 | 0.009569 |
def getter_generator(field_name, short_description):
"""
Generate get_'field name' method for field field_name.
"""
def get_translation_field(cls, language_code=None, fallback=False):
try:
return cls.get_translation(language_code,
fallback=fallb... | [
"def",
"getter_generator",
"(",
"field_name",
",",
"short_description",
")",
":",
"def",
"get_translation_field",
"(",
"cls",
",",
"language_code",
"=",
"None",
",",
"fallback",
"=",
"False",
")",
":",
"try",
":",
"return",
"cls",
".",
"get_translation",
"(",
... | 40.769231 | 0.001845 |
def _get_guidelines(self):
"""
Subclasses may override this method.
"""
return tuple([self._getitem__guidelines(i) for
i in range(self._len__guidelines())]) | [
"def",
"_get_guidelines",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"[",
"self",
".",
"_getitem__guidelines",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_len__guidelines",
"(",
")",
")",
"]",
")"
] | 34 | 0.009569 |
def get_crimes_no_location(self, force, date=None, category=None):
"""
Get crimes with no location for a force. Uses the crimes-no-location_
API call.
.. _crimes-no-location:
https://data.police.uk/docs/method/crimes-no-location/
:rtype: list
:param force: T... | [
"def",
"get_crimes_no_location",
"(",
"self",
",",
"force",
",",
"date",
"=",
"None",
",",
"category",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"force",
",",
"Force",
")",
":",
"force",
"=",
"Force",
"(",
"self",
",",
"id",
"=",
"force"... | 37.973684 | 0.001351 |
def _consolidate(data_type):
"""Enforce the structure of the data type.
Specifically, ensure that if a field is defined as a generic tuple, then it
will be converted into an instance of `Field`.
"""
if isinstance(data_type, _ATOMIC):
out = data_type
elif isinstance(data_type, Array):
... | [
"def",
"_consolidate",
"(",
"data_type",
")",
":",
"if",
"isinstance",
"(",
"data_type",
",",
"_ATOMIC",
")",
":",
"out",
"=",
"data_type",
"elif",
"isinstance",
"(",
"data_type",
",",
"Array",
")",
":",
"element_type",
"=",
"_consolidate",
"(",
"data_type",... | 37.15 | 0.001312 |
def check_bidi(chars):
"""
Check proper bidirectionality as per stringprep. Operates on a list of
unicode characters provided in `chars`.
"""
# the empty string is valid, as it cannot violate the RandALCat constraints
if not chars:
return
# first_is_RorAL = unicodedata.bidirectiona... | [
"def",
"check_bidi",
"(",
"chars",
")",
":",
"# the empty string is valid, as it cannot violate the RandALCat constraints",
"if",
"not",
"chars",
":",
"return",
"# first_is_RorAL = unicodedata.bidirectional(chars[0]) in {\"R\", \"AL\"}",
"# if first_is_RorAL:",
"has_RandALCat",
"=",
... | 32.041667 | 0.001263 |
def extend_rows(self, list_or_dict):
""" Add multiple rows at once
:param list_or_dict: a 2 dimensional structure for adding multiple rows at once
:return:
"""
if isinstance(list_or_dict, list):
for r in list_or_dict:
self.add_row(r)
else:
... | [
"def",
"extend_rows",
"(",
"self",
",",
"list_or_dict",
")",
":",
"if",
"isinstance",
"(",
"list_or_dict",
",",
"list",
")",
":",
"for",
"r",
"in",
"list_or_dict",
":",
"self",
".",
"add_row",
"(",
"r",
")",
"else",
":",
"for",
"k",
",",
"r",
"in",
... | 32.416667 | 0.01 |
def list_configured_members(lbn, profile='default'):
'''
Return a list of member workers from the configuration files
CLI Examples:
.. code-block:: bash
salt '*' modjk.list_configured_members loadbalancer1
salt '*' modjk.list_configured_members loadbalancer1 other-profile
'''
... | [
"def",
"list_configured_members",
"(",
"lbn",
",",
"profile",
"=",
"'default'",
")",
":",
"config",
"=",
"dump_config",
"(",
"profile",
")",
"try",
":",
"ret",
"=",
"config",
"[",
"'worker.{0}.balance_workers'",
".",
"format",
"(",
"lbn",
")",
"]",
"except",... | 24.95 | 0.001931 |
def intervals_to_durations(intervals):
"""Converts an array of n intervals to their n durations.
Parameters
----------
intervals : np.ndarray, shape=(n, 2)
An array of time intervals, as returned by
:func:`mir_eval.io.load_intervals()`.
The ``i`` th interval spans time ``interva... | [
"def",
"intervals_to_durations",
"(",
"intervals",
")",
":",
"validate_intervals",
"(",
"intervals",
")",
"return",
"np",
".",
"abs",
"(",
"np",
".",
"diff",
"(",
"intervals",
",",
"axis",
"=",
"-",
"1",
")",
")",
".",
"flatten",
"(",
")"
] | 29.263158 | 0.001742 |
def calc_el_lz_v1(self):
"""Calculate lake evaporation.
Required control parameters:
|NmbZones|
|ZoneType|
|TTIce|
Required derived parameters:
|RelZoneArea|
Required fluxes sequences:
|TC|
|EPC|
Updated state sequence:
|LZ|
Basic equa... | [
"def",
"calc_el_lz_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
... | 28.944444 | 0.000464 |
def requires_open_handle(method): # pylint: disable=invalid-name
"""Decorator to ensure a handle is open for certain methods.
Subclasses should decorate their Read() and Write() with this rather than
checking their own internal state, keeping all "is this handle open" logic
in is_closed().
Args:
method... | [
"def",
"requires_open_handle",
"(",
"method",
")",
":",
"# pylint: disable=invalid-name",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper_requiring_open_handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"The wra... | 33.708333 | 0.008413 |
def get_indicator(self, time, code, indicator_name=None):
"""
获取某一时间的某一只股票的指标
"""
try:
return self.data.loc[(pd.Timestamp(time), code), indicator_name]
except:
raise ValueError('CANNOT FOUND THIS DATE&CODE') | [
"def",
"get_indicator",
"(",
"self",
",",
"time",
",",
"code",
",",
"indicator_name",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"loc",
"[",
"(",
"pd",
".",
"Timestamp",
"(",
"time",
")",
",",
"code",
")",
",",
"indicato... | 33 | 0.01107 |
def serveInBackground(port, serverName, prefix='/status/'):
"""Convenience function: spawn a background server thread that will
serve HTTP requests to get the status. Returns the thread."""
import flask, threading
from wsgiref.simple_server import make_server
app = flask.Flask(__name__)
registerStatsHandler... | [
"def",
"serveInBackground",
"(",
"port",
",",
"serverName",
",",
"prefix",
"=",
"'/status/'",
")",
":",
"import",
"flask",
",",
"threading",
"from",
"wsgiref",
".",
"simple_server",
"import",
"make_server",
"app",
"=",
"flask",
".",
"Flask",
"(",
"__name__",
... | 42.545455 | 0.023013 |
def upload(import_path, verbose=False, skip_subfolders=False, number_threads=None, max_attempts=None, video_import_path=None, dry_run=False,api_version=1.0):
'''
Upload local images to Mapillary
Args:
import_path: Directory path to where the images are stored.
verbose: Print extra warnings a... | [
"def",
"upload",
"(",
"import_path",
",",
"verbose",
"=",
"False",
",",
"skip_subfolders",
"=",
"False",
",",
"number_threads",
"=",
"None",
",",
"max_attempts",
"=",
"None",
",",
"video_import_path",
"=",
"None",
",",
"dry_run",
"=",
"False",
",",
"api_vers... | 47.680672 | 0.002244 |
def dirs(self):
"""Get an iter of VenvDirs within the directory."""
contents = self.paths
contents = (BinDir(path.path) for path in contents if path.is_dir)
return contents | [
"def",
"dirs",
"(",
"self",
")",
":",
"contents",
"=",
"self",
".",
"paths",
"contents",
"=",
"(",
"BinDir",
"(",
"path",
".",
"path",
")",
"for",
"path",
"in",
"contents",
"if",
"path",
".",
"is_dir",
")",
"return",
"contents"
] | 40 | 0.009804 |
def get_snapshot(name, config_path=_DEFAULT_CONFIG_PATH, with_packages=False):
'''
Get detailed information about a snapshot.
:param str name: The name of the snapshot given during snapshot creation.
:param str config_path: The path to the configuration file for the aptly instance.
:param bool with... | [
"def",
"get_snapshot",
"(",
"name",
",",
"config_path",
"=",
"_DEFAULT_CONFIG_PATH",
",",
"with_packages",
"=",
"False",
")",
":",
"_validate_config",
"(",
"config_path",
")",
"sources",
"=",
"list",
"(",
")",
"cmd",
"=",
"[",
"'snapshot'",
",",
"'show'",
",... | 27.257143 | 0.002024 |
def fromordinal(cls, ordinal):
"""Return the week corresponding to the proleptic Gregorian ordinal,
where January 1 of year 1 starts the week with ordinal 1.
"""
if ordinal < 1:
raise ValueError("ordinal must be >= 1")
return super(Week, cls).__new__(cls, *(date.fromo... | [
"def",
"fromordinal",
"(",
"cls",
",",
"ordinal",
")",
":",
"if",
"ordinal",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"ordinal must be >= 1\"",
")",
"return",
"super",
"(",
"Week",
",",
"cls",
")",
".",
"__new__",
"(",
"cls",
",",
"*",
"(",
"date",... | 51.571429 | 0.008174 |
def python_sidebar(python_input):
"""
Create the `Layout` for the sidebar with the configurable options.
"""
def get_text_fragments():
tokens = []
def append_category(category):
tokens.extend([
('class:sidebar', ' '),
('class:sidebar.title', ... | [
"def",
"python_sidebar",
"(",
"python_input",
")",
":",
"def",
"get_text_fragments",
"(",
")",
":",
"tokens",
"=",
"[",
"]",
"def",
"append_category",
"(",
"category",
")",
":",
"tokens",
".",
"extend",
"(",
"[",
"(",
"'class:sidebar'",
",",
"' '",
")",
... | 33.865672 | 0.001713 |
def des(clas,keyblob,valblob):
"deserialize. translate publish message, basically"
raise NotImplementedError("don't use tuples, it breaks __eq__. this function probably isn't used in real life")
raw_keyvals=msgpack.loads(keyblob)
(namespace,version),keyvals=raw_keyvals[:2],raw_keyvals[2:]
if na... | [
"def",
"des",
"(",
"clas",
",",
"keyblob",
",",
"valblob",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"don't use tuples, it breaks __eq__. this function probably isn't used in real life\"",
")",
"raw_keyvals",
"=",
"msgpack",
".",
"loads",
"(",
"keyblob",
")",
"("... | 59.272727 | 0.034743 |
def ensure_index_from_sequences(sequences, names=None):
"""
Construct an index from sequences of data.
A single sequence returns an Index. Many sequences returns a
MultiIndex.
Parameters
----------
sequences : sequence of sequences
names : sequence of str
Returns
-------
i... | [
"def",
"ensure_index_from_sequences",
"(",
"sequences",
",",
"names",
"=",
"None",
")",
":",
"from",
".",
"multi",
"import",
"MultiIndex",
"if",
"len",
"(",
"sequences",
")",
"==",
"1",
":",
"if",
"names",
"is",
"not",
"None",
":",
"names",
"=",
"names",... | 25.205128 | 0.000979 |
def load():
"""Loads the libzar shared library and its dependencies.
"""
if 'Windows' == platform.system():
# Possible scenarios here
# 1. Run from source, DLLs are in pyzbar directory
# cdll.LoadLibrary() imports DLLs in repo root directory
# 2. Wheel install into ... | [
"def",
"load",
"(",
")",
":",
"if",
"'Windows'",
"==",
"platform",
".",
"system",
"(",
")",
":",
"# Possible scenarios here",
"# 1. Run from source, DLLs are in pyzbar directory",
"# cdll.LoadLibrary() imports DLLs in repo root directory",
"# 2. Wheel install into CPython... | 38.27027 | 0.000689 |
def set_id(device, minor, system_id):
'''
Sets the system ID for the partition. Some typical values are::
b: FAT32 (vfat)
7: HPFS/NTFS
82: Linux Swap
83: Linux
8e: Linux LVM
fd: Linux RAID Auto
CLI Example:
.. code-block:: bash
salt '*' parti... | [
"def",
"set_id",
"(",
"device",
",",
"minor",
",",
"system_id",
")",
":",
"_validate_device",
"(",
"device",
")",
"try",
":",
"int",
"(",
"minor",
")",
"except",
"Exception",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid minor number passed to partition.se... | 23.411765 | 0.001206 |
def parse_localinstancepath(self, tup_tree):
"""
Parse a LOCALINSTANCEPATH element and return the instance path it
represents as a CIMInstanceName object.
::
<!ELEMENT LOCALINSTANCEPATH (LOCALNAMESPACEPATH, INSTANCENAME)>
"""
self.check_node(tup_tree, 'LO... | [
"def",
"parse_localinstancepath",
"(",
"self",
",",
"tup_tree",
")",
":",
"self",
".",
"check_node",
"(",
"tup_tree",
",",
"'LOCALINSTANCEPATH'",
")",
"k",
"=",
"kids",
"(",
"tup_tree",
")",
"if",
"len",
"(",
"k",
")",
"!=",
"2",
":",
"raise",
"CIMXMLPar... | 31.814815 | 0.00226 |
def get_objective_mdata():
"""Return default mdata map for Objective"""
return {
'cognitive_process': {
'element_label': {
'text': 'cognitive process',
'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
... | [
"def",
"get_objective_mdata",
"(",
")",
":",
"return",
"{",
"'cognitive_process'",
":",
"{",
"'element_label'",
":",
"{",
"'text'",
":",
"'cognitive process'",
",",
"'languageTypeId'",
":",
"str",
"(",
"DEFAULT_LANGUAGE_TYPE",
")",
",",
"'scriptTypeId'",
":",
"str... | 36.19403 | 0.000401 |
def set(self, class_name, state, key, value):
"""Set a single style value for a view class and state.
class_name
The name of the class to be styled; do not
include the package name; e.g. 'Button'.
state
The name of the state to be stylized. One of the
... | [
"def",
"set",
"(",
"self",
",",
"class_name",
",",
"state",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_styles",
".",
"setdefault",
"(",
"class_name",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"state",
",",
"{",
"}",
")",
"self",
".",
"_... | 28.740741 | 0.002494 |
def status(config):
"""time series lastest record time by account."""
with open(config) as fh:
config = yaml.safe_load(fh.read())
jsonschema.validate(config, CONFIG_SCHEMA)
last_index = get_incremental_starts(config, None)
accounts = {}
for (a, region), last in last_index.items():
... | [
"def",
"status",
"(",
"config",
")",
":",
"with",
"open",
"(",
"config",
")",
"as",
"fh",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"fh",
".",
"read",
"(",
")",
")",
"jsonschema",
".",
"validate",
"(",
"config",
",",
"CONFIG_SCHEMA",
")",
... | 41.6 | 0.002353 |
def jwt_proccessor():
"""Context processor for jwt."""
def jwt():
"""Context processor function to generate jwt."""
token = current_accounts.jwt_creation_factory()
return Markup(
render_template(
current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'],
... | [
"def",
"jwt_proccessor",
"(",
")",
":",
"def",
"jwt",
"(",
")",
":",
"\"\"\"Context processor function to generate jwt.\"\"\"",
"token",
"=",
"current_accounts",
".",
"jwt_creation_factory",
"(",
")",
"return",
"Markup",
"(",
"render_template",
"(",
"current_app",
"."... | 27.5 | 0.001757 |
def normalize_filename(string):
"""Normalize the filename
:param string: A string to normalize
:type string: str
:returns: Normalized ID
:rtype: str
"""
if not isinstance(string, basestring):
fail("Type of argument must be string, found '{}'"
.format(type(string)))
... | [
"def",
"normalize_filename",
"(",
"string",
")",
":",
"if",
"not",
"isinstance",
"(",
"string",
",",
"basestring",
")",
":",
"fail",
"(",
"\"Type of argument must be string, found '{}'\"",
".",
"format",
"(",
"type",
"(",
"string",
")",
")",
")",
"# get the file... | 30.571429 | 0.002268 |
def get_connection(self, name):
"""Returns the properties for a connection name
This method will return the settings for the configuration specified
by name. Note that the name argument should only be the name.
For instance, give the following eapi.conf file
.. code-block:: i... | [
"def",
"get_connection",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"'connection:{}'",
".",
"format",
"(",
"name",
")",
"if",
"not",
"self",
".",
"has_section",
"(",
"name",
")",
":",
"return",
"None",
"return",
"dict",
"(",
"self",
".",
"items",... | 32.551724 | 0.002058 |
def do_startInstance(self,args):
"""Start specified instance"""
parser = CommandArgumentParser("startInstance")
parser.add_argument(dest='instance',help='instance index or name');
args = vars(parser.parse_args(args))
instanceId = args['instance']
force = args['force']
... | [
"def",
"do_startInstance",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"startInstance\"",
")",
"parser",
".",
"add_argument",
"(",
"dest",
"=",
"'instance'",
",",
"help",
"=",
"'instance index or name'",
")",
"args",
"=",
... | 38.294118 | 0.008996 |
def format(self, record):
"""Space debug messages for more legibility."""
if record.levelno == logging.DEBUG:
record.msg = ' {}'.format(record.msg)
return super(AuditLogFormatter, self).format(record) | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"if",
"record",
".",
"levelno",
"==",
"logging",
".",
"DEBUG",
":",
"record",
".",
"msg",
"=",
"' {}'",
".",
"format",
"(",
"record",
".",
"msg",
")",
"return",
"super",
"(",
"AuditLogFormatter",
... | 46.4 | 0.008475 |
def load_factory(name, directory, configuration=None):
""" Load a factory and have it initialize in a particular directory
:param name: the name of the plugin to load
:param directory: the directory where the factory will reside
:return:
"""
for entry_point in pkg_resources.iter_entry_points(ENT... | [
"def",
"load_factory",
"(",
"name",
",",
"directory",
",",
"configuration",
"=",
"None",
")",
":",
"for",
"entry_point",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"ENTRY_POINT",
")",
":",
"if",
"entry_point",
".",
"name",
"==",
"name",
":",
"fact... | 41.25 | 0.001976 |
def collect_history(self):
"""Build the structure of results in terms of a commit history."""
def format_data(data):
"""Format result data according to the user-defined type."""
# TODO Remove this failsafe once proper error handling is in place.
if type == "percent" o... | [
"def",
"collect_history",
"(",
"self",
")",
":",
"def",
"format_data",
"(",
"data",
")",
":",
"\"\"\"Format result data according to the user-defined type.\"\"\"",
"# TODO Remove this failsafe once proper error handling is in place.",
"if",
"type",
"==",
"\"percent\"",
"or",
"d... | 51.712121 | 0.000575 |
def await_idle(self, parent_id, timeout):
"""Poll the iopub stream until an idle message is received for the given parent ID"""
while True:
# Get a message from the kernel iopub channel
msg = self.get_message(timeout=timeout, stream='iopub') # raises Empty on timeout!
... | [
"def",
"await_idle",
"(",
"self",
",",
"parent_id",
",",
"timeout",
")",
":",
"while",
"True",
":",
"# Get a message from the kernel iopub channel",
"msg",
"=",
"self",
".",
"get_message",
"(",
"timeout",
"=",
"timeout",
",",
"stream",
"=",
"'iopub'",
")",
"# ... | 47.454545 | 0.009398 |
def make_figs(dcfg,dp='figs',force=False):
"""
'figi','plotp'
"""
doutp=abspath(dp)
if isinstance(dcfg,str):
dcfg=pd.read_table(dcfg,
error_bad_lines=False,
comment='#',)
# .dropna(subset=['figi','fign','plotn','plotp'])
dc... | [
"def",
"make_figs",
"(",
"dcfg",
",",
"dp",
"=",
"'figs'",
",",
"force",
"=",
"False",
")",
":",
"doutp",
"=",
"abspath",
"(",
"dp",
")",
"if",
"isinstance",
"(",
"dcfg",
",",
"str",
")",
":",
"dcfg",
"=",
"pd",
".",
"read_table",
"(",
"dcfg",
",... | 49.65 | 0.019259 |
def reroot(self, rppr=None, pretend=False):
"""Reroot the phylogenetic tree.
This operation calls ``rppr reroot`` to generate the rerooted
tree, so you must have ``pplacer`` and its auxiliary tools
``rppr`` and ``guppy`` installed for it to work. You can
specify the path to ``r... | [
"def",
"reroot",
"(",
"self",
",",
"rppr",
"=",
"None",
",",
"pretend",
"=",
"False",
")",
":",
"with",
"scratch_file",
"(",
"prefix",
"=",
"'tree'",
",",
"suffix",
"=",
"'.tre'",
")",
"as",
"name",
":",
"# Use a specific path to rppr, otherwise rely on $PATH"... | 44.578947 | 0.002312 |
def to_glyphs_family_user_data_from_ufo(self, ufo):
"""Set the GSFont userData from the UFO family-wide lib data."""
target_user_data = self.font.userData
try:
for key, value in ufo.lib[FONT_USER_DATA_KEY].items():
# Existing values taken from the designspace lib take precedence
... | [
"def",
"to_glyphs_family_user_data_from_ufo",
"(",
"self",
",",
"ufo",
")",
":",
"target_user_data",
"=",
"self",
".",
"font",
".",
"userData",
"try",
":",
"for",
"key",
",",
"value",
"in",
"ufo",
".",
"lib",
"[",
"FONT_USER_DATA_KEY",
"]",
".",
"items",
"... | 42.818182 | 0.002079 |
def forward(self, serial, remote, local_port=None): #local_port, remote_port=None):
'''
Args:
serial (str): device serial number
remote (str|int): A int means device port, str can be localabstract:service-name
local_port (int): optional, if not given, a random port wi... | [
"def",
"forward",
"(",
"self",
",",
"serial",
",",
"remote",
",",
"local_port",
"=",
"None",
")",
":",
"#local_port, remote_port=None):",
"if",
"isinstance",
"(",
"remote",
",",
"int",
")",
":",
"remote",
"=",
"'tcp:%d'",
"%",
"remote",
"if",
"not",
"local... | 42.681818 | 0.0125 |
def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None,
profile=None):
'''
Revoke a grant from a key.
CLI example::
salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j...
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
... | [
"def",
"revoke_grant",
"(",
"key_id",
",",
"grant_id",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"... | 28.666667 | 0.001608 |
def items(self, founditems=[]): #pylint: disable=dangerous-default-value
"""Returns a depth-first flat list of *all* items below this element (not limited to AbstractElement)"""
l = []
for e in self.data:
if e not in founditems: #prevent going in recursive loops
l.ap... | [
"def",
"items",
"(",
"self",
",",
"founditems",
"=",
"[",
"]",
")",
":",
"#pylint: disable=dangerous-default-value",
"l",
"=",
"[",
"]",
"for",
"e",
"in",
"self",
".",
"data",
":",
"if",
"e",
"not",
"in",
"founditems",
":",
"#prevent going in recursive loops... | 47 | 0.023202 |
def preview(file):
"""Render appropriate template with embed flag."""
params = deepcopy(current_app.config['IIIF_PREVIEWER_PARAMS'])
if 'image_format' not in params:
params['image_format'] = \
'png' if file.has_extensions('.png') else 'jpg'
return render_template(
current_app... | [
"def",
"preview",
"(",
"file",
")",
":",
"params",
"=",
"deepcopy",
"(",
"current_app",
".",
"config",
"[",
"'IIIF_PREVIEWER_PARAMS'",
"]",
")",
"if",
"'image_format'",
"not",
"in",
"params",
":",
"params",
"[",
"'image_format'",
"]",
"=",
"'png'",
"if",
"... | 32.5 | 0.002137 |
def d_step(self, true_frames, gen_frames):
"""Performs the discriminator step in computing the GAN loss.
Applies stop-gradient to the generated frames while computing the
discriminator loss to make sure that the gradients are not back-propagated
to the generator. This makes sure that only the discrimin... | [
"def",
"d_step",
"(",
"self",
",",
"true_frames",
",",
"gen_frames",
")",
":",
"hparam_to_disc_loss",
"=",
"{",
"\"least_squares\"",
":",
"gan_losses",
".",
"least_squares_discriminator_loss",
",",
"\"cross_entropy\"",
":",
"gan_losses",
".",
"modified_discriminator_los... | 40.894737 | 0.001257 |
def qteReplaceAppletInLayout(self, newApplet: (QtmacsApplet, str),
oldApplet: (QtmacsApplet, str)=None,
windowObj: QtmacsWindow=None):
"""
Replace ``oldApplet`` with ``newApplet`` in the window layout.
If ``oldApplet`` is **None*... | [
"def",
"qteReplaceAppletInLayout",
"(",
"self",
",",
"newApplet",
":",
"(",
"QtmacsApplet",
",",
"str",
")",
",",
"oldApplet",
":",
"(",
"QtmacsApplet",
",",
"str",
")",
"=",
"None",
",",
"windowObj",
":",
"QtmacsWindow",
"=",
"None",
")",
":",
"# If ``old... | 40.346154 | 0.001861 |
def checksum(file_path, hash_type='md5', block_size=65536):
"""Returns either the md5 or sha256 hash of a file at `file_path`.
md5 is the default hash_type as it is faster than sha256
The default block size is 64 kb, which appears to be one of a few command
choices according to https://stackoverfl... | [
"def",
"checksum",
"(",
"file_path",
",",
"hash_type",
"=",
"'md5'",
",",
"block_size",
"=",
"65536",
")",
":",
"if",
"hash_type",
"==",
"'md5'",
":",
"hash_",
"=",
"hashlib",
".",
"md5",
"(",
")",
"elif",
"hash_type",
"==",
"'sha256'",
":",
"hash_",
"... | 36.130435 | 0.002345 |
def shared_edges(faces_a, faces_b):
"""
Given two sets of faces, find the edges which are in both sets.
Parameters
---------
faces_a: (n,3) int, set of faces
faces_b: (m,3) int, set of faces
Returns
---------
shared: (p, 2) int, set of edges
"""
e_a = np.sort(faces_to_edges... | [
"def",
"shared_edges",
"(",
"faces_a",
",",
"faces_b",
")",
":",
"e_a",
"=",
"np",
".",
"sort",
"(",
"faces_to_edges",
"(",
"faces_a",
")",
",",
"axis",
"=",
"1",
")",
"e_b",
"=",
"np",
".",
"sort",
"(",
"faces_to_edges",
"(",
"faces_b",
")",
",",
... | 27.176471 | 0.002092 |
def build(config):
"""Incremental build of the website"""
logger.info("\nRendering website now...\n")
logger.info("entries:")
tags = dict()
entries = list()
for post, post_id in find_new_posts_and_pages(DB):
# this method will also parse the post's tags and
# update the db collec... | [
"def",
"build",
"(",
"config",
")",
":",
"logger",
".",
"info",
"(",
"\"\\nRendering website now...\\n\"",
")",
"logger",
".",
"info",
"(",
"\"entries:\"",
")",
"tags",
"=",
"dict",
"(",
")",
"entries",
"=",
"list",
"(",
")",
"for",
"post",
",",
"post_id... | 36.904762 | 0.000629 |
def handle_add(queue_name):
"""Adds a task to a queue."""
source = request.form.get('source', request.remote_addr, type=str)
try:
task_id = work_queue.add(
queue_name,
payload=request.form.get('payload', type=str),
content_type=request.form.get('content_type', typ... | [
"def",
"handle_add",
"(",
"queue_name",
")",
":",
"source",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'source'",
",",
"request",
".",
"remote_addr",
",",
"type",
"=",
"str",
")",
"try",
":",
"task_id",
"=",
"work_queue",
".",
"add",
"(",
"queue_na... | 37.882353 | 0.001515 |
def _compat_compare_digest(a, b):
"""Implementation of hmac.compare_digest for python < 2.7.7.
This function uses an approach designed to prevent timing analysis by
avoiding content-based short circuiting behaviour, making it appropriate
for cryptography.
"""
if len(a) != len(b):
return... | [
"def",
"_compat_compare_digest",
"(",
"a",
",",
"b",
")",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"return",
"False",
"# Computes the bitwise difference of all characters in the two strings",
"# before returning whether or not they are equal.",
... | 38.266667 | 0.001701 |
def admin_print_styles(request):
"""
Returns a dictionary of all unique print_styles, and their latest tag,
revision, and recipe_type.
"""
styles = []
# This fetches all recipes that have been used to successfully bake a
# current book plus all default recipes that have not yet been used
... | [
"def",
"admin_print_styles",
"(",
"request",
")",
":",
"styles",
"=",
"[",
"]",
"# This fetches all recipes that have been used to successfully bake a",
"# current book plus all default recipes that have not yet been used",
"# as well as \"bad\" books that are not \"current\" state, but woul... | 46.546875 | 0.000329 |
def _dataframe_fields(self):
"""
Creates a dictionary of all fields to include with DataFrame.
With the result of the calls to class properties changing based on the
class index value, the dictionary should be regenerated every time the
index is changed when the dataframe proper... | [
"def",
"_dataframe_fields",
"(",
"self",
")",
":",
"fields_to_include",
"=",
"{",
"'and_ones'",
":",
"self",
".",
"and_ones",
",",
"'assist_percentage'",
":",
"self",
".",
"assist_percentage",
",",
"'assists'",
":",
"self",
".",
"assists",
",",
"'block_percentag... | 50.991935 | 0.00031 |
def create_class_from_element_tree(target_class, tree, namespace=None,
tag=None):
"""Instantiates the class and populates members according to the tree.
Note: Only use this function with classes that have c_namespace and c_tag
class members.
:param target_class: The ... | [
"def",
"create_class_from_element_tree",
"(",
"target_class",
",",
"tree",
",",
"namespace",
"=",
"None",
",",
"tag",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"namespace",
"=",
"target_class",
".",
"c_namespace",
"if",
"tag",
"is",
"None"... | 41.677419 | 0.001513 |
def Jz(self,*args,**kwargs):
"""
NAME:
Jz
PURPOSE:
evaluate the action jz
INPUT:
Either:
a) R,vR,vT,z,vz
b) Orbit instance: initial condition used if that's it, orbit(t)
if there is a time given as well
... | [
"def",
"Jz",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_parse_eval_args",
"(",
"*",
"args",
")",
"Phi",
"=",
"_evaluatePotentials",
"(",
"self",
".",
"_pot",
",",
"self",
".",
"_eval_R",
",",
"self",
".",
"_eva... | 39.176471 | 0.021245 |
def read_xml(self, file_configuration):
"""parses C++ code, defined on the file_configurations and returns
GCCXML generated file content"""
xml_file_path = None
delete_xml_file = True
fc = file_configuration
reader = source_reader.source_reader_t(
self.__conf... | [
"def",
"read_xml",
"(",
"self",
",",
"file_configuration",
")",
":",
"xml_file_path",
"=",
"None",
"delete_xml_file",
"=",
"True",
"fc",
"=",
"file_configuration",
"reader",
"=",
"source_reader",
".",
"source_reader_t",
"(",
"self",
".",
"__config",
",",
"None",... | 46.711111 | 0.000932 |
def _childgroup(self, children, grid):
"""
Stores the children in a list following the grid's structure
:param children: list of fields
:param grid: a list of list corresponding of the layout to apply to the
given children
"""
result = []
index = 0
... | [
"def",
"_childgroup",
"(",
"self",
",",
"children",
",",
"grid",
")",
":",
"result",
"=",
"[",
"]",
"index",
"=",
"0",
"hidden_fields",
"=",
"[",
"]",
"for",
"row",
"in",
"grid",
":",
"child_row",
"=",
"[",
"]",
"width_sum",
"=",
"0",
"for",
"width... | 35.189655 | 0.000953 |
def xmoe_tr_1d():
"""Mixture of experts (16 experts).
623M Params, einsum=1.09e13
Returns:
a hparams
"""
hparams = xmoe_tr_dense_2k()
hparams.encoder_layers = ["self_att", "moe_1d"] * 4
hparams.decoder_layers = ["self_att", "enc_att", "moe_1d"] * 4
hparams.layout = "batch:batch;experts:batch"
h... | [
"def",
"xmoe_tr_1d",
"(",
")",
":",
"hparams",
"=",
"xmoe_tr_dense_2k",
"(",
")",
"hparams",
".",
"encoder_layers",
"=",
"[",
"\"self_att\"",
",",
"\"moe_1d\"",
"]",
"*",
"4",
"hparams",
".",
"decoder_layers",
"=",
"[",
"\"self_att\"",
",",
"\"enc_att\"",
",... | 23.875 | 0.02267 |
def get_filters(self):
""" Returns a dictionary of filters """
filters = dict()
for filter in self.get_filter_names():
filters[filter] = getattr(self, filter)
return filters | [
"def",
"get_filters",
"(",
"self",
")",
":",
"filters",
"=",
"dict",
"(",
")",
"for",
"filter",
"in",
"self",
".",
"get_filter_names",
"(",
")",
":",
"filters",
"[",
"filter",
"]",
"=",
"getattr",
"(",
"self",
",",
"filter",
")",
"return",
"filters"
] | 35.333333 | 0.009217 |
def _change_bios_setting(self, properties):
"""Change the bios settings to specified values."""
keys = properties.keys()
# Check if the BIOS resource/property exists.
headers, bios_uri, settings = self._check_bios_resource(keys)
if not self._operation_allowed(headers, 'PATCH'):
... | [
"def",
"_change_bios_setting",
"(",
"self",
",",
"properties",
")",
":",
"keys",
"=",
"properties",
".",
"keys",
"(",
")",
"# Check if the BIOS resource/property exists.",
"headers",
",",
"bios_uri",
",",
"settings",
"=",
"self",
".",
"_check_bios_resource",
"(",
... | 52.6 | 0.002491 |
def subject(self, value):
"""
An asn1crypto.x509.Name object, or a dict with at least the
following keys:
- country_name
- state_or_province_name
- locality_name
- organization_name
- common_name
Less common keys include:
- organiz... | [
"def",
"subject",
"(",
"self",
",",
"value",
")",
":",
"is_dict",
"=",
"isinstance",
"(",
"value",
",",
"dict",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"x509",
".",
"Name",
")",
"and",
"not",
"is_dict",
":",
"raise",
"TypeError",
"(",
"_pr... | 24.038462 | 0.001537 |
def _read_columns_file(f):
"""Return the list of column queries read from the given JSON file.
:param f: path to the file to read
:type f: string
:rtype: list of dicts
"""
try:
columns = json.loads(open(f, 'r').read(),
object_pairs_hook=collections.Ordered... | [
"def",
"_read_columns_file",
"(",
"f",
")",
":",
"try",
":",
"columns",
"=",
"json",
".",
"loads",
"(",
"open",
"(",
"f",
",",
"'r'",
")",
".",
"read",
"(",
")",
",",
"object_pairs_hook",
"=",
"collections",
".",
"OrderedDict",
")",
"except",
"Exceptio... | 27 | 0.001704 |
def train(self, plot):
"""
Compute all the required guides
Parameters
----------
plot : ggplot
ggplot object
Returns
-------
gdefs : list
Guides for the plots
"""
gdefs = []
for scale in plot.scales:
... | [
"def",
"train",
"(",
"self",
",",
"plot",
")",
":",
"gdefs",
"=",
"[",
"]",
"for",
"scale",
"in",
"plot",
".",
"scales",
":",
"for",
"output",
"in",
"scale",
".",
"aesthetics",
":",
"# The guide for aesthetic 'xxx' is stored",
"# in plot.guides['xxx']. The prior... | 36.78125 | 0.000827 |
def delete_items_by_index(list_, index_list, copy=False):
"""
Remove items from ``list_`` at positions specified in ``index_list``
The original ``list_`` is preserved if ``copy`` is True
Args:
list_ (list):
index_list (list):
copy (bool): preserves original list if True
Exa... | [
"def",
"delete_items_by_index",
"(",
"list_",
",",
"index_list",
",",
"copy",
"=",
"False",
")",
":",
"if",
"copy",
":",
"list_",
"=",
"list_",
"[",
":",
"]",
"# Rectify negative indicies",
"index_list_",
"=",
"[",
"(",
"len",
"(",
"list_",
")",
"+",
"x"... | 32.107143 | 0.00108 |
def get_plain_text(self):
"""Returns a list"""
_msg = self.message if self.message is not None else [""]
msg = _msg if isinstance(_msg, list) else [_msg]
line = "" if not self.line else ", line {}".format(self.line)
ret = ["{} found in file '{}'{}::".format(self.type.capital... | [
"def",
"get_plain_text",
"(",
"self",
")",
":",
"_msg",
"=",
"self",
".",
"message",
"if",
"self",
".",
"message",
"is",
"not",
"None",
"else",
"[",
"\"\"",
"]",
"msg",
"=",
"_msg",
"if",
"isinstance",
"(",
"_msg",
",",
"list",
")",
"else",
"[",
"_... | 45.2 | 0.010846 |
def _next_id(self):
"""Return the next available message id."""
assert get_thread_ident() == self.ioloop_thread_id
self._last_msg_id += 1
return str(self._last_msg_id) | [
"def",
"_next_id",
"(",
"self",
")",
":",
"assert",
"get_thread_ident",
"(",
")",
"==",
"self",
".",
"ioloop_thread_id",
"self",
".",
"_last_msg_id",
"+=",
"1",
"return",
"str",
"(",
"self",
".",
"_last_msg_id",
")"
] | 39 | 0.01005 |
def run_command(cmd, out, ignore_errors=False):
"""We want to both send subprocess output to stdout or another file
descriptor as the subprocess runs, *and* capture the actual exception
message on errors. CalledProcessErrors do not reliably contain the
underlying exception in either the 'message' or 'ou... | [
"def",
"run_command",
"(",
"cmd",
",",
"out",
",",
"ignore_errors",
"=",
"False",
")",
":",
"tempdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"output_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempdir",
",",
"\"stderr\"",
")",
"original_cmd",
... | 42.814815 | 0.000846 |
def shutdown(self, save=False, nosave=False):
"""Shutdown the Redis server. If Redis has persistence configured,
data will be flushed before shutdown. If the "save" option is set,
a data flush will be attempted even if there is no persistence
configured. If the "nosave" option is set,... | [
"def",
"shutdown",
"(",
"self",
",",
"save",
"=",
"False",
",",
"nosave",
"=",
"False",
")",
":",
"if",
"save",
"and",
"nosave",
":",
"raise",
"DataError",
"(",
"'SHUTDOWN save and nosave cannot both be set'",
")",
"args",
"=",
"[",
"'SHUTDOWN'",
"]",
"if",
... | 42.6 | 0.002296 |
def ones(shape, ctx=None, dtype=None, **kwargs):
"""Returns a new array filled with all ones, with the given shape and type.
Parameters
----------
shape : int or tuple of int or list of int
The shape of the empty array.
ctx : Context, optional
An optional device context.
Def... | [
"def",
"ones",
"(",
"shape",
",",
"ctx",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable= unused-argument",
"if",
"ctx",
"is",
"None",
":",
"ctx",
"=",
"current_context",
"(",
")",
"dtype",
"=",
"mx_real_t",
... | 32.942857 | 0.001685 |
def populate_field_list(self, excluded_fields=None):
"""Helper to add field of the layer to the list.
:param excluded_fields: List of field that want to be excluded.
:type excluded_fields: list
"""
# Populate fields list
if excluded_fields is None:
excluded_f... | [
"def",
"populate_field_list",
"(",
"self",
",",
"excluded_fields",
"=",
"None",
")",
":",
"# Populate fields list",
"if",
"excluded_fields",
"is",
"None",
":",
"excluded_fields",
"=",
"[",
"]",
"self",
".",
"field_list",
".",
"clear",
"(",
")",
"for",
"field",... | 39.04 | 0.002 |
def parseSyslog(msg):
"""Parses Syslog messages (RFC 5424)
The `Syslog Message Format (RFC 5424)
<https://tools.ietf.org/html/rfc5424#section-6>`_ can be parsed with
simple whitespace tokenization::
SYSLOG-MSG = HEADER SP STRUCTURED-DATA [SP MSG]
HEADER = PRI VERSION SP TIMESTAMP S... | [
"def",
"parseSyslog",
"(",
"msg",
")",
":",
"tokens",
"=",
"msg",
".",
"split",
"(",
"' '",
",",
"6",
")",
"result",
"=",
"{",
"}",
"if",
"len",
"(",
"tokens",
")",
">",
"0",
":",
"pri",
"=",
"tokens",
"[",
"0",
"]",
"start",
"=",
"pri",
".",... | 30.706897 | 0.009249 |
def _align(terms):
"""Align a set of terms"""
try:
# flatten the parse tree (a nested list, really)
terms = list(com.flatten(terms))
except TypeError:
# can't iterate so it must just be a constant or single variable
if isinstance(terms.value, pd.core.generic.NDFrame):
... | [
"def",
"_align",
"(",
"terms",
")",
":",
"try",
":",
"# flatten the parse tree (a nested list, really)",
"terms",
"=",
"list",
"(",
"com",
".",
"flatten",
"(",
"terms",
")",
")",
"except",
"TypeError",
":",
"# can't iterate so it must just be a constant or single variab... | 37.421053 | 0.001372 |
def argvquote(arg, force=False):
""" Returns an argument quoted in such a way that that CommandLineToArgvW
on Windows will return the argument string unchanged.
This is the same thing Popen does when supplied with an list of arguments.
Arguments in a command line should be separated by spaces; this
... | [
"def",
"argvquote",
"(",
"arg",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
"and",
"len",
"(",
"arg",
")",
"!=",
"0",
"and",
"not",
"any",
"(",
"[",
"c",
"in",
"arg",
"for",
"c",
"in",
"' \\t\\n\\v\"'",
"]",
")",
":",
"return",
... | 44.15625 | 0.001385 |
def asRFC2822(self, tzinfo=None, includeDayOfWeek=True):
"""Return this Time formatted as specified in RFC 2822.
RFC 2822 specifies the format of email messages.
RFC 2822 says times in email addresses should reflect the local
timezone. If tzinfo is a datetime.tzinfo instance, the retur... | [
"def",
"asRFC2822",
"(",
"self",
",",
"tzinfo",
"=",
"None",
",",
"includeDayOfWeek",
"=",
"True",
")",
":",
"dtime",
"=",
"self",
".",
"asDatetime",
"(",
"tzinfo",
")",
"if",
"tzinfo",
"is",
"None",
":",
"rfcoffset",
"=",
"'-0000'",
"else",
":",
"rfco... | 34.457143 | 0.001613 |
def htotdev(data, rate=1.0, data_type="phase", taus=None):
""" PRELIMINARY - REQUIRES FURTHER TESTING.
Hadamard Total deviation.
Better confidence at long averages for Hadamard deviation
FIXME: bias corrections from http://www.wriley.com/CI2.pdf
W FM 0.995 alpha= 0
F... | [
"def",
"htotdev",
"(",
"data",
",",
"rate",
"=",
"1.0",
",",
"data_type",
"=",
"\"phase\"",
",",
"taus",
"=",
"None",
")",
":",
"if",
"data_type",
"==",
"\"phase\"",
":",
"phase",
"=",
"data",
"freq",
"=",
"phase2frequency",
"(",
"phase",
",",
"rate",
... | 35.360656 | 0.000902 |
def takeFromTree(self):
"""
Takes this item from the tree.
"""
tree = self.treeWidget()
parent = self.parent()
if parent:
parent.takeChild(parent.indexOfChild(self))
else:
tree.takeTopLevelItem(tree.indexOfTopLevelItem(se... | [
"def",
"takeFromTree",
"(",
"self",
")",
":",
"tree",
"=",
"self",
".",
"treeWidget",
"(",
")",
"parent",
"=",
"self",
".",
"parent",
"(",
")",
"if",
"parent",
":",
"parent",
".",
"takeChild",
"(",
"parent",
".",
"indexOfChild",
"(",
"self",
")",
")"... | 28.545455 | 0.009259 |
def copy_samples(self, other, parameters=None, parameter_names=None,
read_args=None, write_args=None):
"""Should copy samples to the other files.
Parameters
----------
other : InferenceFile
An open inference file to write to.
parameters : list of... | [
"def",
"copy_samples",
"(",
"self",
",",
"other",
",",
"parameters",
"=",
"None",
",",
"parameter_names",
"=",
"None",
",",
"read_args",
"=",
"None",
",",
"write_args",
"=",
"None",
")",
":",
"# select the samples to copy",
"logging",
".",
"info",
"(",
"\"Re... | 47.783784 | 0.001663 |
def fast_sweep_time_evolution(Ep, epsilonp, gamma,
omega_level, rm, xi, theta,
semi_analytic=True,
file_name=None, return_code=False):
r"""Return a spectrum of time evolutions of the density matrix.
We test a basic two-le... | [
"def",
"fast_sweep_time_evolution",
"(",
"Ep",
",",
"epsilonp",
",",
"gamma",
",",
"omega_level",
",",
"rm",
",",
"xi",
",",
"theta",
",",
"semi_analytic",
"=",
"True",
",",
"file_name",
"=",
"None",
",",
"return_code",
"=",
"False",
")",
":",
"# We unpack... | 38.658031 | 0.001176 |
def populate_all_metadata():
""" Create metadata instances for all models in seo_models if empty.
Once you have created a single metadata instance, this will not run.
This is because it is a potentially slow operation that need only be
done once. If you want to ensure that everything is popu... | [
"def",
"populate_all_metadata",
"(",
")",
":",
"for",
"Metadata",
"in",
"registry",
".",
"values",
"(",
")",
":",
"InstanceMetadata",
"=",
"Metadata",
".",
"_meta",
".",
"get_model",
"(",
"'modelinstance'",
")",
"if",
"InstanceMetadata",
"is",
"not",
"None",
... | 53.083333 | 0.001543 |
def get_all_config(self):
'''get all of config values'''
return json.dumps(self.config, indent=4, sort_keys=True, separators=(',', ':')) | [
"def",
"get_all_config",
"(",
"self",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"config",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
")"
] | 50 | 0.019737 |
def solve_sdp(sdp, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices.
:param sdpRelaxation: The SDP relaxation to be solved.
:type sdpRelaxation: :class:`ncpol2sdpa.... | [
"def",
"solve_sdp",
"(",
"sdp",
",",
"solver",
"=",
"None",
",",
"solverparameters",
"=",
"None",
")",
":",
"solvers",
"=",
"autodetect_solvers",
"(",
"solverparameters",
")",
"solver",
"=",
"solver",
".",
"lower",
"(",
")",
"if",
"solver",
"is",
"not",
... | 42.6 | 0.000483 |
def get_weights_fn(modality_type, value=None):
"""Gets default weights function; if none available, return value."""
if modality_type in (ModalityType.CTC_SYMBOL,
ModalityType.IDENTITY_SYMBOL,
ModalityType.MULTI_LABEL,
ModalityType.SYMBOL,
... | [
"def",
"get_weights_fn",
"(",
"modality_type",
",",
"value",
"=",
"None",
")",
":",
"if",
"modality_type",
"in",
"(",
"ModalityType",
".",
"CTC_SYMBOL",
",",
"ModalityType",
".",
"IDENTITY_SYMBOL",
",",
"ModalityType",
".",
"MULTI_LABEL",
",",
"ModalityType",
".... | 45.454545 | 0.009804 |
def nl_groups(self, value):
"""Group setter."""
self.bytearray[self._get_slicers(3)] = bytearray(c_uint32(value or 0)) | [
"def",
"nl_groups",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"bytearray",
"[",
"self",
".",
"_get_slicers",
"(",
"3",
")",
"]",
"=",
"bytearray",
"(",
"c_uint32",
"(",
"value",
"or",
"0",
")",
")"
] | 44 | 0.014925 |
def rename_cols(df,names,renames=None,prefix=None,suffix=None):
"""
rename columns of a pandas table
:param df: pandas dataframe
:param names: list of new column names
"""
if not prefix is None:
renames=[ "%s%s" % (prefix,s) for s in names]
if not suffix is None:
renames... | [
"def",
"rename_cols",
"(",
"df",
",",
"names",
",",
"renames",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"suffix",
"=",
"None",
")",
":",
"if",
"not",
"prefix",
"is",
"None",
":",
"renames",
"=",
"[",
"\"%s%s\"",
"%",
"(",
"prefix",
",",
"s",
... | 34 | 0.039746 |
def append_cluster(self, cluster, data = None, marker = '.', markersize = None, color = None):
"""!
@brief Appends cluster for visualization.
@param[in] cluster (list): cluster that may consist of indexes of objects from the data or object itself.
@param[in] data (list): If defines... | [
"def",
"append_cluster",
"(",
"self",
",",
"cluster",
",",
"data",
"=",
"None",
",",
"marker",
"=",
"'.'",
",",
"markersize",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"if",
"len",
"(",
"cluster",
")",
"==",
"0",
":",
"raise",
"ValueError",
... | 48.173913 | 0.013274 |
def get_iterator(self, dataset, training=False):
"""Get an iterator that allows to loop over the batches of the
given data.
If ``self.iterator_train__batch_size`` and/or
``self.iterator_test__batch_size`` are not set, use
``self.batch_size`` instead.
Parameters
... | [
"def",
"get_iterator",
"(",
"self",
",",
"dataset",
",",
"training",
"=",
"False",
")",
":",
"if",
"training",
":",
"kwargs",
"=",
"self",
".",
"_get_params_for",
"(",
"'iterator_train'",
")",
"iterator",
"=",
"self",
".",
"iterator_train",
"else",
":",
"k... | 31.552632 | 0.001618 |
def run_reports(reportlets_dir, out_dir, subject_label, run_uuid, config=None,
packagename=None):
"""
Runs the reports
.. testsetup::
>>> from shutil import copytree
>>> from tempfile import TemporaryDirectory
>>> new_path = Path(__file__).resolve().parent.parent
>>> test_d... | [
"def",
"run_reports",
"(",
"reportlets_dir",
",",
"out_dir",
",",
"subject_label",
",",
"run_uuid",
",",
"config",
"=",
"None",
",",
"packagename",
"=",
"None",
")",
":",
"report",
"=",
"Report",
"(",
"Path",
"(",
"reportlets_dir",
")",
",",
"out_dir",
","... | 31 | 0.001009 |
def bs_values_df(run_list, estimator_list, estimator_names, n_simulate,
**kwargs):
"""Computes a data frame of bootstrap resampled values.
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
estimator_list: list of functions
Estimators t... | [
"def",
"bs_values_df",
"(",
"run_list",
",",
"estimator_list",
",",
"estimator_names",
",",
"n_simulate",
",",
"*",
"*",
"kwargs",
")",
":",
"tqdm_kwargs",
"=",
"kwargs",
".",
"pop",
"(",
"'tqdm_kwargs'",
",",
"{",
"'desc'",
":",
"'bs values'",
"}",
")",
"... | 40.833333 | 0.000569 |
def get_by_dotted_path(d, path, default=None):
"""
Get an entry from nested dictionaries using a dotted path.
Example:
>>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')
12
"""
if not path:
return d
split_path = path.split('.')
current_option = d
for p in split_path:
... | [
"def",
"get_by_dotted_path",
"(",
"d",
",",
"path",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"return",
"d",
"split_path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"current_option",
"=",
"d",
"for",
"p",
"in",
"split_path",
... | 25.470588 | 0.002227 |
def get_skill_data(self):
""" generates tuples of name, path, url, sha """
path_to_sha = {
folder: sha for folder, sha in self.get_shas()
}
modules = self.read_file('.gitmodules').split('[submodule "')
for i, module in enumerate(modules):
if not module:
... | [
"def",
"get_skill_data",
"(",
"self",
")",
":",
"path_to_sha",
"=",
"{",
"folder",
":",
"sha",
"for",
"folder",
",",
"sha",
"in",
"self",
".",
"get_shas",
"(",
")",
"}",
"modules",
"=",
"self",
".",
"read_file",
"(",
"'.gitmodules'",
")",
".",
"split",... | 42.631579 | 0.002415 |
def _absolute_position_to_relative_position_unmasked(x):
"""Helper function for dot_product_unmasked_self_attention_relative_v2.
Rearrange an attention logits or weights Tensor.
The dimensions of the input represent:
[batch, heads, query_position, memory_position]
The dimensions of the output represent:
... | [
"def",
"_absolute_position_to_relative_position_unmasked",
"(",
"x",
")",
":",
"batch",
",",
"heads",
",",
"length",
",",
"_",
"=",
"common_layers",
".",
"shape_list",
"(",
"x",
")",
"# padd along column",
"x",
"=",
"tf",
".",
"pad",
"(",
"x",
",",
"[",
"[... | 36.551724 | 0.011949 |
def validate_callback(callback):
"""
validates a callback's on_loop_start and on_loop_end methods
Parameters
----------
callback : Callback object
Returns
-------
validated callback
"""
if not(hasattr(callback, '_validated')) or callback._validated == False:
assert hasa... | [
"def",
"validate_callback",
"(",
"callback",
")",
":",
"if",
"not",
"(",
"hasattr",
"(",
"callback",
",",
"'_validated'",
")",
")",
"or",
"callback",
".",
"_validated",
"==",
"False",
":",
"assert",
"hasattr",
"(",
"callback",
",",
"'on_loop_start'",
")",
... | 35.125 | 0.002309 |
def get_dummy_distribution():
"""
Returns a distutils Distribution object used to instrument the setup
environment before calling the actual setup() function.
"""
from .setup_helpers import _module_state
if _module_state['registered_commands'] is None:
raise RuntimeError(
'... | [
"def",
"get_dummy_distribution",
"(",
")",
":",
"from",
".",
"setup_helpers",
"import",
"_module_state",
"if",
"_module_state",
"[",
"'registered_commands'",
"]",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'astropy_helpers.setup_helpers.register_commands() must be '"... | 37.193548 | 0.000845 |
def from_networkx_graph(nx_graph):
"""Returns an UndirectedHypergraph object that is the graph equivalent of
the given NetworkX Graph object.
:param nx_graph: the NetworkX undirected graph object to transform.
:returns: UndirectedHypergraph -- H object equivalent to the
NetworkX undirected ... | [
"def",
"from_networkx_graph",
"(",
"nx_graph",
")",
":",
"import",
"networkx",
"as",
"nx",
"if",
"not",
"isinstance",
"(",
"nx_graph",
",",
"nx",
".",
"Graph",
")",
":",
"raise",
"TypeError",
"(",
"\"Transformation only applicable to undirected \\\n ... | 32.666667 | 0.001101 |
def neverCalledWithMatch(cls, spy, *args, **kwargs): #pylint: disable=invalid-name
"""
Checking the inspector is never called with partial SinonMatcher(args/kwargs)
Args: SinonSpy, args/kwargs
"""
cls.__is_spy(spy)
if not (spy.neverCalledWithMatch(*args, **kwargs)):
... | [
"def",
"neverCalledWithMatch",
"(",
"cls",
",",
"spy",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#pylint: disable=invalid-name",
"cls",
".",
"__is_spy",
"(",
"spy",
")",
"if",
"not",
"(",
"spy",
".",
"neverCalledWithMatch",
"(",
"*",
"args",
... | 44.5 | 0.016529 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.