text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def create(cls, location=None, storage_class=None, **kwargs):
r"""Create a bucket.
:param location: Location of a bucket (instance or name).
Default: Default location.
:param storage_class: Storage class of a bucket.
Default: Default storage class.
:param \**kwar... | [
"def",
"create",
"(",
"cls",
",",
"location",
"=",
"None",
",",
"storage_class",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"if",
"location",
"is",
"None",
":",
"location",
"=",
... | 39.038462 | 16.461538 |
def verifyInputs(self, mode):
"""Goes through and checks all stimuli and input settings are valid
and consistent. Prompts user with a message if there is a condition
that would prevent acquisition.
:param mode: The mode of acquisition trying to be run. Options are
'chart', o... | [
"def",
"verifyInputs",
"(",
"self",
",",
"mode",
")",
":",
"if",
"len",
"(",
"self",
".",
"_aichans",
")",
"<",
"1",
":",
"failmsg",
"=",
"\"Must have at least one input channel selected\"",
"QtGui",
".",
"QMessageBox",
".",
"warning",
"(",
"self",
",",
"\"I... | 64.298507 | 33.940299 |
def _detect(self):
""" Detect state variables that could be const
"""
results = []
all_info = ''
all_variables = [c.state_variables for c in self.slither.contracts]
all_variables = set([item for sublist in all_variables for item in sublist])
all_non_constant_elem... | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"all_info",
"=",
"''",
"all_variables",
"=",
"[",
"c",
".",
"state_variables",
"for",
"c",
"in",
"self",
".",
"slither",
".",
"contracts",
"]",
"all_variables",
"=",
"set",
"(",
"[",
... | 51.580645 | 29.870968 |
def _print_memory(self, memory):
"""Print memory.
"""
for addr, value in memory.items():
print(" 0x%08x : 0x%08x (%d)" % (addr, value, value)) | [
"def",
"_print_memory",
"(",
"self",
",",
"memory",
")",
":",
"for",
"addr",
",",
"value",
"in",
"memory",
".",
"items",
"(",
")",
":",
"print",
"(",
"\" 0x%08x : 0x%08x (%d)\"",
"%",
"(",
"addr",
",",
"value",
",",
"value",
")",
")"
] | 35.4 | 7.6 |
def delete_records_safely_by_xml_id(env, xml_ids):
"""This removes in the safest possible way the records whose XML-IDs are
passed as argument.
:param xml_ids: List of XML-ID string identifiers of the records to remove.
"""
for xml_id in xml_ids:
logger.debug('Deleting record for XML-ID %s'... | [
"def",
"delete_records_safely_by_xml_id",
"(",
"env",
",",
"xml_ids",
")",
":",
"for",
"xml_id",
"in",
"xml_ids",
":",
"logger",
".",
"debug",
"(",
"'Deleting record for XML-ID %s'",
",",
"xml_id",
")",
"try",
":",
"with",
"env",
".",
"cr",
".",
"savepoint",
... | 40.153846 | 17.307692 |
def unsubscribe(self, *args):
"""
Unsubscribe from the supplied channels. If empty, unsubscribe from
all channels
"""
if args:
args = list_or_args(args[0], args[1:])
channels = self._normalize_keys(dict.fromkeys(args))
else:
channels = ... | [
"def",
"unsubscribe",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"args",
":",
"args",
"=",
"list_or_args",
"(",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
":",
"]",
")",
"channels",
"=",
"self",
".",
"_normalize_keys",
"(",
"dict",
".",
"f... | 36.583333 | 15.75 |
def get(self, name):
""" creates connection to the MQ with process-specific settings
:return :mq::flopsy::Publisher instance"""
if name not in self.pools:
self.pools[name] = _Pool(logger=self.logger, name=name)
return self.pools[name].get() | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"pools",
":",
"self",
".",
"pools",
"[",
"name",
"]",
"=",
"_Pool",
"(",
"logger",
"=",
"self",
".",
"logger",
",",
"name",
"=",
"name",
")",
"return",
"s... | 46.5 | 9.333333 |
def audiorate(filename):
"""Determines the samplerate of the given audio recording file
:param filename: filename of the audiofile
:type filename: str
:returns: int -- samplerate of the recording
"""
if '.wav' in filename.lower():
wf = wave.open(filename)
fs = wf.getframerate()
... | [
"def",
"audiorate",
"(",
"filename",
")",
":",
"if",
"'.wav'",
"in",
"filename",
".",
"lower",
"(",
")",
":",
"wf",
"=",
"wave",
".",
"open",
"(",
"filename",
")",
"fs",
"=",
"wf",
".",
"getframerate",
"(",
")",
"wf",
".",
"close",
"(",
")",
"eli... | 28.529412 | 17.294118 |
def main():
""" Parse the arguments and use them to create a ExistCli object """
version = 'Python Exist %s' % __version__
arguments = docopt(__doc__, version=version)
ExistCli(arguments) | [
"def",
"main",
"(",
")",
":",
"version",
"=",
"'Python Exist %s'",
"%",
"__version__",
"arguments",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"version",
")",
"ExistCli",
"(",
"arguments",
")"
] | 39.8 | 11.8 |
def check_module(mod_name):
"""Calls sys.exit() if the module *mod_name* is not found."""
# Special cases #
if mod_name in module_name: mod_name = module_name[mod_name]
# Use a try except block #
try:
__import__(mod_name)
except ImportError as e:
if str(e) != 'No module named %s'... | [
"def",
"check_module",
"(",
"mod_name",
")",
":",
"# Special cases #",
"if",
"mod_name",
"in",
"module_name",
":",
"mod_name",
"=",
"module_name",
"[",
"mod_name",
"]",
"# Use a try except block #",
"try",
":",
"__import__",
"(",
"mod_name",
")",
"except",
"Import... | 46.230769 | 22.769231 |
def plot(self, title='TimeMoc', view=(None, None)):
"""
Plot the TimeMoc in a time window.
This method uses interactive matplotlib. The user can move its mouse through the plot to see the
time (at the mouse position).
Parameters
----------
title : str, optional
... | [
"def",
"plot",
"(",
"self",
",",
"title",
"=",
"'TimeMoc'",
",",
"view",
"=",
"(",
"None",
",",
"None",
")",
")",
":",
"from",
"matplotlib",
".",
"colors",
"import",
"LinearSegmentedColormap",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"if",
"se... | 33.571429 | 24.5 |
def find_path_package_name(thepath):
"""
Takes a file system path and returns the name of the python package
the said path belongs to. If the said path can not be determined, it
returns None.
"""
module_found = False
last_module_found = None
continue_ = True
while contin... | [
"def",
"find_path_package_name",
"(",
"thepath",
")",
":",
"module_found",
"=",
"False",
"last_module_found",
"=",
"None",
"continue_",
"=",
"True",
"while",
"continue_",
":",
"module_found",
"=",
"is_path_python_module",
"(",
"thepath",
")",
"next_path",
"=",
"pa... | 38.25 | 16.416667 |
def new_stats_exporter(option):
""" new_stats_exporter returns an exporter
that exports stats to Prometheus.
"""
if option.namespace == "":
raise ValueError("Namespace can not be empty string.")
collector = new_collector(option)
exporter = PrometheusStatsExporter(options=option,
... | [
"def",
"new_stats_exporter",
"(",
"option",
")",
":",
"if",
"option",
".",
"namespace",
"==",
"\"\"",
":",
"raise",
"ValueError",
"(",
"\"Namespace can not be empty string.\"",
")",
"collector",
"=",
"new_collector",
"(",
"option",
")",
"exporter",
"=",
"Prometheu... | 34.307692 | 15.769231 |
def endpoint_name(self, endpoint_name):
"""
Sets the endpoint_name of this PreSharedKey.
The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters.
:param endpoint_name: ... | [
"def",
"endpoint_name",
"(",
"self",
",",
"endpoint_name",
")",
":",
"if",
"endpoint_name",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `endpoint_name`, must not be `None`\"",
")",
"if",
"endpoint_name",
"is",
"not",
"None",
"and",
"not",
"re... | 53.857143 | 33.714286 |
def read_double(self, little_endian=True):
"""
Read 8 bytes as a double value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
float:
"""
if little_endian:
endian = "<"
els... | [
"def",
"read_double",
"(",
"self",
",",
"little_endian",
"=",
"True",
")",
":",
"if",
"little_endian",
":",
"endian",
"=",
"\"<\"",
"else",
":",
"endian",
"=",
"\">\"",
"return",
"self",
".",
"unpack",
"(",
"\"%sd\"",
"%",
"endian",
",",
"8",
")"
] | 25.266667 | 19.4 |
def _escapify(qstring):
"""Escape the characters in a quoted string which need it.
@param qstring: the string
@type qstring: string
@returns: the escaped string
@rtype: string
"""
text = ''
for c in qstring:
if c in __escaped:
text += '\\' + c
elif ord(c) >=... | [
"def",
"_escapify",
"(",
"qstring",
")",
":",
"text",
"=",
"''",
"for",
"c",
"in",
"qstring",
":",
"if",
"c",
"in",
"__escaped",
":",
"text",
"+=",
"'\\\\'",
"+",
"c",
"elif",
"ord",
"(",
"c",
")",
">=",
"0x20",
"and",
"ord",
"(",
"c",
")",
"<"... | 23.166667 | 16.888889 |
def _execute(self, ifile, process):
""" Execution loop
:param ifile: Input file object. Unused.
:type ifile: file
:return: `None`.
"""
if self._protocol_version == 2:
result = self._read_chunk(ifile)
if not result:
return
... | [
"def",
"_execute",
"(",
"self",
",",
"ifile",
",",
"process",
")",
":",
"if",
"self",
".",
"_protocol_version",
"==",
"2",
":",
"result",
"=",
"self",
".",
"_read_chunk",
"(",
"ifile",
")",
"if",
"not",
"result",
":",
"return",
"metadata",
",",
"body",... | 25.521739 | 20.26087 |
def parse_name(name):
"""Parses a subject string as used in OpenSSLs command line utilities.
The ``name`` is expected to be close to the subject format commonly used by OpenSSL, for example
``/C=AT/L=Vienna/CN=example.com/emailAddress=user@example.com``. The function does its best to be lenient
on devi... | [
"def",
"parse_name",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"strip",
"(",
")",
"if",
"not",
"name",
":",
"# empty subjects are ok",
"return",
"[",
"]",
"try",
":",
"items",
"=",
"[",
"(",
"NAME_CASE_MAPPINGS",
"[",
"t",
"[",
"0",
"]",
".",
... | 46.035088 | 32.649123 |
def set_limits(self, limits):
"""
Set the limit data to the given list of limits. Limits are
specified as the raw msgpack string representing the limit.
Computes the checksum of the limits; if the checksum is
identical to the current one, no action is taken.
"""
... | [
"def",
"set_limits",
"(",
"self",
",",
"limits",
")",
":",
"# First task, build the checksum of the new limits",
"chksum",
"=",
"hashlib",
".",
"md5",
"(",
")",
"# sufficient for our purposes",
"for",
"lim",
"in",
"limits",
":",
"chksum",
".",
"update",
"(",
"lim"... | 36.380952 | 16.285714 |
def _terminal_use_capability(capability_name):
"""
If the terminal supports the given capability, output it. Return whether
it was output.
"""
curses.setupterm()
capability = curses.tigetstr(capability_name)
if capability:
sys.stdout.write(_unicode(capability))
return bool(capab... | [
"def",
"_terminal_use_capability",
"(",
"capability_name",
")",
":",
"curses",
".",
"setupterm",
"(",
")",
"capability",
"=",
"curses",
".",
"tigetstr",
"(",
"capability_name",
")",
"if",
"capability",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"_unicode",
... | 31.7 | 13.3 |
def activate_network_interface(iface):
"""Bring up the given network interface.
@raise OSError: if interface does not exist or permissions are missing
"""
iface = iface.encode()
SIOCGIFFLAGS = 0x8913 # /usr/include/bits/ioctls.h
SIOCSIFFLAGS = 0x8914 # /usr/include/bits/ioctls.h
IFF_UP = 0x... | [
"def",
"activate_network_interface",
"(",
"iface",
")",
":",
"iface",
"=",
"iface",
".",
"encode",
"(",
")",
"SIOCGIFFLAGS",
"=",
"0x8913",
"# /usr/include/bits/ioctls.h",
"SIOCSIFFLAGS",
"=",
"0x8914",
"# /usr/include/bits/ioctls.h",
"IFF_UP",
"=",
"0x1",
"# /usr/inc... | 46.137931 | 26.034483 |
def show_devices(verbose=False, **kwargs):
"""Show information about connected devices.
The verbose flag sets to verbose or not.
**kwargs are passed directly to the find() function.
"""
kwargs["find_all"] = True
devices = find(**kwargs)
strings = ""
for device in devices:
if not... | [
"def",
"show_devices",
"(",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"find_all\"",
"]",
"=",
"True",
"devices",
"=",
"find",
"(",
"*",
"*",
"kwargs",
")",
"strings",
"=",
"\"\"",
"for",
"device",
"in",
"devices",
"... | 31.411765 | 15.235294 |
def dbtemplate_save(sender, instance, created, **kwargs):
"""create widget/page content/base theme from given db template::
/widget/icon/my_awesome.html
/base/widget/my_new_widget_box.html
/base/page/my_new_page_layout.html
"""
if created:
if 'widget' in instance.name:
... | [
"def",
"dbtemplate_save",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"created",
":",
"if",
"'widget'",
"in",
"instance",
".",
"name",
":",
"name",
"=",
"instance",
".",
"name",
".",
"split",
"(",
"'/'",
"... | 42.891892 | 14.189189 |
def add_tip_lines_to_axes(self):
"add lines to connect tips to zero axis for tip_labels_align=True"
# get tip-coords and align-coords from verts
xpos, ypos, aedges, averts = self.get_tip_label_coords()
if self.style.tip_labels_align:
self.axes.graph(
aedges,... | [
"def",
"add_tip_lines_to_axes",
"(",
"self",
")",
":",
"# get tip-coords and align-coords from verts",
"xpos",
",",
"ypos",
",",
"aedges",
",",
"averts",
"=",
"self",
".",
"get_tip_label_coords",
"(",
")",
"if",
"self",
".",
"style",
".",
"tip_labels_align",
":",
... | 35.923077 | 16.846154 |
def find_n90(contig_lengths_dict, genome_length_dict):
"""
Calculate the N90 for each strain. N90 is defined as the largest contig such that at least 9/10 of the total
genome size is contained in contigs equal to or larger than this contig
:param contig_lengths_dict: dictionary of strain name: reverse-s... | [
"def",
"find_n90",
"(",
"contig_lengths_dict",
",",
"genome_length_dict",
")",
":",
"# Initialise the dictionary",
"n90_dict",
"=",
"dict",
"(",
")",
"for",
"file_name",
",",
"contig_lengths",
"in",
"contig_lengths_dict",
".",
"items",
"(",
")",
":",
"currentlength"... | 50.7 | 23.9 |
def get_transformation_matrix(self, theta):
""" Computes the homogeneous transformation matrix for this link. """
ct = numpy.cos(theta + self.theta)
st = numpy.sin(theta + self.theta)
ca = numpy.cos(self.alpha)
sa = numpy.sin(self.alpha)
return numpy.matrix(((ct, -st * c... | [
"def",
"get_transformation_matrix",
"(",
"self",
",",
"theta",
")",
":",
"ct",
"=",
"numpy",
".",
"cos",
"(",
"theta",
"+",
"self",
".",
"theta",
")",
"st",
"=",
"numpy",
".",
"sin",
"(",
"theta",
"+",
"self",
".",
"theta",
")",
"ca",
"=",
"numpy",... | 45.090909 | 11.181818 |
def mint_token_if_balance_low(
token_contract: ContractProxy,
target_address: str,
min_balance: int,
fund_amount: int,
gas_limit: int,
mint_msg: str,
no_action_msg: str = None,
) -> Optional[TransactionHash]:
""" Check token balance and mint if below minimum "... | [
"def",
"mint_token_if_balance_low",
"(",
"token_contract",
":",
"ContractProxy",
",",
"target_address",
":",
"str",
",",
"min_balance",
":",
"int",
",",
"fund_amount",
":",
"int",
",",
"gas_limit",
":",
"int",
",",
"mint_msg",
":",
"str",
",",
"no_action_msg",
... | 36.35 | 18.1 |
def permitted_query(self, query, group, operations):
'''Change the ``query`` so that only instances for which
``group`` has roles with permission on ``operations`` are returned.'''
session = query.session
models = session.router
user = group.user
if user.is_superuser: # super-u... | [
"def",
"permitted_query",
"(",
"self",
",",
"query",
",",
"group",
",",
"operations",
")",
":",
"session",
"=",
"query",
".",
"session",
"models",
"=",
"session",
".",
"router",
"user",
"=",
"group",
".",
"user",
"if",
"user",
".",
"is_superuser",
":",
... | 48.8 | 18.628571 |
def xrdb(xrdb_files=None):
"""Merge the colors into the X db so new terminals use them."""
xrdb_files = xrdb_files or \
[os.path.join(CACHE_DIR, "colors.Xresources")]
if shutil.which("xrdb") and OS != "Darwin":
for file in xrdb_files:
subprocess.run(["xrdb", "-merge", "-quiet", ... | [
"def",
"xrdb",
"(",
"xrdb_files",
"=",
"None",
")",
":",
"xrdb_files",
"=",
"xrdb_files",
"or",
"[",
"os",
".",
"path",
".",
"join",
"(",
"CACHE_DIR",
",",
"\"colors.Xresources\"",
")",
"]",
"if",
"shutil",
".",
"which",
"(",
"\"xrdb\"",
")",
"and",
"O... | 39.875 | 14.25 |
def make_copy_paste_env(env: Dict[str, str]) -> str:
"""
Convert an environment into a set of commands that can be copied/pasted, on
the build platform, to recreate that environment.
"""
windows = platform.system() == "Windows"
cmd = "set" if windows else "export"
return (
"\n".join(... | [
"def",
"make_copy_paste_env",
"(",
"env",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"str",
":",
"windows",
"=",
"platform",
".",
"system",
"(",
")",
"==",
"\"Windows\"",
"cmd",
"=",
"\"set\"",
"if",
"windows",
"else",
"\"export\"",
"return",
... | 32.5 | 16.25 |
def xor(cls, obj, **kwargs):
"""Query an object.
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if exactly one `kwargs` expression is `True`,
`False` otherwise.
:rtype: bool
"""
return cls.__... | [
"def",
"xor",
"(",
"cls",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"__eval_seqexp",
"(",
"obj",
",",
"operator",
".",
"xor",
",",
"*",
"*",
"kwargs",
")"
] | 24.785714 | 19.928571 |
def qwarp_align(dset_from,dset_to,skull_strip=True,mask=None,affine_suffix='_aff',suffix='_qwarp',prefix=None):
'''aligns ``dset_from`` to ``dset_to`` using 3dQwarp
Will run ``3dSkullStrip`` (unless ``skull_strip`` is ``False``), ``3dUnifize``,
``3dAllineate``, and then ``3dQwarp``. This method will add su... | [
"def",
"qwarp_align",
"(",
"dset_from",
",",
"dset_to",
",",
"skull_strip",
"=",
"True",
",",
"mask",
"=",
"None",
",",
"affine_suffix",
"=",
"'_aff'",
",",
"suffix",
"=",
"'_qwarp'",
",",
"prefix",
"=",
"None",
")",
":",
"dset_ss",
"=",
"lambda",
"dset"... | 47.120482 | 30.662651 |
def add_current_text(self):
"""
Add current text to combo box history (convenient method).
If path ends in os separator ("\" windows, "/" unix) remove it.
"""
text = self.currentText()
if osp.isdir(text) and text:
if text[-1] == os.sep:
... | [
"def",
"add_current_text",
"(",
"self",
")",
":",
"text",
"=",
"self",
".",
"currentText",
"(",
")",
"if",
"osp",
".",
"isdir",
"(",
"text",
")",
"and",
"text",
":",
"if",
"text",
"[",
"-",
"1",
"]",
"==",
"os",
".",
"sep",
":",
"text",
"=",
"t... | 35.7 | 10.5 |
def setup(self, universe):
"""
Setup Security with universe. Speeds up future runs.
Args:
* universe (DataFrame): DataFrame of prices with security's name as
one of the columns.
"""
# if we already have all the prices, we will store them to speed up
... | [
"def",
"setup",
"(",
"self",
",",
"universe",
")",
":",
"# if we already have all the prices, we will store them to speed up",
"# future updates",
"try",
":",
"prices",
"=",
"universe",
"[",
"self",
".",
"name",
"]",
"except",
"KeyError",
":",
"prices",
"=",
"None",... | 32.714286 | 17.914286 |
def mv_files(src, dst):
"""
Move all files from one directory to another
:param str src: Source directory
:param str dst: Destination directory
:return none:
"""
# list the files in the src directory
files = os.listdir(src)
# loop for each file found
for file in files:
#... | [
"def",
"mv_files",
"(",
"src",
",",
"dst",
")",
":",
"# list the files in the src directory",
"files",
"=",
"os",
".",
"listdir",
"(",
"src",
")",
"# loop for each file found",
"for",
"file",
"in",
"files",
":",
"# move the file from the src to the dst",
"shutil",
"... | 28.333333 | 13.4 |
def _delete_service_nwk(self, tenant_id, tenant_name, direc):
"""Function to delete the service in network in DCNM. """
net_dict = {}
if direc == 'in':
seg, vlan = self.get_in_seg_vlan(tenant_id)
net_dict['part_name'] = None
else:
seg, vlan = self.get_... | [
"def",
"_delete_service_nwk",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
",",
"direc",
")",
":",
"net_dict",
"=",
"{",
"}",
"if",
"direc",
"==",
"'in'",
":",
"seg",
",",
"vlan",
"=",
"self",
".",
"get_in_seg_vlan",
"(",
"tenant_id",
")",
"net_dic... | 39.578947 | 15.210526 |
def import_mod_attr(path):
"""
Import string format module, e.g. 'uliweb.orm' or an object
return module object and object
"""
import inspect
if isinstance(path, (str, unicode)):
v = path.split(':')
if len(v) == 1:
module, func = path.rsplit('.', 1)
else:
... | [
"def",
"import_mod_attr",
"(",
"path",
")",
":",
"import",
"inspect",
"if",
"isinstance",
"(",
"path",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"v",
"=",
"path",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"v",
")",
"==",
"1",
":",
... | 27.625 | 16.625 |
def ping(bot, mask, target, args):
"""ping/pong
%%ping
"""
bot.send('NOTICE %(nick)s :PONG %(nick)s!' % dict(nick=mask.nick)) | [
"def",
"ping",
"(",
"bot",
",",
"mask",
",",
"target",
",",
"args",
")",
":",
"bot",
".",
"send",
"(",
"'NOTICE %(nick)s :PONG %(nick)s!'",
"%",
"dict",
"(",
"nick",
"=",
"mask",
".",
"nick",
")",
")"
] | 23.5 | 17 |
def seat_button_count(self):
"""The total number of buttons pressed on all devices on the
associated seat after the event was triggered.
For pointer events that are not of type
:attr:`~libinput.constant.EventType.POINTER_BUTTON`, this property
raises :exc:`AssertionError`.
Returns:
int: The seat wide p... | [
"def",
"seat_button_count",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"POINTER_BUTTON",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"return",
"self",
".",
"_libinput... | 31.666667 | 20.055556 |
def onKeyPressInCanvas(self, event):
'''Called when a key is pressed when the canvas has focus.'''
char_map = { 'w':'move 1', 'a':'strafe -1', 's':'move -1', 'd':'strafe 1', ' ':'jump 1' }
keysym_map = { 'continuous': { 'Left':'turn -1', 'Right':'turn 1', 'Up':'pitch -1', 'Down':'pitch 1', 'Shif... | [
"def",
"onKeyPressInCanvas",
"(",
"self",
",",
"event",
")",
":",
"char_map",
"=",
"{",
"'w'",
":",
"'move 1'",
",",
"'a'",
":",
"'strafe -1'",
",",
"'s'",
":",
"'move -1'",
",",
"'d'",
":",
"'strafe 1'",
",",
"' '",
":",
"'jump 1'",
"}",
"keysym_map",
... | 85 | 46.875 |
def system_monitor_LineCard_alert_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
LineCard = ET.SubElement(system_monitor, "LineCard")
... | [
"def",
"system_monitor_LineCard_alert_state",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"system_monitor",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"system-monitor\"",
",",
"xmlns",
... | 44.333333 | 16.25 |
def get_final_text(pred_text, orig_text, do_lower_case, verbose_logging=False):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# now `ori... | [
"def",
"get_final_text",
"(",
"pred_text",
",",
"orig_text",
",",
"do_lower_case",
",",
"verbose_logging",
"=",
"False",
")",
":",
"# When we created the data, we kept track of the alignment between original",
"# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So",
... | 39.021277 | 22.265957 |
def skeleton_path(parts):
"""Gets the path to a skeleton asset"""
return os.path.join(os.path.dirname(oz.__file__), "skeleton", parts) | [
"def",
"skeleton_path",
"(",
"parts",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"oz",
".",
"__file__",
")",
",",
"\"skeleton\"",
",",
"parts",
")"
] | 46.666667 | 15.666667 |
def invalidation_hash(self, fingerprint_strategy=None):
"""
:API: public
"""
fingerprint_strategy = fingerprint_strategy or DefaultFingerprintStrategy()
if fingerprint_strategy not in self._cached_fingerprint_map:
self._cached_fingerprint_map[fingerprint_strategy] = self.compute_invalidation_h... | [
"def",
"invalidation_hash",
"(",
"self",
",",
"fingerprint_strategy",
"=",
"None",
")",
":",
"fingerprint_strategy",
"=",
"fingerprint_strategy",
"or",
"DefaultFingerprintStrategy",
"(",
")",
"if",
"fingerprint_strategy",
"not",
"in",
"self",
".",
"_cached_fingerprint_m... | 50 | 24.25 |
def parallel_progbar(mapper, iterable, nprocs=None, starmap=False, flatmap=False, shuffle=False,
verbose=True, verbose_flatmap=None, **kwargs):
"""Performs a parallel mapping of the given iterable, reporting a progress bar as values get returned
:param mapper: The mapping function to apply... | [
"def",
"parallel_progbar",
"(",
"mapper",
",",
"iterable",
",",
"nprocs",
"=",
"None",
",",
"starmap",
"=",
"False",
",",
"flatmap",
"=",
"False",
",",
"shuffle",
"=",
"False",
",",
"verbose",
"=",
"True",
",",
"verbose_flatmap",
"=",
"None",
",",
"*",
... | 72 | 39.6 |
def available_services_regions(self):
"""Returns list of unique region name values in service catalog."""
regions = []
if self.service_catalog:
for service in self.service_catalog:
service_type = service.get('type')
if service_type is None or service_t... | [
"def",
"available_services_regions",
"(",
"self",
")",
":",
"regions",
"=",
"[",
"]",
"if",
"self",
".",
"service_catalog",
":",
"for",
"service",
"in",
"self",
".",
"service_catalog",
":",
"service_type",
"=",
"service",
".",
"get",
"(",
"'type'",
")",
"i... | 46 | 12.692308 |
def vhost_add(cls, resource, params):
""" Add a vhost into a webaccelerator """
try:
oper = cls.call(
'hosting.rproxy.vhost.create', cls.usable_id(resource), params)
cls.echo('Adding your virtual host (%s) into %s' %
(params['vhost'], resource... | [
"def",
"vhost_add",
"(",
"cls",
",",
"resource",
",",
"params",
")",
":",
"try",
":",
"oper",
"=",
"cls",
".",
"call",
"(",
"'hosting.rproxy.vhost.create'",
",",
"cls",
".",
"usable_id",
"(",
"resource",
")",
",",
"params",
")",
"cls",
".",
"echo",
"("... | 49.472222 | 22.388889 |
def setup_parser(self, parser):
""" Setup the argument parser.
`parser`
``FocusArgParser`` object.
"""
parser.add_argument('task_name', help='task to create')
parser.add_argument('clone_task', nargs='?',
help='existing task to... | [
"def",
"setup_parser",
"(",
"self",
",",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'task_name'",
",",
"help",
"=",
"'task to create'",
")",
"parser",
".",
"add_argument",
"(",
"'clone_task'",
",",
"nargs",
"=",
"'?'",
",",
"help",
"=",
"'exi... | 37.666667 | 18.083333 |
def to_json(value, **kwargs):
"""Return a copy of the dictionary
If the values are HasProperties instances, they are serialized
"""
serial_dict = {
key: (
val.serialize(**kwargs) if isinstance(val, HasProperties)
else val
)
... | [
"def",
"to_json",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"serial_dict",
"=",
"{",
"key",
":",
"(",
"val",
".",
"serialize",
"(",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"val",
",",
"HasProperties",
")",
"else",
"val",
")",
"for"... | 29.384615 | 18.846154 |
def fill_list(self, list, input_list):
"""
fills a tree with nested parameters
Args:
tree: QtGui.QTreeView to fill
parameters: dictionary or Parameter object which contains the information to use to fill
"""
for name in input_list:
# print(inde... | [
"def",
"fill_list",
"(",
"self",
",",
"list",
",",
"input_list",
")",
":",
"for",
"name",
"in",
"input_list",
":",
"# print(index, loaded_item, loaded_item_settings)",
"item",
"=",
"QtGui",
".",
"QStandardItem",
"(",
"name",
")",
"item",
".",
"setSelectable",
"(... | 36 | 12.571429 |
def rt(nu, size=None):
"""
Student's t random variates.
"""
return rnormal(0, 1, size) / np.sqrt(rchi2(nu, size) / nu) | [
"def",
"rt",
"(",
"nu",
",",
"size",
"=",
"None",
")",
":",
"return",
"rnormal",
"(",
"0",
",",
"1",
",",
"size",
")",
"/",
"np",
".",
"sqrt",
"(",
"rchi2",
"(",
"nu",
",",
"size",
")",
"/",
"nu",
")"
] | 26 | 9.6 |
def json_is_exception(resp):
"""
Is the given response object
an exception traceback?
Return True if so
Return False if not
"""
if not json_is_error(resp):
return False
if 'traceback' not in resp.keys() or 'error' not in resp.keys():
return False
return True | [
"def",
"json_is_exception",
"(",
"resp",
")",
":",
"if",
"not",
"json_is_error",
"(",
"resp",
")",
":",
"return",
"False",
"if",
"'traceback'",
"not",
"in",
"resp",
".",
"keys",
"(",
")",
"or",
"'error'",
"not",
"in",
"resp",
".",
"keys",
"(",
")",
"... | 19.933333 | 19.4 |
def __getOrganizations(self, web):
"""Scrap the number of organizations from a GitHub profile.
:param web: parsed web.
:type web: BeautifulSoup node.
"""
orgsElements = web.find_all("a", {"class": "avatar-group-item"})
self.organizations = len(orgsElements) | [
"def",
"__getOrganizations",
"(",
"self",
",",
"web",
")",
":",
"orgsElements",
"=",
"web",
".",
"find_all",
"(",
"\"a\"",
",",
"{",
"\"class\"",
":",
"\"avatar-group-item\"",
"}",
")",
"self",
".",
"organizations",
"=",
"len",
"(",
"orgsElements",
")"
] | 37.375 | 11.875 |
def ip_rtm_config_route_static_route_oif_vrf_next_hop_vrf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
rtm_config = ET.SubElement(ip, "rtm-config", xmlns="urn:brocade.co... | [
"def",
"ip_rtm_config_route_static_route_oif_vrf_next_hop_vrf",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ip",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ip\"",
",",
"xmlns",
"=",
... | 63.789474 | 31.315789 |
def erf(f=Ellipsis):
'''
erf(x) yields a potential function that calculates the error function over the input x. If x is
a constant, yields a constant potential function.
erf() is equivalent to erf(...), which is just the error function, calculated over its inputs.
'''
f = to_potential(f)
... | [
"def",
"erf",
"(",
"f",
"=",
"Ellipsis",
")",
":",
"f",
"=",
"to_potential",
"(",
"f",
")",
"if",
"is_const_potential",
"(",
"f",
")",
":",
"return",
"const_potential",
"(",
"np",
".",
"erf",
"(",
"f",
".",
"c",
")",
")",
"elif",
"is_identity_potenti... | 47.3 | 27.9 |
def accuracy_helper(egg, match='exact', distance='euclidean',
features=None):
"""
Computes proportion of words recalled
Parameters
----------
egg : quail.Egg
Data to analyze
match : str (exact, best or smooth)
Matching approach to compute recall matrix. If ... | [
"def",
"accuracy_helper",
"(",
"egg",
",",
"match",
"=",
"'exact'",
",",
"distance",
"=",
"'euclidean'",
",",
"features",
"=",
"None",
")",
":",
"def",
"acc",
"(",
"lst",
")",
":",
"return",
"len",
"(",
"[",
"i",
"for",
"i",
"in",
"np",
".",
"uniqu... | 33.217391 | 23.043478 |
def safe_mkdir_for(path, clean=False):
"""Ensure that the parent directory for a file is present.
If it's not there, create it. If it is, no-op.
"""
safe_mkdir(os.path.dirname(path), clean=clean) | [
"def",
"safe_mkdir_for",
"(",
"path",
",",
"clean",
"=",
"False",
")",
":",
"safe_mkdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
",",
"clean",
"=",
"clean",
")"
] | 33.166667 | 9.666667 |
def cmode(self, channel, modes=''):
"""
Sets or gets the channel mode.
Required arguments:
* channel - Channel to set/get modes of.
Optional arguments:
* modes='' - Modes to set.
If not specified return the modes of the channel.
"""
with self.l... | [
"def",
"cmode",
"(",
"self",
",",
"channel",
",",
"modes",
"=",
"''",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"is_in_channel",
"(",
"channel",
")",
"if",
"not",
"modes",
":",
"self",
".",
"send",
"(",
"'MODE %s'",
"%",
"channel",
"... | 41.222222 | 14.111111 |
def dumps(self):
"""Turn the tabu object into a string in Latex format."""
_s = super().dumps()
# Tabu tables support a unusual syntax:
# \begin{tabu} spread 0pt {<col format...>}
#
# Since this syntax isn't common, it doesn't make
# sense to support it in the b... | [
"def",
"dumps",
"(",
"self",
")",
":",
"_s",
"=",
"super",
"(",
")",
".",
"dumps",
"(",
")",
"# Tabu tables support a unusual syntax:",
"# \\begin{tabu} spread 0pt {<col format...>}",
"#",
"# Since this syntax isn't common, it doesn't make",
"# sense to support it in the basecl... | 38.333333 | 20.666667 |
def honeycomb_lattice( a, b, spacing, alternating_sites=False ):
"""
Generate a honeycomb lattice.
Args:
a (Int): Number of lattice repeat units along x.
b (Int): Number of lattice repeat units along y.
spacing (Float): Distance between lattice sites.
alterna... | [
"def",
"honeycomb_lattice",
"(",
"a",
",",
"b",
",",
"spacing",
",",
"alternating_sites",
"=",
"False",
")",
":",
"if",
"alternating_sites",
":",
"site_labels",
"=",
"[",
"'A'",
",",
"'B'",
",",
"'A'",
",",
"'B'",
"]",
"else",
":",
"site_labels",
"=",
... | 49.803922 | 26.862745 |
def assert_equals(actual, expected, ignore_order=False, ignore_index=False, all_close=False):
'''
Assert 2 series are equal.
Like ``assert equals(series1, series2, ...)``, but with better hints at
where the series differ. See `equals` for
detailed parameter doc.
Parameters
----------
a... | [
"def",
"assert_equals",
"(",
"actual",
",",
"expected",
",",
"ignore_order",
"=",
"False",
",",
"ignore_index",
"=",
"False",
",",
"all_close",
"=",
"False",
")",
":",
"equals_",
",",
"reason",
"=",
"equals",
"(",
"actual",
",",
"expected",
",",
"ignore_or... | 35.166667 | 28.388889 |
def _init_usrgos(self, goids):
"""Return user GO IDs which have GO Terms."""
usrgos = set()
goids_missing = set()
_go2obj = self.gosubdag.go2obj
for goid in goids:
if goid in _go2obj:
usrgos.add(goid)
else:
goids_missing.add... | [
"def",
"_init_usrgos",
"(",
"self",
",",
"goids",
")",
":",
"usrgos",
"=",
"set",
"(",
")",
"goids_missing",
"=",
"set",
"(",
")",
"_go2obj",
"=",
"self",
".",
"gosubdag",
".",
"go2obj",
"for",
"goid",
"in",
"goids",
":",
"if",
"goid",
"in",
"_go2obj... | 37.428571 | 15.071429 |
def Page_screencastFrameAck(self, sessionId):
"""
Function path: Page.screencastFrameAck
Domain: Page
Method name: screencastFrameAck
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'sessionId' (type: integer) -> Frame number.
No return value.
Des... | [
"def",
"Page_screencastFrameAck",
"(",
"self",
",",
"sessionId",
")",
":",
"assert",
"isinstance",
"(",
"sessionId",
",",
"(",
"int",
",",
")",
")",
",",
"\"Argument 'sessionId' must be of type '['int']'. Received type: '%s'\"",
"%",
"type",
"(",
"sessionId",
")",
"... | 30.809524 | 19.761905 |
def thorium(opts, functions, runners):
'''
Load the thorium runtime modules
'''
pack = {'__salt__': functions, '__runner__': runners, '__context__': {}}
ret = LazyLoader(_module_dirs(opts, 'thorium'),
opts,
tag='thorium',
pack=pack)
ret.pack['__thorium__'] = r... | [
"def",
"thorium",
"(",
"opts",
",",
"functions",
",",
"runners",
")",
":",
"pack",
"=",
"{",
"'__salt__'",
":",
"functions",
",",
"'__runner__'",
":",
"runners",
",",
"'__context__'",
":",
"{",
"}",
"}",
"ret",
"=",
"LazyLoader",
"(",
"_module_dirs",
"("... | 29.727273 | 18.818182 |
def UploadAccount(self, hash_algorithm, hash_key, accounts):
"""Uploads multiple accounts to Gitkit server.
Args:
hash_algorithm: string, algorithm to hash password.
hash_key: string, base64-encoded key of the algorithm.
accounts: array of accounts to be uploaded.
Returns:
Response... | [
"def",
"UploadAccount",
"(",
"self",
",",
"hash_algorithm",
",",
"hash_key",
",",
"accounts",
")",
":",
"param",
"=",
"{",
"'hashAlgorithm'",
":",
"hash_algorithm",
",",
"'signerKey'",
":",
"hash_key",
",",
"'users'",
":",
"accounts",
"}",
"# pylint does not rec... | 31.736842 | 18.526316 |
def write(self, *args, **kwargs):
"""Write that shows progress in statusbar for each <freq> cells"""
self.progress_status()
# Check abortes state and raise StopIteration if aborted
if self.aborted:
statustext = _("File saving aborted.")
post_command_event(self.m... | [
"def",
"write",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"progress_status",
"(",
")",
"# Check abortes state and raise StopIteration if aborted",
"if",
"self",
".",
"aborted",
":",
"statustext",
"=",
"_",
"(",
"\"File savi... | 37.230769 | 20.615385 |
def charge_credit_card(self, credit_card_psp_object: Model, amount: Money, client_ref: str) -> Tuple[bool, Model]:
"""
:param credit_card_psp_object: an instance representing the credit card in the psp
:param amount: the amount to charge
:param client_ref: a reference that will appear on... | [
"def",
"charge_credit_card",
"(",
"self",
",",
"credit_card_psp_object",
":",
"Model",
",",
"amount",
":",
"Money",
",",
"client_ref",
":",
"str",
")",
"->",
"Tuple",
"[",
"bool",
",",
"Model",
"]",
":",
"pass"
] | 53.375 | 27.625 |
def eval_multi(self, inc_epoch=True):
"""
Run the evaluation on multiple attacks.
"""
sess = self.sess
preds = self.preds
x = self.x_pre
y = self.y
X_train = self.X_train
Y_train = self.Y_train
X_test = self.X_test
Y_test = self.Y_test
writer = self.writer
self.summa... | [
"def",
"eval_multi",
"(",
"self",
",",
"inc_epoch",
"=",
"True",
")",
":",
"sess",
"=",
"self",
".",
"sess",
"preds",
"=",
"self",
".",
"preds",
"x",
"=",
"self",
".",
"x_pre",
"y",
"=",
"self",
".",
"y",
"X_train",
"=",
"self",
".",
"X_train",
"... | 32.545455 | 17.781818 |
def get_value(self, key, default={}, nested=True, decrypt=True):
"""
Retrieve a value from the configuration based on its key. The key
may be nested.
:param str key: A path to the value, with nested levels joined by '.'
:param default: Value to return if the key does not exist (... | [
"def",
"get_value",
"(",
"self",
",",
"key",
",",
"default",
"=",
"{",
"}",
",",
"nested",
"=",
"True",
",",
"decrypt",
"=",
"True",
")",
":",
"key",
"=",
"key",
".",
"lstrip",
"(",
")",
"if",
"key",
".",
"endswith",
"(",
"\".\"",
")",
":",
"ke... | 37.384615 | 17.769231 |
def _form_onset_offset_fronts(ons_or_offs, sample_rate_hz, threshold_ms=20):
"""
Takes an array of onsets or offsets (shape = [nfrequencies, nsamples], where a 1 corresponds to an on/offset,
and samples are 0 otherwise), and returns a new array of the same shape, where each 1 has been replaced by
either... | [
"def",
"_form_onset_offset_fronts",
"(",
"ons_or_offs",
",",
"sample_rate_hz",
",",
"threshold_ms",
"=",
"20",
")",
":",
"threshold_s",
"=",
"threshold_ms",
"/",
"1000",
"threshold_samples",
"=",
"sample_rate_hz",
"*",
"threshold_s",
"ons_or_offs",
"=",
"np",
".",
... | 53.123077 | 29.246154 |
def set_operator(self, operator):
"""Set the current :ref:`OPERATOR`
to be used for all drawing operations.
The default operator is :obj:`OVER <OPERATOR_OVER>`.
:param operator: A :ref:`OPERATOR` string.
"""
cairo.cairo_set_operator(self._pointer, operator)
sel... | [
"def",
"set_operator",
"(",
"self",
",",
"operator",
")",
":",
"cairo",
".",
"cairo_set_operator",
"(",
"self",
".",
"_pointer",
",",
"operator",
")",
"self",
".",
"_check_status",
"(",
")"
] | 29.727273 | 17.454545 |
def _on_scan(_loop, adapter, _adapter_id, info, expiration_time):
"""Callback when a new device is seen."""
info['validity_period'] = expiration_time
adapter.notify_event_nowait(info.get('connection_string'), 'device_seen', info) | [
"def",
"_on_scan",
"(",
"_loop",
",",
"adapter",
",",
"_adapter_id",
",",
"info",
",",
"expiration_time",
")",
":",
"info",
"[",
"'validity_period'",
"]",
"=",
"expiration_time",
"adapter",
".",
"notify_event_nowait",
"(",
"info",
".",
"get",
"(",
"'connection... | 47.6 | 22.6 |
def _low_level_exec_command(self, conn, cmd, tmp, sudoable=False, executable=None):
''' execute a command string over SSH, return the output '''
if executable is None:
executable = '/bin/sh'
sudo_user = self.sudo_user
rc, stdin, stdout, stderr = conn.exec_command(cmd, tmp, ... | [
"def",
"_low_level_exec_command",
"(",
"self",
",",
"conn",
",",
"cmd",
",",
"tmp",
",",
"sudoable",
"=",
"False",
",",
"executable",
"=",
"None",
")",
":",
"if",
"executable",
"is",
"None",
":",
"executable",
"=",
"'/bin/sh'",
"sudo_user",
"=",
"self",
... | 33.173913 | 23.869565 |
def load_schema(schema_path):
'''
Returns a schema loaded from the file at `schema_path`.
Will recursively load referenced schemas assuming they can be found in
files in the same directory and named with the convention
`<type_name>.avsc`.
'''
with open(schema_path) as fd:
schema = j... | [
"def",
"load_schema",
"(",
"schema_path",
")",
":",
"with",
"open",
"(",
"schema_path",
")",
"as",
"fd",
":",
"schema",
"=",
"json",
".",
"load",
"(",
"fd",
")",
"schema_dir",
",",
"schema_file",
"=",
"path",
".",
"split",
"(",
"schema_path",
")",
"ret... | 34.916667 | 20.083333 |
def expand_url(status):
"""Expand url on statuses.
:param status: A tweepy status to expand urls.
:type status: :class:`tweepy.models.Status`
:returns: A string with expanded urls.
:rtype: :class:`str`
"""
try:
txt = get_full_text(status)
for url in status.entities['urls']:... | [
"def",
"expand_url",
"(",
"status",
")",
":",
"try",
":",
"txt",
"=",
"get_full_text",
"(",
"status",
")",
"for",
"url",
"in",
"status",
".",
"entities",
"[",
"'urls'",
"]",
":",
"txt",
"=",
"txt",
".",
"replace",
"(",
"url",
"[",
"'url'",
"]",
","... | 28.458333 | 15.166667 |
def get_asset_content(self, asset_content_id):
"""Gets the ``AssetContent`` specified by its ``Id``.
In plenary mode, the exact ``Id`` is found or a ``NotFound``
results. Otherwise, the returned ``AssetContent`` may have a different
``Id`` than requested, such as the case where a duplic... | [
"def",
"get_asset_content",
"(",
"self",
",",
"asset_content_id",
")",
":",
"collection",
"=",
"JSONClientValidated",
"(",
"'repository'",
",",
"collection",
"=",
"'Asset'",
",",
"runtime",
"=",
"self",
".",
"_runtime",
")",
"asset_content_identifier",
"=",
"Objec... | 56.225806 | 27.129032 |
def LoadSecondaryConfig(self, filename=None, parser=None):
"""Loads an additional configuration file.
The configuration system has the concept of a single Primary configuration
file, and multiple secondary files. The primary configuration file is the
main file that is used by the program. Any writeback... | [
"def",
"LoadSecondaryConfig",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"parser",
"=",
"None",
")",
":",
"if",
"filename",
":",
"# Maintain a stack of config file locations in loaded order.",
"self",
".",
"files",
".",
"append",
"(",
"filename",
")",
"parser... | 38.984127 | 24.365079 |
def cinder(*arg):
"""
Cinder annotation for adding function to process cinder notification.
if event_type include wildcard, will put {pattern: function} into process_wildcard dict
else will put {event_type: function} into process dict
:param arg: event_type of notification
"""
check_event_... | [
"def",
"cinder",
"(",
"*",
"arg",
")",
":",
"check_event_type",
"(",
"Openstack",
".",
"Cinder",
",",
"*",
"arg",
")",
"event_type",
"=",
"arg",
"[",
"0",
"]",
"def",
"decorator",
"(",
"func",
")",
":",
"if",
"event_type",
".",
"find",
"(",
"\"*\"",
... | 31.703704 | 22.518519 |
def mjd2gmst(mjd):
"""Convert Modfied Juian Date (JD = 2400000.5) to GMST
Taken from P.T. Walace routines.
"""
tu = (mjd - MJD0) / (100*DPY)
st = math.fmod(mjd, 1.0) * D2PI + (24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * tu) * tu) * tu) * DS2R
w = math.fmod(st, D2PI)
if w >=... | [
"def",
"mjd2gmst",
"(",
"mjd",
")",
":",
"tu",
"=",
"(",
"mjd",
"-",
"MJD0",
")",
"/",
"(",
"100",
"*",
"DPY",
")",
"st",
"=",
"math",
".",
"fmod",
"(",
"mjd",
",",
"1.0",
")",
"*",
"D2PI",
"+",
"(",
"24110.54841",
"+",
"(",
"8640184.812866",
... | 22.5625 | 25.75 |
def fit(self, X=None, y=None, **kwargs):
"""Fit the blocks of this pipeline.
Sequentially call the `fit` and the `produce` methods of each block,
capturing the outputs each `produce` method before calling the `fit`
method of the next one.
During the whole process a context dict... | [
"def",
"fit",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"{",
"'X'",
":",
"X",
",",
"'y'",
":",
"y",
"}",
"context",
".",
"update",
"(",
"kwargs",
")",
"last_block_name",
"=",
... | 42.608696 | 24.913043 |
def open_machine(self, settings_file):
"""Opens a virtual machine from the existing settings file.
The opened machine remains unregistered until you call
:py:func:`register_machine` .
The specified settings file name must be fully qualified.
The file must exist and be a ... | [
"def",
"open_machine",
"(",
"self",
",",
"settings_file",
")",
":",
"if",
"not",
"isinstance",
"(",
"settings_file",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"settings_file can only be an instance of type basestring\"",
")",
"machine",
"=",
"self",
... | 38.5 | 18.966667 |
def _str_to_type(cls, context_class, string):
"""
:type context_class: type
:type string: str
:rtype: type
"""
if string in cls._TYPE_NAMES_BUILTIN:
return eval(string)
module_ = sys.modules[context_class.__module__]
if hasattr(module_, str... | [
"def",
"_str_to_type",
"(",
"cls",
",",
"context_class",
",",
"string",
")",
":",
"if",
"string",
"in",
"cls",
".",
"_TYPE_NAMES_BUILTIN",
":",
"return",
"eval",
"(",
"string",
")",
"module_",
"=",
"sys",
".",
"modules",
"[",
"context_class",
".",
"__modul... | 24.823529 | 18.235294 |
def _mouseUp(x, y, button):
"""Send the mouse up event to Windows by calling the mouse_event() win32
function.
Args:
x (int): The x position of the mouse event.
y (int): The y position of the mouse event.
button (str): The mouse button, either 'left', 'middle', or 'right'
Returns:
... | [
"def",
"_mouseUp",
"(",
"x",
",",
"y",
",",
"button",
")",
":",
"if",
"button",
"==",
"'left'",
":",
"try",
":",
"_sendMouseEvent",
"(",
"MOUSEEVENTF_LEFTUP",
",",
"x",
",",
"y",
")",
"except",
"(",
"PermissionError",
",",
"OSError",
")",
":",
"# TODO:... | 41.206897 | 31.241379 |
def make_pattern(self, pattern, listsep=','):
"""Make pattern for a data type with the specified cardinality.
.. code-block:: python
yes_no_pattern = r"yes|no"
many_yes_no = Cardinality.one_or_more.make_pattern(yes_no_pattern)
:param pattern: Regular expression for ty... | [
"def",
"make_pattern",
"(",
"self",
",",
"pattern",
",",
"listsep",
"=",
"','",
")",
":",
"if",
"self",
"is",
"Cardinality",
".",
"one",
":",
"return",
"pattern",
"elif",
"self",
"is",
"Cardinality",
".",
"zero_or_one",
":",
"return",
"self",
".",
"schem... | 39.277778 | 18.944444 |
def _make_param_matcher(annotation, kind=None):
'''
For a given annotation, return a function which, when called on a
function argument, returns true if that argument matches the annotation.
If the annotation is a type, it calls isinstance; if it's a callable,
it calls it on the ... | [
"def",
"_make_param_matcher",
"(",
"annotation",
",",
"kind",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"annotation",
",",
"type",
")",
"or",
"(",
"isinstance",
"(",
"annotation",
",",
"tuple",
")",
"and",
"all",
"(",
"isinstance",
"(",
"a",
",",
... | 50.25 | 22.75 |
def length(self,threshold=0.2,phys=False,ang=False,tdisrupt=None,
**kwargs):
"""
NAME:
length
PURPOSE:
calculate the length of the stream
INPUT:
threshold - threshold down from the density near the progenitor at which to define the 'en... | [
"def",
"length",
"(",
"self",
",",
"threshold",
"=",
"0.2",
",",
"phys",
"=",
"False",
",",
"ang",
"=",
"False",
",",
"tdisrupt",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"peak_dens",
"=",
"self",
".",
"density_par",
"(",
"0.1",
",",
"tdisru... | 46.25 | 30.888889 |
def get(self, project):
"""Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code"""
try:
data = self.request(project + '/')
except:
raise
if not isinstance(data, clam.common.data.CLAMData):
... | [
"def",
"get",
"(",
"self",
",",
"project",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"request",
"(",
"project",
"+",
"'/'",
")",
"except",
":",
"raise",
"if",
"not",
"isinstance",
"(",
"data",
",",
"clam",
".",
"common",
".",
"data",
".",
"... | 40.4 | 18.1 |
def kent_mean(dec=None, inc=None, di_block=None):
"""
Calculates the Kent mean and associated statistical parameters from either a list of
declination values and a separate list of inclination values or from a
di_block (a nested list a nested list of [dec,inc,1.0]). Returns a
dictionary with the Ken... | [
"def",
"kent_mean",
"(",
"dec",
"=",
"None",
",",
"inc",
"=",
"None",
",",
"di_block",
"=",
"None",
")",
":",
"if",
"di_block",
"is",
"None",
":",
"di_block",
"=",
"make_di_block",
"(",
"dec",
",",
"inc",
")",
"return",
"pmag",
".",
"dokent",
"(",
... | 31.708333 | 23.583333 |
def http_keepalive (headers):
"""
Get HTTP keepalive value, either from the Keep-Alive header or a
default value.
@param headers: HTTP headers
@type headers: dict
@return: keepalive in seconds
@rtype: int
"""
keepalive = headers.get("Keep-Alive")
if keepalive is not None:
... | [
"def",
"http_keepalive",
"(",
"headers",
")",
":",
"keepalive",
"=",
"headers",
".",
"get",
"(",
"\"Keep-Alive\"",
")",
"if",
"keepalive",
"is",
"not",
"None",
":",
"try",
":",
"keepalive",
"=",
"int",
"(",
"keepalive",
"[",
"8",
":",
"]",
".",
"strip"... | 27.052632 | 14 |
def IsComposite(self):
"""Determines if the data type is composite.
A composite data type consists of other data types.
Returns:
bool: True if the data type is composite, False otherwise.
"""
return bool(self.condition) or (
self.member_data_type_definition and
self.member_da... | [
"def",
"IsComposite",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"condition",
")",
"or",
"(",
"self",
".",
"member_data_type_definition",
"and",
"self",
".",
"member_data_type_definition",
".",
"IsComposite",
"(",
")",
")"
] | 31.181818 | 17.090909 |
def get_resource_notification_session_for_bin(self, resource_receiver, bin_id, proxy):
"""Gets the resource notification session for the given bin.
arg: resource_receiver (osid.resource.ResourceReceiver):
notification callback
arg: bin_id (osid.id.Id): the ``Id`` of the bi... | [
"def",
"get_resource_notification_session_for_bin",
"(",
"self",
",",
"resource_receiver",
",",
"bin_id",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_resource_notification",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
... | 50.962963 | 22.185185 |
def row(self, columnnames=[], exclude=False):
"""Return a tablerow object which includes (or excludes) the
given columns.
:class:`tablerow` makes it possible to get/put values in one or
more rows.
"""
from .tablerow import tablerow
return tablerow(self, columnna... | [
"def",
"row",
"(",
"self",
",",
"columnnames",
"=",
"[",
"]",
",",
"exclude",
"=",
"False",
")",
":",
"from",
".",
"tablerow",
"import",
"tablerow",
"return",
"tablerow",
"(",
"self",
",",
"columnnames",
",",
"exclude",
")"
] | 32.4 | 16.9 |
def read_handle(url, cache=None, mode="rb"):
"""Read from any URL with a file handle.
Use this to get a handle to a file rather than eagerly load the data:
```
with read_handle(url) as handle:
result = something.load(handle)
result.do_something()
```
When program execution leaves th... | [
"def",
"read_handle",
"(",
"url",
",",
"cache",
"=",
"None",
",",
"mode",
"=",
"\"rb\"",
")",
":",
"scheme",
"=",
"urlparse",
"(",
"url",
")",
".",
"scheme",
"if",
"cache",
"==",
"'purge'",
":",
"_purge_cached",
"(",
"url",
")",
"cache",
"=",
"None",... | 26.681818 | 23.25 |
def non_dependency (self):
""" Returns properties that are not dependencies.
"""
result = [p for p in self.lazy_properties if not p.feature.dependency]
result.extend(self.non_dependency_)
return result | [
"def",
"non_dependency",
"(",
"self",
")",
":",
"result",
"=",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"lazy_properties",
"if",
"not",
"p",
".",
"feature",
".",
"dependency",
"]",
"result",
".",
"extend",
"(",
"self",
".",
"non_dependency_",
")",
"ret... | 39.333333 | 12.333333 |
def _param_from_config(key, data):
'''
Return EC2 API parameters based on the given config data.
Examples:
1. List of dictionaries
>>> data = [
... {'DeviceIndex': 0, 'SubnetId': 'subid0',
... 'AssociatePublicIpAddress': True},
... {'DeviceIndex': 1,
... 'SubnetId'... | [
"def",
"_param_from_config",
"(",
"key",
",",
"data",
")",
":",
"param",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"data",
")",
":",
"param",
".",
"update",
"(... | 35.342857 | 18.142857 |
def enable_root_user(self):
"""
Enables login from any host for the root user and provides
the user with a generated root password.
"""
uri = "/instances/%s/root" % self.id
resp, body = self.manager.api.method_post(uri)
return body["user"]["password"] | [
"def",
"enable_root_user",
"(",
"self",
")",
":",
"uri",
"=",
"\"/instances/%s/root\"",
"%",
"self",
".",
"id",
"resp",
",",
"body",
"=",
"self",
".",
"manager",
".",
"api",
".",
"method_post",
"(",
"uri",
")",
"return",
"body",
"[",
"\"user\"",
"]",
"... | 37.5 | 8.25 |
def add_data(self):
"""This function properly constructs a QR code's data string. It takes
into account the interleaving pattern required by the standard.
"""
#Encode the data into a QR code
self.buffer.write(self.binary_string(self.mode, 4))
self.buffer.write(self.get_da... | [
"def",
"add_data",
"(",
"self",
")",
":",
"#Encode the data into a QR code",
"self",
".",
"buffer",
".",
"write",
"(",
"self",
".",
"binary_string",
"(",
"self",
".",
"mode",
",",
"4",
")",
")",
"self",
".",
"buffer",
".",
"write",
"(",
"self",
".",
"g... | 40.009901 | 19.564356 |
def processing_block_list():
"""Return the list of processing blocks known to SDP."""
pb_list = ProcessingBlockList()
return dict(active=pb_list.active,
completed=pb_list.completed,
aborted=pb_list.aborted) | [
"def",
"processing_block_list",
"(",
")",
":",
"pb_list",
"=",
"ProcessingBlockList",
"(",
")",
"return",
"dict",
"(",
"active",
"=",
"pb_list",
".",
"active",
",",
"completed",
"=",
"pb_list",
".",
"completed",
",",
"aborted",
"=",
"pb_list",
".",
"aborted"... | 40.833333 | 3.833333 |
def oauth2_token_exchange(client_id, client_secret, redirect_uri,
base_url=OH_BASE_URL, code=None, refresh_token=None):
"""
Exchange code or refresh token for a new token and refresh token. For the
first time when a project is created, code is required to generate refresh
token... | [
"def",
"oauth2_token_exchange",
"(",
"client_id",
",",
"client_secret",
",",
"redirect_uri",
",",
"base_url",
"=",
"OH_BASE_URL",
",",
"code",
"=",
"None",
",",
"refresh_token",
"=",
"None",
")",
":",
"if",
"not",
"(",
"code",
"or",
"refresh_token",
")",
"or... | 44.666667 | 22.461538 |
def questions(self, type=None):
"""Get questions associated with this participant.
Return a list of questions associated with the participant. If
specified, ``type`` filters by class.
"""
if type is None:
type = Question
if not issubclass(type, Question):
... | [
"def",
"questions",
"(",
"self",
",",
"type",
"=",
"None",
")",
":",
"if",
"type",
"is",
"None",
":",
"type",
"=",
"Question",
"if",
"not",
"issubclass",
"(",
"type",
",",
"Question",
")",
":",
"raise",
"TypeError",
"(",
"\"{} is not a valid question type.... | 32.071429 | 21.142857 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.