text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_app_volume_mounts(app_name, assembled_specs, test=False):
""" This returns a list of formatted volume specs for an app. These mounts declared in the apps' spec
and mounts declared in all lib specs the app depends on"""
app_spec = assembled_specs['apps'][app_name]
volumes = [get_command_files_vol... | [
"def",
"get_app_volume_mounts",
"(",
"app_name",
",",
"assembled_specs",
",",
"test",
"=",
"False",
")",
":",
"app_spec",
"=",
"assembled_specs",
"[",
"'apps'",
"]",
"[",
"app_name",
"]",
"volumes",
"=",
"[",
"get_command_files_volume_mount",
"(",
"app_name",
",... | 53.727273 | 14.909091 |
def setAutoRangeOn(self, axisNumber):
""" Sets the auto-range of the axis on.
:param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
"""
setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber) | [
"def",
"setAutoRangeOn",
"(",
"self",
",",
"axisNumber",
")",
":",
"setXYAxesAutoRangeOn",
"(",
"self",
",",
"self",
".",
"xAxisRangeCti",
",",
"self",
".",
"yAxisRangeCti",
",",
"axisNumber",
")"
] | 43.166667 | 21.166667 |
def ultimate_oscillator(close_data, low_data):
"""
Ultimate Oscillator.
Formula:
UO = 100 * ((4 * AVG7) + (2 * AVG14) + AVG28) / (4 + 2 + 1)
"""
a7 = 4 * average_7(close_data, low_data)
a14 = 2 * average_14(close_data, low_data)
a28 = average_28(close_data, low_data)
uo = 100 * ((a7... | [
"def",
"ultimate_oscillator",
"(",
"close_data",
",",
"low_data",
")",
":",
"a7",
"=",
"4",
"*",
"average_7",
"(",
"close_data",
",",
"low_data",
")",
"a14",
"=",
"2",
"*",
"average_14",
"(",
"close_data",
",",
"low_data",
")",
"a28",
"=",
"average_28",
... | 28.416667 | 12.916667 |
def data(self, index, role=Qt.DisplayRole):
"""Return a model data element"""
if not index.isValid():
return to_qvariant()
if role == Qt.DisplayRole:
return self._display_data(index)
elif role == Qt.BackgroundColorRole:
return to_qvariant(get_co... | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"to_qvariant",
"(",
")",
"if",
"role",
"==",
"Qt",
".",
"DisplayRole",
":",
"return",
"se... | 45.545455 | 11.181818 |
def execute(helper, config, args):
"""
Lists environments
"""
envs = config.get('app', {}).get('environments', [])
out("Parsed environments:")
for name, conf in list(envs.items()):
out('\t'+name)
envs = helper.get_environments()
out("Deployed environments:")
for env in envs:
... | [
"def",
"execute",
"(",
"helper",
",",
"config",
",",
"args",
")",
":",
"envs",
"=",
"config",
".",
"get",
"(",
"'app'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'environments'",
",",
"[",
"]",
")",
"out",
"(",
"\"Parsed environments:\"",
")",
"for",
"... | 34.615385 | 12.307692 |
def _basename_in_blacklist_re(base_name, black_list_re):
"""Determines if the basename is matched in a regex blacklist
:param str base_name: The basename of the file
:param list black_list_re: A collection of regex patterns to match against.
Successful matches are blacklisted.
:returns: `True`... | [
"def",
"_basename_in_blacklist_re",
"(",
"base_name",
",",
"black_list_re",
")",
":",
"for",
"file_pattern",
"in",
"black_list_re",
":",
"if",
"file_pattern",
".",
"match",
"(",
"base_name",
")",
":",
"return",
"True",
"return",
"False"
] | 36.071429 | 17.642857 |
def get_stroke_features(recording, strokeid1, strokeid2):
"""Get the features used to decide if two strokes belong to the same symbol
or not.
Parameters
----------
recording : list
A list of strokes
strokeid1 : int
strokeid2 : int
Returns
-------
list :
A list o... | [
"def",
"get_stroke_features",
"(",
"recording",
",",
"strokeid1",
",",
"strokeid2",
")",
":",
"stroke1",
"=",
"recording",
"[",
"strokeid1",
"]",
"stroke2",
"=",
"recording",
"[",
"strokeid2",
"]",
"assert",
"isinstance",
"(",
"stroke1",
",",
"list",
")",
",... | 36.058824 | 20.176471 |
def shelf(self, shelf=None):
""" Defines a shelf to use for this recipe """
if shelf is None:
self._shelf = Shelf({})
elif isinstance(shelf, Shelf):
self._shelf = shelf
elif isinstance(shelf, dict):
self._shelf = Shelf(shelf)
else:
... | [
"def",
"shelf",
"(",
"self",
",",
"shelf",
"=",
"None",
")",
":",
"if",
"shelf",
"is",
"None",
":",
"self",
".",
"_shelf",
"=",
"Shelf",
"(",
"{",
"}",
")",
"elif",
"isinstance",
"(",
"shelf",
",",
"Shelf",
")",
":",
"self",
".",
"_shelf",
"=",
... | 36.4 | 13.6 |
def max_validator(max_value):
"""Return validator function that ensures upper bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check.
Args:
max_value: maximum value for new validator
"""
def valid... | [
"def",
"max_validator",
"(",
"max_value",
")",
":",
"def",
"validator",
"(",
"value",
")",
":",
"if",
"value",
">",
"max_value",
":",
"raise",
"ValidationError",
"(",
"\"{} is not <= {}\"",
".",
"format",
"(",
"value",
",",
"max_value",
")",
")",
"return",
... | 29.866667 | 23.133333 |
def decode(self, targets, encoder_outputs, attention_bias):
"""Generate logits for each value in the target sequence.
Args:
targets: target values for the output sequence.
int tensor with shape [batch_size, target_length]
encoder_outputs: continuous representation of input sequence.
... | [
"def",
"decode",
"(",
"self",
",",
"targets",
",",
"encoder_outputs",
",",
"attention_bias",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"decode\"",
")",
":",
"# Prepare inputs to decoder layers by shifting targets, adding positional",
"# encoding and applying dropout... | 43.975 | 19.575 |
def kill_running_submission(self, submissionid, user_check=True):
""" Attempt to kill the remote job associated with this submission id.
:param submissionid:
:param user_check: Check if the current user owns this submission
:return: True if the job was killed, False if an error occurred
... | [
"def",
"kill_running_submission",
"(",
"self",
",",
"submissionid",
",",
"user_check",
"=",
"True",
")",
":",
"submission",
"=",
"self",
".",
"get_submission",
"(",
"submissionid",
",",
"user_check",
")",
"if",
"not",
"submission",
":",
"return",
"False",
"if"... | 43.076923 | 17.923077 |
def kill(config, container, *args, **kwargs):
'''
Kill a running container
:type container: string
:param container: The container id to kill
:rtype: dict
:returns: boolean
'''
err = "Unknown"
client = _get_client(config)
try:
dcontainer = _get_container_infos(config, c... | [
"def",
"kill",
"(",
"config",
",",
"container",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"err",
"=",
"\"Unknown\"",
"client",
"=",
"_get_client",
"(",
"config",
")",
"try",
":",
"dcontainer",
"=",
"_get_container_infos",
"(",
"config",
",",
... | 27.192308 | 17.961538 |
def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 3)
self.set_attributes(priority, address, rtr)
self._wday = data[0... | [
"def",
"populate",
"(",
"self",
",",
"priority",
",",
"address",
",",
"rtr",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"needs_low_priority",
"(",
"priority",
")",
"self",
".",
"needs_no_rtr",
"(",
"rtr",
... | 30.583333 | 8.083333 |
def pypackable(name, pytype, format):
"""
Create a "mix-in" class with a python type and a
Packable with the given struct format
"""
size, items = _formatinfo(format)
return type(Packable)(name, (pytype, Packable), {
'_format_': format,
'_size_': size,
'_items_': items,
... | [
"def",
"pypackable",
"(",
"name",
",",
"pytype",
",",
"format",
")",
":",
"size",
",",
"items",
"=",
"_formatinfo",
"(",
"format",
")",
"return",
"type",
"(",
"Packable",
")",
"(",
"name",
",",
"(",
"pytype",
",",
"Packable",
")",
",",
"{",
"'_format... | 28.636364 | 10.090909 |
def get_json(self, path, watch=None):
"""Reads the data of the specified node and converts it to json."""
data, _ = self.get(path, watch)
return load_json(data) if data else None | [
"def",
"get_json",
"(",
"self",
",",
"path",
",",
"watch",
"=",
"None",
")",
":",
"data",
",",
"_",
"=",
"self",
".",
"get",
"(",
"path",
",",
"watch",
")",
"return",
"load_json",
"(",
"data",
")",
"if",
"data",
"else",
"None"
] | 49.75 | 3 |
def _gen_next(self, history):
"""Generate next character sampled from the distribution of characters next.
"""
orig_history = history
if not history:
return helper.START
history = history[-(self._n-1):]
kv = [(k, v) for k, v in self._T.items(history)
... | [
"def",
"_gen_next",
"(",
"self",
",",
"history",
")",
":",
"orig_history",
"=",
"history",
"if",
"not",
"history",
":",
"return",
"helper",
".",
"START",
"history",
"=",
"history",
"[",
"-",
"(",
"self",
".",
"_n",
"-",
"1",
")",
":",
"]",
"kv",
"=... | 44.947368 | 10.368421 |
def update_system_numbers(self):
"""035 Externals."""
scn_035_fields = record_get_field_instances(self.record, '035')
new_fields = []
for field in scn_035_fields:
subs = field_get_subfields(field)
if '9' in subs:
if subs['9'][0].lower() == "cds" an... | [
"def",
"update_system_numbers",
"(",
"self",
")",
":",
"scn_035_fields",
"=",
"record_get_field_instances",
"(",
"self",
".",
"record",
",",
"'035'",
")",
"new_fields",
"=",
"[",
"]",
"for",
"field",
"in",
"scn_035_fields",
":",
"subs",
"=",
"field_get_subfields... | 49.4 | 18.466667 |
def requestHistoricalData(self, contracts=None, resolution="1 min",
lookback="1 D", data="TRADES", end_datetime=None, rth=False,
csv_path=None, format_date=2, utc=False):
"""
Download to historical data
https://www.interactivebrokers.com/en/software/api/apiguide/java/req... | [
"def",
"requestHistoricalData",
"(",
"self",
",",
"contracts",
"=",
"None",
",",
"resolution",
"=",
"\"1 min\"",
",",
"lookback",
"=",
"\"1 D\"",
",",
"data",
"=",
"\"TRADES\"",
",",
"end_datetime",
"=",
"None",
",",
"rth",
"=",
"False",
",",
"csv_path",
"... | 36.236842 | 17.394737 |
async def register(self, channel, event, callback):
"""Register a callback to ``channel_name`` and ``event``.
A prefix will be added to the channel name if not already available or
the prefix is an empty string
:param channel: channel name
:param event: event name
:para... | [
"async",
"def",
"register",
"(",
"self",
",",
"channel",
",",
"event",
",",
"callback",
")",
":",
"channel",
"=",
"self",
".",
"channel",
"(",
"channel",
")",
"event",
"=",
"channel",
".",
"register",
"(",
"event",
",",
"callback",
")",
"await",
"chann... | 39.75 | 16 |
def transfer_sanity_check( name, consensus_hash ):
"""
Verify that data for a transfer is valid.
Return True on success
Raise Exception on error
"""
if name is not None and (not is_b40( name ) or "+" in name or name.count(".") > 1):
raise Exception("Name '%s' has non-base-38 characters" ... | [
"def",
"transfer_sanity_check",
"(",
"name",
",",
"consensus_hash",
")",
":",
"if",
"name",
"is",
"not",
"None",
"and",
"(",
"not",
"is_b40",
"(",
"name",
")",
"or",
"\"+\"",
"in",
"name",
"or",
"name",
".",
"count",
"(",
"\".\"",
")",
">",
"1",
")",... | 37.866667 | 24 |
def get_comments(jam, ann):
'''Get the metadata from a jam and an annotation, combined as a string.
Parameters
----------
jam : JAMS
The jams object
ann : Annotation
An annotation object
Returns
-------
comments : str
The jam.file_metadata and ann.annotation_me... | [
"def",
"get_comments",
"(",
"jam",
",",
"ann",
")",
":",
"jam_comments",
"=",
"jam",
".",
"file_metadata",
".",
"__json__",
"ann_comments",
"=",
"ann",
".",
"annotation_metadata",
".",
"__json__",
"return",
"json",
".",
"dumps",
"(",
"{",
"'metadata'",
":",
... | 27.571429 | 23.952381 |
def add_section_break(self):
"""Return `w:sectPr` element for new section added at end of document.
The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an
exact clone of the previous one, except that all header and footer references
are removed (and are therefo... | [
"def",
"add_section_break",
"(",
"self",
")",
":",
"# ---get the sectPr at file-end, which controls last section (sections[-1])---",
"sentinel_sectPr",
"=",
"self",
".",
"get_or_add_sectPr",
"(",
")",
"# ---add exact copy to new `w:p` element; that is now second-to last section---",
"s... | 59.47619 | 29.809524 |
def should_include_node(
self, node: Union[FragmentSpreadNode, FieldNode, InlineFragmentNode]
) -> bool:
"""Check if node should be included
Determines if a field should be included based on the @include and @skip
directives, where @skip has higher precedence than @include.
... | [
"def",
"should_include_node",
"(",
"self",
",",
"node",
":",
"Union",
"[",
"FragmentSpreadNode",
",",
"FieldNode",
",",
"InlineFragmentNode",
"]",
")",
"->",
"bool",
":",
"skip",
"=",
"get_directive_values",
"(",
"GraphQLSkipDirective",
",",
"node",
",",
"self",... | 34.263158 | 22.578947 |
def dispatch(self, request, *args, **kwargs):
""" Dispatches an incoming request. """
self.request = request
self.args = args
self.kwargs = kwargs
response = self.check_permissions(request)
if response:
return response
return super().dispatch(request, ... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"request",
"=",
"request",
"self",
".",
"args",
"=",
"args",
"self",
".",
"kwargs",
"=",
"kwargs",
"response",
"=",
"self",
".",
"chec... | 36.444444 | 11.444444 |
def drop_retention_policy(database, name, **client_args):
'''
Drop a retention policy.
database
Name of the database for which the retention policy will be dropped.
name
Name of the retention policy to drop.
CLI Example:
.. code-block:: bash
salt '*' influxdb.drop_re... | [
"def",
"drop_retention_policy",
"(",
"database",
",",
"name",
",",
"*",
"*",
"client_args",
")",
":",
"client",
"=",
"_client",
"(",
"*",
"*",
"client_args",
")",
"client",
".",
"drop_retention_policy",
"(",
"name",
",",
"database",
")",
"return",
"True"
] | 21.75 | 26.55 |
def main():
"""
Install a package from pypi or gemfury
:return:
"""
pypitools.common.setup_main()
config = pypitools.common.ConfigData()
module_name = os.path.basename(os.getcwd())
args = []
if config.use_sudo:
args.extend([
'sudo',
'-H',
])
... | [
"def",
"main",
"(",
")",
":",
"pypitools",
".",
"common",
".",
"setup_main",
"(",
")",
"config",
"=",
"pypitools",
".",
"common",
".",
"ConfigData",
"(",
")",
"module_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"getcwd",
"(",
")",... | 24.810811 | 16.108108 |
def replace_embedded(self,src_file,dst_file):
"""Replace one embdded object by another one into a docx
This has been done mainly because it is not possible to add images
in docx header/footer.
With this function, put a dummy picture in your header/footer,
then specify it with it... | [
"def",
"replace_embedded",
"(",
"self",
",",
"src_file",
",",
"dst_file",
")",
":",
"with",
"open",
"(",
"dst_file",
",",
"'rb'",
")",
"as",
"fh",
":",
"crc",
"=",
"self",
".",
"get_file_crc",
"(",
"src_file",
")",
"self",
".",
"crc_to_new_embedded",
"["... | 43.8125 | 20.375 |
def _handle_update_msg(self, update_msg):
"""Extracts and processes new paths or withdrawals in given
`update_msg`.
Parameter:
- `update_msg`: update message to process.
- `valid_rts`: current valid/interesting rts to the application
according to configurati... | [
"def",
"_handle_update_msg",
"(",
"self",
",",
"update_msg",
")",
":",
"assert",
"self",
".",
"state",
".",
"bgp_state",
"==",
"const",
".",
"BGP_FSM_ESTABLISHED",
"# Increment count of update received.",
"self",
".",
"state",
".",
"incr",
"(",
"PeerCounterNames",
... | 40.791667 | 22.916667 |
def mapsplice(job, job_vars):
"""
Maps RNA-Seq reads to a reference genome.
job_vars: tuple Tuple of dictionaries: input_args and ids
"""
# Unpack variables
input_args, ids = job_vars
work_dir = job.fileStore.getLocalTempDir()
cores = input_args['cpu_count']
sudo = input_args['s... | [
"def",
"mapsplice",
"(",
"job",
",",
"job_vars",
")",
":",
"# Unpack variables",
"input_args",
",",
"ids",
"=",
"job_vars",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
"cores",
"=",
"input_args",
"[",
"'cpu_count'",
"]",
"sudo... | 41.76087 | 16.804348 |
def embedRasters(element, options):
import base64
"""
Converts raster references to inline images.
NOTE: there are size limits to base64-encoding handling in browsers
"""
global _num_rasters_embedded
href = element.getAttributeNS(NS['XLINK'], 'href')
# if xlink:href is set, then gr... | [
"def",
"embedRasters",
"(",
"element",
",",
"options",
")",
":",
"import",
"base64",
"global",
"_num_rasters_embedded",
"href",
"=",
"element",
".",
"getAttributeNS",
"(",
"NS",
"[",
"'XLINK'",
"]",
",",
"'href'",
")",
"# if xlink:href is set, then grab the id",
"... | 48.276316 | 24.144737 |
def parse_oxi_states(self, data):
"""
Parse oxidation states from data dictionary
"""
try:
oxi_states = {
data["_atom_type_symbol"][i]:
str2float(data["_atom_type_oxidation_number"][i])
for i in range(len(data["_atom_type_sy... | [
"def",
"parse_oxi_states",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"oxi_states",
"=",
"{",
"data",
"[",
"\"_atom_type_symbol\"",
"]",
"[",
"i",
"]",
":",
"str2float",
"(",
"data",
"[",
"\"_atom_type_oxidation_number\"",
"]",
"[",
"i",
"]",
")",
"... | 41.722222 | 17.944444 |
def ConsultarDepositosAcopio(self, sep="||"):
"Retorna los depósitos de acopio pertenencientes al contribuyente"
ret = self.client.consultarDepositosAcopio(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, }... | [
"def",
"ConsultarDepositosAcopio",
"(",
"self",
",",
"sep",
"=",
"\"||\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"consultarDepositosAcopio",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
":",
"self",
".",
"Sign",... | 46.666667 | 17.466667 |
def read_frames(self, nframes, dtype=np.float64):
"""Read nframes frames of the file.
:Parameters:
nframes : int
number of frames to read.
dtype : numpy dtype
dtype of the returned array containing read data (see note).
Notes
----... | [
"def",
"read_frames",
"(",
"self",
",",
"nframes",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
":",
"return",
"self",
".",
"_sndfile",
".",
"read_frames",
"(",
"nframes",
",",
"dtype",
")"
] | 45.26087 | 23.347826 |
def continue_object(self, workflow_object, restart_point='restart_task',
task_offset=1, stop_on_halt=False):
"""Continue workflow for one given object from "restart_point".
:param object:
:param stop_on_halt:
:param restart_point: can be one of:
* res... | [
"def",
"continue_object",
"(",
"self",
",",
"workflow_object",
",",
"restart_point",
"=",
"'restart_task'",
",",
"task_offset",
"=",
"1",
",",
"stop_on_halt",
"=",
"False",
")",
":",
"translate",
"=",
"{",
"'restart_task'",
":",
"'current'",
",",
"'continue_next... | 43.608696 | 20.565217 |
def _assign_kwargs(self, kwargs):
"""
Assigns all keyword arguments to a given instance, raising an exception
if one of the keywords is not already the name of a property.
"""
for k in kwargs:
if not hasattr(self, k):
raise AttributeError(k, 'Not valid for', self.__class__.__name... | [
"def",
"_assign_kwargs",
"(",
"self",
",",
"kwargs",
")",
":",
"for",
"k",
"in",
"kwargs",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"k",
")",
":",
"raise",
"AttributeError",
"(",
"k",
",",
"'Not valid for'",
",",
"self",
".",
"__class__",
".",
... | 39 | 15.222222 |
def print_graph(self, format=None, output=sys.stdout, depth=0, **kwargs):
"""
Print the graph for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
depth (int): depth of the graph.
"... | [
"def",
"print_graph",
"(",
"self",
",",
"format",
"=",
"None",
",",
"output",
"=",
"sys",
".",
"stdout",
",",
"depth",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"graph",
"=",
"self",
".",
"as_graph",
"(",
"depth",
"=",
"depth",
")",
"graph",
"... | 37.727273 | 15.181818 |
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network na... | [
"def",
"call",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The call function must be called with '",
"'-f or --function.'",
")",
"if",
"'f... | 25.475 | 21.725 |
def _find_dependant_trees(self, tree_obj):
""" returns list of trees that are dependent_on given tree_obj """
dependant_trees = []
for tree_name, tree in self.trees.items():
if tree_obj in tree.dependent_on:
dependant_trees.append(tree)
return dependant_trees | [
"def",
"_find_dependant_trees",
"(",
"self",
",",
"tree_obj",
")",
":",
"dependant_trees",
"=",
"[",
"]",
"for",
"tree_name",
",",
"tree",
"in",
"self",
".",
"trees",
".",
"items",
"(",
")",
":",
"if",
"tree_obj",
"in",
"tree",
".",
"dependent_on",
":",
... | 44.714286 | 6.142857 |
def next_state(self):
"""This is a method that will be called when the time remaining ends.
The current state can be: roasting, cooling, idle, sleeping, connecting,
or unkown."""
if(self.roaster.get_roaster_state() == 'roasting'):
self.roaster.time_remaining = 20
... | [
"def",
"next_state",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"roaster",
".",
"get_roaster_state",
"(",
")",
"==",
"'roasting'",
")",
":",
"self",
".",
"roaster",
".",
"time_remaining",
"=",
"20",
"self",
".",
"roaster",
".",
"cool",
"(",
")",
... | 47.111111 | 13.333333 |
def get_memory_map_xml(self):
"""! @brief Generate GDB memory map XML.
"""
root = ElementTree.Element('memory-map')
for r in self._context.core.memory_map:
# Look up the region type name. Regions default to ram if gdb doesn't
# have a concept of the region type.
... | [
"def",
"get_memory_map_xml",
"(",
"self",
")",
":",
"root",
"=",
"ElementTree",
".",
"Element",
"(",
"'memory-map'",
")",
"for",
"r",
"in",
"self",
".",
"_context",
".",
"core",
".",
"memory_map",
":",
"# Look up the region type name. Regions default to ram if gdb d... | 49.125 | 17.0625 |
def list_load_areas(self, session, mv_districts):
"""list load_areas (load areas) peak load from database for a single MV grid_district
Parameters
----------
session : sqlalchemy.orm.session.Session
Database session
mv_districts:
List of MV districts
... | [
"def",
"list_load_areas",
"(",
"self",
",",
"session",
",",
"mv_districts",
")",
":",
"# threshold: load area peak load, if peak load < threshold => disregard",
"# load area",
"lv_loads_threshold",
"=",
"cfg_ding0",
".",
"get",
"(",
"'mv_routing'",
",",
"'load_area_threshold'... | 46.145833 | 24.645833 |
def label_for_lm(self, **kwargs):
"A special labelling method for language models."
self.__class__ = LMTextList
kwargs['label_cls'] = LMLabelList
return self.label_const(0, **kwargs) | [
"def",
"label_for_lm",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__class__",
"=",
"LMTextList",
"kwargs",
"[",
"'label_cls'",
"]",
"=",
"LMLabelList",
"return",
"self",
".",
"label_const",
"(",
"0",
",",
"*",
"*",
"kwargs",
")"
] | 42 | 6.8 |
def update_role_config_group(resource_root, service_name, name, apigroup,
cluster_name="default"):
"""
Update a role config group by name.
@param resource_root: The root Resource object.
@param service_name: Service name.
@param name: Role config group name.
@param apigroup: The updated role config grou... | [
"def",
"update_role_config_group",
"(",
"resource_root",
",",
"service_name",
",",
"name",
",",
"apigroup",
",",
"cluster_name",
"=",
"\"default\"",
")",
":",
"return",
"call",
"(",
"resource_root",
".",
"put",
",",
"_get_role_config_group_path",
"(",
"cluster_name"... | 38.4 | 10.666667 |
def to_yaml(obj):
"""
This function returns correct YAML representation of a UAVCAN structure (message, request, or response), or
a DSDL entity (array or primitive), or a UAVCAN transfer, with comments for human benefit.
Args:
obj: Object to convert.
Returns: Unicode string conta... | [
"def",
"to_yaml",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"CompoundValue",
")",
"and",
"hasattr",
"(",
"obj",
",",
"'transfer'",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'message'",
")",
":",
"payload",
"=",
"obj",
".",
... | 38.451613 | 20.774194 |
def parallel_compute_ll_matrix(gp, bounds, num_pts, num_proc=None):
"""Compute matrix of the log likelihood over the parameter space in parallel.
Parameters
----------
bounds : 2-tuple or list of 2-tuples with length equal to the number of free parameters
Bounds on the range to use for each... | [
"def",
"parallel_compute_ll_matrix",
"(",
"gp",
",",
"bounds",
",",
"num_pts",
",",
"num_proc",
"=",
"None",
")",
":",
"if",
"num_proc",
"is",
"None",
":",
"num_proc",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"present_free_params",
"=",
"gp",
".",... | 37.164384 | 22.287671 |
def raw_command(netfn, command, bridge_request=None, data=(), retry=True, delay_xmit=None, **kwargs):
'''
Send raw ipmi command
This allows arbitrary IPMI bytes to be issued. This is commonly used
for certain vendor specific commands.
:param netfn: Net function number
:param command: Command ... | [
"def",
"raw_command",
"(",
"netfn",
",",
"command",
",",
"bridge_request",
"=",
"None",
",",
"data",
"=",
"(",
")",
",",
"retry",
"=",
"True",
",",
"delay_xmit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"_IpmiSession",
"(",
"*",
"*",
... | 32.416667 | 20.638889 |
def _argsort_and_resolve_ties(time, random_state):
"""Like numpy.argsort, but resolves ties uniformly at random"""
n_samples = len(time)
order = numpy.argsort(time, kind="mergesort")
i = 0
while i < n_samples - 1:
inext = i + 1
while inext < n_samples and... | [
"def",
"_argsort_and_resolve_ties",
"(",
"time",
",",
"random_state",
")",
":",
"n_samples",
"=",
"len",
"(",
"time",
")",
"order",
"=",
"numpy",
".",
"argsort",
"(",
"time",
",",
"kind",
"=",
"\"mergesort\"",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"n_... | 33.625 | 17.3125 |
def setitem(self, key, value):
# type: (Any, Any, Any) -> Any
'''Takes an object, a key, and a value and produces a new object
that is a copy of the original but with ``value`` as the new value of
``key``.
The following equality should hold for your definition:
.. code-block:: python
... | [
"def",
"setitem",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# type: (Any, Any, Any) -> Any",
"try",
":",
"self",
".",
"_lens_setitem",
"except",
"AttributeError",
":",
"selfcopy",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"selfcopy",
"[",
"key",
... | 34.714286 | 23.514286 |
def ConvertToTemplate(self,visibility,description=None,password=None):
"""Converts existing server to a template.
visibility is one of private or shared.
>>> d = clc.v2.Datacenter()
>>> clc.v2.Server(alias='BTDI',id='WA1BTDIAPI207').ConvertToTemplate("private","my template")
0
"""
if visibility not in... | [
"def",
"ConvertToTemplate",
"(",
"self",
",",
"visibility",
",",
"description",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"visibility",
"not",
"in",
"(",
"'private'",
",",
"'shared'",
")",
":",
"raise",
"(",
"clc",
".",
"CLCException",
"... | 41.1 | 29.95 |
def set_room_name(self, name):
"""Return True if room name successfully changed."""
try:
self.client.api.set_room_name(self.room_id, name)
self.name = name
return True
except MatrixRequestError:
return False | [
"def",
"set_room_name",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"self",
".",
"client",
".",
"api",
".",
"set_room_name",
"(",
"self",
".",
"room_id",
",",
"name",
")",
"self",
".",
"name",
"=",
"name",
"return",
"True",
"except",
"MatrixRequest... | 34 | 13.75 |
def average_true_range_percent(close_data, period):
"""
Average True Range Percent.
Formula:
ATRP = (ATR / CLOSE) * 100
"""
catch_errors.check_for_period_error(close_data, period)
atrp = (atr(close_data, period) / np.array(close_data)) * 100
return atrp | [
"def",
"average_true_range_percent",
"(",
"close_data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"close_data",
",",
"period",
")",
"atrp",
"=",
"(",
"atr",
"(",
"close_data",
",",
"period",
")",
"/",
"np",
".",
"array",
"(... | 27.7 | 16.7 |
def get_profile(self, img_type, coordinate, num_points):
''' Extract a profile from (lat1,lon1) to (lat2,lon2)
Args:
img_type (str): Either lola or wac.
coordinate (float,float,float,flaot): A tupple
``(lon0,lon1,lat0,lat1)`` with:
- lon0: First ... | [
"def",
"get_profile",
"(",
"self",
",",
"img_type",
",",
"coordinate",
",",
"num_points",
")",
":",
"lon0",
",",
"lon1",
",",
"lat0",
",",
"lat1",
"=",
"coordinate",
"X",
",",
"Y",
",",
"Z",
"=",
"self",
".",
"get_arrays",
"(",
"img_type",
")",
"y0",... | 37.233333 | 20.433333 |
def get_headers(data, extra_headers=None):
'''
Takes the response data as well as any additional headers and returns a
tuple of tuples of headers suitable for passing to start_response()
'''
response_headers = {
'Content-Length': str(len(data)),
}
if extra_headers:
response_... | [
"def",
"get_headers",
"(",
"data",
",",
"extra_headers",
"=",
"None",
")",
":",
"response_headers",
"=",
"{",
"'Content-Length'",
":",
"str",
"(",
"len",
"(",
"data",
")",
")",
",",
"}",
"if",
"extra_headers",
":",
"response_headers",
".",
"update",
"(",
... | 29.230769 | 22.461538 |
def assert_keys_have_values(self, caller, *keys):
"""Check that keys list are all in context and all have values.
Args:
*keys: Will check each of these keys in context
caller: string. Calling function name - just used for informational
messages
Raise... | [
"def",
"assert_keys_have_values",
"(",
"self",
",",
"caller",
",",
"*",
"keys",
")",
":",
"for",
"key",
"in",
"keys",
":",
"self",
".",
"assert_key_has_value",
"(",
"key",
",",
"caller",
")"
] | 34.6875 | 19.5625 |
def unpatch(*module_names):
"""undo :func:`patch`\es to standard library modules
this function takes one or more module names and puts back their patched
attributes to the standard library originals.
valid arguments are the same as for :func:`patch`.
with no arguments, undoes all monkeypatches th... | [
"def",
"unpatch",
"(",
"*",
"module_names",
")",
":",
"if",
"not",
"module_names",
":",
"module_names",
"=",
"_standard",
".",
"keys",
"(",
")",
"log",
".",
"info",
"(",
"\"undoing monkey-patches in-place (%d modules)\"",
"%",
"len",
"(",
"module_names",
")",
... | 35.615385 | 21.423077 |
def update(self, *args, **kw):
'''
Update the dictionary with items and names::
(items, names, **kw)
(dict, names, **kw)
(MIDict, names, **kw)
Optional positional argument ``names`` is only allowed when ``self.indices``
is empty (no indices are set y... | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
"and",
"self",
".",
"indices",
":",
"raise",
"ValueError",
"(",
"'Only one positional argument is allowed when the'",
"'index names are al... | 32.515152 | 20.818182 |
def requires(self):
"""
This task's dependencies:
* :py:class:`~.AggregateArtists` or
* :py:class:`~.AggregateArtistsSpark` if :py:attr:`~/.Top10Artists.use_spark` is set.
:return: object (:py:class:`luigi.task.Task`)
"""
if self.use_spark:
return Ag... | [
"def",
"requires",
"(",
"self",
")",
":",
"if",
"self",
".",
"use_spark",
":",
"return",
"AggregateArtistsSpark",
"(",
"self",
".",
"date_interval",
")",
"else",
":",
"return",
"AggregateArtists",
"(",
"self",
".",
"date_interval",
")"
] | 32.076923 | 19.461538 |
async def _wrap_ws(self, handler, *args, **kwargs):
''' wraps a handler by receiving a websocket request and returning a websocket response '''
try:
method = self.request_method()
# call the wrapped handler
data = await handler(self, *args, **kwargs)
statu... | [
"async",
"def",
"_wrap_ws",
"(",
"self",
",",
"handler",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"method",
"=",
"self",
".",
"request_method",
"(",
")",
"# call the wrapped handler",
"data",
"=",
"await",
"handler",
"(",
"self",
... | 41.181818 | 14.909091 |
def send_message(
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
"""
Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.... | [
"def",
"send_message",
"(",
"self",
",",
"request",
":",
"str",
",",
"response_expected",
":",
"bool",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Response",
":",
"response",
"=",
"self",
".",
"session",
".",
"post",
"(",
"self",
".",
"endpoint",
... | 33.666667 | 22.333333 |
def clear_caches(): # suppress(unused-function)
"""Clear all caches."""
for _, reader in _spellchecker_cache.values():
reader.close()
_spellchecker_cache.clear()
_valid_words_cache.clear()
_user_dictionary_cache.clear() | [
"def",
"clear_caches",
"(",
")",
":",
"# suppress(unused-function)",
"for",
"_",
",",
"reader",
"in",
"_spellchecker_cache",
".",
"values",
"(",
")",
":",
"reader",
".",
"close",
"(",
")",
"_spellchecker_cache",
".",
"clear",
"(",
")",
"_valid_words_cache",
".... | 30.25 | 12.625 |
def get_json(self):
"""Get the JSON stored on the usernotes wiki page.
Returns a dict representation of the usernotes (with the notes BLOB
decoded).
Raises:
RuntimeError if the usernotes version is incompatible with this
version of puni.
"""
... | [
"def",
"get_json",
"(",
"self",
")",
":",
"try",
":",
"usernotes",
"=",
"self",
".",
"subreddit",
".",
"wiki",
"[",
"self",
".",
"page_name",
"]",
".",
"content_md",
"notes",
"=",
"json",
".",
"loads",
"(",
"usernotes",
")",
"except",
"NotFound",
":",
... | 31.72 | 20.56 |
def update(self, z, R=None, UT=None, hx=None, **hx_args):
"""
Update the UKF with the given measurements. On return,
self.x and self.P contain the new mean and covariance of the filter.
Parameters
----------
z : numpy.array of shape (dim_z)
measurement vecto... | [
"def",
"update",
"(",
"self",
",",
"z",
",",
"R",
"=",
"None",
",",
"UT",
"=",
"None",
",",
"hx",
"=",
"None",
",",
"*",
"*",
"hx_args",
")",
":",
"if",
"z",
"is",
"None",
":",
"self",
".",
"z",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"No... | 32.893333 | 21.213333 |
def get_pools():
"""Get all pools."""
try:
pools = pool_api.get_pools()
except AirflowException as err:
_log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
else:
return jsonify([p.to_json() for ... | [
"def",
"get_pools",
"(",
")",
":",
"try",
":",
"pools",
"=",
"pool_api",
".",
"get_pools",
"(",
")",
"except",
"AirflowException",
"as",
"err",
":",
"_log",
".",
"error",
"(",
"err",
")",
"response",
"=",
"jsonify",
"(",
"error",
"=",
"\"{}\"",
".",
... | 29.272727 | 14.363636 |
def is_valid_sse_object(sse):
"""
Validate the SSE object and type
:param sse: SSE object defined.
"""
if sse and sse.type() != "SSE-C" and sse.type() != "SSE-KMS" and sse.type() != "SSE-S3":
raise InvalidArgumentError("unsuported type of sse argument in put_object") | [
"def",
"is_valid_sse_object",
"(",
"sse",
")",
":",
"if",
"sse",
"and",
"sse",
".",
"type",
"(",
")",
"!=",
"\"SSE-C\"",
"and",
"sse",
".",
"type",
"(",
")",
"!=",
"\"SSE-KMS\"",
"and",
"sse",
".",
"type",
"(",
")",
"!=",
"\"SSE-S3\"",
":",
"raise",
... | 36.125 | 19.375 |
def cal_v(self, p, temp, min_strain=0.3, max_strain=1.0):
"""
calculate unit-cell volume at given pressure and temperature
:param p: pressure in GPa
:param temp: temperature in K
:param min_strain: minimum strain searched for volume root
:param max_strain: maximum strain... | [
"def",
"cal_v",
"(",
"self",
",",
"p",
",",
"temp",
",",
"min_strain",
"=",
"0.3",
",",
"max_strain",
"=",
"1.0",
")",
":",
"v0",
"=",
"self",
".",
"params_therm",
"[",
"'v0'",
"]",
".",
"nominal_value",
"self",
".",
"force_norm",
"=",
"True",
"pp",
... | 37.258065 | 14.16129 |
def from_dict(cls, val):
"""Creates dict2 object from dict object
Args:
val (:obj:`dict`): Value to create from
Returns:
Equivalent dict2 object.
"""
if isinstance(val, dict2):
return val
elif isinstance(val, dict):
res =... | [
"def",
"from_dict",
"(",
"cls",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"dict2",
")",
":",
"return",
"val",
"elif",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"res",
"=",
"cls",
"(",
")",
"for",
"k",
",",
"v",
"in",
"va... | 23.96 | 16.72 |
def write(
stream_fragments, stream, normalize=True,
book=None, sources=None, names=None, mappings=None):
"""
Given an iterable of stream fragments, write it to the stream object
by using its write method. Returns a 3-tuple, where the first
element is the mapping, second element is the ... | [
"def",
"write",
"(",
"stream_fragments",
",",
"stream",
",",
"normalize",
"=",
"True",
",",
"book",
"=",
"None",
",",
"sources",
"=",
"None",
",",
"names",
"=",
"None",
",",
"mappings",
"=",
"None",
")",
":",
"def",
"push_line",
"(",
")",
":",
"mappi... | 42.915 | 23.375 |
def _load_file(self, f):
"""Get values from config file"""
try:
with open(f, 'r') as _fo:
_seria_in = seria.load(_fo)
_y = _seria_in.dump('yaml')
except IOError:
raise FiggypyError("could not open configuration file")
self.values.up... | [
"def",
"_load_file",
"(",
"self",
",",
"f",
")",
":",
"try",
":",
"with",
"open",
"(",
"f",
",",
"'r'",
")",
"as",
"_fo",
":",
"_seria_in",
"=",
"seria",
".",
"load",
"(",
"_fo",
")",
"_y",
"=",
"_seria_in",
".",
"dump",
"(",
"'yaml'",
")",
"ex... | 36.777778 | 10.888889 |
def remove_from_pythonpath(self, path):
"""Remove path from project's PYTHONPATH
Return True if path was removed, False if it was not found"""
pathlist = self.get_pythonpath()
if path in pathlist:
pathlist.pop(pathlist.index(path))
self.set_pythonpath(pathli... | [
"def",
"remove_from_pythonpath",
"(",
"self",
",",
"path",
")",
":",
"pathlist",
"=",
"self",
".",
"get_pythonpath",
"(",
")",
"if",
"path",
"in",
"pathlist",
":",
"pathlist",
".",
"pop",
"(",
"pathlist",
".",
"index",
"(",
"path",
")",
")",
"self",
".... | 38 | 7.9 |
def by_login(cls, session, login, local=True):
"""
Get a user from a given login.
:param session: SQLAlchemy session
:type session: :class:`sqlalchemy.Session`
:param login: the user login
:type login: unicode
:return: the associated user
:rtype: :class... | [
"def",
"by_login",
"(",
"cls",
",",
"session",
",",
"login",
",",
"local",
"=",
"True",
")",
":",
"user",
"=",
"cls",
".",
"first",
"(",
"session",
",",
"where",
"=",
"(",
"(",
"cls",
".",
"login",
"==",
"login",
")",
",",
"(",
"cls",
".",
"loc... | 33 | 13.210526 |
def _in(field, value, document):
"""
Returns True if document[field] is in the interable value. If the
supplied value is not an iterable, then a MalformedQueryException is raised
"""
try:
values = iter(value)
except TypeError:
raise MalformedQueryException("'$in' must accept an i... | [
"def",
"_in",
"(",
"field",
",",
"value",
",",
"document",
")",
":",
"try",
":",
"values",
"=",
"iter",
"(",
"value",
")",
"except",
"TypeError",
":",
"raise",
"MalformedQueryException",
"(",
"\"'$in' must accept an iterable\"",
")",
"return",
"document",
".",... | 33.363636 | 19.545455 |
def show_portindex_interface_info_input_all(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_portindex_interface_info = ET.Element("show_portindex_interface_info")
config = show_portindex_interface_info
input = ET.SubElement(show_portindex_in... | [
"def",
"show_portindex_interface_info_input_all",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_portindex_interface_info",
"=",
"ET",
".",
"Element",
"(",
"\"show_portindex_interface_info\"",
")",
... | 42.272727 | 15.272727 |
def is_oriented(self):
"""
Returns whether or not the current box is rotated at all.
"""
if util.is_shape(self.primitive.transform, (4, 4)):
return not np.allclose(self.primitive.transform[
0:3, 0:3], np.eye(3))
else:
ret... | [
"def",
"is_oriented",
"(",
"self",
")",
":",
"if",
"util",
".",
"is_shape",
"(",
"self",
".",
"primitive",
".",
"transform",
",",
"(",
"4",
",",
"4",
")",
")",
":",
"return",
"not",
"np",
".",
"allclose",
"(",
"self",
".",
"primitive",
".",
"transf... | 35.666667 | 15.666667 |
def dist(self,*args,**kwargs):
"""
NAME:
dist
PURPOSE:
return distance from the observer
INPUT:
t - (optional) time at which to get dist (can be Quantity)
obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity)
... | [
"def",
"dist",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"self",
".",
"_orb",
".",
"dist",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"out",
")",
"==",
"1",
":",
"return",
"out",
"[... | 24 | 27.875 |
def ip_access_control_lists(self):
"""
Access the ip_access_control_lists
:returns: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList
:rtype: twilio.rest.trunking.v1.trunk.ip_access_control_list.IpAccessControlListList
"""
if self._ip_access_co... | [
"def",
"ip_access_control_lists",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ip_access_control_lists",
"is",
"None",
":",
"self",
".",
"_ip_access_control_lists",
"=",
"IpAccessControlListList",
"(",
"self",
".",
"_version",
",",
"trunk_sid",
"=",
"self",
".",
... | 41.230769 | 18.461538 |
def change_size_for_pane(self, pane, up=0, right=0, down=0, left=0):
"""
Increase the size of the current pane in any of the four directions.
Positive values indicate an increase, negative values a decrease.
"""
assert isinstance(pane, Pane)
def find_split_and_child(spli... | [
"def",
"change_size_for_pane",
"(",
"self",
",",
"pane",
",",
"up",
"=",
"0",
",",
"right",
"=",
"0",
",",
"down",
"=",
"0",
",",
"left",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"pane",
",",
"Pane",
")",
"def",
"find_split_and_child",
"(",
... | 42.894737 | 22.087719 |
def write_task_options(self, **kw):
"""
Write an options line for a task definition::
writer.write_task_options(
start_time=time(12, 34, 56),
task_time=timedelta(hours=1, minutes=45, seconds=12),
waypoint_distance=False,
dista... | [
"def",
"write_task_options",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"self",
".",
"in_task_section",
":",
"raise",
"RuntimeError",
"(",
"u'Task options have to be written in task section'",
")",
"fields",
"=",
"[",
"'Options'",
"]",
"if",
"'star... | 38.85 | 21.65 |
def _MultipleModulesFoundError(path, candidates):
"""Generates an error message to be used when multiple matches are found.
Args:
path: The breakpoint location path that the user provided.
candidates: List of paths that match the user provided path. Must
contain at least 2 entries (throws Assertion... | [
"def",
"_MultipleModulesFoundError",
"(",
"path",
",",
"candidates",
")",
":",
"assert",
"len",
"(",
"candidates",
")",
">",
"1",
"params",
"=",
"[",
"path",
"]",
"+",
"_StripCommonPathPrefix",
"(",
"candidates",
"[",
":",
"2",
"]",
")",
"if",
"len",
"("... | 36.3 | 18.5 |
def normalize_init_values(cls, release, species, server):
"""
Normalizes the arguments which uniquely specify an EnsemblRelease
genome.
"""
release = check_release_number(release)
species = check_species_object(species)
return (release, species, server) | [
"def",
"normalize_init_values",
"(",
"cls",
",",
"release",
",",
"species",
",",
"server",
")",
":",
"release",
"=",
"check_release_number",
"(",
"release",
")",
"species",
"=",
"check_species_object",
"(",
"species",
")",
"return",
"(",
"release",
",",
"speci... | 37.75 | 11.25 |
def use_kwargs(args, locations=None, inherit=None, apply=None, **kwargs):
"""Inject keyword arguments from the specified webargs arguments into the
decorated view function.
Usage:
.. code-block:: python
from marshmallow import fields
@use_kwargs({'name': fields.Str(), 'category': fie... | [
"def",
"use_kwargs",
"(",
"args",
",",
"locations",
"=",
"None",
",",
"inherit",
"=",
"None",
",",
"apply",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'locations'",
":",
"locations",
"}",
")",
"def",
"wrapper"... | 34.645161 | 22.645161 |
def printoptions():
'''print paver options.
Prettified by json.
`long_description` is removed
'''
x = json.dumps(environment.options,
indent=4,
sort_keys=True,
skipkeys=True,
cls=MyEncoder)
print(x) | [
"def",
"printoptions",
"(",
")",
":",
"x",
"=",
"json",
".",
"dumps",
"(",
"environment",
".",
"options",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"skipkeys",
"=",
"True",
",",
"cls",
"=",
"MyEncoder",
")",
"print",
"(",
"x",
")... | 24 | 16 |
def set_texture(self, name, value):
""" Set a texture sampler. Value is the id of the texture to link.
"""
if not self._linked:
raise RuntimeError('Cannot set uniform when program has no code')
# Get handle for the uniform, first try cache
handle = self._handles.get(n... | [
"def",
"set_texture",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"_linked",
":",
"raise",
"RuntimeError",
"(",
"'Cannot set uniform when program has no code'",
")",
"# Get handle for the uniform, first try cache",
"handle",
"=",
"self"... | 44.387097 | 14.935484 |
def notify_ar_retract(self, sample):
"""Sends an email notification to sample's client contact if the sample
passed in has a retest associated
"""
retest = sample.getRetest()
if not retest:
logger.warn("No retest found for {}. And it should!"
.... | [
"def",
"notify_ar_retract",
"(",
"self",
",",
"sample",
")",
":",
"retest",
"=",
"sample",
".",
"getRetest",
"(",
")",
"if",
"not",
"retest",
":",
"logger",
".",
"warn",
"(",
"\"No retest found for {}. And it should!\"",
".",
"format",
"(",
"api",
".",
"get_... | 43.055556 | 17.222222 |
def register(self, schema):
"""Register input schema class.
When registering a schema, all inner schemas are registered as well.
:param Schema schema: schema to register.
:return: old registered schema.
:rtype: type
"""
result = None
uuid = schema.uuid
... | [
"def",
"register",
"(",
"self",
",",
"schema",
")",
":",
"result",
"=",
"None",
"uuid",
"=",
"schema",
".",
"uuid",
"if",
"uuid",
"in",
"self",
".",
"_schbyuuid",
":",
"result",
"=",
"self",
".",
"_schbyuuid",
"[",
"uuid",
"]",
"if",
"result",
"!=",
... | 24.09375 | 22.65625 |
def is_valid_consumer(request):
"""
Validate the client for view/resource access with the given key
The client is authorized to access the view:
- if there is a `Consumer` with the client's *IP* that is explicitly allowed to use the given key,
- if there is no `Consumer` with a differen... | [
"def",
"is_valid_consumer",
"(",
"request",
")",
":",
"try",
":",
"ip",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'REMOTE_ADDR'",
",",
"None",
")",
"return",
"Consumer",
".",
"objects",
".",
"get",
"(",
"key",
"=",
"request",
".",
"key",
",",
"i... | 45.428571 | 22.571429 |
def view_class2(self, fatherid=''):
'''
Publishing from 2ed range category.
'''
if self.is_admin():
pass
else:
return False
kwd = {'class1str': self.format_class2(fatherid),
'parentid': '0',
'parentlist': MCategory.g... | [
"def",
"view_class2",
"(",
"self",
",",
"fatherid",
"=",
"''",
")",
":",
"if",
"self",
".",
"is_admin",
"(",
")",
":",
"pass",
"else",
":",
"return",
"False",
"kwd",
"=",
"{",
"'class1str'",
":",
"self",
".",
"format_class2",
"(",
"fatherid",
")",
",... | 30.809524 | 20.52381 |
def bin_data(data, dim = 40, num_bins = 10):
"""
Fully bins the data generated by generate_data, using generate_RF_bins and
bin_number.
"""
intervals = generate_RF_bins(data, dim, num_bins)
binned_data = [numpy.concatenate([bin_number(data[x][i], intervals[i])
for i in range(len(data[x]))]) for x in r... | [
"def",
"bin_data",
"(",
"data",
",",
"dim",
"=",
"40",
",",
"num_bins",
"=",
"10",
")",
":",
"intervals",
"=",
"generate_RF_bins",
"(",
"data",
",",
"dim",
",",
"num_bins",
")",
"binned_data",
"=",
"[",
"numpy",
".",
"concatenate",
"(",
"[",
"bin_numbe... | 38.777778 | 17 |
def load_ccd_data_from_fits(image_path, pixel_scale, image_hdu=0,
resized_ccd_shape=None, resized_ccd_origin_pixels=None,
resized_ccd_origin_arcsec=None,
psf_path=None, psf_hdu=0, resized_psf_shape=None, renormalize_psf=True,
... | [
"def",
"load_ccd_data_from_fits",
"(",
"image_path",
",",
"pixel_scale",
",",
"image_hdu",
"=",
"0",
",",
"resized_ccd_shape",
"=",
"None",
",",
"resized_ccd_origin_pixels",
"=",
"None",
",",
"resized_ccd_origin_arcsec",
"=",
"None",
",",
"psf_path",
"=",
"None",
... | 64.798883 | 36.921788 |
def _SkipFieldValue(tokenizer):
"""Skips over a field value.
Args:
tokenizer: A tokenizer to parse the field name and values.
Raises:
ParseError: In case an invalid field value is found.
"""
# String/bytes tokens can come in multiple adjacent string literals.
# If we can consume one, consume as ma... | [
"def",
"_SkipFieldValue",
"(",
"tokenizer",
")",
":",
"# String/bytes tokens can come in multiple adjacent string literals.",
"# If we can consume one, consume as many as we can.",
"if",
"tokenizer",
".",
"TryConsumeByteString",
"(",
")",
":",
"while",
"tokenizer",
".",
"TryConsu... | 32.5 | 20.35 |
def build_parser(line):
# type: (Text) -> optparse.OptionParser
"""
Return a parser for parsing requirement lines
"""
parser = optparse.OptionParser(add_help_option=False)
option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ
for option_factory in option_factories:
option = o... | [
"def",
"build_parser",
"(",
"line",
")",
":",
"# type: (Text) -> optparse.OptionParser",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"add_help_option",
"=",
"False",
")",
"option_factories",
"=",
"SUPPORTED_OPTIONS",
"+",
"SUPPORTED_OPTIONS_REQ",
"for",
"option... | 34.173913 | 14.695652 |
def decorator(cls, candidate, *exp_args, **exp_kwargs):
'''
Decorate a control function in order to conduct an experiment when called.
:param callable candidate: your candidate function
:param iterable exp_args: positional arguments passed to :class:`Experiment`
:param dict exp_... | [
"def",
"decorator",
"(",
"cls",
",",
"candidate",
",",
"*",
"exp_args",
",",
"*",
"*",
"exp_kwargs",
")",
":",
"def",
"wrapper",
"(",
"control",
")",
":",
"@",
"wraps",
"(",
"control",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",... | 35.615385 | 23.615385 |
def list_dir(self):
"""
Non-recursive file listing.
:returns: A generator over files in this "directory" for efficiency.
"""
bucket = self.s3_object.Bucket()
prefix = self.s3_object.key
if not prefix.endswith('/'): prefix += '/'
for obj in bucket.object... | [
"def",
"list_dir",
"(",
"self",
")",
":",
"bucket",
"=",
"self",
".",
"s3_object",
".",
"Bucket",
"(",
")",
"prefix",
"=",
"self",
".",
"s3_object",
".",
"key",
"if",
"not",
"prefix",
".",
"endswith",
"(",
"'/'",
")",
":",
"prefix",
"+=",
"'/'",
"f... | 31.615385 | 19.307692 |
def identify_imagesize(self, image_type, image_path='/tmp/img.'):
"""
Identify the image size using the data location and other parameters
"""
dims = ()
try:
if (image_type.lower() == 'png'):
dims = np.shape(ndpng.load('{}{}'.format(
... | [
"def",
"identify_imagesize",
"(",
"self",
",",
"image_type",
",",
"image_path",
"=",
"'/tmp/img.'",
")",
":",
"dims",
"=",
"(",
")",
"try",
":",
"if",
"(",
"image_type",
".",
"lower",
"(",
")",
"==",
"'png'",
")",
":",
"dims",
"=",
"np",
".",
"shape"... | 36.681818 | 18.318182 |
def exec_func_src(func, globals_=None, locals_=None, key_list=None,
sentinal=None, update=None, keys=None, verbose=False,
start=None, stop=None):
"""
execs a func and returns requested local vars.
Does not modify globals unless update=True (or in IPython)
SeeAlso:
... | [
"def",
"exec_func_src",
"(",
"func",
",",
"globals_",
"=",
"None",
",",
"locals_",
"=",
"None",
",",
"key_list",
"=",
"None",
",",
"sentinal",
"=",
"None",
",",
"update",
"=",
"None",
",",
"keys",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"star... | 36.173077 | 15.480769 |
def parse_line(self, line: str) -> PriceModel:
""" Parse a CSV line into a price element """
line = line.rstrip()
parts = line.split(',')
result = PriceModel()
# symbol
result.symbol = self.translate_symbol(parts[0])
# value
result.value = Decimal(parts... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
":",
"str",
")",
"->",
"PriceModel",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"parts",
"=",
"line",
".",
"split",
"(",
"','",
")",
"result",
"=",
"PriceModel",
"(",
")",
"# symbol",
"result",
... | 26.538462 | 20.115385 |
def _add_genotype_calls(self, variant_obj, variant_line, case_obj):
"""Add the genotype calls for the variant
Args:
variant_obj (puzzle.models.Variant)
variant_dict (dict): A variant dictionary
case_obj (puzzle.models.Case)
"""
variant_line = variant... | [
"def",
"_add_genotype_calls",
"(",
"self",
",",
"variant_obj",
",",
"variant_line",
",",
"case_obj",
")",
":",
"variant_line",
"=",
"variant_line",
".",
"split",
"(",
"'\\t'",
")",
"#if there is gt calls we have no individuals to add",
"if",
"len",
"(",
"variant_line"... | 39.861111 | 16.861111 |
def _set_history(self, history):
""" Replace the current history with a sequence of history items.
"""
self._history = list(history)
self._history_edits = {}
self._history_index = len(self._history) | [
"def",
"_set_history",
"(",
"self",
",",
"history",
")",
":",
"self",
".",
"_history",
"=",
"list",
"(",
"history",
")",
"self",
".",
"_history_edits",
"=",
"{",
"}",
"self",
".",
"_history_index",
"=",
"len",
"(",
"self",
".",
"_history",
")"
] | 38.833333 | 4.5 |
def _mark_master_dead(self, master):
'''
Mark a master as dead. This will start the sign-in routine
'''
# if its connected, mark it dead
if self._syndics[master].done():
syndic = self._syndics[master].result() # pylint: disable=no-member
self._syndics[mas... | [
"def",
"_mark_master_dead",
"(",
"self",
",",
"master",
")",
":",
"# if its connected, mark it dead",
"if",
"self",
".",
"_syndics",
"[",
"master",
"]",
".",
"done",
"(",
")",
":",
"syndic",
"=",
"self",
".",
"_syndics",
"[",
"master",
"]",
".",
"result",
... | 37.142857 | 18.857143 |
def attack_selection(attack_string):
"""
Selects the Attack Class using string input.
:param attack_string: adversarial attack name in string format
:return: attack class defined in cleverhans.attacks_eager
"""
# List of Implemented attacks
attacks_list = AVAILABLE_ATTACKS.keys()
# Checking for reque... | [
"def",
"attack_selection",
"(",
"attack_string",
")",
":",
"# List of Implemented attacks",
"attacks_list",
"=",
"AVAILABLE_ATTACKS",
".",
"keys",
"(",
")",
"# Checking for requested attack in list of available attacks.",
"if",
"attack_string",
"is",
"None",
":",
"raise",
... | 39 | 15.1 |
def write_spmatrix_to_sparse_tensor(file, array, labels=None):
"""Writes a scipy sparse matrix to a sparse tensor"""
if not issparse(array):
raise TypeError("Array must be sparse")
# Validate shape of array and labels, resolve array and label types
if not len(array.shape) == 2:
raise V... | [
"def",
"write_spmatrix_to_sparse_tensor",
"(",
"file",
",",
"array",
",",
"labels",
"=",
"None",
")",
":",
"if",
"not",
"issparse",
"(",
"array",
")",
":",
"raise",
"TypeError",
"(",
"\"Array must be sparse\"",
")",
"# Validate shape of array and labels, resolve array... | 36.342105 | 20.157895 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.