text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def PrintStats(self):
"""Build stats and print in MarkDown format."""
self.BuildStats()
self.PrintSummaryTable()
self.PrintSourceTypeTable()
self.PrintOSTable()
self.PrintLabelTable() | [
"def",
"PrintStats",
"(",
"self",
")",
":",
"self",
".",
"BuildStats",
"(",
")",
"self",
".",
"PrintSummaryTable",
"(",
")",
"self",
".",
"PrintSourceTypeTable",
"(",
")",
"self",
".",
"PrintOSTable",
"(",
")",
"self",
".",
"PrintLabelTable",
"(",
")"
] | 28.714286 | 12.857143 |
def _redefines_import(node):
""" Detect that the given node (AssignName) is inside an
exception handler and redefines an import from the tryexcept body.
Returns True if the node redefines an import, False otherwise.
"""
current = node
while current and not isinstance(current.parent, astroid.Exce... | [
"def",
"_redefines_import",
"(",
"node",
")",
":",
"current",
"=",
"node",
"while",
"current",
"and",
"not",
"isinstance",
"(",
"current",
".",
"parent",
",",
"astroid",
".",
"ExceptHandler",
")",
":",
"current",
"=",
"current",
".",
"parent",
"if",
"not",... | 41.473684 | 16.578947 |
def threshold_monitor_hidden_threshold_monitor_interface_apply(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_... | [
"def",
"threshold_monitor_hidden_threshold_monitor_interface_apply",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"threshold_monitor_hidden",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"thres... | 52.25 | 24.166667 |
def hook(self, pc):
"""
A decorator used to register a hook function for a given instruction address.
Equivalent to calling :func:`~add_hook`.
:param pc: Address of instruction to hook
:type pc: int or None
"""
def decorator(f):
self.add_hook(pc, f)
... | [
"def",
"hook",
"(",
"self",
",",
"pc",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"add_hook",
"(",
"pc",
",",
"f",
")",
"return",
"f",
"return",
"decorator"
] | 29.416667 | 16.083333 |
def read_code_bytes(self, size = 128, offset = 0):
"""
Tries to read some bytes of the code currently being executed.
@type size: int
@param size: Number of bytes to read.
@type offset: int
@param offset: Offset from the program counter to begin reading.
@rty... | [
"def",
"read_code_bytes",
"(",
"self",
",",
"size",
"=",
"128",
",",
"offset",
"=",
"0",
")",
":",
"return",
"self",
".",
"get_process",
"(",
")",
".",
"read",
"(",
"self",
".",
"get_pc",
"(",
")",
"+",
"offset",
",",
"size",
")"
] | 32 | 21.875 |
async def zrange(self, name, start, end, desc=False, withscores=False,
score_cast_func=float):
"""
Return a range of values from sorted set ``name`` between
``start`` and ``end`` sorted in ascending order.
``start`` and ``end`` can be negative, indicating the end of... | [
"async",
"def",
"zrange",
"(",
"self",
",",
"name",
",",
"start",
",",
"end",
",",
"desc",
"=",
"False",
",",
"withscores",
"=",
"False",
",",
"score_cast_func",
"=",
"float",
")",
":",
"if",
"desc",
":",
"return",
"await",
"self",
".",
"zrevrange",
... | 40.115385 | 22.115385 |
def bogoliubov_trans(p, q, theta):
r"""The 2-mode Bogoliubov transformation is mapped to two-qubit operations.
We use the identity X S^\dag X S X = Y X S^\dag Y S X = X to transform
the Hamiltonian XY+YX to XX+YY type. The time evolution of the XX + YY
Hamiltonian can be expressed as a power of the i... | [
"def",
"bogoliubov_trans",
"(",
"p",
",",
"q",
",",
"theta",
")",
":",
"# The iSWAP gate corresponds to evolve under the Hamiltonian XX+YY for",
"# time -pi/4.",
"expo",
"=",
"-",
"4",
"*",
"theta",
"/",
"np",
".",
"pi",
"yield",
"cirq",
".",
"X",
"(",
"p",
")... | 34.608696 | 21.391304 |
def validate_block(self, block: BaseBlock) -> None:
"""
Performs validation on a block that is either being mined or imported.
Since block validation (specifically the uncle validation) must have
access to the ancestor blocks, this validation must occur at the Chain
level.
... | [
"def",
"validate_block",
"(",
"self",
",",
"block",
":",
"BaseBlock",
")",
"->",
"None",
":",
"if",
"block",
".",
"is_genesis",
":",
"raise",
"ValidationError",
"(",
"\"Cannot validate genesis block this way\"",
")",
"VM_class",
"=",
"self",
".",
"get_vm_class_for... | 46.176471 | 24.058824 |
def _request(self, text, properties, retries=0):
"""Send a request to the CoreNLP server.
:param (str | unicode) text: raw text for the CoreNLPServer to parse
:param (dict) properties: properties that the server expects
:return: request result
"""
text = to_unicode(text)... | [
"def",
"_request",
"(",
"self",
",",
"text",
",",
"properties",
",",
"retries",
"=",
"0",
")",
":",
"text",
"=",
"to_unicode",
"(",
"text",
")",
"# ensures unicode",
"try",
":",
"r",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"server",
",",
"par... | 44.555556 | 19.925926 |
def position_after_whitespace(self, body: str, start_position: int) -> int:
"""Go to next position after a whitespace.
Reads from body starting at start_position until it finds a non-whitespace
character, then returns the position of that character for lexing.
"""
body_length = ... | [
"def",
"position_after_whitespace",
"(",
"self",
",",
"body",
":",
"str",
",",
"start_position",
":",
"int",
")",
"->",
"int",
":",
"body_length",
"=",
"len",
"(",
"body",
")",
"position",
"=",
"start_position",
"while",
"position",
"<",
"body_length",
":",
... | 35.884615 | 13.846154 |
def handle_exec(args):
"""usage: cosmic-ray exec <session-file>
Perform the remaining work to be done in the specified session.
This requires that the rest of your mutation testing
infrastructure (e.g. worker processes) are already running.
"""
session_file = get_db_name(args.get('<session-file... | [
"def",
"handle_exec",
"(",
"args",
")",
":",
"session_file",
"=",
"get_db_name",
"(",
"args",
".",
"get",
"(",
"'<session-file>'",
")",
")",
"cosmic_ray",
".",
"commands",
".",
"execute",
"(",
"session_file",
")",
"return",
"ExitCode",
".",
"OK"
] | 34.909091 | 18.636364 |
def people(self):
"""
The people list stored in payload (decoded upon every call())
:return: The people
:rtype: list[paps.people.People]
:raises ProtocolViolation:
Failed to find marker
Wrong number of bits in payload -> cannot decode into people
... | [
"def",
"people",
"(",
"self",
")",
":",
"people",
"=",
"[",
"]",
"bits",
"=",
"bytearray",
"(",
")",
"byts",
"=",
"struct",
".",
"unpack",
"(",
"APPUpdateMessage",
".",
"fmt",
".",
"format",
"(",
"len",
"(",
"self",
".",
"payload",
")",
")",
",",
... | 32.942308 | 15.557692 |
def remove_all_nexusnve_bindings():
"""Removes all nexusnve bindings."""
LOG.debug("remove_all_nexusport_bindings() called")
session = bc.get_writer_session()
session.query(nexus_models_v2.NexusNVEBinding).delete()
session.flush() | [
"def",
"remove_all_nexusnve_bindings",
"(",
")",
":",
"LOG",
".",
"debug",
"(",
"\"remove_all_nexusport_bindings() called\"",
")",
"session",
"=",
"bc",
".",
"get_writer_session",
"(",
")",
"session",
".",
"query",
"(",
"nexus_models_v2",
".",
"NexusNVEBinding",
")"... | 35 | 14.714286 |
def apply(self, func, mapping=None, new_dtype=None, **kwargs):
"""Apply an element-wise UDF to the Series.
There are currently 6 options for using a UDF. First 4 are lazy,
other 2 are eager and require the use of the raw decorator:
- One of the predefined functions in baloo.functions.
... | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"mapping",
"=",
"None",
",",
"new_dtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"func",
")",
":",
"return",
"Series",
"(",
"func",
"(",
"self",
".",
"values",
",",
"w... | 35.138889 | 23.712963 |
def _check(self):
'''Check and close connection if needed.'''
_logger.debug('Check if timeout.')
self._call_later_handle = None
if self._touch_time is not None:
difference = self._event_loop.time() - self._touch_time
_logger.debug('Time difference %s', difference... | [
"def",
"_check",
"(",
"self",
")",
":",
"_logger",
".",
"debug",
"(",
"'Check if timeout.'",
")",
"self",
".",
"_call_later_handle",
"=",
"None",
"if",
"self",
".",
"_touch_time",
"is",
"not",
"None",
":",
"difference",
"=",
"self",
".",
"_event_loop",
"."... | 33.533333 | 14.733333 |
def decode(data):
"""
Handles decoding of the CSV `data`.
Args:
data (str): Data which will be decoded.
Returns:
dict: Dictionary with decoded data.
"""
# try to guess dialect of the csv file
dialect = None
try:
dialect = csv.Sniffer().sniff(data)
except Exc... | [
"def",
"decode",
"(",
"data",
")",
":",
"# try to guess dialect of the csv file",
"dialect",
"=",
"None",
"try",
":",
"dialect",
"=",
"csv",
".",
"Sniffer",
"(",
")",
".",
"sniff",
"(",
"data",
")",
"except",
"Exception",
":",
"pass",
"# parse data with csv pa... | 26.76 | 21.16 |
def run(_, data, out_dir):
"""Run kraken, generating report in specified directory and parsing metrics.
Using only first paired reads.
"""
# logger.info("Number of aligned reads < than 0.60 in %s: %s" % (dd.get_sample_name(data), ratio))
logger.info("Running kraken to determine contaminant: %s" %... | [
"def",
"run",
"(",
"_",
",",
"data",
",",
"out_dir",
")",
":",
"# logger.info(\"Number of aligned reads < than 0.60 in %s: %s\" % (dd.get_sample_name(data), ratio))",
"logger",
".",
"info",
"(",
"\"Running kraken to determine contaminant: %s\"",
"%",
"dd",
".",
"get_sample_name... | 50.166667 | 18.952381 |
def parse(self, lines):
"""
Parses the `.gitignore` file represented by the *lines*.
"""
if isinstance(lines, str):
lines = lines.split('\n')
sub = _re.sub
for line in lines:
if line.endswith('\n'):
line = line[:-1]
line = line.lstrip()
if not line.startswith('#'... | [
"def",
"parse",
"(",
"self",
",",
"lines",
")",
":",
"if",
"isinstance",
"(",
"lines",
",",
"str",
")",
":",
"lines",
"=",
"lines",
".",
"split",
"(",
"'\\n'",
")",
"sub",
"=",
"_re",
".",
"sub",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
... | 30.458333 | 13.958333 |
def quick_send(self, send, echo=None, loglevel=logging.INFO):
"""Quick and dirty send that ignores background tasks. Intended for internal use.
"""
shutit = self.shutit
shutit.log('Quick send: ' + send, level=loglevel)
res = self.sendline(ShutItSendSpec(self,
send=send,
... | [
"def",
"quick_send",
"(",
"self",
",",
"send",
",",
"echo",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"INFO",
")",
":",
"shutit",
"=",
"self",
".",
"shutit",
"shutit",
".",
"log",
"(",
"'Quick send: '",
"+",
"send",
",",
"level",
"=",
"logle... | 46.357143 | 12.928571 |
def update(self, new: 'Sentence', flags: Flags):
"""
Erase items with the specified flags and insert the new items from
the other sentence instead.
"""
items = [i for i in self.items if i.flags != flags]
items.extend(new.items)
self.items = items | [
"def",
"update",
"(",
"self",
",",
"new",
":",
"'Sentence'",
",",
"flags",
":",
"Flags",
")",
":",
"items",
"=",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"items",
"if",
"i",
".",
"flags",
"!=",
"flags",
"]",
"items",
".",
"extend",
"(",
"new",
... | 32.777778 | 14.333333 |
def checkout(self, transparent=False, **kwargs):
""" create a pagseguro checkout """
self.data['currency'] = self.config.CURRENCY
self.build_checkout_params(**kwargs)
if transparent:
response = self.post(url=self.config.TRANSPARENT_CHECKOUT_URL)
else:
resp... | [
"def",
"checkout",
"(",
"self",
",",
"transparent",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"data",
"[",
"'currency'",
"]",
"=",
"self",
".",
"config",
".",
"CURRENCY",
"self",
".",
"build_checkout_params",
"(",
"*",
"*",
"kwargs"... | 48.555556 | 18 |
def readadd(file, system):
"""read DYR file"""
dyr = {}
data = []
end = 0
retval = True
sep = ','
fid = open(file, 'r')
for line in fid.readlines():
if line.find('/') >= 0:
line = line.split('/')[0]
end = 1
if line.find(',') >= 0: # mixed comma a... | [
"def",
"readadd",
"(",
"file",
",",
"system",
")",
":",
"dyr",
"=",
"{",
"}",
"data",
"=",
"[",
"]",
"end",
"=",
"0",
"retval",
"=",
"True",
"sep",
"=",
"','",
"fid",
"=",
"open",
"(",
"file",
",",
"'r'",
")",
"for",
"line",
"in",
"fid",
".",... | 23.881356 | 19.864407 |
def _cleanup_keys_with_confirmation(self, keys_to_delete):
"""Asks confirmation and then deletes entries with keys.
Args:
keys_to_delete: list of datastore keys for which entries should be deleted
"""
print('Round name: ', self.round_name)
print('Number of entities to be deleted: ', len(keys_... | [
"def",
"_cleanup_keys_with_confirmation",
"(",
"self",
",",
"keys_to_delete",
")",
":",
"print",
"(",
"'Round name: '",
",",
"self",
".",
"round_name",
")",
"print",
"(",
"'Number of entities to be deleted: '",
",",
"len",
"(",
"keys_to_delete",
")",
")",
"if",
"n... | 33.3 | 16.875 |
def is_ipv4_filter(ip, options=None):
'''
Returns a bool telling if the value passed to it was a valid IPv4 address.
ip
The IP address.
net: False
Consider IP addresses followed by netmask.
options
CSV of options regarding the nature of the IP address. E.g.: loopback, mult... | [
"def",
"is_ipv4_filter",
"(",
"ip",
",",
"options",
"=",
"None",
")",
":",
"_is_ipv4",
"=",
"_is_ipv",
"(",
"ip",
",",
"4",
",",
"options",
"=",
"options",
")",
"return",
"isinstance",
"(",
"_is_ipv4",
",",
"six",
".",
"string_types",
")"
] | 28.666667 | 28 |
def image_data(Z, X=[0,1.0], Y=[0,1.0], aspect=1.0, zmin=None, zmax=None, clear=1, clabel='z', autoformat=True, colormap="Last Used", shell_history=0, **kwargs):
"""
Generates an image plot.
Parameters
----------
Z
2-d array of z-values
X=[0,1.0], Y=[0,1.0]
1-d array of x... | [
"def",
"image_data",
"(",
"Z",
",",
"X",
"=",
"[",
"0",
",",
"1.0",
"]",
",",
"Y",
"=",
"[",
"0",
",",
"1.0",
"]",
",",
"aspect",
"=",
"1.0",
",",
"zmin",
"=",
"None",
",",
"zmax",
"=",
"None",
",",
"clear",
"=",
"1",
",",
"clabel",
"=",
... | 27.170732 | 24.243902 |
def http_error_handler(f):
"""Handle 404 errors returned by the API server
"""
def hrefs_to_resources(hrefs):
for href in hrefs.replace(',', '').split():
type, uuid = href.split('/')[-2:]
yield Resource(type, uuid=uuid)
def hrefs_list_to_resources(hrefs_list):
f... | [
"def",
"http_error_handler",
"(",
"f",
")",
":",
"def",
"hrefs_to_resources",
"(",
"hrefs",
")",
":",
"for",
"href",
"in",
"hrefs",
".",
"replace",
"(",
"','",
",",
"''",
")",
".",
"split",
"(",
")",
":",
"type",
",",
"uuid",
"=",
"href",
".",
"spl... | 42.208333 | 16.791667 |
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
c... | [
"def",
"create",
"(",
"provider",
",",
"names",
",",
"opts",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"if",
"isinstance",
"(",
"opts",
",",
"dict",
")",
":",
"client",
".",
"opts",
".",
"update",
"(",
... | 30.6 | 28.466667 |
def reconstruct(self, t:Tensor, x:Tensor=None):
"Reconstruct one of the underlying item for its data `t`."
return self[0].reconstruct(t,x) if has_arg(self[0].reconstruct, 'x') else self[0].reconstruct(t) | [
"def",
"reconstruct",
"(",
"self",
",",
"t",
":",
"Tensor",
",",
"x",
":",
"Tensor",
"=",
"None",
")",
":",
"return",
"self",
"[",
"0",
"]",
".",
"reconstruct",
"(",
"t",
",",
"x",
")",
"if",
"has_arg",
"(",
"self",
"[",
"0",
"]",
".",
"reconst... | 72.333333 | 32.333333 |
def description(self) -> str:
'''Test name in nose output (intended to be overridden).'''
return '{0.uuid.hex}—{1}'.format(self, self.context.module) | [
"def",
"description",
"(",
"self",
")",
"->",
"str",
":",
"return",
"'{0.uuid.hex}—{1}'.f",
"o",
"rmat(s",
"e",
"lf, ",
"s",
"lf.c",
"o",
"ntext.m",
"o",
"dule)",
""
] | 40.75 | 26.25 |
def move_up(self):
"""Make the drone rise upwards."""
self.at(ardrone.at.pcmd, True, 0, 0, self.speed, 0) | [
"def",
"move_up",
"(",
"self",
")",
":",
"self",
".",
"at",
"(",
"ardrone",
".",
"at",
".",
"pcmd",
",",
"True",
",",
"0",
",",
"0",
",",
"self",
".",
"speed",
",",
"0",
")"
] | 39.666667 | 13.666667 |
async def next(self) -> Any:
"""Emits the next multipart body part."""
# So, if we're at BOF, we need to skip till the boundary.
if self._at_eof:
return
await self._maybe_release_last_part()
if self._at_bof:
await self._read_until_first_boundary()
... | [
"async",
"def",
"next",
"(",
"self",
")",
"->",
"Any",
":",
"# So, if we're at BOF, we need to skip till the boundary.",
"if",
"self",
".",
"_at_eof",
":",
"return",
"await",
"self",
".",
"_maybe_release_last_part",
"(",
")",
"if",
"self",
".",
"_at_bof",
":",
"... | 37.933333 | 15.2 |
def strictly_increasing(self):
"""
:returns:
a new vulnerability function that is strictly increasing.
It is built by removing piece of the function where the mean
loss ratio is constant.
"""
imls, mlrs, covs = [], [], []
previous_mlr = None
... | [
"def",
"strictly_increasing",
"(",
"self",
")",
":",
"imls",
",",
"mlrs",
",",
"covs",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"previous_mlr",
"=",
"None",
"for",
"i",
",",
"mlr",
"in",
"enumerate",
"(",
"self",
".",
"mean_loss_ratios",
")",
"... | 32.571429 | 14.761905 |
def download_device(headers, cookies, temp_target_disk,
device_url, lease_updater,
total_bytes_written, total_bytes_to_write):
""" Download disk device of HttpNfcLease.info.deviceUrl
list of devices
:param headers: Request headers
:type cookies: dict
:param co... | [
"def",
"download_device",
"(",
"headers",
",",
"cookies",
",",
"temp_target_disk",
",",
"device_url",
",",
"lease_updater",
",",
"total_bytes_written",
",",
"total_bytes_to_write",
")",
":",
"with",
"open",
"(",
"temp_target_disk",
",",
"'wb'",
")",
"as",
"handle"... | 39.964912 | 15.684211 |
def partition(self, var: str = '', fraction: float = .7, seed: int = 9878, kfold: int = 1,
out: 'SASdata' = None, singleOut: bool = True) -> object:
"""
Partition a sas data object using SRS sampling or if a variable is specified then
stratifying with respect to that variable
... | [
"def",
"partition",
"(",
"self",
",",
"var",
":",
"str",
"=",
"''",
",",
"fraction",
":",
"float",
"=",
".7",
",",
"seed",
":",
"int",
"=",
"9878",
",",
"kfold",
":",
"int",
"=",
"1",
",",
"out",
":",
"'SASdata'",
"=",
"None",
",",
"singleOut",
... | 46.253623 | 21.478261 |
def index(request):
session = Session(request.body)
print 'request.body begin'
print request.body
print 'request.body end'
t = Tropo()
smsContent = session.initialText
#t.call(to=session.parameters['callToNumber'], network='SIP')
#t.say(session.parameters['message'])
"""
t = Trop... | [
"def",
"index",
"(",
"request",
")",
":",
"session",
"=",
"Session",
"(",
"request",
".",
"body",
")",
"print",
"'request.body begin'",
"print",
"request",
".",
"body",
"print",
"'request.body end'",
"t",
"=",
"Tropo",
"(",
")",
"smsContent",
"=",
"session",... | 49.71875 | 28.96875 |
def to_native(self, value, context=None):
""" Schematics deserializer override
We return a us.states.State object so the abbreviation
or long name can be trivially accessed. Additionally,
some geo type ops are available.
TIP: The us.states library expects unicode so we
... | [
"def",
"to_native",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"us",
".",
"states",
".",
"State",
")",
":",
"return",
"value",
"try",
":",
"state",
"=",
"us",
".",
"states",
".",
"lookup... | 30.26087 | 18.043478 |
def connection_lost(self, exc: Optional[Exception]) -> None:
"""
7.1.4. The WebSocket Connection is Closed.
"""
logger.debug("%s - event = connection_lost(%s)", self.side, exc)
self.state = State.CLOSED
logger.debug("%s - state = CLOSED", self.side)
if not hasatt... | [
"def",
"connection_lost",
"(",
"self",
",",
"exc",
":",
"Optional",
"[",
"Exception",
"]",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"\"%s - event = connection_lost(%s)\"",
",",
"self",
".",
"side",
",",
"exc",
")",
"self",
".",
"state",
"=",
... | 38.916667 | 13.75 |
def humidity_unit(self):
"""Get unit of humidity."""
if CONST.UNIT_PERCENT in self._get_status(CONST.HUMI_STATUS_KEY):
return CONST.UNIT_PERCENT
return None | [
"def",
"humidity_unit",
"(",
"self",
")",
":",
"if",
"CONST",
".",
"UNIT_PERCENT",
"in",
"self",
".",
"_get_status",
"(",
"CONST",
".",
"HUMI_STATUS_KEY",
")",
":",
"return",
"CONST",
".",
"UNIT_PERCENT",
"return",
"None"
] | 37.6 | 14.6 |
def col_transform(self, col, digits):
"""
The lambda body to transform the column values
"""
if col is None or float(col) < 0.0:
return None
else:
col = self.number_to_base(int(col), self.base, digits)
if len(col) == digits:
re... | [
"def",
"col_transform",
"(",
"self",
",",
"col",
",",
"digits",
")",
":",
"if",
"col",
"is",
"None",
"or",
"float",
"(",
"col",
")",
"<",
"0.0",
":",
"return",
"None",
"else",
":",
"col",
"=",
"self",
".",
"number_to_base",
"(",
"int",
"(",
"col",
... | 30.846154 | 15.307692 |
def _guess_file_format(f):
"""
Tries to guess file format, first based on file extension (csv / tsv),
then by looking for common column separators in the first 10 non-commented lines.
Splits by tab / comma / space and counts resulting number of columns. Finds the most
common column count, then compa... | [
"def",
"_guess_file_format",
"(",
"f",
")",
":",
"filename",
",",
"file_extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"f",
"[",
"'fn'",
"]",
")",
"tabs",
"=",
"[",
"]",
"commas",
"=",
"[",
"]",
"spaces",
"=",
"[",
"]",
"j",
"=",
"0",
... | 38.043478 | 18.521739 |
def stop(self):
"""
Stop animation thread.
"""
time.sleep(self.speed)
self._count = -9999
sys.stdout.write(self.reverser + '\r\033[K\033[A')
sys.stdout.flush()
return | [
"def",
"stop",
"(",
"self",
")",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"speed",
")",
"self",
".",
"_count",
"=",
"-",
"9999",
"sys",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"reverser",
"+",
"'\\r\\033[K\\033[A'",
")",
"sys",
".",
"std... | 24.666667 | 12.888889 |
def __getX(self):
'''
Gets the View X coordinate
'''
if DEBUG_COORDS:
print >>sys.stderr, "getX(%s %s ## %s)" % (self.getClass(), self.getId(), self.getUniqueId())
x = 0
if self.useUiAutomator:
x = self.map['bounds'][0][0]
else:
... | [
"def",
"__getX",
"(",
"self",
")",
":",
"if",
"DEBUG_COORDS",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"getX(%s %s ## %s)\"",
"%",
"(",
"self",
".",
"getClass",
"(",
")",
",",
"self",
".",
"getId",
"(",
")",
",",
"self",
".",
"getUniqueId",
"... | 36.409091 | 29.863636 |
def _randomize_subject_list(data_list, random):
"""Randomly permute the voxels of a subject list.
The method shuffles the subject one by one in place according to
the random type. If RandomType.NORANDOM, return the original list.
Parameters
----------
data_list: list of 2D array in shape [nV... | [
"def",
"_randomize_subject_list",
"(",
"data_list",
",",
"random",
")",
":",
"if",
"random",
"==",
"RandomType",
".",
"REPRODUCIBLE",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"data_list",
")",
")",
":",
"_randomize_single_subject",
"(",
"data_list",
... | 31.086957 | 18.304348 |
def from_proto_dict(proto_dict: Dict) -> 'GridQubit':
"""Proto dict must have 'row' and 'col' keys."""
if 'row' not in proto_dict or 'col' not in proto_dict:
raise ValueError(
'Proto dict does not contain row or col: {}'.format(proto_dict))
return GridQubit(row=proto_... | [
"def",
"from_proto_dict",
"(",
"proto_dict",
":",
"Dict",
")",
"->",
"'GridQubit'",
":",
"if",
"'row'",
"not",
"in",
"proto_dict",
"or",
"'col'",
"not",
"in",
"proto_dict",
":",
"raise",
"ValueError",
"(",
"'Proto dict does not contain row or col: {}'",
".",
"form... | 58.333333 | 19.333333 |
def template(tpl, template_adapter=SimpleTemplate, **kwargs):
'''
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
'''
if tpl not in TEMPLATES or DEBUG:
settings = kwargs.get('template_settings',{})
lookup = kwargs.... | [
"def",
"template",
"(",
"tpl",
",",
"template_adapter",
"=",
"SimpleTemplate",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"tpl",
"not",
"in",
"TEMPLATES",
"or",
"DEBUG",
":",
"settings",
"=",
"kwargs",
".",
"get",
"(",
"'template_settings'",
",",
"{",
"}",... | 45.428571 | 19.428571 |
def createproject(self, name, **kwargs):
"""
Creates a new project owned by the authenticated user.
:param name: new project name
:param path: custom repository name for new project. By default generated based on name
:param namespace_id: namespace for the new project (defaults ... | [
"def",
"createproject",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"'name'",
":",
"name",
"}",
"if",
"kwargs",
":",
"data",
".",
"update",
"(",
"kwargs",
")",
"request",
"=",
"requests",
".",
"post",
"(",
"self",... | 34.142857 | 17.514286 |
def iscm_md_append_array(self, arraypath, member):
"""
Append a member to a metadata array entry
"""
array_path = string.split(arraypath, ".")
array_key = array_path.pop()
current = self.metadata
for k in array_path:
if not current.has_key(k):
... | [
"def",
"iscm_md_append_array",
"(",
"self",
",",
"arraypath",
",",
"member",
")",
":",
"array_path",
"=",
"string",
".",
"split",
"(",
"arraypath",
",",
"\".\"",
")",
"array_key",
"=",
"array_path",
".",
"pop",
"(",
")",
"current",
"=",
"self",
".",
"met... | 37.625 | 7.375 |
def create_replication_group(name, primary_cluster_id, replication_group_description,
wait=None, region=None, key=None,
keyid=None, profile=None):
'''
Create replication group.
CLI example::
salt myminion boto_elasticache.create_replication... | [
"def",
"create_replication_group",
"(",
"name",
",",
"primary_cluster_id",
",",
"replication_group_description",
",",
"wait",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
... | 35.96875 | 25.40625 |
def clean_url(url, force_scheme=None):
"""Cleans the given URL."""
# URL should be ASCII according to RFC 3986
url = str(url)
# Collapse ../../ and related
url_parts = urlparse.urlparse(url)
path_parts = []
for part in url_parts.path.split('/'):
if part == '.':
continue
... | [
"def",
"clean_url",
"(",
"url",
",",
"force_scheme",
"=",
"None",
")",
":",
"# URL should be ASCII according to RFC 3986",
"url",
"=",
"str",
"(",
"url",
")",
"# Collapse ../../ and related",
"url_parts",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"path_pa... | 26.16129 | 14.580645 |
def Verify(self, message, signature, hash_algorithm=None):
"""Verifies a given message."""
# This method accepts both PSS and PKCS1v15 padding. PSS is preferred but
# old clients only support PKCS1v15.
if hash_algorithm is None:
hash_algorithm = hashes.SHA256()
last_e = None
for padding_... | [
"def",
"Verify",
"(",
"self",
",",
"message",
",",
"signature",
",",
"hash_algorithm",
"=",
"None",
")",
":",
"# This method accepts both PSS and PKCS1v15 padding. PSS is preferred but",
"# old clients only support PKCS1v15.",
"if",
"hash_algorithm",
"is",
"None",
":",
"has... | 29.375 | 18.833333 |
def calc_wind_chill(t, windspeed, windspeed10min=None):
'''
calculates the wind chill value based upon the temperature (F) and
wind.
returns the wind chill in degrees F.
'''
w = max(windspeed10min, windspeed)
return 35.74 + 0.6215 * t - 35.75 * (w ** 0.16) + 0.4275 * t * (w ** 0.16); | [
"def",
"calc_wind_chill",
"(",
"t",
",",
"windspeed",
",",
"windspeed10min",
"=",
"None",
")",
":",
"w",
"=",
"max",
"(",
"windspeed10min",
",",
"windspeed",
")",
"return",
"35.74",
"+",
"0.6215",
"*",
"t",
"-",
"35.75",
"*",
"(",
"w",
"**",
"0.16",
... | 30.5 | 26.3 |
def add_html_report_optgroup(parser):
"""
Option group for the HTML report format
"""
g = parser.add_argument_group("HTML Report Options")
g.add_argument("--html-stylesheet", action="append",
dest="html_stylesheets", default=list())
g.add_argument("--html-javascript", actio... | [
"def",
"add_html_report_optgroup",
"(",
"parser",
")",
":",
"g",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"HTML Report Options\"",
")",
"g",
".",
"add_argument",
"(",
"\"--html-stylesheet\"",
",",
"action",
"=",
"\"append\"",
",",
"dest",
"=",
"\"html_styl... | 35.8125 | 20.3125 |
def overlaps_range(self, begin, end):
"""
Returns whether some interval in the tree overlaps the given
range. Returns False if given a null interval over which to
test.
Completes in O(r*log n) time, where r is the range length and n
is the table size.
:rtype: boo... | [
"def",
"overlaps_range",
"(",
"self",
",",
"begin",
",",
"end",
")",
":",
"if",
"self",
".",
"is_empty",
"(",
")",
":",
"return",
"False",
"elif",
"begin",
">=",
"end",
":",
"return",
"False",
"elif",
"self",
".",
"overlaps_point",
"(",
"begin",
")",
... | 30.095238 | 15.714286 |
def show_max(df):
"""Pour chaque serie (colonne) d'un DataFrame, va rechercher la (les) valeur(s)
et la (les) date(s) du (des) max.
Paramètres:
df: DataFrame de valeurs à calculer
Retourne:
Un DataFrame montrant pour chaque serie (colonne), les valeurs maxs aux dates
d'apparition.
"""
... | [
"def",
"show_max",
"(",
"df",
")",
":",
"df",
"=",
"df",
".",
"astype",
"(",
"pd",
".",
"np",
".",
"float",
")",
"res",
"=",
"list",
"(",
")",
"for",
"c",
"in",
"df",
".",
"columns",
":",
"serie",
"=",
"df",
"[",
"c",
"]",
"res",
".",
"appe... | 30.294118 | 20.294118 |
def _unwrap_stream(uri, timeout, scanner, requests_session):
"""
Get a stream URI from a playlist URI, ``uri``.
Unwraps nested playlists until something that's not a playlist is found or
the ``timeout`` is reached.
"""
original_uri = uri
seen_uris = set()
deadline = time.time() + timeou... | [
"def",
"_unwrap_stream",
"(",
"uri",
",",
"timeout",
",",
"scanner",
",",
"requests_session",
")",
":",
"original_uri",
"=",
"uri",
"seen_uris",
"=",
"set",
"(",
")",
"deadline",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"while",
"time",
".",
... | 34.328358 | 19.820896 |
def set_acl(self, acl_or_str, key_name='', validate=True, headers=None,
version_id=None):
"""sets or updates a bucket's acl"""
if not self.bucket_name:
raise InvalidUriError('set_acl on bucket-less URI (%s)' %
self.uri)
self.get_bucke... | [
"def",
"set_acl",
"(",
"self",
",",
"acl_or_str",
",",
"key_name",
"=",
"''",
",",
"validate",
"=",
"True",
",",
"headers",
"=",
"None",
",",
"version_id",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"bucket_name",
":",
"raise",
"InvalidUriError",
... | 54.375 | 17.625 |
def Chung(T, MW, Tc, omega, Cvm, mu):
r'''Estimates the thermal conductivity of a gas as a function of
temperature using the CSP method of Chung [1]_.
.. math::
\frac{\lambda M}{\eta C_v} = \frac{3.75 \Psi}{C_v/R}
\Psi = 1 + \alpha \left\{[0.215+0.28288\alpha-1.061\beta+0.26665Z]/
... | [
"def",
"Chung",
"(",
"T",
",",
"MW",
",",
"Tc",
",",
"omega",
",",
"Cvm",
",",
"mu",
")",
":",
"MW",
"=",
"MW",
"/",
"1000.",
"alpha",
"=",
"Cvm",
"/",
"R",
"-",
"1.5",
"beta",
"=",
"0.7862",
"-",
"0.7109",
"*",
"omega",
"+",
"1.3168",
"*",
... | 30.578125 | 24.328125 |
def get_derived_from(self, address):
"""Get the target the specified target was derived from.
If a Target was injected programmatically, e.g. from codegen, this allows us to trace its
ancestry. If a Target is not derived, default to returning itself.
:API: public
"""
parent_address = self._de... | [
"def",
"get_derived_from",
"(",
"self",
",",
"address",
")",
":",
"parent_address",
"=",
"self",
".",
"_derived_from_by_derivative",
".",
"get",
"(",
"address",
",",
"address",
")",
"return",
"self",
".",
"get_target",
"(",
"parent_address",
")"
] | 40 | 22.9 |
def create_exception(error_codec):
"""
Creates an exception with given error codec.
:param error_codec: (Error Codec), error codec which includes the class name, message and exception trace.
:return: (Exception), the created exception.
"""
if error_codec.error_code in ERROR_CODE_TO_ERROR:
... | [
"def",
"create_exception",
"(",
"error_codec",
")",
":",
"if",
"error_codec",
".",
"error_code",
"in",
"ERROR_CODE_TO_ERROR",
":",
"return",
"ERROR_CODE_TO_ERROR",
"[",
"error_codec",
".",
"error_code",
"]",
"(",
"error_codec",
".",
"message",
")",
"stack_trace",
... | 48.176471 | 25 |
def mlt(self, _id):
'''
High-level method to do "more like this".
Its exact implementation can vary.
'''
query = {
'query': {'more_like_this': {
'like': {'_id': _id},
'min_term_freq': 1,
'min_doc_freq'... | [
"def",
"mlt",
"(",
"self",
",",
"_id",
")",
":",
"query",
"=",
"{",
"'query'",
":",
"{",
"'more_like_this'",
":",
"{",
"'like'",
":",
"{",
"'_id'",
":",
"_id",
"}",
",",
"'min_term_freq'",
":",
"1",
",",
"'min_doc_freq'",
":",
"1",
",",
"}",
"}",
... | 28.277778 | 14.611111 |
def hrepr_with_resources(self, obj, **cfg):
"""
This is equivalent to __call__, but performs the additional step of
putting the set of resources required to properly display the object
in the _resources property of the return value.
"""
res = self(obj, **cfg)
res.... | [
"def",
"hrepr_with_resources",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"cfg",
")",
":",
"res",
"=",
"self",
"(",
"obj",
",",
"*",
"*",
"cfg",
")",
"res",
".",
"resources",
"=",
"self",
".",
"resources",
"return",
"res"
] | 39.666667 | 13.666667 |
def on_page_layout_choice(self, event):
"""Page layout choice event handler"""
width, height = self.paper_sizes_points[event.GetString()]
self.page_width_text_ctrl.SetValue(str(width / 72.0))
self.page_height_text_ctrl.SetValue(str(height / 72.0))
event.Skip() | [
"def",
"on_page_layout_choice",
"(",
"self",
",",
"event",
")",
":",
"width",
",",
"height",
"=",
"self",
".",
"paper_sizes_points",
"[",
"event",
".",
"GetString",
"(",
")",
"]",
"self",
".",
"page_width_text_ctrl",
".",
"SetValue",
"(",
"str",
"(",
"widt... | 36.875 | 21.375 |
def set_sides(self, key, data, field, local=False):
"""
Assign data on the 'key' tile to all the edges
"""
for side in ['left', 'right', 'top', 'bottom']:
self.set(key, data, field, side, local) | [
"def",
"set_sides",
"(",
"self",
",",
"key",
",",
"data",
",",
"field",
",",
"local",
"=",
"False",
")",
":",
"for",
"side",
"in",
"[",
"'left'",
",",
"'right'",
",",
"'top'",
",",
"'bottom'",
"]",
":",
"self",
".",
"set",
"(",
"key",
",",
"data"... | 38.833333 | 8.5 |
def set_gcc():
"""Try to use GCC on OSX for OpenMP support."""
# For macports and homebrew
if 'darwin' in platform.platform().lower():
gcc = extract_gcc_binaries()
if gcc is not None:
os.environ["CC"] = gcc
os.environ["CXX"] = gcc
else:
global u... | [
"def",
"set_gcc",
"(",
")",
":",
"# For macports and homebrew",
"if",
"'darwin'",
"in",
"platform",
".",
"platform",
"(",
")",
".",
"lower",
"(",
")",
":",
"gcc",
"=",
"extract_gcc_binaries",
"(",
")",
"if",
"gcc",
"is",
"not",
"None",
":",
"os",
".",
... | 29.6875 | 17.875 |
def find_one(self, query):
"""Find one wrapper with conversion to dictionary
:param dict query: A Mongo query
"""
mongo_response = yield self.collection.find_one(query)
raise Return(self._obj_cursor_to_dictionary(mongo_response)) | [
"def",
"find_one",
"(",
"self",
",",
"query",
")",
":",
"mongo_response",
"=",
"yield",
"self",
".",
"collection",
".",
"find_one",
"(",
"query",
")",
"raise",
"Return",
"(",
"self",
".",
"_obj_cursor_to_dictionary",
"(",
"mongo_response",
")",
")"
] | 37.714286 | 14.857143 |
def start_auth(self, context, internal_request, get_state=stateID):
"""
See super class method satosa.backends.base#start_auth
:param get_state: Generates a state to be used in the authentication call.
:type get_state: Callable[[str, bytes], str]
:type context: satosa.context.Co... | [
"def",
"start_auth",
"(",
"self",
",",
"context",
",",
"internal_request",
",",
"get_state",
"=",
"stateID",
")",
":",
"oauth_state",
"=",
"get_state",
"(",
"self",
".",
"config",
"[",
"\"base_url\"",
"]",
",",
"rndstr",
"(",
")",
".",
"encode",
"(",
")"... | 46.222222 | 22.888889 |
def score(self, X, y):
"""
Draws a confusion matrix based on the test data supplied by comparing
predictions on instances X with the true values specified by the
target vector y.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix o... | [
"def",
"score",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"# Create predictions from X (will raise not fitted error)",
"y_pred",
"=",
"self",
".",
"predict",
"(",
"X",
")",
"# Encode the target with the supplied label encoder",
"if",
"self",
".",
"label_encoder",
":"... | 35.839286 | 22.482143 |
def select_python_parser(parser=None):
"""
Select default parser for loading and refactoring steps. Passing `redbaron` as argument
will select the old paring engine from v0.3.3
Replacing the redbaron parser was necessary to support Python 3 syntax. We have tried our
best to make... | [
"def",
"select_python_parser",
"(",
"parser",
"=",
"None",
")",
":",
"if",
"parser",
"==",
"'redbaron'",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"'GETGAUGE_USE_0_3_3_PARSER'",
")",
":",
"PythonFile",
".",
"Class",
"=",
"RedbaronPythonFile",
"else",
":",
... | 49.222222 | 30.444444 |
def _apply_unitary(val: Any, args: 'ApplyChannelArgs') -> Optional[np.ndarray]:
"""Attempt to use `apply_unitary` and return the result.
If `val` does not support `apply_unitary` returns None.
"""
left_args = ApplyUnitaryArgs(target_tensor=args.target_tensor,
available_... | [
"def",
"_apply_unitary",
"(",
"val",
":",
"Any",
",",
"args",
":",
"'ApplyChannelArgs'",
")",
"->",
"Optional",
"[",
"np",
".",
"ndarray",
"]",
":",
"left_args",
"=",
"ApplyUnitaryArgs",
"(",
"target_tensor",
"=",
"args",
".",
"target_tensor",
",",
"availabl... | 43.333333 | 15.611111 |
def _computeChart(chart, date):
""" Internal function to return a new chart for
a specific date using properties from old chart.
"""
pos = chart.pos
hsys = chart.hsys
IDs = [obj.id for obj in chart.objects]
return Chart(date, pos, IDs=IDs, hsys=hsys) | [
"def",
"_computeChart",
"(",
"chart",
",",
"date",
")",
":",
"pos",
"=",
"chart",
".",
"pos",
"hsys",
"=",
"chart",
".",
"hsys",
"IDs",
"=",
"[",
"obj",
".",
"id",
"for",
"obj",
"in",
"chart",
".",
"objects",
"]",
"return",
"Chart",
"(",
"date",
... | 30.555556 | 11.888889 |
def generate_html_files(*args):
'''
Generate the templates for adding, editing, viewing.
:return: None
'''
_ = args
for tag_key, tag_list in SWITCH_DICS.items():
if tag_key.startswith('dic_'):
__write_view_tmpl(tag_list)
__write_filter_tmpl(TPL_LIST)
__write_list_tm... | [
"def",
"generate_html_files",
"(",
"*",
"args",
")",
":",
"_",
"=",
"args",
"for",
"tag_key",
",",
"tag_list",
"in",
"SWITCH_DICS",
".",
"items",
"(",
")",
":",
"if",
"tag_key",
".",
"startswith",
"(",
"'dic_'",
")",
":",
"__write_view_tmpl",
"(",
"tag_l... | 24.923077 | 18.923077 |
def execute(self, requete_SQL):
"""Execute one or many requests
requete_SQL may be a tuple(requete,args) or a list of such tuples
Return the result or a list of results
"""
try:
cursor = self.cursor()
if isinstance(requete_SQL,tuple):
res =... | [
"def",
"execute",
"(",
"self",
",",
"requete_SQL",
")",
":",
"try",
":",
"cursor",
"=",
"self",
".",
"cursor",
"(",
")",
"if",
"isinstance",
"(",
"requete_SQL",
",",
"tuple",
")",
":",
"res",
"=",
"self",
".",
"_execute_one",
"(",
"cursor",
",",
"*",... | 33.363636 | 15.545455 |
def getAnalogUnit(self,num):
"""
Returns the COMTRADE channel unit (e.g., kV, V, kA, A)
of a given channel number.
The number to be given is the same of the COMTRADE header.
"""
listidx = self.An.index(num) # Get the position of the channel number.
return self.uu[... | [
"def",
"getAnalogUnit",
"(",
"self",
",",
"num",
")",
":",
"listidx",
"=",
"self",
".",
"An",
".",
"index",
"(",
"num",
")",
"# Get the position of the channel number.",
"return",
"self",
".",
"uu",
"[",
"listidx",
"]"
] | 40.125 | 14.125 |
def rcategorical(p, size=None):
"""
Categorical random variates.
"""
out = flib.rcat(p, np.random.random(size=size))
if sum(out.shape) == 1:
return out.squeeze()
else:
return out | [
"def",
"rcategorical",
"(",
"p",
",",
"size",
"=",
"None",
")",
":",
"out",
"=",
"flib",
".",
"rcat",
"(",
"p",
",",
"np",
".",
"random",
".",
"random",
"(",
"size",
"=",
"size",
")",
")",
"if",
"sum",
"(",
"out",
".",
"shape",
")",
"==",
"1"... | 23.333333 | 11.777778 |
def save_config(self, cmd="save config", confirm=True, confirm_response="y"):
"""Saves Config."""
self.enable()
if confirm:
output = self.send_command_timing(command_string=cmd)
if confirm_response:
output += self.send_command_timing(confirm_response)
... | [
"def",
"save_config",
"(",
"self",
",",
"cmd",
"=",
"\"save config\"",
",",
"confirm",
"=",
"True",
",",
"confirm_response",
"=",
"\"y\"",
")",
":",
"self",
".",
"enable",
"(",
")",
"if",
"confirm",
":",
"output",
"=",
"self",
".",
"send_command_timing",
... | 42.428571 | 20.214286 |
def _get_widget_id(self, package_name):
"""
returns widget_id for given package_name does not care
about multiple widget ids at the moment, just picks the first
:param str package_name: package to check for
:return: id of first widget which belongs to the given package_name
... | [
"def",
"_get_widget_id",
"(",
"self",
",",
"package_name",
")",
":",
"widget_id",
"=",
"\"\"",
"for",
"app",
"in",
"self",
".",
"get_apps_list",
"(",
")",
":",
"if",
"app",
".",
"package",
"==",
"package_name",
":",
"widget_id",
"=",
"list",
"(",
"app",
... | 34.866667 | 16.866667 |
def output_after_run_set(self, runSet, cputime=None, walltime=None, energy={}):
"""
The method output_after_run_set() stores the times of a run set in XML.
@params cputime, walltime: accumulated times of the run set
"""
self.add_values_to_run_set_xml(runSet, cputime, walltime, e... | [
"def",
"output_after_run_set",
"(",
"self",
",",
"runSet",
",",
"cputime",
"=",
"None",
",",
"walltime",
"=",
"None",
",",
"energy",
"=",
"{",
"}",
")",
":",
"self",
".",
"add_values_to_run_set_xml",
"(",
"runSet",
",",
"cputime",
",",
"walltime",
",",
"... | 43.947368 | 26.052632 |
def swap_buffers(self):
"""
Swap buffers, increment frame counter and pull events
"""
if not self.window.context:
return
self.frames += 1
self.window.flip()
self.window.dispatch_events() | [
"def",
"swap_buffers",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"window",
".",
"context",
":",
"return",
"self",
".",
"frames",
"+=",
"1",
"self",
".",
"window",
".",
"flip",
"(",
")",
"self",
".",
"window",
".",
"dispatch_events",
"(",
")"
] | 25.5 | 13.3 |
def get(self):
"""
*download the image*
"""
self.log.info('starting the ``get`` method')
ra = self.ra
dec = self.dec
if self.covered == False or self.covered == 999 or self.covered == "999":
return self.covered
self._download_sdss_image()
... | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``get`` method'",
")",
"ra",
"=",
"self",
".",
"ra",
"dec",
"=",
"self",
".",
"dec",
"if",
"self",
".",
"covered",
"==",
"False",
"or",
"self",
".",
"covered",
... | 25.666667 | 19.266667 |
def assert_valid(self):
"""For debugging; does some sanity checks on this set. Raises
InvalidNamespaceSetError if this namespace set is invalid. Otherwise,
raises/returns nothing."""
for ns_uri, ni in six.iteritems(self.__ns_uri_map):
if not ni.uri:
raise I... | [
"def",
"assert_valid",
"(",
"self",
")",
":",
"for",
"ns_uri",
",",
"ni",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"__ns_uri_map",
")",
":",
"if",
"not",
"ni",
".",
"uri",
":",
"raise",
"InvalidNamespaceSetError",
"(",
"\"URI not set in _NamespaceInf... | 41.288462 | 18.596154 |
def encode(python_object, indent=None, large_object=False):
""":returns: a JSON-representation of the object"""
# sorted keys is easier to read; however, Python-2.7.2 does not have this feature
kwargs = dict(indent=indent)
if can_dumps_sort_keys():
kwargs.update(sort_keys=True)
try:
... | [
"def",
"encode",
"(",
"python_object",
",",
"indent",
"=",
"None",
",",
"large_object",
"=",
"False",
")",
":",
"# sorted keys is easier to read; however, Python-2.7.2 does not have this feature",
"kwargs",
"=",
"dict",
"(",
"indent",
"=",
"indent",
")",
"if",
"can_du... | 39.5625 | 15.75 |
def offer_random(pool, answer, rationale, student_id, options):
"""
The random selection algorithm. The same as simple algorithm
"""
offer_simple(pool, answer, rationale, student_id, options) | [
"def",
"offer_random",
"(",
"pool",
",",
"answer",
",",
"rationale",
",",
"student_id",
",",
"options",
")",
":",
"offer_simple",
"(",
"pool",
",",
"answer",
",",
"rationale",
",",
"student_id",
",",
"options",
")"
] | 40.6 | 13.8 |
def _cli_main(args=None):
""" Pass input arguments to open_tunnel
Mandatory: ssh_address, -R (remote bind address list)
Optional:
-U (username) we may gather it from SSH_CONFIG_FILE or current username
-p (server_port), defaults to 22
-P (password)
-L (local_bind_ad... | [
"def",
"_cli_main",
"(",
"args",
"=",
"None",
")",
":",
"arguments",
"=",
"_parse_arguments",
"(",
"args",
")",
"# Remove all \"None\" input values",
"_remove_none_values",
"(",
"arguments",
")",
"verbosity",
"=",
"min",
"(",
"arguments",
".",
"pop",
"(",
"'verb... | 36.871795 | 18.461538 |
def fromFile(self, fname):
"""Displays a spectrogram of an audio file. Supported formats see :func:`sparkle.tools.audiotools.audioread`
:param fname: file path of the audiofile to display
:type fname: str
:returns: float -- duration of audio recording (seconds)
"""
spec,... | [
"def",
"fromFile",
"(",
"self",
",",
"fname",
")",
":",
"spec",
",",
"f",
",",
"bins",
",",
"dur",
"=",
"audiotools",
".",
"spectrogram",
"(",
"fname",
",",
"*",
"*",
"self",
".",
"specgramArgs",
")",
"self",
".",
"updateImage",
"(",
"spec",
",",
"... | 43.6 | 17.5 |
def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1,
catch_exceptions=()):
"""Executes a method until the retry limit is hit or not None is returned."""
return retry_until_valid_or_limit_reached(
method, limit, lambda x: x is not None, sleep_s, catch_ex... | [
"def",
"retry_until_not_none_or_limit_reached",
"(",
"method",
",",
"limit",
",",
"sleep_s",
"=",
"1",
",",
"catch_exceptions",
"=",
"(",
")",
")",
":",
"return",
"retry_until_valid_or_limit_reached",
"(",
"method",
",",
"limit",
",",
"lambda",
"x",
":",
"x",
... | 65 | 17.2 |
def _threshold_nans(data, tolerate_nans):
"""Thresholds data based on proportion of subjects with NaNs
Takes in data and a threshold value (float between 0.0 and 1.0) determining
the permissible proportion of subjects with non-NaN values. For example, if
threshold=.8, any voxel where >= 80% of subject... | [
"def",
"_threshold_nans",
"(",
"data",
",",
"tolerate_nans",
")",
":",
"nans",
"=",
"np",
".",
"all",
"(",
"np",
".",
"any",
"(",
"np",
".",
"isnan",
"(",
"data",
")",
",",
"axis",
"=",
"0",
")",
",",
"axis",
"=",
"1",
")",
"# Check tolerate_nans i... | 38.854545 | 26.181818 |
def display(message, wpm, element_duration, word_ref, strip=False):
"""
Display
text message
morse code
binary morse code
"""
fmt = "{0:>8s}: '{1}'"
key = "text"
if strip:
print(fmt.format(key, message.strip()))
else:
print(fmt.format(key, message.stri... | [
"def",
"display",
"(",
"message",
",",
"wpm",
",",
"element_duration",
",",
"word_ref",
",",
"strip",
"=",
"False",
")",
":",
"fmt",
"=",
"\"{0:>8s}: '{1}'\"",
"key",
"=",
"\"text\"",
"if",
"strip",
":",
"print",
"(",
"fmt",
".",
"format",
"(",
"key",
... | 31.846154 | 17 |
def queries(self, rcSuffix='', rcNeeded=False, padChar='-',
queryInsertionChar='N', unknownQualityChar='!',
allowDuplicateIds=False, addAlignment=False):
"""
Produce padded (with gaps) queries according to the CIGAR string and
reference sequence length for each ma... | [
"def",
"queries",
"(",
"self",
",",
"rcSuffix",
"=",
"''",
",",
"rcNeeded",
"=",
"False",
",",
"padChar",
"=",
"'-'",
",",
"queryInsertionChar",
"=",
"'N'",
",",
"unknownQualityChar",
"=",
"'!'",
",",
"allowDuplicateIds",
"=",
"False",
",",
"addAlignment",
... | 51.814634 | 22.868293 |
def withTracebackPrint(ErrorType, thrownError, _traceback):
'''returns an Exception object for the given ErrorType of the thrownError
and the _traceback
can be used like withTracebackPrint(*sys.exc_info())'''
file = StringIO.StringIO()
traceback.print_exception(ErrorType, thrownError, _traceback, file = fi... | [
"def",
"withTracebackPrint",
"(",
"ErrorType",
",",
"thrownError",
",",
"_traceback",
")",
":",
"file",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"traceback",
".",
"print_exception",
"(",
"ErrorType",
",",
"thrownError",
",",
"_traceback",
",",
"file",
"=",
... | 47.375 | 25.375 |
def put(self):
"""
Save changes made to the object to DocumentCloud.
According to DocumentCloud's docs, edits are allowed for the following
fields:
* title
* source
* description
* related_article
* access
* publis... | [
"def",
"put",
"(",
"self",
")",
":",
"params",
"=",
"dict",
"(",
"title",
"=",
"self",
".",
"title",
"or",
"''",
",",
"source",
"=",
"self",
".",
"source",
"or",
"''",
",",
"description",
"=",
"self",
".",
"description",
"or",
"''",
",",
"related_a... | 29.074074 | 18.777778 |
def encrypt(self, passphrase, sessionkey=None, **prefs):
"""
Encrypt the contents of this message using a passphrase.
:param passphrase: The passphrase to use for encrypting this message.
:type passphrase: ``str``, ``unicode``, ``bytes``
:optional param sessionkey: Provide a ses... | [
"def",
"encrypt",
"(",
"self",
",",
"passphrase",
",",
"sessionkey",
"=",
"None",
",",
"*",
"*",
"prefs",
")",
":",
"cipher_algo",
"=",
"prefs",
".",
"pop",
"(",
"'cipher'",
",",
"SymmetricKeyAlgorithm",
".",
"AES256",
")",
"hash_algo",
"=",
"prefs",
"."... | 40.891304 | 26.413043 |
def pop(self):
'''Return a new ImmutableVector with the last item removed.'''
if self._length == 0:
raise IndexError()
newvec = ImmutableVector()
newvec.tree = self.tree.remove(self._length-1)
newvec._length = self._length-1
return newvec | [
"def",
"pop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_length",
"==",
"0",
":",
"raise",
"IndexError",
"(",
")",
"newvec",
"=",
"ImmutableVector",
"(",
")",
"newvec",
".",
"tree",
"=",
"self",
".",
"tree",
".",
"remove",
"(",
"self",
".",
"_leng... | 36.375 | 14.625 |
def mutect_caller(align_bams, items, ref_file, assoc_files, region=None,
out_file=None):
"""Run the MuTect paired analysis algorithm.
"""
config = items[0]["config"]
if out_file is None:
out_file = "%s-paired-variants.vcf.gz" % os.path.splitext(align_bams[0])[0]
if not file... | [
"def",
"mutect_caller",
"(",
"align_bams",
",",
"items",
",",
"ref_file",
",",
"assoc_files",
",",
"region",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"config",
"=",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
"if",
"out_file",
"is",
"No... | 63.890244 | 29.097561 |
def register(self, newitems, *args, **kwargs):
"""
Register newitems in registry.
:param newitems: New items to add to registry. When registering new
items, keys are not allowed to override existing keys in the
registry.
:type newitems: mapping
:param arg... | [
"def",
"register",
"(",
"self",
",",
"newitems",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"newkeys",
"=",
"newitems",
".",
"viewkeys",
"(",
")",
"# set of the new item keys",
"if",
"any",
"(",
"self",
".",
"viewkeys",
"(",
")",
"&",
"newkey... | 46.107143 | 18.178571 |
def decode_contents(self, contents, obj):
"""
Decodes the list of siblings from the protobuf representation
into the object.
:param contents: a list of RpbContent messages
:type contents: list
:param obj: a RiakObject
:type obj: RiakObject
:rtype RiakObje... | [
"def",
"decode_contents",
"(",
"self",
",",
"contents",
",",
"obj",
")",
":",
"obj",
".",
"siblings",
"=",
"[",
"self",
".",
"decode_content",
"(",
"c",
",",
"RiakContent",
"(",
"obj",
")",
")",
"for",
"c",
"in",
"contents",
"]",
"# Invoke sibling-resolu... | 34.117647 | 13.411765 |
def _finalize_nonblock_blob(self, sd, metadata, digest):
# type: (SyncCopy, blobxfer.models.synccopy.Descriptor, dict,
# str) -> None
"""Finalize Non-Block blob
:param SyncCopy self: this
:param blobxfer.models.synccopy.Descriptor sd: synccopy descriptor
:param dic... | [
"def",
"_finalize_nonblock_blob",
"(",
"self",
",",
"sd",
",",
"metadata",
",",
"digest",
")",
":",
"# type: (SyncCopy, blobxfer.models.synccopy.Descriptor, dict,",
"# str) -> None",
"# set md5 page blob property if required",
"if",
"(",
"blobxfer",
".",
"util",
".",
... | 44.9375 | 10.625 |
def _fake_createinstance(self, namespace, **params):
"""
Implements a server responder for
:meth:`~pywbem.WBEMConnection.CreateInstance`
Create a CIM instance in the local repository of this class.
Always use the namespace parameter assuming that
pywbem.CreateInstance h... | [
"def",
"_fake_createinstance",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"params",
")",
":",
"if",
"self",
".",
"_repo_lite",
":",
"raise",
"CIMError",
"(",
"CIM_ERR_NOT_SUPPORTED",
",",
"\"CreateInstance not supported when repo_lite set.\"",
")",
"# Validate para... | 41.253425 | 20.280822 |
def predict_topk(self, dataset, max_neighbors=10, radius=None, k=3,
verbose=False):
"""
Return top-k most likely predictions for each observation in
``dataset``. Predictions are returned as an SFrame with three columns:
`row_id`, `class`, and `probability`.
... | [
"def",
"predict_topk",
"(",
"self",
",",
"dataset",
",",
"max_neighbors",
"=",
"10",
",",
"radius",
"=",
"None",
",",
"k",
"=",
"3",
",",
"verbose",
"=",
"False",
")",
":",
"## Validate the number of results to return. Note that the",
"# 'max_neighbors' and 'radius... | 39.991667 | 24.358333 |
def get_textnode_subtrees(html_tree,
xpath_to_text=TEXT_FINDER_XPATH):
"""A modification of get_sentence_xpath_tuples: some code was
refactored-out, variable names are slightly different. This function
does wrap the ltml.tree construction, so a file path, file-like
structu... | [
"def",
"get_textnode_subtrees",
"(",
"html_tree",
",",
"xpath_to_text",
"=",
"TEXT_FINDER_XPATH",
")",
":",
"try",
":",
"xpath_finder",
"=",
"html_tree",
".",
"getroot",
"(",
")",
".",
"getroottree",
"(",
")",
".",
"getpath",
"except",
"(",
"AttributeError",
"... | 42.037037 | 21.740741 |
def eval_adiabatic_limit(YABFGN, Ytilde, P0):
"""Compute the limiting SLH model for the adiabatic approximation
Args:
YABFGN: The tuple (Y, A, B, F, G, N)
as returned by prepare_adiabatic_limit.
Ytilde: The pseudo-inverse of Y, satisfying Y * Ytilde = P0.
P0: The projector o... | [
"def",
"eval_adiabatic_limit",
"(",
"YABFGN",
",",
"Ytilde",
",",
"P0",
")",
":",
"Y",
",",
"A",
",",
"B",
",",
"F",
",",
"G",
",",
"N",
"=",
"YABFGN",
"Klim",
"=",
"(",
"P0",
"*",
"(",
"B",
"-",
"A",
"*",
"Ytilde",
"*",
"A",
")",
"*",
"P0"... | 34 | 21.913043 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.