text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def to_json(self):
"""
Returns the JSON Representation of the content type field validation.
"""
result = {}
for k, v in self._data.items():
result[camel_case(k)] = v
return result | [
"def",
"to_json",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_data",
".",
"items",
"(",
")",
":",
"result",
"[",
"camel_case",
"(",
"k",
")",
"]",
"=",
"v",
"return",
"result"
] | 25.888889 | 15.888889 |
def setPageSizeOptions( self, options ):
"""
Sets the options that will be displayed for this default size.
:param options | [<str>,. ..]
"""
self._pageSizeCombo.blockSignals(True)
self._pageSizeCombo.addItems(options)
ssize = nativ... | [
"def",
"setPageSizeOptions",
"(",
"self",
",",
"options",
")",
":",
"self",
".",
"_pageSizeCombo",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"_pageSizeCombo",
".",
"addItems",
"(",
"options",
")",
"ssize",
"=",
"nativestring",
"(",
"self",
".",
"... | 33.875 | 12.5 |
def next(self, match, predicate=None, index=None):
"""
Retrieves the nearest next matches.
:param match:
:type match:
:param predicate:
:type predicate:
:param index:
:type index: int
:return:
:rtype:
"""
current = match.sta... | [
"def",
"next",
"(",
"self",
",",
"match",
",",
"predicate",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"current",
"=",
"match",
".",
"start",
"+",
"1",
"while",
"current",
"<=",
"self",
".",
"_max_end",
":",
"next_matches",
"=",
"self",
".",
... | 30.947368 | 14 |
def editCell(self, vcolidx=None, rowidx=None, **kwargs):
'Call `editText` at its place on the screen. Returns the new value, properly typed'
if vcolidx is None:
vcolidx = self.cursorVisibleColIndex
x, w = self.visibleColLayout.get(vcolidx, (0, 0))
col = self.visibleCols[vc... | [
"def",
"editCell",
"(",
"self",
",",
"vcolidx",
"=",
"None",
",",
"rowidx",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"vcolidx",
"is",
"None",
":",
"vcolidx",
"=",
"self",
".",
"cursorVisibleColIndex",
"x",
",",
"w",
"=",
"self",
".",
"... | 39.115385 | 20.269231 |
def translate_text(
self,
contents,
target_language_code,
mime_type=None,
source_language_code=None,
parent=None,
model=None,
glossary_config=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAU... | [
"def",
"translate_text",
"(",
"self",
",",
"contents",
",",
"target_language_code",
",",
"mime_type",
"=",
"None",
",",
"source_language_code",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"model",
"=",
"None",
",",
"glossary_config",
"=",
"None",
",",
"ret... | 46.5 | 27.434426 |
def get_attr_text(self):
"""Get html attr text to render in template"""
return ' '.join([
'{}="{}"'.format(key, value)
for key, value in self.attr.items()
]) | [
"def",
"get_attr_text",
"(",
"self",
")",
":",
"return",
"' '",
".",
"join",
"(",
"[",
"'{}=\"{}\"'",
".",
"format",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"attr",
".",
"items",
"(",
")",
"]",
")"
] | 33.333333 | 11.333333 |
def dict_stack(dict_list, key_prefix=''):
r"""
stacks values from two dicts into a new dict where the values are list of
the input values. the keys are the same.
DEPRICATE in favor of dict_stack2
Args:
dict_list (list): list of dicts with similar keys
Returns:
dict dict_stacke... | [
"def",
"dict_stack",
"(",
"dict_list",
",",
"key_prefix",
"=",
"''",
")",
":",
"dict_stacked_",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"dict_",
"in",
"dict_list",
":",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"dict_",
")",
":... | 34.104167 | 16.75 |
def plot(self, win=None, newfig=True, figsize=None, orientation='hor', topfigfrac=0.8):
"""Plot layout
Parameters
----------
win : list or tuple
[x1, x2, y1, y2]
"""
if newfig:
plt.figure(figsize=figsize)
... | [
"def",
"plot",
"(",
"self",
",",
"win",
"=",
"None",
",",
"newfig",
"=",
"True",
",",
"figsize",
"=",
"None",
",",
"orientation",
"=",
"'hor'",
",",
"topfigfrac",
"=",
"0.8",
")",
":",
"if",
"newfig",
":",
"plt",
".",
"figure",
"(",
"figsize",
"=",... | 36.830189 | 16.018868 |
def remove_folder(self, folder, recurse=False, force=False, **kwargs):
"""
:param folder: Full path to the folder to remove
:type folder: string
:param recurse: If True, recursively remove all objects and subfolders in the folder
:type recurse: bool
:param force: If True,... | [
"def",
"remove_folder",
"(",
"self",
",",
"folder",
",",
"recurse",
"=",
"False",
",",
"force",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"api_method",
"=",
"dxpy",
".",
"api",
".",
"container_remove_folder",
"if",
"isinstance",
"(",
"self",
",",
... | 44.322581 | 22.709677 |
def derivativeZ(self,x,y,z):
'''
Evaluate the first derivative with respect to z of the function at given
state space points.
Parameters
----------
x : np.array
First input values.
y : np.array
Second input values; should be of same shap... | [
"def",
"derivativeZ",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"xShift",
"=",
"self",
".",
"lowerBound",
"(",
"y",
")",
"dfdz_out",
"=",
"self",
".",
"func",
".",
"derivativeZ",
"(",
"x",
"-",
"xShift",
",",
"y",
",",
"z",
")",
"ret... | 30.869565 | 22.173913 |
def to_full_path(cls, path):
"""
:return: string with a full repository-relative path which can be used to initialize
a Reference instance, for instance by using ``Reference.from_path``"""
if isinstance(path, SymbolicReference):
path = path.path
full_ref_path = pa... | [
"def",
"to_full_path",
"(",
"cls",
",",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"SymbolicReference",
")",
":",
"path",
"=",
"path",
".",
"path",
"full_ref_path",
"=",
"path",
"if",
"not",
"cls",
".",
"_common_path_default",
":",
"return",
... | 45.75 | 14 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"assert",
"all",
"(",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"for",
"stddev_type",
"in",
"stddev_typ... | 41.05 | 15.55 |
def scatterAlign(seq1, seq2, window=7):
"""
Visually align two sequences.
"""
d1 = defaultdict(list)
d2 = defaultdict(list)
for (seq, section_dict) in [(seq1, d1), (seq2, d2)]:
for i in range(len(seq) - window):
section = seq[i:i + window]
section_dict[section].ap... | [
"def",
"scatterAlign",
"(",
"seq1",
",",
"seq2",
",",
"window",
"=",
"7",
")",
":",
"d1",
"=",
"defaultdict",
"(",
"list",
")",
"d2",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"(",
"seq",
",",
"section_dict",
")",
"in",
"[",
"(",
"seq1",
",",
... | 31.241379 | 11.172414 |
def get_boto_client(
client,
region=None,
aws_access_key_id=None,
aws_secret_access_key=None,
aws_session_token=None,
endpoint_url=None
):
"""Get a boto3 client connection."""
cache_key = '{0}:{1}:{2}:{3}'.format(
client,
region,
aw... | [
"def",
"get_boto_client",
"(",
"client",
",",
"region",
"=",
"None",
",",
"aws_access_key_id",
"=",
"None",
",",
"aws_secret_access_key",
"=",
"None",
",",
"aws_session_token",
"=",
"None",
",",
"endpoint_url",
"=",
"None",
")",
":",
"cache_key",
"=",
"'{0}:{1... | 25.151515 | 16.848485 |
def get_all_unresolved(self):
"""Returns a set of all unresolved imports."""
assert self.final, 'Call build() before using the graph.'
out = set()
for v in self.broken_deps.values():
out |= v
return out | [
"def",
"get_all_unresolved",
"(",
"self",
")",
":",
"assert",
"self",
".",
"final",
",",
"'Call build() before using the graph.'",
"out",
"=",
"set",
"(",
")",
"for",
"v",
"in",
"self",
".",
"broken_deps",
".",
"values",
"(",
")",
":",
"out",
"|=",
"v",
... | 35.428571 | 14.571429 |
def handle_stream_features(self, stream, features):
"""Process incoming StartTLS related element of <stream:features/>.
[initiating entity only]
"""
if self.stream and stream is not self.stream:
raise ValueError("Single StreamTLSHandler instance can handle"
... | [
"def",
"handle_stream_features",
"(",
"self",
",",
"stream",
",",
"features",
")",
":",
"if",
"self",
".",
"stream",
"and",
"stream",
"is",
"not",
"self",
".",
"stream",
":",
"raise",
"ValueError",
"(",
"\"Single StreamTLSHandler instance can handle\"",
"\" only o... | 43.121212 | 19 |
def GetRarPassword(skipUserInput):
"""
Get password for rar archive from user input.
Parameters
----------
skipUserInput : boolean
Set to skip user input.
Returns
----------
string or boolean
If no password is given then returns False otherwise returns user
response string.
"""... | [
"def",
"GetRarPassword",
"(",
"skipUserInput",
")",
":",
"goodlogging",
".",
"Log",
".",
"Info",
"(",
"\"EXTRACT\"",
",",
"\"RAR file needs password to extract\"",
")",
"if",
"skipUserInput",
"is",
"False",
":",
"prompt",
"=",
"\"Enter password, 'x' to skip this file or... | 29.166667 | 22.433333 |
def make(self):
"""
Creates this directory and any of the missing directories in the path.
Any errors that may occur are eaten.
"""
try:
if not self.exists:
logger.info("Creating %s" % self.path)
os.makedirs(self.path)
except os... | [
"def",
"make",
"(",
"self",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"exists",
":",
"logger",
".",
"info",
"(",
"\"Creating %s\"",
"%",
"self",
".",
"path",
")",
"os",
".",
"makedirs",
"(",
"self",
".",
"path",
")",
"except",
"os",
".",
"e... | 29.416667 | 15.083333 |
def get_type_string(self, data, type_string):
""" Gets type string.
Finds the type string for 'data' contained in
``python_type_strings`` using its ``type``. Non-``None``
'type_string` overrides whatever type string is looked up.
The override makes it easier for subclasses to co... | [
"def",
"get_type_string",
"(",
"self",
",",
"data",
",",
"type_string",
")",
":",
"if",
"type_string",
"is",
"not",
"None",
":",
"return",
"type_string",
"else",
":",
"tp",
"=",
"type",
"(",
"data",
")",
"try",
":",
"return",
"self",
".",
"type_to_typest... | 33.894737 | 20.368421 |
def _is_wildcard_match(self, domain_labels, valid_domain_labels):
"""
Determines if the labels in a domain are a match for labels from a
wildcard valid domain name
:param domain_labels:
A list of unicode strings, with A-label form for IDNs, of the labels
in the d... | [
"def",
"_is_wildcard_match",
"(",
"self",
",",
"domain_labels",
",",
"valid_domain_labels",
")",
":",
"first_domain_label",
"=",
"domain_labels",
"[",
"0",
"]",
"other_domain_labels",
"=",
"domain_labels",
"[",
"1",
":",
"]",
"wildcard_label",
"=",
"valid_domain_lab... | 33.861111 | 22.361111 |
def update_models(new_obj, current_table, tables, relations):
""" Update the state of the parsing. """
_update_check_inputs(current_table, tables, relations)
_check_no_current_table(new_obj, current_table)
if isinstance(new_obj, Table):
tables_names = [t.name for t in tables]
_check_not... | [
"def",
"update_models",
"(",
"new_obj",
",",
"current_table",
",",
"tables",
",",
"relations",
")",
":",
"_update_check_inputs",
"(",
"current_table",
",",
"tables",
",",
"relations",
")",
"_check_no_current_table",
"(",
"new_obj",
",",
"current_table",
")",
"if",... | 46.125 | 20.458333 |
def get_cpds(self):
"""
Adds tables to BIF
Returns
-------
dict: dict of type {variable: array}
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_model()
>>> writer = BIFWrit... | [
"def",
"get_cpds",
"(",
"self",
")",
":",
"cpds",
"=",
"self",
".",
"model",
".",
"get_cpds",
"(",
")",
"tables",
"=",
"{",
"}",
"for",
"cpd",
"in",
"cpds",
":",
"tables",
"[",
"cpd",
".",
"variable",
"]",
"=",
"cpd",
".",
"values",
".",
"ravel",... | 32.08 | 17.52 |
def log(self, output, exit_status):
"""Log given CompletedProcess and return exit status code."""
if exit_status != 0:
self.logger.error(f'Error running command! Exit status: {exit_status}, {output}')
return exit_status | [
"def",
"log",
"(",
"self",
",",
"output",
",",
"exit_status",
")",
":",
"if",
"exit_status",
"!=",
"0",
":",
"self",
".",
"logger",
".",
"error",
"(",
"f'Error running command! Exit status: {exit_status}, {output}'",
")",
"return",
"exit_status"
] | 41.833333 | 20.666667 |
def add_shellwidget(self, shellwidget):
"""
Register shell with figure explorer.
This function opens a new FigureBrowser for browsing the figures
in the shell.
"""
shellwidget_id = id(shellwidget)
if shellwidget_id not in self.shellwidgets:
self.optio... | [
"def",
"add_shellwidget",
"(",
"self",
",",
"shellwidget",
")",
":",
"shellwidget_id",
"=",
"id",
"(",
"shellwidget",
")",
"if",
"shellwidget_id",
"not",
"in",
"self",
".",
"shellwidgets",
":",
"self",
".",
"options_button",
".",
"setVisible",
"(",
"True",
"... | 43.208333 | 11.458333 |
def _parse_index(self, section, content):
"""
.. index: default
:refguide: something, else, and more
"""
def strip_each_in(lst):
return [s.strip() for s in lst]
out = {}
section = section.split('::')
if len(section) > 1:
out['d... | [
"def",
"_parse_index",
"(",
"self",
",",
"section",
",",
"content",
")",
":",
"def",
"strip_each_in",
"(",
"lst",
")",
":",
"return",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"lst",
"]",
"out",
"=",
"{",
"}",
"section",
"=",
"section",
... | 29.5 | 14.277778 |
def lookup(self, hostname):
"""
Find a hostkey entry for a given hostname or IP. If no entry is found,
C{None} is returned. Otherwise a dictionary of keytype to key is
returned. The keytype will be either C{"ssh-rsa"} or C{"ssh-dss"}.
@param hostname: the hostname (or IP) to ... | [
"def",
"lookup",
"(",
"self",
",",
"hostname",
")",
":",
"class",
"SubDict",
"(",
"UserDict",
".",
"DictMixin",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"hostname",
",",
"entries",
",",
"hostkeys",
")",
":",
"self",
".",
"_hostname",
"=",
"hostna... | 37.583333 | 14.75 |
def xzhdr(self, header, msgid_range=None):
"""XZHDR command.
Args:
msgid_range: A message-id as a string, or an article number as an
integer, or a tuple of specifying a range of article numbers in
the form (first, [last]) - if last is omitted then all article... | [
"def",
"xzhdr",
"(",
"self",
",",
"header",
",",
"msgid_range",
"=",
"None",
")",
":",
"args",
"=",
"header",
"if",
"msgid_range",
"is",
"not",
"None",
":",
"args",
"+=",
"\" \"",
"+",
"utils",
".",
"unparse_msgid_range",
"(",
"msgid_range",
")",
"code",... | 39 | 21.105263 |
def pca(df, n_components=2, mean_center=False, fcol=None, ecol=None, marker='o', markersize=40, threshold=None, label_threshold=None, label_weights=None, label_scores=None, return_df=False, show_covariance_ellipse=False, *args, **kwargs):
"""
Perform Principal Component Analysis (PCA) from input DataFrame and g... | [
"def",
"pca",
"(",
"df",
",",
"n_components",
"=",
"2",
",",
"mean_center",
"=",
"False",
",",
"fcol",
"=",
"None",
",",
"ecol",
"=",
"None",
",",
"marker",
"=",
"'o'",
",",
"markersize",
"=",
"40",
",",
"threshold",
"=",
"None",
",",
"label_threshol... | 58.568182 | 40.022727 |
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__ | [
"def",
"network_create",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"nt_ks",
"=",
"self",
".",
"compute_conn",
"kwargs",
"[",
"'label'",
"]",
"=",
"name",
"kwargs",
"=",
"self",
".",
"_sanatize_network_params",
"(",
"kwargs",
")",
"net"... | 32 | 12.444444 |
def _getPropertyValue(schema, propertyName, options):
"""Checks to see if property is specified in 'options'. If not, reads the
default value from the schema"""
if propertyName not in options:
paramsSchema = schema['properties'][propertyName]
if 'default' in paramsSchema:
options[propertyName] = pa... | [
"def",
"_getPropertyValue",
"(",
"schema",
",",
"propertyName",
",",
"options",
")",
":",
"if",
"propertyName",
"not",
"in",
"options",
":",
"paramsSchema",
"=",
"schema",
"[",
"'properties'",
"]",
"[",
"propertyName",
"]",
"if",
"'default'",
"in",
"paramsSche... | 37.7 | 13 |
def connect(signal, receiver):
"""Register `receiver` method/function as a receiver for the `signal`.
When the signal is emitted, this receiver will be invoked along with
all other associated signals.
Args:
signal: A signal identifier (e.g., a signal name)
receiver: A callable object t... | [
"def",
"connect",
"(",
"signal",
",",
"receiver",
")",
":",
"__check_receiver",
"(",
"receiver",
")",
"if",
"__is_bound_method",
"(",
"receiver",
")",
":",
"ref",
"=",
"WeakMethod",
"else",
":",
"ref",
"=",
"weakref",
".",
"ref",
"with",
"__lock",
":",
"... | 27.4 | 20.55 |
def insert_file(file, media_type):
"""Upsert the ``file`` and ``media_type`` into the files table.
Returns the ``fileid`` and ``sha1`` of the upserted file.
"""
resource_hash = get_file_sha1(file)
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
cursor.execute("SEL... | [
"def",
"insert_file",
"(",
"file",
",",
"media_type",
")",
":",
"resource_hash",
"=",
"get_file_sha1",
"(",
"file",
")",
"with",
"db_connect",
"(",
")",
"as",
"db_conn",
":",
"with",
"db_conn",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"cursor",
".",... | 43.105263 | 12.473684 |
def corner_depots(self) -> Set[Point2]:
""" Finds the 2 depot positions on the outside """
if len(self.upper2_for_ramp_wall) == 2:
points = self.upper2_for_ramp_wall
p1 = points.pop().offset((self.x_offset, self.y_offset)) # still an error with pixelmap?
p2 = points.... | [
"def",
"corner_depots",
"(",
"self",
")",
"->",
"Set",
"[",
"Point2",
"]",
":",
"if",
"len",
"(",
"self",
".",
"upper2_for_ramp_wall",
")",
"==",
"2",
":",
"points",
"=",
"self",
".",
"upper2_for_ramp_wall",
"p1",
"=",
"points",
".",
"pop",
"(",
")",
... | 62 | 22.5 |
def array(self):
"""
The underlying array of shape (N, L, I)
"""
return numpy.array([self[sid].array for sid in sorted(self)]) | [
"def",
"array",
"(",
"self",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"[",
"self",
"[",
"sid",
"]",
".",
"array",
"for",
"sid",
"in",
"sorted",
"(",
"self",
")",
"]",
")"
] | 30.8 | 12 |
def get_by_index(self, index):
""" Return a dataset by its index.
Args:
index (int): The index of the dataset that should be returned.
Raises:
DataInvalidIndex: If the index does not represent a valid dataset.
"""
if index >= len(self._datasets):
... | [
"def",
"get_by_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
">=",
"len",
"(",
"self",
".",
"_datasets",
")",
":",
"raise",
"DataInvalidIndex",
"(",
"'A dataset with index {} does not exist'",
".",
"format",
"(",
"index",
")",
")",
"return",
"s... | 33 | 23.692308 |
def get_preorder_burn_info( outputs ):
"""
Given the set of outputs, find the fee sent
to our burn address. This is always the third output.
Return the fee and burn address on success as {'op_fee': ..., 'burn_address': ...}
Return None if not found
"""
if len(outputs) != 3:
... | [
"def",
"get_preorder_burn_info",
"(",
"outputs",
")",
":",
"if",
"len",
"(",
"outputs",
")",
"!=",
"3",
":",
"# not a well-formed preorder ",
"return",
"None",
"op_fee",
"=",
"outputs",
"[",
"2",
"]",
"[",
"'value'",
"]",
"burn_address",
"=",
"None",
"try",
... | 29.5 | 22.333333 |
def run_tpm(tpm, time_scale):
"""Iterate a TPM by the specified number of time steps.
Args:
tpm (np.ndarray): A state-by-node tpm.
time_scale (int): The number of steps to run the tpm.
Returns:
np.ndarray
"""
sbs_tpm = convert.state_by_node2state_by_state(tpm)
if sparse... | [
"def",
"run_tpm",
"(",
"tpm",
",",
"time_scale",
")",
":",
"sbs_tpm",
"=",
"convert",
".",
"state_by_node2state_by_state",
"(",
"tpm",
")",
"if",
"sparse",
"(",
"tpm",
")",
":",
"tpm",
"=",
"sparse_time",
"(",
"sbs_tpm",
",",
"time_scale",
")",
"else",
"... | 29.1875 | 18.0625 |
def create_vm(client, name, compute_resource, datastore, disksize, nics,
memory, num_cpus, guest_id, host=None):
"""Create a virtual machine using the specified values.
:param name: The name of the VM to create.
:type name: str
:param compute_resource: The name of a ComputeResource in whi... | [
"def",
"create_vm",
"(",
"client",
",",
"name",
",",
"compute_resource",
",",
"datastore",
",",
"disksize",
",",
"nics",
",",
"memory",
",",
"num_cpus",
",",
"guest_id",
",",
"host",
"=",
"None",
")",
":",
"print",
"(",
"\"Creating VM %s\"",
"%",
"name",
... | 38 | 19.647059 |
def export_wavefront(mesh,
include_normals=True,
include_texture=True):
"""
Export a mesh as a Wavefront OBJ file
Parameters
-----------
mesh: Trimesh object
Returns
-----------
export: str, string of OBJ format output
"""
# store the m... | [
"def",
"export_wavefront",
"(",
"mesh",
",",
"include_normals",
"=",
"True",
",",
"include_texture",
"=",
"True",
")",
":",
"# store the multiple options for formatting",
"# a vertex index for a face",
"face_formats",
"=",
"{",
"(",
"'v'",
",",
")",
":",
"'{}'",
","... | 36.833333 | 17.4 |
def _add_span_node_ids_to_token_nodes(self):
"""
Adds to every token node the list of spans (span node IDs) that it
belongs to.
TokenNode.spans - a list of `int` ids of `SpanNode`s
"""
span_dict = defaultdict(list)
for span_edge in self._spanning_relation_ids:
... | [
"def",
"_add_span_node_ids_to_token_nodes",
"(",
"self",
")",
":",
"span_dict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"span_edge",
"in",
"self",
".",
"_spanning_relation_ids",
":",
"token_node_id",
"=",
"self",
".",
"edges",
"[",
"span_edge",
"]",
".",
... | 39.066667 | 16.933333 |
def userItem(self):
"""returns a reference to the UserItem class"""
if self.ownerFolder is not None:
url = "%s/users/%s/%s/items/%s" % (self.root.split('/items/')[0], self.owner,self.ownerFolder, self.id)
else:
url = "%s/users/%s/items/%s" % (self.root.split('/items/')[0]... | [
"def",
"userItem",
"(",
"self",
")",
":",
"if",
"self",
".",
"ownerFolder",
"is",
"not",
"None",
":",
"url",
"=",
"\"%s/users/%s/%s/items/%s\"",
"%",
"(",
"self",
".",
"root",
".",
"split",
"(",
"'/items/'",
")",
"[",
"0",
"]",
",",
"self",
".",
"own... | 53.3 | 23 |
def to_web(self, host=None, user=None, password=None):
"""Send the model to BEL Commons by wrapping :py:func:`pybel.to_web`
The parameters ``host``, ``user``, and ``password`` all check the
PyBEL configuration, which is located at
``~/.config/pybel/config.json`` by default
Para... | [
"def",
"to_web",
"(",
"self",
",",
"host",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"response",
"=",
"pybel",
".",
"to_web",
"(",
"self",
".",
"model",
",",
"host",
"=",
"host",
",",
"user",
"=",
"user",
",",... | 43.387097 | 20.516129 |
def playlist_songs(self, playlist):
"""Get a listing of songs from a playlist.
Paramters:
playlist (dict): A playlist dict.
Returns:
list: Playlist song dicts.
"""
playlist_type = playlist.get('type')
playlist_song_list = []
if playlist_type in ('USER_GENERATED', None):
start_token = None
... | [
"def",
"playlist_songs",
"(",
"self",
",",
"playlist",
")",
":",
"playlist_type",
"=",
"playlist",
".",
"get",
"(",
"'type'",
")",
"playlist_song_list",
"=",
"[",
"]",
"if",
"playlist_type",
"in",
"(",
"'USER_GENERATED'",
",",
"None",
")",
":",
"start_token"... | 22.527273 | 19.527273 |
def estimate_angle(coord, angle, new_frame, offset=1e-7):
"""
https://github.com/astropy/astropy/issues/3093
"""
delta = delta_coord(coord, angle, offset)
new_coord = coord.transform_to(new_frame)
new_delta = delta.transform_to(new_frame)
return new_coord.position_angle(new_delta).deg | [
"def",
"estimate_angle",
"(",
"coord",
",",
"angle",
",",
"new_frame",
",",
"offset",
"=",
"1e-7",
")",
":",
"delta",
"=",
"delta_coord",
"(",
"coord",
",",
"angle",
",",
"offset",
")",
"new_coord",
"=",
"coord",
".",
"transform_to",
"(",
"new_frame",
")... | 38.25 | 6.5 |
def _get_game_type_des(cls, game_type):
"""
get game type description
:param game_type: game type
:return: game type description
"""
if game_type == 'S':
return 'Spring Training'
elif game_type == 'R':
return 'Regular Season'
elif g... | [
"def",
"_get_game_type_des",
"(",
"cls",
",",
"game_type",
")",
":",
"if",
"game_type",
"==",
"'S'",
":",
"return",
"'Spring Training'",
"elif",
"game_type",
"==",
"'R'",
":",
"return",
"'Regular Season'",
"elif",
"game_type",
"==",
"'F'",
":",
"return",
"'Wil... | 30.736842 | 6.210526 |
def create(self, data, **kwargs):
"""Create a new object.
Args:
data (dict): parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
RESTObject, RESTObject: The sourc... | [
"def",
"create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_missing_create_attrs",
"(",
"data",
")",
"server_data",
"=",
"self",
".",
"gitlab",
".",
"http_post",
"(",
"self",
".",
"path",
",",
"post_data",
"=",
"d... | 41.304348 | 21.217391 |
def add_model(self, ic, N=1, index=0):
"""
Should only be able to do this to a leaf node.
Either N and index both integers OR index is
list of length=N
"""
if type(index) in [list,tuple]:
if len(index) != N:
raise ValueError('If a list, index ... | [
"def",
"add_model",
"(",
"self",
",",
"ic",
",",
"N",
"=",
"1",
",",
"index",
"=",
"0",
")",
":",
"if",
"type",
"(",
"index",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"if",
"len",
"(",
"index",
")",
"!=",
"N",
":",
"raise",
"ValueError... | 31.470588 | 14.882353 |
def replace(self, infile):
'''Replace: 任意の箇所のバイト列と 同サイズの任意のバイト列を入れ換える
'''
gf = infile[31:]
same_size_index = []
while len(same_size_index) <= 1:
index = random.randint(0,len(gf)-1)
index_len = len(gf[index])
same_size_index = [i for (i,g) in en... | [
"def",
"replace",
"(",
"self",
",",
"infile",
")",
":",
"gf",
"=",
"infile",
"[",
"31",
":",
"]",
"same_size_index",
"=",
"[",
"]",
"while",
"len",
"(",
"same_size_index",
")",
"<=",
"1",
":",
"index",
"=",
"random",
".",
"randint",
"(",
"0",
",",
... | 40.384615 | 17.153846 |
def raise_for_status(self):
'''Raise Postmark-specific HTTP errors. If there isn't one, the
standard HTTP error is raised.
HTTP 401 raises :class:`UnauthorizedError`
HTTP 422 raises :class:`UnprocessableEntityError`
HTTP 500 raises :class:`InternalServerError`
'''
... | [
"def",
"raise_for_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"status_code",
"==",
"401",
":",
"raise",
"UnauthorizedError",
"(",
"self",
".",
"_requests_response",
")",
"elif",
"self",
".",
"status_code",
"==",
"422",
":",
"raise",
"UnprocessableEntity... | 38.882353 | 19.470588 |
def get_object(self, resource_url):
"""Get remote resource information. Creates a local directory for the
resource if this is the first access to the resource. Downloads the
resource Json representation and writes it into a .json file in the
cache directory.
Raises ValueError if... | [
"def",
"get_object",
"(",
"self",
",",
"resource_url",
")",
":",
"# Check if resource is in local cache. If not, create a new cache",
"# identifier and set is_cached flag to false",
"if",
"resource_url",
"in",
"self",
".",
"cache",
":",
"cache_id",
"=",
"self",
".",
"cache"... | 43.338983 | 18.59322 |
def check_public_permissions(payload):
"""Raise ``PermissionDenied`` if public permissions are too open."""
allowed_public_permissions = ['view', 'add', 'download']
for perm_type in ['add', 'remove']:
for perm in payload.get('public', {}).get(perm_type, []):
if perm not in allowed_public... | [
"def",
"check_public_permissions",
"(",
"payload",
")",
":",
"allowed_public_permissions",
"=",
"[",
"'view'",
",",
"'add'",
",",
"'download'",
"]",
"for",
"perm_type",
"in",
"[",
"'add'",
",",
"'remove'",
"]",
":",
"for",
"perm",
"in",
"payload",
".",
"get"... | 60.285714 | 16.571429 |
def write_genotypes(self, genotypes):
"""Write genotypes to binary file.
Args:
genotypes (numpy.ndarray): The genotypes to write in the BED file.
"""
if self._mode != "w":
raise UnsupportedOperation("not available in 'r' mode")
# Initializing the number... | [
"def",
"write_genotypes",
"(",
"self",
",",
"genotypes",
")",
":",
"if",
"self",
".",
"_mode",
"!=",
"\"w\"",
":",
"raise",
"UnsupportedOperation",
"(",
"\"not available in 'r' mode\"",
")",
"# Initializing the number of samples if required",
"if",
"self",
".",
"_nb_v... | 33.185185 | 20.333333 |
def flairlist(self, r, limit=1000, after=None, before=None):
"""Login required. Gets flairlist for subreddit `r`. See https://github.com/reddit/reddit/wiki/API%3A-flairlist.
However, the wiki docs are wrong (as of 2012/5/4). Returns :class:`things.ListBlob` of :class:`things.Blob` objects, e... | [
"def",
"flairlist",
"(",
"self",
",",
"r",
",",
"limit",
"=",
"1000",
",",
"after",
"=",
"None",
",",
"before",
"=",
"None",
")",
":",
"params",
"=",
"dict",
"(",
"limit",
"=",
"limit",
")",
"if",
"after",
":",
"params",
"[",
"'after'",
"]",
"=",... | 49.105263 | 24.842105 |
def lazy_import(path, pattern=None):
"""
Import a single file or collection of files.
:param path: A path to a data file (remote or local).
:param pattern: Character string containing a regular expression to match file(s) in the folder.
:returns: either a :class:`H2OFrame` with the content of the p... | [
"def",
"lazy_import",
"(",
"path",
",",
"pattern",
"=",
"None",
")",
":",
"assert_is_type",
"(",
"path",
",",
"str",
",",
"[",
"str",
"]",
")",
"assert_is_type",
"(",
"pattern",
",",
"str",
",",
"None",
")",
"paths",
"=",
"[",
"path",
"]",
"if",
"i... | 43 | 16.846154 |
def show_bokehjs(bokehjs_action, develop=False):
''' Print a useful report after setuptools output describing where and how
BokehJS is installed.
Args:
bokehjs_action (str) : one of 'built', 'installed', or 'packaged'
how (or if) BokehJS was installed into the python source tree
... | [
"def",
"show_bokehjs",
"(",
"bokehjs_action",
",",
"develop",
"=",
"False",
")",
":",
"print",
"(",
")",
"if",
"develop",
":",
"print",
"(",
"\"Installed Bokeh for DEVELOPMENT:\"",
")",
"else",
":",
"print",
"(",
"\"Installed Bokeh:\"",
")",
"if",
"bokehjs_actio... | 35.28 | 31.52 |
def persist(self, name, project=None, drop_model=False, **kwargs):
"""
Persist the execution into a new model.
:param name: model name
:param project: name of the project
:param drop_model: drop model before creation
"""
return super(ODPSModelExpr, self).persist(... | [
"def",
"persist",
"(",
"self",
",",
"name",
",",
"project",
"=",
"None",
",",
"drop_model",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"ODPSModelExpr",
",",
"self",
")",
".",
"persist",
"(",
"name",
",",
"project",
"=",
... | 40.777778 | 18.111111 |
def viewAt(self, point):
"""
Looks up the view at the inputed point.
:param point | <QtCore.QPoint>
:return <projexui.widgets.xviewwidget.XView> || None
"""
widget = self.childAt(point)
if widget:
return projexui.ancestor(widget, XView)
... | [
"def",
"viewAt",
"(",
"self",
",",
"point",
")",
":",
"widget",
"=",
"self",
".",
"childAt",
"(",
"point",
")",
"if",
"widget",
":",
"return",
"projexui",
".",
"ancestor",
"(",
"widget",
",",
"XView",
")",
"else",
":",
"return",
"None"
] | 26.230769 | 16.230769 |
def read(path, corpus=True, index_by='wosid', streaming=False, parse_only=None,
corpus_class=Corpus, **kwargs):
"""
Parse one or more WoS field-tagged data files.
Examples
--------
.. code-block:: python
>>> from tethne.readers import wos
>>> corpus = wos.read("/path/to/some... | [
"def",
"read",
"(",
"path",
",",
"corpus",
"=",
"True",
",",
"index_by",
"=",
"'wosid'",
",",
"streaming",
"=",
"False",
",",
"parse_only",
"=",
"None",
",",
"corpus_class",
"=",
"Corpus",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"os",
".",
... | 32.038462 | 22.153846 |
def set_status(self, status, msg):
"""
Set and return the status of the task.
Args:
status: Status object or string representation of the status
msg: string with human-readable message used in the case of errors.
"""
# truncate string if it's long. msg wi... | [
"def",
"set_status",
"(",
"self",
",",
"status",
",",
"msg",
")",
":",
"# truncate string if it's long. msg will be logged in the object and we don't want to waste memory.",
"if",
"len",
"(",
"msg",
")",
">",
"2000",
":",
"msg",
"=",
"msg",
"[",
":",
"2000",
"]",
... | 37.901408 | 22.661972 |
def make_nameko_helper(config):
"""Create a fake module that provides some convenient access to nameko
standalone functionality for interactive shell usage.
"""
module = ModuleType('nameko')
module.__doc__ = """Nameko shell helper for making rpc calls and dispatching
events.
Usage:
>>> n.rpc.se... | [
"def",
"make_nameko_helper",
"(",
"config",
")",
":",
"module",
"=",
"ModuleType",
"(",
"'nameko'",
")",
"module",
".",
"__doc__",
"=",
"\"\"\"Nameko shell helper for making rpc calls and dispatching\nevents.\n\nUsage:\n >>> n.rpc.service.method()\n \"reply\"\n\n >>> n.dispa... | 29.8 | 15.6 |
def convert_tags_to_dict(item):
"""
Convert AWS inconvenient tags model of a list of {"Key": <key>, "Value": <value>} pairs
to a dict of {<key>: <value>} for easier querying.
This returns a proxied object over given item to return a different tags format as the tags
attribute is read-only and we ca... | [
"def",
"convert_tags_to_dict",
"(",
"item",
")",
":",
"if",
"hasattr",
"(",
"item",
",",
"'tags'",
")",
":",
"tags",
"=",
"item",
".",
"tags",
"if",
"isinstance",
"(",
"tags",
",",
"list",
")",
":",
"tags_dict",
"=",
"{",
"}",
"for",
"kv_dict",
"in",... | 41.764706 | 20.823529 |
def zones(self):
"""
Return a new raw REST interface to zone resources
:rtype: :py:class:`ns1.rest.zones.Zones`
"""
import ns1.rest.zones
return ns1.rest.zones.Zones(self.config) | [
"def",
"zones",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"zones",
"return",
"ns1",
".",
"rest",
".",
"zones",
".",
"Zones",
"(",
"self",
".",
"config",
")"
] | 27.5 | 13.5 |
def make_posthook(self):
""" Run the post hook into the project directory. """
print(id(self.posthook), self.posthook)
print(id(super(self.__class__, self).posthook), super(self.__class__, self).posthook)
import ipdb;ipdb.set_trace()
if self.posthook:
os.chdir(self.pr... | [
"def",
"make_posthook",
"(",
"self",
")",
":",
"print",
"(",
"id",
"(",
"self",
".",
"posthook",
")",
",",
"self",
".",
"posthook",
")",
"print",
"(",
"id",
"(",
"super",
"(",
"self",
".",
"__class__",
",",
"self",
")",
".",
"posthook",
")",
",",
... | 48.375 | 17.75 |
def allow(self, ctx, ops):
''' Checks that the authorizer's request is authorized to
perform all the given operations. Note that allow does not check
first party caveats - if there is more than one macaroon that may
authorize the request, it will choose the first one that does
re... | [
"def",
"allow",
"(",
"self",
",",
"ctx",
",",
"ops",
")",
":",
"auth_info",
",",
"_",
"=",
"self",
".",
"allow_any",
"(",
"ctx",
",",
"ops",
")",
"return",
"auth_info"
] | 43.233333 | 25.833333 |
def gifs_trending_get(self, api_key, **kwargs):
"""
Trending GIFs Endpoint
Fetch GIFs currently trending online. Hand curated by the GIPHY editorial team. The data returned mirrors the GIFs showcased on the <a href = \"http://www.giphy.com\">GIPHY homepage</a>. Returns 25 results by default.
... | [
"def",
"gifs_trending_get",
"(",
"self",
",",
"api_key",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"gifs_trending_get_with_h... | 52.142857 | 24.428571 |
def configureLogging(self):
"""Configure logging for nose, or optionally other packages. Any logger
name may be set with the debug option, and that logger will be set to
debug level and be assigned the same handler as the nose loggers, unless
it already has a handler.
"""
... | [
"def",
"configureLogging",
"(",
"self",
")",
":",
"if",
"self",
".",
"loggingConfig",
":",
"from",
"logging",
".",
"config",
"import",
"fileConfig",
"fileConfig",
"(",
"self",
".",
"loggingConfig",
")",
"return",
"format",
"=",
"logging",
".",
"Formatter",
"... | 36.369565 | 16.195652 |
def get_crimes_location(self, location_id, date=None):
"""
Get crimes at a particular snap-point location. Uses the
crimes-at-location_ API call.
.. _crimes-at-location:
https://data.police.uk/docs/method/crimes-at-location/
:rtype: list
:param int location_... | [
"def",
"get_crimes_location",
"(",
"self",
",",
"location_id",
",",
"date",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'location_id'",
":",
"location_id",
",",
"}",
"crimes",
"=",
"[",
"]",
"if",
"date",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'date... | 38.115385 | 21.423077 |
def GetColLabelValue(self, col):
"""
Get col label from dataframe
"""
if len(self.dataframe):
return self.dataframe.columns[col]
return '' | [
"def",
"GetColLabelValue",
"(",
"self",
",",
"col",
")",
":",
"if",
"len",
"(",
"self",
".",
"dataframe",
")",
":",
"return",
"self",
".",
"dataframe",
".",
"columns",
"[",
"col",
"]",
"return",
"''"
] | 26.285714 | 7.142857 |
def _slice_cov(self, cov):
"""
Slice the correct dimensions for use in the kernel, as indicated by
`self.active_dims` for covariance matrices. This requires slicing the
rows *and* columns. This will also turn flattened diagonal
matrices into a tensor of full diagonal matrices.
... | [
"def",
"_slice_cov",
"(",
"self",
",",
"cov",
")",
":",
"cov",
"=",
"tf",
".",
"cond",
"(",
"tf",
".",
"equal",
"(",
"tf",
".",
"rank",
"(",
"cov",
")",
",",
"2",
")",
",",
"lambda",
":",
"tf",
".",
"matrix_diag",
"(",
"cov",
")",
",",
"lambd... | 52.904762 | 25.761905 |
def export_translations(request, language):
"""
Export translations view.
"""
FieldTranslation.delete_orphan_translations()
translations = FieldTranslation.objects.filter(lang=language)
for trans in translations:
trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
trans.translation = ... | [
"def",
"export_translations",
"(",
"request",
",",
"language",
")",
":",
"FieldTranslation",
".",
"delete_orphan_translations",
"(",
")",
"translations",
"=",
"FieldTranslation",
".",
"objects",
".",
"filter",
"(",
"lang",
"=",
"language",
")",
"for",
"trans",
"... | 53.555556 | 26.222222 |
def init_distributed(cuda):
"""
Initializes distributed backend.
:param cuda: (bool) if True initializes nccl backend, if False initializes
gloo backend
"""
world_size = int(os.environ.get('WORLD_SIZE', 1))
distributed = (world_size > 1)
if distributed:
backend = 'nccl' if c... | [
"def",
"init_distributed",
"(",
"cuda",
")",
":",
"world_size",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'WORLD_SIZE'",
",",
"1",
")",
")",
"distributed",
"=",
"(",
"world_size",
">",
"1",
")",
"if",
"distributed",
":",
"backend",
"=",
... | 32.266667 | 13.466667 |
def serialize_tag(tag, *, indent=None, compact=False, quote=None):
"""Serialize an nbt tag to its literal representation."""
serializer = Serializer(indent=indent, compact=compact, quote=quote)
return serializer.serialize(tag) | [
"def",
"serialize_tag",
"(",
"tag",
",",
"*",
",",
"indent",
"=",
"None",
",",
"compact",
"=",
"False",
",",
"quote",
"=",
"None",
")",
":",
"serializer",
"=",
"Serializer",
"(",
"indent",
"=",
"indent",
",",
"compact",
"=",
"compact",
",",
"quote",
... | 58.75 | 15.5 |
def peek(self, size=-1):
"""
Return bytes from the stream without advancing the position.
Args:
size (int): Number of bytes to read. -1 to read the full
stream.
Returns:
bytes: bytes read
"""
if not self._readable:
rai... | [
"def",
"peek",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"not",
"self",
".",
"_readable",
":",
"raise",
"UnsupportedOperation",
"(",
"'read'",
")",
"with",
"self",
".",
"_seek_lock",
":",
"self",
".",
"_raw",
".",
"seek",
"(",
"self",
... | 26.235294 | 17.647059 |
def from_jsons(graph_json_str: str, check_version: bool = True) -> BELGraph:
"""Read a BEL graph from a Node-Link JSON string."""
graph_json_dict = json.loads(graph_json_str)
return from_json(graph_json_dict, check_version=check_version) | [
"def",
"from_jsons",
"(",
"graph_json_str",
":",
"str",
",",
"check_version",
":",
"bool",
"=",
"True",
")",
"->",
"BELGraph",
":",
"graph_json_dict",
"=",
"json",
".",
"loads",
"(",
"graph_json_str",
")",
"return",
"from_json",
"(",
"graph_json_dict",
",",
... | 61.5 | 17.5 |
def format_help_text(self, ctx, formatter):
"""Writes the help text to the formatter if it exists."""
if self.help:
formatter.write_paragraph()
with formatter.indentation():
formatter.write_text(self.help) | [
"def",
"format_help_text",
"(",
"self",
",",
"ctx",
",",
"formatter",
")",
":",
"if",
"self",
".",
"help",
":",
"formatter",
".",
"write_paragraph",
"(",
")",
"with",
"formatter",
".",
"indentation",
"(",
")",
":",
"formatter",
".",
"write_text",
"(",
"s... | 42.666667 | 5.166667 |
def build(matrix):
"""Yield lines generated from given matrix"""
max_x = max(matrix, key=lambda t: t[0])[0]
min_x = min(matrix, key=lambda t: t[0])[0]
max_y = max(matrix, key=lambda t: t[1])[1]
min_y = min(matrix, key=lambda t: t[1])[1]
yield from (
# '{}:'.format(j).ljust(4) + ''.join(m... | [
"def",
"build",
"(",
"matrix",
")",
":",
"max_x",
"=",
"max",
"(",
"matrix",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"min_x",
"=",
"min",
"(",
"matrix",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
"[",
"0"... | 41.727273 | 16 |
def _makes_clone(_func, *args, **kw):
"""
A decorator that returns a clone of the current object so that
we can re-use the object for similar requests.
"""
self = args[0]._clone()
_func(self, *args[1:], **kw)
return self | [
"def",
"_makes_clone",
"(",
"_func",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
".",
"_clone",
"(",
")",
"_func",
"(",
"self",
",",
"*",
"args",
"[",
"1",
":",
"]",
",",
"*",
"*",
"kw",
")",
"return... | 30.125 | 10.625 |
def QuickAddEvent(self, event_text, reminders=None):
"""Wrapper around Google Calendar API's quickAdd"""
if not event_text:
raise GcalcliError('event_text is required for a quickAdd')
if len(self.cals) != 1:
# TODO: get a better name for this exception class
... | [
"def",
"QuickAddEvent",
"(",
"self",
",",
"event_text",
",",
"reminders",
"=",
"None",
")",
":",
"if",
"not",
"event_text",
":",
"raise",
"GcalcliError",
"(",
"'event_text is required for a quickAdd'",
")",
"if",
"len",
"(",
"self",
".",
"cals",
")",
"!=",
"... | 37.697674 | 17.534884 |
def load_suite_from_stdin(self):
"""Load a test suite with test lines from the TAP stream on STDIN.
:returns: A ``unittest.TestSuite`` instance
"""
suite = unittest.TestSuite()
rules = Rules("stream", suite)
line_generator = self._parser.parse_stdin()
return self... | [
"def",
"load_suite_from_stdin",
"(",
"self",
")",
":",
"suite",
"=",
"unittest",
".",
"TestSuite",
"(",
")",
"rules",
"=",
"Rules",
"(",
"\"stream\"",
",",
"suite",
")",
"line_generator",
"=",
"self",
".",
"_parser",
".",
"parse_stdin",
"(",
")",
"return",... | 40.444444 | 11.888889 |
def project_activities(self, project_id_or_key, extra_query_params={}):
"""
client = BacklogClient("your_space_name", "your_api_key")
client.project_activities("YOUR_PROJECT")
client.project_activities("YOUR_PROJECT", {"activityTypeId[]": [1, 2],})
"""
return self.do("get... | [
"def",
"project_activities",
"(",
"self",
",",
"project_id_or_key",
",",
"extra_query_params",
"=",
"{",
"}",
")",
":",
"return",
"self",
".",
"do",
"(",
"\"get\"",
",",
"\"projects/{project_id_or_key}/activities\"",
",",
"url_params",
"=",
"{",
"\"project_id_or_key... | 51.3 | 20.3 |
def remove_bgp(self, **kwargs):
"""Remove BGP process completely.
Args:
vrf (str): The VRF for this BGP process.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
callback (function): A function executed u... | [
"def",
"remove_bgp",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"vrf",
"=",
"kwargs",
".",
"pop",
"(",
"'vrf'",
",",
"'default'",
")",
"rbridge_id",
"=",
"kwargs",
".",
"pop",
"(",
"'rbridge_id'",
",",
"'1'",
")",
"callback",
"=",
"kwargs",
".",... | 38.088235 | 19.5 |
def tss(self, up=0, down=0):
"""
Return a start, end tuple of positions around the transcription-start
site
Parameters
----------
up : int
if greature than 0, the strand is used to add this many upstream
bases in the appropriate direction
... | [
"def",
"tss",
"(",
"self",
",",
"up",
"=",
"0",
",",
"down",
"=",
"0",
")",
":",
"if",
"not",
"self",
".",
"is_gene_pred",
":",
"return",
"None",
"tss",
"=",
"self",
".",
"txEnd",
"if",
"self",
".",
"strand",
"==",
"'-'",
"else",
"self",
".",
"... | 29.37037 | 19.666667 |
def token_permission_view(token):
"""Show permission garanted to authorized application token."""
scopes = [current_oauth2server.scopes[x] for x in token.scopes]
return render_template(
"invenio_oauth2server/settings/token_permission_view.html",
token=token,
scopes=scopes,
) | [
"def",
"token_permission_view",
"(",
"token",
")",
":",
"scopes",
"=",
"[",
"current_oauth2server",
".",
"scopes",
"[",
"x",
"]",
"for",
"x",
"in",
"token",
".",
"scopes",
"]",
"return",
"render_template",
"(",
"\"invenio_oauth2server/settings/token_permission_view.... | 38.5 | 18.375 |
async def update(self, _id=None, **new_data):
"""Updates fields values.
Accepts id of sigle entry and
fields with values.
update(id, **kwargs) => {"success":200, "reason":"Updated"} (if success)
update(id, **kwargs) => {"error":400, "reason":"Missed required fields"} (if error)
"""
if not _id or not ne... | [
"async",
"def",
"update",
"(",
"self",
",",
"_id",
"=",
"None",
",",
"*",
"*",
"new_data",
")",
":",
"if",
"not",
"_id",
"or",
"not",
"new_data",
":",
"return",
"{",
"\"error\"",
":",
"400",
",",
"\"reason\"",
":",
"\"Missed required fields\"",
"}",
"d... | 31.041667 | 18.125 |
def security_rule_absent(name, security_group, resource_group, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a security rule does not exist in the network security group.
:param name:
Name of the security rule.
:param security_group:
The network security group conta... | [
"def",
"security_rule_absent",
"(",
"name",
",",
"security_group",
",",
"resource_group",
",",
"connection_auth",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
"... | 28.092308 | 26.553846 |
def without_extra_phrases(self):
"""Removes parenthethical and dashed phrases"""
# the last parenthesis is optional, because sometimes they are truncated
name = re.sub(r'\s*\([^)]*\)?\s*$', '', self.name)
name = re.sub(r'(?i)\s* formerly.*$', '', name)
name = re.sub(r'(?i)\s*and ... | [
"def",
"without_extra_phrases",
"(",
"self",
")",
":",
"# the last parenthesis is optional, because sometimes they are truncated",
"name",
"=",
"re",
".",
"sub",
"(",
"r'\\s*\\([^)]*\\)?\\s*$'",
",",
"''",
",",
"self",
".",
"name",
")",
"name",
"=",
"re",
".",
"sub"... | 58.826087 | 32.173913 |
def build_input_pipeline(x_train, x_test, y_train, y_test,
batch_size, valid_size):
"""Build an Iterator switching between train and heldout data."""
x_train = x_train.astype("float32")
x_test = x_test.astype("float32")
x_train /= 255
x_test /= 255
y_train = y_train.flatten()
y... | [
"def",
"build_input_pipeline",
"(",
"x_train",
",",
"x_test",
",",
"y_train",
",",
"y_test",
",",
"batch_size",
",",
"valid_size",
")",
":",
"x_train",
"=",
"x_train",
".",
"astype",
"(",
"\"float32\"",
")",
"x_test",
"=",
"x_test",
".",
"astype",
"(",
"\"... | 38.681818 | 20.931818 |
def begin_update(self, x_data, drop=0.0):
"""Return the output of the wrapped PyTorch model for the given input,
along with a callback to handle the backward pass.
"""
x_var = torch.autograd.Variable(xp2torch(x_data), requires_grad=True)
# Make prediction
y_var = self._m... | [
"def",
"begin_update",
"(",
"self",
",",
"x_data",
",",
"drop",
"=",
"0.0",
")",
":",
"x_var",
"=",
"torch",
".",
"autograd",
".",
"Variable",
"(",
"xp2torch",
"(",
"x_data",
")",
",",
"requires_grad",
"=",
"True",
")",
"# Make prediction",
"y_var",
"=",... | 39.3 | 14.35 |
def get_start_time(self, file_path):
"""
:param file_path: the path to the file that's being processed
:type file_path: unicode
:return: the start time of the process that's processing the
specified file or None if the file is not currently being processed
:rtype: dat... | [
"def",
"get_start_time",
"(",
"self",
",",
"file_path",
")",
":",
"if",
"file_path",
"in",
"self",
".",
"_processors",
":",
"return",
"self",
".",
"_processors",
"[",
"file_path",
"]",
".",
"start_time",
"return",
"None"
] | 40.636364 | 14.818182 |
def find_clique_embedding(k, m=None, target_graph=None):
"""Find an embedding of a k-sized clique on a Pegasus graph (target_graph).
This clique is found by transforming the Pegasus graph into a K2,2 Chimera graph and then
applying a Chimera clique finding algorithm. The results are then converted back in ... | [
"def",
"find_clique_embedding",
"(",
"k",
",",
"m",
"=",
"None",
",",
"target_graph",
"=",
"None",
")",
":",
"# Organize parameter values",
"if",
"target_graph",
"is",
"None",
":",
"if",
"m",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"m and target_graph ... | 47.217949 | 28.141026 |
def delete_gauge(self, slug):
"""Removes all gauges with the given ``slug``."""
key = self._gauge_key(slug)
self.r.delete(key) # Remove the Gauge
self.r.srem(self._gauge_slugs_key, slug) | [
"def",
"delete_gauge",
"(",
"self",
",",
"slug",
")",
":",
"key",
"=",
"self",
".",
"_gauge_key",
"(",
"slug",
")",
"self",
".",
"r",
".",
"delete",
"(",
"key",
")",
"# Remove the Gauge",
"self",
".",
"r",
".",
"srem",
"(",
"self",
".",
"_gauge_slugs... | 43 | 6 |
def asl_obctrl_encode(self, timestamp, uElev, uThrot, uThrot2, uAilL, uAilR, uRud, obctrl_status):
'''
Off-board controls/commands for ASLUAVs
timestamp : Time since system start [us] (uint64_t)
uElev : Elevator command... | [
"def",
"asl_obctrl_encode",
"(",
"self",
",",
"timestamp",
",",
"uElev",
",",
"uThrot",
",",
"uThrot2",
",",
"uAilL",
",",
"uAilR",
",",
"uRud",
",",
"obctrl_status",
")",
":",
"return",
"MAVLink_asl_obctrl_message",
"(",
"timestamp",
",",
"uElev",
",",
"uTh... | 60.866667 | 37.133333 |
def get_default_config_help(self):
"""
Return help text for collector configuration.
"""
config_help = super(MemoryLxcCollector, self).get_default_config_help()
config_help.update({
"sys_path": "Defaults to '/sys/fs/cgroup/lxc'",
})
return config_help | [
"def",
"get_default_config_help",
"(",
"self",
")",
":",
"config_help",
"=",
"super",
"(",
"MemoryLxcCollector",
",",
"self",
")",
".",
"get_default_config_help",
"(",
")",
"config_help",
".",
"update",
"(",
"{",
"\"sys_path\"",
":",
"\"Defaults to '/sys/fs/cgroup/l... | 34.555556 | 14.777778 |
def pformat(
object,
indent=_UNSET_SENTINEL,
width=_UNSET_SENTINEL,
depth=_UNSET_SENTINEL,
*,
ribbon_width=_UNSET_SENTINEL,
max_seq_len=_UNSET_SENTINEL,
compact=_UNSET_SENTINEL,
sort_dict_keys=_UNSET_SENTINEL
):
"""
Returns a pretty printed representation of the object as a `... | [
"def",
"pformat",
"(",
"object",
",",
"indent",
"=",
"_UNSET_SENTINEL",
",",
"width",
"=",
"_UNSET_SENTINEL",
",",
"depth",
"=",
"_UNSET_SENTINEL",
",",
"*",
",",
"ribbon_width",
"=",
"_UNSET_SENTINEL",
",",
"max_seq_len",
"=",
"_UNSET_SENTINEL",
",",
"compact",... | 26.133333 | 15.733333 |
def get_config(self, slot, config_id):
"""Get a config variable assignment previously set on this sensor graph.
Args:
slot (SlotIdentifier): The slot that we are setting this config variable
on.
config_id (int): The 16-bit config variable identifier.
Ret... | [
"def",
"get_config",
"(",
"self",
",",
"slot",
",",
"config_id",
")",
":",
"if",
"slot",
"not",
"in",
"self",
".",
"config_database",
":",
"raise",
"ArgumentError",
"(",
"\"No config variables have been set on specified slot\"",
",",
"slot",
"=",
"slot",
")",
"i... | 39.333333 | 28.708333 |
def transliterate(table, text):
"""
Transliterate text according to one of the tables above.
`table` chooses the table. It looks like a language code but comes from a
very restricted set:
- 'sr-Latn' means to convert Serbian, which may be in Cyrillic, into the
Latin alphabet.
- 'az-Latn'... | [
"def",
"transliterate",
"(",
"table",
",",
"text",
")",
":",
"if",
"table",
"==",
"'sr-Latn'",
":",
"return",
"text",
".",
"translate",
"(",
"SR_LATN_TABLE",
")",
"elif",
"table",
"==",
"'az-Latn'",
":",
"return",
"text",
".",
"translate",
"(",
"AZ_LATN_TA... | 35 | 20.176471 |
def _get_clause_words( sentence_text, clause_id ):
''' Collects clause with index *clause_id* from given *sentence_text*.
Returns a pair (clause, isEmbedded), where:
*clause* is a list of word tokens in the clause;
*isEmbedded* is a bool indicating whether the clause is embedded;
'''
... | [
"def",
"_get_clause_words",
"(",
"sentence_text",
",",
"clause_id",
")",
":",
"clause",
"=",
"[",
"]",
"isEmbedded",
"=",
"False",
"indices",
"=",
"sentence_text",
".",
"clause_indices",
"clause_anno",
"=",
"sentence_text",
".",
"clause_annotations",
"for",
"wid",... | 44.125 | 16.375 |
def check_render_pipe_str(pipestr, renderers, blacklist, whitelist):
'''
Check that all renderers specified in the pipe string are available.
If so, return the list of render functions in the pipe as
(render_func, arg_str) tuples; otherwise return [].
'''
if pipestr is None:
return []
... | [
"def",
"check_render_pipe_str",
"(",
"pipestr",
",",
"renderers",
",",
"blacklist",
",",
"whitelist",
")",
":",
"if",
"pipestr",
"is",
"None",
":",
"return",
"[",
"]",
"parts",
"=",
"[",
"r",
".",
"strip",
"(",
")",
"for",
"r",
"in",
"pipestr",
".",
... | 39.466667 | 21.4 |
def for_category(self, category, live_only=False):
"""
Returns queryset of EntryTag instances for specified category.
:param category: the Category instance.
:param live_only: flag to include only "live" entries.
:rtype: django.db.models.query.QuerySet.
"""
filte... | [
"def",
"for_category",
"(",
"self",
",",
"category",
",",
"live_only",
"=",
"False",
")",
":",
"filters",
"=",
"{",
"'tag'",
":",
"category",
".",
"tag",
"}",
"if",
"live_only",
":",
"filters",
".",
"update",
"(",
"{",
"'entry__live'",
":",
"True",
"}"... | 31.785714 | 16.357143 |
def write_fits(self, data, outfile, extname="SKYMAP", clobber=True):
""" Write input data to a FITS file
data : The data begin stored
outfile : The name of the output file
extname : The HDU extension name
clobber : True -> overwrite existing files
"""
... | [
"def",
"write_fits",
"(",
"self",
",",
"data",
",",
"outfile",
",",
"extname",
"=",
"\"SKYMAP\"",
",",
"clobber",
"=",
"True",
")",
":",
"hdu_prim",
"=",
"fits",
".",
"PrimaryHDU",
"(",
")",
"hdu_hpx",
"=",
"self",
".",
"make_hdu",
"(",
"data",
",",
... | 41.157895 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.