text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _iterator(self, response):
'''
Iterate through query data.
'''
while True:
result = self._parse_data(response)
bookmark = response.get('bookmark')
if result:
for row in result:
yield row
del res... | [
"def",
"_iterator",
"(",
"self",
",",
"response",
")",
":",
"while",
"True",
":",
"result",
"=",
"self",
".",
"_parse_data",
"(",
"response",
")",
"bookmark",
"=",
"response",
".",
"get",
"(",
"'bookmark'",
")",
"if",
"result",
":",
"for",
"row",
"in",... | 22 | 20.857143 |
def toLily(self):
'''
Method which converts the object instance, its attributes and children to a string of lilypond code
:return: str of lilypond code
'''
lilystring = ""
if not self.autoBeam:
lilystring += "\\autoBeamOff"
children = self.SortedChi... | [
"def",
"toLily",
"(",
"self",
")",
":",
"lilystring",
"=",
"\"\"",
"if",
"not",
"self",
".",
"autoBeam",
":",
"lilystring",
"+=",
"\"\\\\autoBeamOff\"",
"children",
"=",
"self",
".",
"SortedChildren",
"(",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"... | 34.3 | 19.7 |
def show_letter(
self,
s,
text_colour=[255, 255, 255],
back_colour=[0, 0, 0]
):
"""
Displays a single text character on the LED matrix using the specified
colours
"""
if len(s) > 1:
raise ValueError('Only one ch... | [
"def",
"show_letter",
"(",
"self",
",",
"s",
",",
"text_colour",
"=",
"[",
"255",
",",
"255",
",",
"255",
"]",
",",
"back_colour",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
")",
":",
"if",
"len",
"(",
"s",
")",
">",
"1",
":",
"raise",
"ValueErr... | 34.137931 | 15.172414 |
def validate(config):
'''
Validate the beacon configuration
'''
valid = True
messages = []
if not isinstance(config, list):
valid = False
messages.append('[-] Configuration for %s beacon must be a list', config)
else:
_config = {}
list(map(_config.update, con... | [
"def",
"validate",
"(",
"config",
")",
":",
"valid",
"=",
"True",
"messages",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"config",
",",
"list",
")",
":",
"valid",
"=",
"False",
"messages",
".",
"append",
"(",
"'[-] Configuration for %s beacon must be a l... | 34.804878 | 23.878049 |
def _parse_Sigma(self,Sigma_amp,Sigma,dSigmadR,d2SigmadR2):
"""
NAME:
_parse_Sigma
PURPOSE:
Parse the various input options for Sigma* functions
HISTORY:
2016-12-27 - Written - Bovy (UofT/CCA)
"""
if isinstance(Sigma,dict):
Sig... | [
"def",
"_parse_Sigma",
"(",
"self",
",",
"Sigma_amp",
",",
"Sigma",
",",
"dSigmadR",
",",
"d2SigmadR2",
")",
":",
"if",
"isinstance",
"(",
"Sigma",
",",
"dict",
")",
":",
"Sigma",
"=",
"[",
"Sigma",
"]",
"try",
":",
"nsigma",
"=",
"len",
"(",
"Sigma"... | 29.266667 | 12.6 |
def make_sqlite_url(filename: str) -> str:
"""
Makes an SQLAlchemy URL for a SQLite database.
"""
absfile = os.path.abspath(filename)
return "sqlite://{host}/{path}".format(host="", path=absfile) | [
"def",
"make_sqlite_url",
"(",
"filename",
":",
"str",
")",
"->",
"str",
":",
"absfile",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"return",
"\"sqlite://{host}/{path}\"",
".",
"format",
"(",
"host",
"=",
"\"\"",
",",
"path",
"=",
"abs... | 35 | 6.333333 |
def do_up(self, arg):
"""Run up migration with name or numeric id matching arg"""
print "running up migration"
self.manager.run(arg, Direction.UP) | [
"def",
"do_up",
"(",
"self",
",",
"arg",
")",
":",
"print",
"\"running up migration\"",
"self",
".",
"manager",
".",
"run",
"(",
"arg",
",",
"Direction",
".",
"UP",
")"
] | 41.75 | 6.5 |
def knearest(self, table, chrom_or_feat, start=None, end=None, k=1,
_direction=None):
"""
Return k-nearest features
Parameters
----------
table : str or table
table against which to query
chrom_or_feat : str or feat
either a chromoso... | [
"def",
"knearest",
"(",
"self",
",",
"table",
",",
"chrom_or_feat",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"k",
"=",
"1",
",",
"_direction",
"=",
"None",
")",
":",
"assert",
"_direction",
"in",
"(",
"None",
",",
"\"up\"",
",",
"\"... | 30.206897 | 20.367816 |
def processBED(fh, genome_alig, window_size, window_centre,
mi_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS, species=None,
verbose=False):
"""
Process BED file, produce profile of conservation using whole genome alig.
:param fh:
:param genome_alig: the whole-genome alignment to... | [
"def",
"processBED",
"(",
"fh",
",",
"genome_alig",
",",
"window_size",
",",
"window_centre",
",",
"mi_seqs",
"=",
"MissingSequenceHandler",
".",
"TREAT_AS_ALL_GAPS",
",",
"species",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"mean_profile",
"=",
"["... | 42.733333 | 19.533333 |
def pick_signed_metadata_statements_regex(self, pattern, context):
"""
Pick signed metadata statements based on ISS pattern matching
:param pattern: A regular expression to match the iss against
:return: list of tuples (FO ID, signed metadata statement)
"""
comp_... | [
"def",
"pick_signed_metadata_statements_regex",
"(",
"self",
",",
"pattern",
",",
"context",
")",
":",
"comp_pat",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"sms_dict",
"=",
"self",
".",
"signer",
".",
"metadata_statements",
"[",
"context",
"]",
"res",
... | 39.142857 | 15.428571 |
def _build_menu(docs):
"""
Builds the menu used for the current ``DocumentWriter``.
"""
paths = []
current = docs.filename
while current != docs.root:
current = current.parent
paths.append(current)
for path in reversed(paths):
docs.add_menu(path.stem.title(), link=p... | [
"def",
"_build_menu",
"(",
"docs",
")",
":",
"paths",
"=",
"[",
"]",
"current",
"=",
"docs",
".",
"filename",
"while",
"current",
"!=",
"docs",
".",
"root",
":",
"current",
"=",
"current",
".",
"parent",
"paths",
".",
"append",
"(",
"current",
")",
"... | 24.222222 | 18.666667 |
def debug_bad_encoding(data):
"""Let's try to help user figure out what is at fault."""
at_fault_files = set()
for source_file_data in data['source_files']:
for value in source_file_data.values():
try:
json.dumps(value)
except Unico... | [
"def",
"debug_bad_encoding",
"(",
"data",
")",
":",
"at_fault_files",
"=",
"set",
"(",
")",
"for",
"source_file_data",
"in",
"data",
"[",
"'source_files'",
"]",
":",
"for",
"value",
"in",
"source_file_data",
".",
"values",
"(",
")",
":",
"try",
":",
"json"... | 42.857143 | 15.071429 |
def open_raw_data_file(filename, mode="w", title="", scan_parameters=None, socket_address=None):
'''Mimics pytables.open_file() and stores the configuration and run configuration
Returns:
RawDataFile Object
Examples:
with open_raw_data_file(filename = self.scan_data_filename, title=self.scan_id, s... | [
"def",
"open_raw_data_file",
"(",
"filename",
",",
"mode",
"=",
"\"w\"",
",",
"title",
"=",
"\"\"",
",",
"scan_parameters",
"=",
"None",
",",
"socket_address",
"=",
"None",
")",
":",
"return",
"RawDataFile",
"(",
"filename",
"=",
"filename",
",",
"mode",
"... | 52.333333 | 45.5 |
def build_benchmark_plugin(name: str) -> LaserPlugin:
""" Creates an instance of the benchmark plugin with the given name """
from mythril.laser.ethereum.plugins.implementations.benchmark import (
BenchmarkPlugin,
)
return BenchmarkPlugin(name) | [
"def",
"build_benchmark_plugin",
"(",
"name",
":",
"str",
")",
"->",
"LaserPlugin",
":",
"from",
"mythril",
".",
"laser",
".",
"ethereum",
".",
"plugins",
".",
"implementations",
".",
"benchmark",
"import",
"(",
"BenchmarkPlugin",
",",
")",
"return",
"Benchmar... | 40.428571 | 19.714286 |
def parse_handshake_messages(data):
"""
Creates a generator returning tuples of information about each message in
a byte string of data from a TLS handshake record
:param data:
A byte string of a TLS handshake record data
:return:
A generator that yields 2-element tuples:
[... | [
"def",
"parse_handshake_messages",
"(",
"data",
")",
":",
"pointer",
"=",
"0",
"data_len",
"=",
"len",
"(",
"data",
")",
"while",
"pointer",
"<",
"data_len",
":",
"length",
"=",
"int_from_bytes",
"(",
"data",
"[",
"pointer",
"+",
"1",
":",
"pointer",
"+"... | 28.565217 | 17.521739 |
def open_ports(start, end, protocol="TCP"):
"""Opens a range of service network ports"""
_args = ['open-port']
_args.append('{}-{}/{}'.format(start, end, protocol))
subprocess.check_call(_args) | [
"def",
"open_ports",
"(",
"start",
",",
"end",
",",
"protocol",
"=",
"\"TCP\"",
")",
":",
"_args",
"=",
"[",
"'open-port'",
"]",
"_args",
".",
"append",
"(",
"'{}-{}/{}'",
".",
"format",
"(",
"start",
",",
"end",
",",
"protocol",
")",
")",
"subprocess"... | 41 | 8.6 |
def tuples(stream, *keys):
"""Reformat data as tuples.
Parameters
----------
stream : iterable
Stream of data objects.
*keys : strings
Keys to use for ordering data.
Yields
------
items : tuple of np.ndarrays
Data object reformated as a tuple.
Raises
-... | [
"def",
"tuples",
"(",
"stream",
",",
"*",
"keys",
")",
":",
"if",
"not",
"keys",
":",
"raise",
"PescadorError",
"(",
"'Unable to generate tuples from '",
"'an empty item set'",
")",
"for",
"data",
"in",
"stream",
":",
"try",
":",
"yield",
"tuple",
"(",
"data... | 24.645161 | 21.096774 |
def wait_until_not_visible(self, timeout=None):
"""Search element and wait until it is not visible
:param timeout: max time to wait
:returns: page element instance
"""
try:
self.utils.wait_until_element_not_visible(self, timeout)
except TimeoutException as ex... | [
"def",
"wait_until_not_visible",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"utils",
".",
"wait_until_element_not_visible",
"(",
"self",
",",
"timeout",
")",
"except",
"TimeoutException",
"as",
"exception",
":",
"parent_msg",
... | 52.0625 | 25.625 |
def move_version(self, id, after=None, position=None):
"""Move a version within a project's ordered version list and return a new version Resource for it.
One, but not both, of ``after`` and ``position`` must be specified.
:param id: ID of the version to move
:param after: the self att... | [
"def",
"move_version",
"(",
"self",
",",
"id",
",",
"after",
"=",
"None",
",",
"position",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"after",
"is",
"not",
"None",
":",
"data",
"[",
"'after'",
"]",
"=",
"after",
"elif",
"position",
"is",
... | 42.136364 | 22.136364 |
def subclasses(self, inherited=False):
"""Iterate over the subclasses of the class.
This function is the Python equivalent
of the CLIPS class-subclasses command.
"""
data = clips.data.DataObject(self._env)
lib.EnvClassSubclasses(self._env, self._cls, data.byref, int(in... | [
"def",
"subclasses",
"(",
"self",
",",
"inherited",
"=",
"False",
")",
":",
"data",
"=",
"clips",
".",
"data",
".",
"DataObject",
"(",
"self",
".",
"_env",
")",
"lib",
".",
"EnvClassSubclasses",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_cls",
","... | 30.384615 | 19.230769 |
def extract_columns_from_table_definition_file(xmltag, table_definition_file):
"""
Extract all columns mentioned in the result tag of a table definition file.
"""
def handle_path(path):
"""Convert path from a path relative to table-definition file."""
if not path or path.startswith("http... | [
"def",
"extract_columns_from_table_definition_file",
"(",
"xmltag",
",",
"table_definition_file",
")",
":",
"def",
"handle_path",
"(",
"path",
")",
":",
"\"\"\"Convert path from a path relative to table-definition file.\"\"\"",
"if",
"not",
"path",
"or",
"path",
".",
"start... | 41.818182 | 21.590909 |
def calibrate(self, data, calibration):
"""Calibrate the data."""
tic = datetime.now()
if calibration == 'counts':
res = data
elif calibration in ['radiance', 'brightness_temperature']:
res = self._calibrate(data)
else:
raise NotImplementedErro... | [
"def",
"calibrate",
"(",
"self",
",",
"data",
",",
"calibration",
")",
":",
"tic",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"calibration",
"==",
"'counts'",
":",
"res",
"=",
"data",
"elif",
"calibration",
"in",
"[",
"'radiance'",
",",
"'brightness_te... | 36.5625 | 17.75 |
def web(connection, host, port):
"""Run a combine web interface."""
from bio2bel.web.application import create_application
app = create_application(connection=connection)
app.run(host=host, port=port) | [
"def",
"web",
"(",
"connection",
",",
"host",
",",
"port",
")",
":",
"from",
"bio2bel",
".",
"web",
".",
"application",
"import",
"create_application",
"app",
"=",
"create_application",
"(",
"connection",
"=",
"connection",
")",
"app",
".",
"run",
"(",
"ho... | 42.4 | 8.8 |
def _call(self, x, out=None):
"""Multiply ``x`` and write to ``out`` if given."""
if out is None:
return x * self.multiplicand
elif not self.__range_is_field:
if self.__domain_is_field:
out.lincomb(x, self.multiplicand)
else:
ou... | [
"def",
"_call",
"(",
"self",
",",
"x",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"return",
"x",
"*",
"self",
".",
"multiplicand",
"elif",
"not",
"self",
".",
"__range_is_field",
":",
"if",
"self",
".",
"__domain_is_field",
":... | 39.181818 | 12.181818 |
def read(self, count):
"""
Reads up to C{count} bytes from the file.
:rtype: list
:return: the list of symbolic bytes read
"""
if self.pos > self.max_size:
return []
else:
size = min(count, self.max_size - self.pos)
ret = [self.... | [
"def",
"read",
"(",
"self",
",",
"count",
")",
":",
"if",
"self",
".",
"pos",
">",
"self",
".",
"max_size",
":",
"return",
"[",
"]",
"else",
":",
"size",
"=",
"min",
"(",
"count",
",",
"self",
".",
"max_size",
"-",
"self",
".",
"pos",
")",
"ret... | 31.615385 | 14.230769 |
def FilterRange(self, start_time=None, stop_time=None):
"""Filter the series to lie between start_time and stop_time.
Removes all values of the series which are outside of some time range.
Args:
start_time: If set, timestamps before start_time will be dropped.
stop_time: If set, timestamps at ... | [
"def",
"FilterRange",
"(",
"self",
",",
"start_time",
"=",
"None",
",",
"stop_time",
"=",
"None",
")",
":",
"start_time",
"=",
"self",
".",
"_NormalizeTime",
"(",
"start_time",
")",
"stop_time",
"=",
"self",
".",
"_NormalizeTime",
"(",
"stop_time",
")",
"s... | 35.411765 | 21.882353 |
def groups(username, **kwargs):
'''
Authenticate against an LDAP group
Behavior is highly dependent on if Active Directory is in use.
AD handles group membership very differently than OpenLDAP.
See the :ref:`External Authentication <acl-eauth>` documentation for a thorough
discussion of availa... | [
"def",
"groups",
"(",
"username",
",",
"*",
"*",
"kwargs",
")",
":",
"group_list",
"=",
"[",
"]",
"# If bind credentials are configured, use them instead of user's",
"if",
"_config",
"(",
"'binddn'",
",",
"mandatory",
"=",
"False",
")",
"and",
"_config",
"(",
"'... | 58.410714 | 35.035714 |
def _get_rate(self, value):
"""Return the rate in Hz from the short int value"""
if value == 0:
return 0
else:
return MINIMAL_RATE_HZ * math.exp(value * self._get_factor()) | [
"def",
"_get_rate",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"0",
":",
"return",
"0",
"else",
":",
"return",
"MINIMAL_RATE_HZ",
"*",
"math",
".",
"exp",
"(",
"value",
"*",
"self",
".",
"_get_factor",
"(",
")",
")"
] | 35.833333 | 18.5 |
def to_method(func):
"""
Lift :func:`func` to a method; it will be called with the first argument
'self' ignored.
:param func: Any callable object
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Wrapper function.
"""
return func(*args[1:], **kwargs)
... | [
"def",
"to_method",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapper function.\n \"\"\"",
"return",
"func",
"(",
"*",
"args",
"[",
"1",
... | 22.928571 | 14.571429 |
def __add_coreference_chain_tiers(self, docgraph, body,
min_chain_length=3):
"""
Parameters
----------
docgraph : DiscourseDocumentGraph
the document graph from which the chains will be extracted
body : etree._Element
... | [
"def",
"__add_coreference_chain_tiers",
"(",
"self",
",",
"docgraph",
",",
"body",
",",
"min_chain_length",
"=",
"3",
")",
":",
"E",
"=",
"self",
".",
"E",
"for",
"i",
",",
"chain",
"in",
"enumerate",
"(",
"get_pointing_chains",
"(",
"docgraph",
")",
")",
... | 42.948718 | 19.307692 |
def compress(expression):
"""
Compress a reference expression to group spans on the same id.
Also works on space-separated ID lists, although a sequence of space
characters will be considered a delimiter.
>>> compress('a1')
'a1'
>>> compress('a1[3:5]')
'a1[3:5]'
>>> compress('a1[3:5... | [
"def",
"compress",
"(",
"expression",
")",
":",
"tokens",
"=",
"[",
"]",
"selection",
"=",
"[",
"]",
"last_id",
"=",
"None",
"for",
"(",
"pre",
",",
"_id",
",",
"_range",
")",
"in",
"robust_ref_re",
".",
"findall",
"(",
"expression",
")",
":",
"if",
... | 26.432432 | 16.918919 |
def connect(self, target, acceptor, wrapper=None):
"""
Initiate a connection from the tendril manager's endpoint.
Once the connection is completed, a Tendril object will be
created and passed to the given acceptor.
:param target: The target of the connection attempt.
:pa... | [
"def",
"connect",
"(",
"self",
",",
"target",
",",
"acceptor",
",",
"wrapper",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"running",
":",
"raise",
"ValueError",
"(",
"\"TendrilManager not running\"",
")",
"# Check the target address",
"fam",
"=",
"utils"... | 42.413793 | 20 |
def BGPNeighborPrefixExceeded_originator_switch_info_switchVcsId(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
BGPNeighborPrefixExceeded = ET.SubElement(config, "BGPNeighborPrefixExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")
ori... | [
"def",
"BGPNeighborPrefixExceeded_originator_switch_info_switchVcsId",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"BGPNeighborPrefixExceeded",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"BG... | 56.090909 | 29.090909 |
def to_schema(self):
"""
Generate a schema based on previous inputs.
:rtype: ``dict``
"""
schema = self._base_schema()
schema.update(self._root_node.to_schema())
return schema | [
"def",
"to_schema",
"(",
"self",
")",
":",
"schema",
"=",
"self",
".",
"_base_schema",
"(",
")",
"schema",
".",
"update",
"(",
"self",
".",
"_root_node",
".",
"to_schema",
"(",
")",
")",
"return",
"schema"
] | 24.888889 | 13.333333 |
def get_pval_uncorr(self, study, log=sys.stdout):
"""Calculate the uncorrected pvalues for study items."""
results = []
study_in_pop = self.pop.intersection(study)
# " 99% 378 of 382 study items found in population"
go2studyitems = get_terms("study", study_in_pop, self.asso... | [
"def",
"get_pval_uncorr",
"(",
"self",
",",
"study",
",",
"log",
"=",
"sys",
".",
"stdout",
")",
":",
"results",
"=",
"[",
"]",
"study_in_pop",
"=",
"self",
".",
"pop",
".",
"intersection",
"(",
"study",
")",
"# \" 99% 378 of 382 study items found in pop... | 46.128205 | 21.153846 |
def sdiff(a, b):
"""
Take the symmetric difference of two sets of any data type to form a
third set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sdiff_c.html
:param a: First input set.
:type a: spiceypy.utils.support_types.SpiceCell
:param b: Second input set.
:type b: spic... | [
"def",
"sdiff",
"(",
"a",
",",
"b",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"isinstance",
"(",
"b",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"a",
".",
"dtype",
"==",
"b",
".",
"dtype",
"# T... | 35.172414 | 16.896552 |
def send_text_message(self, user_id, content, kf_account=None):
"""
发送文本消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param content: 消息正文
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
data = {
"touser": us... | [
"def",
"send_text_message",
"(",
"self",
",",
"user_id",
",",
"content",
",",
"kf_account",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"touser\"",
":",
"user_id",
",",
"\"msgtype\"",
":",
"\"text\"",
",",
"\"text\"",
":",
"{",
"\"content\"",
":",
"content"... | 29.363636 | 18 |
def _getModelPosterior(self,min):
"""
USES LAPLACE APPROXIMATION TO CALCULATE THE BAYESIAN MODEL POSTERIOR
"""
Sigma = self._getLaplaceCovar(min)
n_params = self.vd.getNumberScales()
ModCompl = 0.5*n_params*sp.log(2*sp.pi)+0.5*sp.log(sp.linalg.det(Sigma))
RV = min... | [
"def",
"_getModelPosterior",
"(",
"self",
",",
"min",
")",
":",
"Sigma",
"=",
"self",
".",
"_getLaplaceCovar",
"(",
"min",
")",
"n_params",
"=",
"self",
".",
"vd",
".",
"getNumberScales",
"(",
")",
"ModCompl",
"=",
"0.5",
"*",
"n_params",
"*",
"sp",
".... | 38.444444 | 13.333333 |
def get_polygon_from_nuts(conn, nuts):
r"""A one-line summary that does not use variable names or the
function name.
Several sentences providing an extended description. Refer to
variables using back-ticks, e.g. `var`.
Parameters
----------
var1 : array_like
Array_like means all th... | [
"def",
"get_polygon_from_nuts",
"(",
"conn",
",",
"nuts",
")",
":",
"# TODO@Günni",
"if",
"isinstance",
"(",
"nuts",
",",
"str",
")",
":",
"nuts",
"=",
"[",
"nuts",
",",
"'xyz'",
"]",
"logging",
".",
"debug",
"(",
"'Getting polygon from DB'",
")",
"sql",
... | 28.265957 | 22.723404 |
def _before_flush_handler(session, _flush_context, _instances):
"""Update version ID for all dirty, modified rows"""
dialect = get_dialect(session)
for row in session.dirty:
if isinstance(row, SavageModelMixin) and is_modified(row, dialect):
# Update row version_id
row.update... | [
"def",
"_before_flush_handler",
"(",
"session",
",",
"_flush_context",
",",
"_instances",
")",
":",
"dialect",
"=",
"get_dialect",
"(",
"session",
")",
"for",
"row",
"in",
"session",
".",
"dirty",
":",
"if",
"isinstance",
"(",
"row",
",",
"SavageModelMixin",
... | 46.714286 | 12.142857 |
def match_seq(self, nodes, results=None):
"""Does this pattern exactly match a sequence of nodes?"""
for c, r in self.generate_matches(nodes):
if c == len(nodes):
if results is not None:
results.update(r)
if self.name:
... | [
"def",
"match_seq",
"(",
"self",
",",
"nodes",
",",
"results",
"=",
"None",
")",
":",
"for",
"c",
",",
"r",
"in",
"self",
".",
"generate_matches",
"(",
"nodes",
")",
":",
"if",
"c",
"==",
"len",
"(",
"nodes",
")",
":",
"if",
"results",
"is",
"not... | 39.9 | 7.9 |
def url_fix(s, charset='utf-8'):
r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix(u'http://de.wikipedia.org/w... | [
"def",
"url_fix",
"(",
"s",
",",
"charset",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"charset",
",",
"'replace'",
")",
"scheme",
",",
"netloc",
",",
"path",
",",
"qs",
",... | 43.421053 | 19.315789 |
def iget_list_column_slice(list_, start=None, stop=None, stride=None):
""" iterator version of get_list_column """
if isinstance(start, slice):
slice_ = start
else:
slice_ = slice(start, stop, stride)
return (row[slice_] for row in list_) | [
"def",
"iget_list_column_slice",
"(",
"list_",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"stride",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"start",
",",
"slice",
")",
":",
"slice_",
"=",
"start",
"else",
":",
"slice_",
"=",
"s... | 37.714286 | 13 |
def main(argv=None):
'''this is called if run from command line'''
t = CrfTokenizer()
print t.tokenize("This is a sentence.")
print t.tokenize("Buy???This...Now!!!")
print t.tokenize("The <bold>only</bold> source.")
print t.tokenize("The<bold>only</bold>source.")
print t.tokenize("Big>li... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"t",
"=",
"CrfTokenizer",
"(",
")",
"print",
"t",
".",
"tokenize",
"(",
"\"This is a sentence.\"",
")",
"print",
"t",
".",
"tokenize",
"(",
"\"Buy???This...Now!!!\"",
")",
"print",
"t",
".",
"tokenize",
... | 39.680851 | 8.829787 |
def normalize_cols(table):
"""
Pad short rows to the length of the longest row to help render "jagged"
CSV files
"""
longest_row_len = max([len(row) for row in table])
for row in table:
while len(row) < longest_row_len:
row.append('')
return table | [
"def",
"normalize_cols",
"(",
"table",
")",
":",
"longest_row_len",
"=",
"max",
"(",
"[",
"len",
"(",
"row",
")",
"for",
"row",
"in",
"table",
"]",
")",
"for",
"row",
"in",
"table",
":",
"while",
"len",
"(",
"row",
")",
"<",
"longest_row_len",
":",
... | 28.6 | 14.8 |
def get_types(self):
"""
Retrieve a set of all recognized content types for this
translator object.
"""
# Convert translators into a set of content types
content_types = set()
for name in self.translators:
content_types |= type_names[name]
re... | [
"def",
"get_types",
"(",
"self",
")",
":",
"# Convert translators into a set of content types",
"content_types",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"self",
".",
"translators",
":",
"content_types",
"|=",
"type_names",
"[",
"name",
"]",
"return",
"content_t... | 27.25 | 15.416667 |
def generate_order(self, package_keyname, location, item_keynames, complex_type=None,
hourly=True, preset_keyname=None, extras=None, quantity=1):
"""Generates an order with the given package and prices.
This function takes in parameters needed for an order and generates an order
... | [
"def",
"generate_order",
"(",
"self",
",",
"package_keyname",
",",
"location",
",",
"item_keynames",
",",
"complex_type",
"=",
"None",
",",
"hourly",
"=",
"True",
",",
"preset_keyname",
"=",
"None",
",",
"extras",
"=",
"None",
",",
"quantity",
"=",
"1",
")... | 52.75 | 30.266667 |
def vcenter_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcenter = ET.SubElement(config, "vcenter", xmlns="urn:brocade.com:mgmt:brocade-vswitch")
id = ET.SubElement(vcenter, "id")
id.text = kwargs.pop('id')
callback = kwargs.pop('c... | [
"def",
"vcenter_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"vcenter",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"vcenter\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:brocade... | 36.8 | 14.1 |
def assert_is_valid_key(key):
"""
Raise KeyError if a given config key violates any requirements.
The requirements are the following and can be individually deactivated
in ``sacred.SETTINGS.CONFIG_KEYS``:
* ENFORCE_MONGO_COMPATIBLE (default: True):
make sure the keys don't contain a '.' o... | [
"def",
"assert_is_valid_key",
"(",
"key",
")",
":",
"if",
"SETTINGS",
".",
"CONFIG",
".",
"ENFORCE_KEYS_MONGO_COMPATIBLE",
"and",
"(",
"isinstance",
"(",
"key",
",",
"basestring",
")",
"and",
"(",
"'.'",
"in",
"key",
"or",
"key",
"[",
"0",
"]",
"==",
"'$... | 41.90566 | 22.509434 |
def push(self, my_dict, key, element):
''' Push an element onto an array that may not have been defined in
the dict '''
group_info = my_dict.setdefault(key, [])
if isinstance(group_info, dict):
host_list = group_info.setdefault('hosts', [])
host_list.append(elemen... | [
"def",
"push",
"(",
"self",
",",
"my_dict",
",",
"key",
",",
"element",
")",
":",
"group_info",
"=",
"my_dict",
".",
"setdefault",
"(",
"key",
",",
"[",
"]",
")",
"if",
"isinstance",
"(",
"group_info",
",",
"dict",
")",
":",
"host_list",
"=",
"group_... | 40.777778 | 12.777778 |
def results(self, job_id):
"""
Yield the result of a completed bulk verification job.
:param int job_id: ID of a job to retrieve the results for.
:yields: The next VerifiedEmail objects.
"""
resp = self._call(endpoint='download', data={'job_id': job_id})
Row = nam... | [
"def",
"results",
"(",
"self",
",",
"job_id",
")",
":",
"resp",
"=",
"self",
".",
"_call",
"(",
"endpoint",
"=",
"'download'",
",",
"data",
"=",
"{",
"'job_id'",
":",
"job_id",
"}",
")",
"Row",
"=",
"namedtuple",
"(",
"'Row'",
",",
"[",
"'email'",
... | 47 | 17.545455 |
def get_resource_by_key(self, resource_key):
"""Return resource by quick_key/folder_key.
key -- quick_key or folder_key
"""
# search for quick_key by default
lookup_order = ["quick_key", "folder_key"]
if len(resource_key) == FOLDER_KEY_LENGTH:
lookup_order ... | [
"def",
"get_resource_by_key",
"(",
"self",
",",
"resource_key",
")",
":",
"# search for quick_key by default",
"lookup_order",
"=",
"[",
"\"quick_key\"",
",",
"\"folder_key\"",
"]",
"if",
"len",
"(",
"resource_key",
")",
"==",
"FOLDER_KEY_LENGTH",
":",
"lookup_order",... | 30.787879 | 18.909091 |
def set_global_provenance(wf: Workflow, registry: Registry):
"""Compute a global provenance key for the entire workflow
before evaluation. This key can be used to store and retrieve
results in a database. The key computed in this stage is different
from the (local) provenance key that can be computed fo... | [
"def",
"set_global_provenance",
"(",
"wf",
":",
"Workflow",
",",
"registry",
":",
"Registry",
")",
":",
"stack",
"=",
"[",
"wf",
".",
"root",
"]",
"while",
"stack",
":",
"i",
"=",
"stack",
".",
"pop",
"(",
")",
"n",
"=",
"wf",
".",
"nodes",
"[",
... | 37.020408 | 22.204082 |
def data(args):
"""
%prog data data.bin samples.ids STR.ids meta.tsv
Make data.tsv based on meta.tsv.
"""
p = OptionParser(data.__doc__)
p.add_option("--notsv", default=False, action="store_true",
help="Do not write data.tsv")
opts, args = p.parse_args(args)
if len(arg... | [
"def",
"data",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"data",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--notsv\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Do not write data.tsv\"",... | 32.058824 | 17.392157 |
def _run_with_kvm(self, qemu_path, options):
"""
Check if we could run qemu with KVM
:param qemu_path: Path to qemu
:param options: String of qemu user options
:returns: Boolean True if we need to enable KVM
"""
if sys.platform.startswith("linux") and self.manag... | [
"def",
"_run_with_kvm",
"(",
"self",
",",
"qemu_path",
",",
"options",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"linux\"",
")",
"and",
"self",
".",
"manager",
".",
"config",
".",
"get_section_config",
"(",
"\"Qemu\"",
")",
".",
"... | 45.695652 | 28.913043 |
def __decode_webpush_b64(self, data):
"""
Re-pads and decodes urlsafe base64.
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += '=' * (4 - missing_padding)
return base64.urlsafe_b64decode(data) | [
"def",
"__decode_webpush_b64",
"(",
"self",
",",
"data",
")",
":",
"missing_padding",
"=",
"len",
"(",
"data",
")",
"%",
"4",
"if",
"missing_padding",
"!=",
"0",
":",
"data",
"+=",
"'='",
"*",
"(",
"4",
"-",
"missing_padding",
")",
"return",
"base64",
... | 33.125 | 3.375 |
def from_content(cls, content):
"""Parses a Tibia.com response into a House object.
Parameters
----------
content: :class:`str`
HTML content of the page.
Returns
-------
:class:`House`
The house contained in the page, or None if the house... | [
"def",
"from_content",
"(",
"cls",
",",
"content",
")",
":",
"parsed_content",
"=",
"parse_tibiacom_content",
"(",
"content",
")",
"image_column",
",",
"desc_column",
",",
"",
"*",
"_",
"=",
"parsed_content",
".",
"find_all",
"(",
"'td'",
")",
"if",
"\"Error... | 33.846154 | 19.115385 |
def _calculate_correct_axis_for_cube(self, axis):
"""Return correct axis for cube, based on ndim.
If cube has 3 dimensions, increase axis by 1. This will translate the
default 0 (cols direction) and 1 (rows direction) to actual 1
(cols direction) and 2 (rows direction). This is needed b... | [
"def",
"_calculate_correct_axis_for_cube",
"(",
"self",
",",
"axis",
")",
":",
"if",
"self",
".",
"_cube",
".",
"ndim",
"<",
"3",
":",
"if",
"self",
".",
"ca_as_0th",
"and",
"axis",
"is",
"None",
":",
"# Special case for CA slices (in multitables). In this case,",... | 56.55 | 29.35 |
def cmd_migrate(self, name=None, fake=False):
"""Run migrations."""
from peewee_migrate.router import Router, LOGGER
LOGGER.setLevel('INFO')
LOGGER.propagate = 0
router = Router(self.database,
migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'],
... | [
"def",
"cmd_migrate",
"(",
"self",
",",
"name",
"=",
"None",
",",
"fake",
"=",
"False",
")",
":",
"from",
"peewee_migrate",
".",
"router",
"import",
"Router",
",",
"LOGGER",
"LOGGER",
".",
"setLevel",
"(",
"'INFO'",
")",
"LOGGER",
".",
"propagate",
"=",
... | 37.714286 | 21.5 |
def _workflow_node_structure(node_results):
'''
Takes the list results from the API in `node_results` and
translates this data into a dictionary organized in a
human-readable heirarchial structure
'''
# Build list address translation, and create backlink lists
nod... | [
"def",
"_workflow_node_structure",
"(",
"node_results",
")",
":",
"# Build list address translation, and create backlink lists",
"node_list_pos",
"=",
"{",
"}",
"for",
"i",
",",
"node_result",
"in",
"enumerate",
"(",
"node_results",
")",
":",
"for",
"rel",
"in",
"[",
... | 42.177419 | 15.209677 |
def end(self):
"""End HTML output."""
if self.lastUrl is not None:
self.html.write(u'</li>\n')
if self.lastComic is not None:
self.html.write(u'</ul>\n')
self.html.write(u'</ul>\n')
self.addNavLinks()
self.html.close() | [
"def",
"end",
"(",
"self",
")",
":",
"if",
"self",
".",
"lastUrl",
"is",
"not",
"None",
":",
"self",
".",
"html",
".",
"write",
"(",
"u'</li>\\n'",
")",
"if",
"self",
".",
"lastComic",
"is",
"not",
"None",
":",
"self",
".",
"html",
".",
"write",
... | 31.333333 | 7.555556 |
def stop_event_loop(self, event=None):
"""
Stop an event loop. This is used to stop a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events.
Call signature::
stop_event_loop_default(self)
"""
if ha... | [
"def",
"stop_event_loop",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_event_loop'",
")",
":",
"if",
"self",
".",
"_event_loop",
".",
"IsRunning",
"(",
")",
":",
"self",
".",
"_event_loop",
".",
"Exit",
"(",
... | 32.214286 | 12.214286 |
def parse_range(s, range_separator = '-'):
''' Parses the string s which contains indices and ranges and returns the explicit list of integers defined by s.
Written by Laurens Kraal 2014.
'''
return reduce(lambda x,y: x+y, (map(lambda r: (range(int(r.split(range_separator)[0]), int(r.split(range_sep... | [
"def",
"parse_range",
"(",
"s",
",",
"range_separator",
"=",
"'-'",
")",
":",
"return",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"y",
",",
"(",
"map",
"(",
"lambda",
"r",
":",
"(",
"range",
"(",
"int",
"(",
"r",
".",
"split",
"(",... | 77.2 | 51.2 |
def load_class(location: str) -> type:
""" Loads a class from a string and returns it.
>>> from arca.utils import load_class
>>> load_class("arca.backend.BaseBackend")
<class 'arca.backend.base.BaseBackend'>
:raise ArcaMisconfigured: If the class can't be loaded.
"""
module_name, _, class_... | [
"def",
"load_class",
"(",
"location",
":",
"str",
")",
"->",
"type",
":",
"module_name",
",",
"_",
",",
"class_name",
"=",
"location",
".",
"rpartition",
"(",
"\".\"",
")",
"if",
"not",
"module_name",
":",
"raise",
"ArcaMisconfigured",
"(",
"f\"The module is... | 37.666667 | 21 |
def copy(self):
"""
Copy the selected text to the clipboard. If no text was selected, the
entire line is copied (this feature can be turned off by
setting :attr:`select_line_on_copy_empty` to False.
"""
if self.select_line_on_copy_empty and not self.textCursor().hasSelect... | [
"def",
"copy",
"(",
"self",
")",
":",
"if",
"self",
".",
"select_line_on_copy_empty",
"and",
"not",
"self",
".",
"textCursor",
"(",
")",
".",
"hasSelection",
"(",
")",
":",
"TextHelper",
"(",
"self",
")",
".",
"select_whole_line",
"(",
")",
"super",
"(",... | 44.888889 | 17.777778 |
def update_endpoint(self, updated_ed):
"""
Update a previously advertised endpoint_description.
:param endpoint_description: an instance of EndpointDescription to
update. Must not be None.
:return: True if advertised, False if not
(e.g. it's already been advertised)
... | [
"def",
"update_endpoint",
"(",
"self",
",",
"updated_ed",
")",
":",
"endpoint_id",
"=",
"updated_ed",
".",
"get_id",
"(",
")",
"with",
"self",
".",
"_published_endpoints_lock",
":",
"if",
"self",
".",
"get_advertised_endpoint",
"(",
"endpoint_id",
")",
"is",
"... | 35.857143 | 15.571429 |
def scaled_dimensions(self, width=None, height=None):
"""
Return a (cx, cy) 2-tuple representing the native dimensions of this
image scaled by applying the following rules to *width* and *height*.
If both *width* and *height* are specified, the return value is
(*width*, *height*)... | [
"def",
"scaled_dimensions",
"(",
"self",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"if",
"width",
"is",
"None",
"and",
"height",
"is",
"None",
":",
"return",
"self",
".",
"width",
",",
"self",
".",
"height",
"if",
"width",
"is"... | 48.346154 | 22.192308 |
def CanonicalPathToLocalPath(path):
r"""Converts the canonical paths as used by GRR to OS specific paths.
Due to the inconsistencies between handling paths in windows we need to
convert a path to an OS specific version prior to using it. This function
should be called just before any OS specific functions.
... | [
"def",
"CanonicalPathToLocalPath",
"(",
"path",
")",
":",
"# Account for raw devices",
"path",
"=",
"path",
".",
"replace",
"(",
"\"/\\\\\"",
",",
"\"\\\\\"",
")",
"path",
"=",
"path",
".",
"replace",
"(",
"\"/\"",
",",
"\"\\\\\"",
")",
"m",
"=",
"re",
"."... | 28.96 | 20.48 |
def detect_namespace(rdf):
"""Try to automatically detect the URI namespace of the vocabulary.
Return namespace as URIRef.
"""
# pick a concept
conc = rdf.value(None, RDF.type, SKOS.Concept, any=True)
if conc is None:
logging.critical(
"Namespace auto-detection failed. "
... | [
"def",
"detect_namespace",
"(",
"rdf",
")",
":",
"# pick a concept",
"conc",
"=",
"rdf",
".",
"value",
"(",
"None",
",",
"RDF",
".",
"type",
",",
"SKOS",
".",
"Concept",
",",
"any",
"=",
"True",
")",
"if",
"conc",
"is",
"None",
":",
"logging",
".",
... | 28.037037 | 19.222222 |
def list_deployments(self, namespace=None):
"""
List all available deployments.
:param namespace: str, if not specified list deployments for all namespaces
:return: collection of instances of :class:`conu.backend.k8s.deployment.Deployment`
"""
if namespace:
... | [
"def",
"list_deployments",
"(",
"self",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
":",
"return",
"[",
"Deployment",
"(",
"name",
"=",
"d",
".",
"metadata",
".",
"name",
",",
"namespace",
"=",
"d",
".",
"metadata",
".",
"namespace",
",... | 53.636364 | 29 |
def clean_api_docs_dirs():
"""Empty previous api-docs directory.
:returns: Path to api-docs directory.
:rtype: str
"""
inasafe_docs_path = os.path.abspath(
os.path.join(
os.path.dirname(__file__), '..', 'docs', 'api-docs'))
if os.path.exists(inasafe_docs_path):
rmtre... | [
"def",
"clean_api_docs_dirs",
"(",
")",
":",
"inasafe_docs_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'..'",
",",
"'docs'",
",",
"'api-docs'",
... | 30.153846 | 11.538462 |
def get_account(self, portfolio_cookie: str, account_cookie: str):
"""直接从二级目录拿到account
Arguments:
portfolio_cookie {str} -- [description]
account_cookie {str} -- [description]
Returns:
[type] -- [description]
"""
try:
return self... | [
"def",
"get_account",
"(",
"self",
",",
"portfolio_cookie",
":",
"str",
",",
"account_cookie",
":",
"str",
")",
":",
"try",
":",
"return",
"self",
".",
"portfolio_list",
"[",
"portfolio_cookie",
"]",
"[",
"account_cookie",
"]",
"except",
":",
"return",
"None... | 26.333333 | 21.266667 |
def _EccZmaxRperiRap(self,*args,**kwargs):
"""
NAME:
EccZmaxRperiRap (_EccZmaxRperiRap)
PURPOSE:
evaluate the eccentricity, maximum height above the plane, peri- and apocenter in the adiabatic approximation
INPUT:
Either:
a) R,vR,vT,z,vz[,ph... | [
"def",
"_EccZmaxRperiRap",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"(",
"self",
".",
"_c",
"and",
"not",
"(",
"'c'",
"in",
"kwargs",
"and",
"not",
"kwargs",
"[",
"'c'",
"]",
")",
")",
"or",
"(",
"ext_loaded",
... | 48.090909 | 17.954545 |
async def fetchrow(self, query, *args, timeout=None):
"""Run a query and return the first row.
Pool performs this operation using one of its connections. Other than
that, it behaves identically to
:meth:`Connection.fetchrow() <connection.Connection.fetchrow>`.
.. versionadded:... | [
"async",
"def",
"fetchrow",
"(",
"self",
",",
"query",
",",
"*",
"args",
",",
"timeout",
"=",
"None",
")",
":",
"async",
"with",
"self",
".",
"acquire",
"(",
")",
"as",
"con",
":",
"return",
"await",
"con",
".",
"fetchrow",
"(",
"query",
",",
"*",
... | 40.090909 | 18.181818 |
def _get_SRF_sigma(self, imt_per):
"""
Table 8 and equation 19 of 2013 report. NB change in notation,
2013 report calls this term 'sigma_t' but it is referred to
here as sigma. Note that Table 8 is identical to Table 7 in
the 2013 report.
"""
if imt_per < 0.6:
... | [
"def",
"_get_SRF_sigma",
"(",
"self",
",",
"imt_per",
")",
":",
"if",
"imt_per",
"<",
"0.6",
":",
"srf",
"=",
"0.8",
"elif",
"0.6",
"<=",
"imt_per",
"<",
"1",
":",
"srf",
"=",
"self",
".",
"_interp_function",
"(",
"0.7",
",",
"0.8",
",",
"1",
",",
... | 33.823529 | 18.647059 |
def _get_changes_from_diff_dict(diff_dict):
'''
Returns a list of string message of the differences in a diff dict.
Each inner message is tabulated one tab deeper
'''
changes_strings = []
for p in diff_dict.keys():
if not isinstance(diff_dict[p], dict):
raise ValueError('Une... | [
"def",
"_get_changes_from_diff_dict",
"(",
"diff_dict",
")",
":",
"changes_strings",
"=",
"[",
"]",
"for",
"p",
"in",
"diff_dict",
".",
"keys",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"diff_dict",
"[",
"p",
"]",
",",
"dict",
")",
":",
"raise",
"... | 47.290323 | 19.741935 |
def keysym_definitions():
"""Yields all keysym definitions parsed as tuples.
"""
for keysym_line in keysym_lines():
# As described in the input text, the format of a line is:
# 0x20 U0020 . # space /* optional comment */
keysym_number, codepoint, status, _, name_part = [
... | [
"def",
"keysym_definitions",
"(",
")",
":",
"for",
"keysym_line",
"in",
"keysym_lines",
"(",
")",
":",
"# As described in the input text, the format of a line is:",
"# 0x20 U0020 . # space /* optional comment */",
"keysym_number",
",",
"codepoint",
",",
"status",
",",
"_",
... | 41.909091 | 14.909091 |
def _save_to_checkpoint(self, filename):
"""Save the current running config to the given file."""
command = 'checkpoint file {}'.format(filename)
self.device.send_command(command) | [
"def",
"_save_to_checkpoint",
"(",
"self",
",",
"filename",
")",
":",
"command",
"=",
"'checkpoint file {}'",
".",
"format",
"(",
"filename",
")",
"self",
".",
"device",
".",
"send_command",
"(",
"command",
")"
] | 50 | 4 |
def choi_to_rauli(choi, order=1):
"""
Convert a Choi-matrix to a Pauli-basis superoperator.
Note that this function assumes that the Choi-matrix
is defined in the standard column-stacking convention
and is normalized to have trace 1. For a channel E this
is defined as: choi = (I \\otimes E)(bel... | [
"def",
"choi_to_rauli",
"(",
"choi",
",",
"order",
"=",
"1",
")",
":",
"if",
"order",
"==",
"0",
":",
"order",
"=",
"'weight'",
"elif",
"order",
"==",
"1",
":",
"order",
"=",
"'tensor'",
"# get number of qubits'",
"num_qubits",
"=",
"int",
"(",
"np",
"... | 35.205128 | 19 |
def ws004c(self, value=None):
"""Corresponds to IDD Field `ws004c`
Args:
value (float): value for IDD Field `ws004c`
Unit: m/s
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Ra... | [
"def",
"ws004c",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float '... | 31.333333 | 21 |
def minify(drop_semi=True):
"""
Rules for minifying output.
Arguments:
drop_semi
Drop semicolons whenever possible. Note that if Dedent and
OptionalNewline has a handler defined, it will stop final break
statements from being resolved due to reliance on normalized
reso... | [
"def",
"minify",
"(",
"drop_semi",
"=",
"True",
")",
":",
"layout_handlers",
"=",
"{",
"OpenBlock",
":",
"layout_handler_openbrace",
",",
"CloseBlock",
":",
"layout_handler_closebrace",
",",
"EndStatement",
":",
"layout_handler_semicolon",
",",
"Space",
":",
"layout... | 32.448276 | 21.241379 |
def generate_cutJ_genomic_CDR3_segs(self):
"""Add palindromic inserted nucleotides to germline J sequences.
The maximum number of palindromic insertions are appended to the
germline J segments so that delJ can index directly for number of
nucleotides to delete from a segment.
... | [
"def",
"generate_cutJ_genomic_CDR3_segs",
"(",
"self",
")",
":",
"max_palindrome",
"=",
"self",
".",
"max_delJ_palindrome",
"self",
".",
"cutJ_genomic_CDR3_segs",
"=",
"[",
"]",
"for",
"CDR3_J_seg",
"in",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"self",
".... | 43.333333 | 19.944444 |
def match_path(entry, opts):
"""Return True if `path` matches `match` and `exclude` options."""
if entry.name in ALWAYS_OMIT:
return False
# TODO: currently we use fnmatch syntax and match against names.
# We also might allow glob syntax and match against the whole relative path instead
# pa... | [
"def",
"match_path",
"(",
"entry",
",",
"opts",
")",
":",
"if",
"entry",
".",
"name",
"in",
"ALWAYS_OMIT",
":",
"return",
"False",
"# TODO: currently we use fnmatch syntax and match against names.",
"# We also might allow glob syntax and match against the whole relative path inst... | 32.730769 | 14.5 |
def to_array(self):
"""
Serializes this LabeledPrice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(LabeledPrice, self).to_array()
array['label'] = u(self.label) # py2: type unicode, py3: type str
arra... | [
"def",
"to_array",
"(",
"self",
")",
":",
"array",
"=",
"super",
"(",
"LabeledPrice",
",",
"self",
")",
".",
"to_array",
"(",
")",
"array",
"[",
"'label'",
"]",
"=",
"u",
"(",
"self",
".",
"label",
")",
"# py2: type unicode, py3: type str",
"array",
"[",... | 31 | 19.333333 |
def calculate_signature(key, data, timestamp=None):
"""
Calculates the signature for the given request data.
"""
# Create a timestamp if one was not given
if timestamp is None:
timestamp = int(time.time())
# Construct the message from the timestamp and the data in the request
messag... | [
"def",
"calculate_signature",
"(",
"key",
",",
"data",
",",
"timestamp",
"=",
"None",
")",
":",
"# Create a timestamp if one was not given",
"if",
"timestamp",
"is",
"None",
":",
"timestamp",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"# Construct th... | 36.266667 | 21.866667 |
def encap(self, pkt):
"""encapsulate a frame using this Secure Association"""
if pkt.name != Ether().name:
raise TypeError('cannot encapsulate packet in MACsec, must be Ethernet') # noqa: E501
hdr = copy.deepcopy(pkt)
payload = hdr.payload
del hdr.payload
tag... | [
"def",
"encap",
"(",
"self",
",",
"pkt",
")",
":",
"if",
"pkt",
".",
"name",
"!=",
"Ether",
"(",
")",
".",
"name",
":",
"raise",
"TypeError",
"(",
"'cannot encapsulate packet in MACsec, must be Ethernet'",
")",
"# noqa: E501",
"hdr",
"=",
"copy",
".",
"deepc... | 44.142857 | 13.357143 |
def _get_socket(self, sslversion=ssl.PROTOCOL_TLSv1):
"""Sets up an https connection and do an HTTP/raw socket request
:param sslversion: version of ssl session
:raises: IloConnectionError, for connection failures
:returns: ssl wrapped socket object
"""
err = None
... | [
"def",
"_get_socket",
"(",
"self",
",",
"sslversion",
"=",
"ssl",
".",
"PROTOCOL_TLSv1",
")",
":",
"err",
"=",
"None",
"sock",
"=",
"None",
"try",
":",
"for",
"res",
"in",
"socket",
".",
"getaddrinfo",
"(",
"self",
".",
"hostname",
",",
"self",
".",
... | 42.696429 | 16.928571 |
def unmount(self):
"""Unmounts the sftp system if it's currently mounted."""
if not self.mounted:
return
# Try to unmount properly.
cmd = 'fusermount -u %s' % self.mount_point_local
shell_exec(cmd)
# The filesystem is probably still in use.
# kill ss... | [
"def",
"unmount",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"mounted",
":",
"return",
"# Try to unmount properly.",
"cmd",
"=",
"'fusermount -u %s'",
"%",
"self",
".",
"mount_point_local",
"shell_exec",
"(",
"cmd",
")",
"# The filesystem is probably still in ... | 30.0625 | 19 |
def _bar(self, serie, parent, x, y, i, zero, secondary=False):
"""Internal stacking bar drawing function"""
if serie.index % 2:
y = -y
return super(VerticalPyramid,
self)._bar(serie, parent, x, y, i, zero, secondary) | [
"def",
"_bar",
"(",
"self",
",",
"serie",
",",
"parent",
",",
"x",
",",
"y",
",",
"i",
",",
"zero",
",",
"secondary",
"=",
"False",
")",
":",
"if",
"serie",
".",
"index",
"%",
"2",
":",
"y",
"=",
"-",
"y",
"return",
"super",
"(",
"VerticalPyram... | 44.666667 | 15.333333 |
def PartialDynamicSystem(self, ieq, variable):
"""
returns dynamical system blocks associated to output variable
"""
if ieq == 0:
# U1=0
if variable == self.variables[0]:
return[Gain(self.commands[0], variable, -self.Tmax)] | [
"def",
"PartialDynamicSystem",
"(",
"self",
",",
"ieq",
",",
"variable",
")",
":",
"if",
"ieq",
"==",
"0",
":",
"# U1=0",
"if",
"variable",
"==",
"self",
".",
"variables",
"[",
"0",
"]",
":",
"return",
"[",
"Gain",
"(",
"self",
".",
"commands",
"[",
... | 36 | 13.75 |
def print_attrs(data_file, node_name='/', which='user', compress=False):
"""Print the HDF5 attributes for `node_name`.
Parameters:
data_file (pytables HDF5 file object): the data file to print
node_name (string): name of the path inside the file to be printed.
Can be either a group ... | [
"def",
"print_attrs",
"(",
"data_file",
",",
"node_name",
"=",
"'/'",
",",
"which",
"=",
"'user'",
",",
"compress",
"=",
"False",
")",
":",
"node",
"=",
"data_file",
".",
"get_node",
"(",
"node_name",
")",
"print",
"(",
"'List of attributes for:\\n %s\\n'",
... | 47.142857 | 18.761905 |
def get_recent_pages(self, namespaces, rccontinue=''):
"""Retrieve recent pages from all namespaces starting from rccontinue."""
namespaces.sort()
params = {
"action": "query",
"list": "recentchanges",
"rclimit": self.limit,
"rcnamespace": "|".joi... | [
"def",
"get_recent_pages",
"(",
"self",
",",
"namespaces",
",",
"rccontinue",
"=",
"''",
")",
":",
"namespaces",
".",
"sort",
"(",
")",
"params",
"=",
"{",
"\"action\"",
":",
"\"query\"",
",",
"\"list\"",
":",
"\"recentchanges\"",
",",
"\"rclimit\"",
":",
... | 31.625 | 14.8125 |
def write_molpro(basis):
'''Converts a basis set to Molpro format
'''
# Uncontract all, and make as generally-contracted as possible
basis = manip.uncontract_spdf(basis, 0, True)
basis = manip.make_general(basis, False)
basis = sort.sort_basis(basis, True)
s = ''
# Elements for which ... | [
"def",
"write_molpro",
"(",
"basis",
")",
":",
"# Uncontract all, and make as generally-contracted as possible",
"basis",
"=",
"manip",
".",
"uncontract_spdf",
"(",
"basis",
",",
"0",
",",
"True",
")",
"basis",
"=",
"manip",
".",
"make_general",
"(",
"basis",
",",... | 37.333333 | 22.555556 |
def list_directory(self, mdir, limit=None, marker=None):
"""ListDirectory
https://apidocs.joyent.com/manta/api.html#ListDirectory
@param mdir {str} A manta path, e.g. '/trent/stor/mydir'.
@param limit {int} Limits the number of records to come back (default
and max is 1000).... | [
"def",
"list_directory",
"(",
"self",
",",
"mdir",
",",
"limit",
"=",
"None",
",",
"marker",
"=",
"None",
")",
":",
"res",
",",
"dirents",
"=",
"self",
".",
"list_directory2",
"(",
"mdir",
",",
"limit",
"=",
"limit",
",",
"marker",
"=",
"marker",
")"... | 46.714286 | 23.071429 |
def _execute_stage(self, index, stage, stop):
""" Execute a pipeline stage.
:param index: Stage index.
:param stage: Stage object.
"""
if stop.is_set():
_LOGGER.info("Stopped pipeline on group %s", self._group)
return
_LOGGER.info(" -> Running sta... | [
"def",
"_execute_stage",
"(",
"self",
",",
"index",
",",
"stage",
",",
"stop",
")",
":",
"if",
"stop",
".",
"is_set",
"(",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Stopped pipeline on group %s\"",
",",
"self",
".",
"_group",
")",
"return",
"_LOGGER",
".... | 38.277778 | 7.351852 |
def qsturng(p, r, v):
"""Approximates the quantile p for a studentized range
distribution having v degrees of freedom and r samples
for probability p.
Parameters
----------
p : (scalar, array_like)
The cumulative probability value
p >= .1 and p <=.999
(values under... | [
"def",
"qsturng",
"(",
"p",
",",
"r",
",",
"v",
")",
":",
"if",
"all",
"(",
"map",
"(",
"_isfloat",
",",
"[",
"p",
",",
"r",
",",
"v",
"]",
")",
")",
":",
"return",
"_qsturng",
"(",
"p",
",",
"r",
",",
"v",
")",
"return",
"_vqsturng",
"(",
... | 26.09375 | 16.625 |
def __isListOfTexts(self, docs):
""" Checks whether the input is a list of strings or Text-s;
"""
return isinstance(docs, list) and \
all(isinstance(d, (basestring, Text)) for d in docs) | [
"def",
"__isListOfTexts",
"(",
"self",
",",
"docs",
")",
":",
"return",
"isinstance",
"(",
"docs",
",",
"list",
")",
"and",
"all",
"(",
"isinstance",
"(",
"d",
",",
"(",
"basestring",
",",
"Text",
")",
")",
"for",
"d",
"in",
"docs",
")"
] | 44.4 | 7.6 |
def _connect(self):
""" Connect to the remote if not already connected. """
if not self.connected.is_set():
try:
self.lock.acquire()
# Another thread may have connected while we were
# waiting to acquire the lock
if not self.con... | [
"def",
"_connect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
".",
"is_set",
"(",
")",
":",
"try",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"# Another thread may have connected while we were",
"# waiting to acquire the lock",
"if",
... | 38.8125 | 10.875 |
def _generic_distance_calc(fn, t1, t2, normalise, min_overlap=4, overlap_fail_value=0):
"""(fn, t1, t2, normalise)
Calculates the distance between trees t1 and t2. Can optionally be normalised to range [0, 1].
If the trees have different leaf sets, the distance is calculated on their intersection. This inc... | [
"def",
"_generic_distance_calc",
"(",
"fn",
",",
"t1",
",",
"t2",
",",
"normalise",
",",
"min_overlap",
"=",
"4",
",",
"overlap_fail_value",
"=",
"0",
")",
":",
"if",
"t1",
"^",
"t2",
":",
"if",
"len",
"(",
"t1",
"&",
"t2",
")",
"<",
"min_overlap",
... | 41.658537 | 28.707317 |
def rotate(self):
""" Rotate the kill ring, then yank back the new top.
Returns
-------
A text string or None.
"""
self._index -= 1
if self._index >= 0:
return self._ring[self._index]
return None | [
"def",
"rotate",
"(",
"self",
")",
":",
"self",
".",
"_index",
"-=",
"1",
"if",
"self",
".",
"_index",
">=",
"0",
":",
"return",
"self",
".",
"_ring",
"[",
"self",
".",
"_index",
"]",
"return",
"None"
] | 23.818182 | 15.818182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.