repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
numenta/nupic | src/nupic/swarming/hypersearch/hs_state.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/hypersearch/hs_state.py#L620-L637 | def anyGoodSprintsActive(self):
"""Return True if there are any more good sprints still being explored.
A 'good' sprint is one that is earlier than where we detected an increase
in error from sprint to subsequent sprint.
"""
if self._state['lastGoodSprint'] is not None:
goodSprints = self._state['sprints'][0:self._state['lastGoodSprint']+1]
else:
goodSprints = self._state['sprints']
for sprint in goodSprints:
if sprint['status'] == 'active':
anyActiveSprints = True
break
else:
anyActiveSprints = False
return anyActiveSprints | [
"def",
"anyGoodSprintsActive",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"[",
"'lastGoodSprint'",
"]",
"is",
"not",
"None",
":",
"goodSprints",
"=",
"self",
".",
"_state",
"[",
"'sprints'",
"]",
"[",
"0",
":",
"self",
".",
"_state",
"[",
"'la... | Return True if there are any more good sprints still being explored.
A 'good' sprint is one that is earlier than where we detected an increase
in error from sprint to subsequent sprint. | [
"Return",
"True",
"if",
"there",
"are",
"any",
"more",
"good",
"sprints",
"still",
"being",
"explored",
".",
"A",
"good",
"sprint",
"is",
"one",
"that",
"is",
"earlier",
"than",
"where",
"we",
"detected",
"an",
"increase",
"in",
"error",
"from",
"sprint",
... | python | valid |
7sDream/zhihu-py3 | zhihu/author.py | https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/author.py#L118-L137 | def motto(self):
"""获取用户自我介绍,由于历史原因,我还是把这个属性叫做motto吧.
:return: 用户自我介绍
:rtype: str
"""
if self.url is None:
return ''
else:
if self.soup is not None:
bar = self.soup.find(
'div', class_='title-section')
if len(bar.contents) < 4:
return ''
else:
return bar.contents[3].text
else:
assert self.card is not None
motto = self.card.find('div', class_='tagline')
return motto.text if motto is not None else '' | [
"def",
"motto",
"(",
"self",
")",
":",
"if",
"self",
".",
"url",
"is",
"None",
":",
"return",
"''",
"else",
":",
"if",
"self",
".",
"soup",
"is",
"not",
"None",
":",
"bar",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'div'",
",",
"class_",
"="... | 获取用户自我介绍,由于历史原因,我还是把这个属性叫做motto吧.
:return: 用户自我介绍
:rtype: str | [
"获取用户自我介绍,由于历史原因,我还是把这个属性叫做motto吧",
"."
] | python | train |
tensorlayer/tensorlayer | tensorlayer/layers/utils.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/utils.py#L47-L61 | def compute_alpha(x):
"""Computing the scale parameter."""
threshold = _compute_threshold(x)
alpha1_temp1 = tf.where(tf.greater(x, threshold), x, tf.zeros_like(x, tf.float32))
alpha1_temp2 = tf.where(tf.less(x, -threshold), x, tf.zeros_like(x, tf.float32))
alpha_array = tf.add(alpha1_temp1, alpha1_temp2, name=None)
alpha_array_abs = tf.abs(alpha_array)
alpha_array_abs1 = tf.where(
tf.greater(alpha_array_abs, 0), tf.ones_like(alpha_array_abs, tf.float32),
tf.zeros_like(alpha_array_abs, tf.float32)
)
alpha_sum = tf.reduce_sum(alpha_array_abs)
n = tf.reduce_sum(alpha_array_abs1)
alpha = tf.div(alpha_sum, n)
return alpha | [
"def",
"compute_alpha",
"(",
"x",
")",
":",
"threshold",
"=",
"_compute_threshold",
"(",
"x",
")",
"alpha1_temp1",
"=",
"tf",
".",
"where",
"(",
"tf",
".",
"greater",
"(",
"x",
",",
"threshold",
")",
",",
"x",
",",
"tf",
".",
"zeros_like",
"(",
"x",
... | Computing the scale parameter. | [
"Computing",
"the",
"scale",
"parameter",
"."
] | python | valid |
calmjs/calmjs.parse | src/calmjs/parse/unparsers/es5.py | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/unparsers/es5.py#L329-L342 | def pretty_print(ast, indent_str=' '):
"""
Simple pretty print function; returns a string rendering of an input
AST of an ES5 Program.
arguments
ast
The AST to pretty print
indent_str
The string used for indentations. Defaults to two spaces.
"""
return ''.join(chunk.text for chunk in pretty_printer(indent_str)(ast)) | [
"def",
"pretty_print",
"(",
"ast",
",",
"indent_str",
"=",
"' '",
")",
":",
"return",
"''",
".",
"join",
"(",
"chunk",
".",
"text",
"for",
"chunk",
"in",
"pretty_printer",
"(",
"indent_str",
")",
"(",
"ast",
")",
")"
] | Simple pretty print function; returns a string rendering of an input
AST of an ES5 Program.
arguments
ast
The AST to pretty print
indent_str
The string used for indentations. Defaults to two spaces. | [
"Simple",
"pretty",
"print",
"function",
";",
"returns",
"a",
"string",
"rendering",
"of",
"an",
"input",
"AST",
"of",
"an",
"ES5",
"Program",
"."
] | python | train |
adamrehn/ue4cli | ue4cli/UnrealManagerBase.py | https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L297-L314 | def cleanDescriptor(self, dir=os.getcwd()):
"""
Cleans the build artifacts for the Unreal project or plugin in the specified directory
"""
# Verify that an Unreal project or plugin exists in the specified directory
descriptor = self.getDescriptor(dir)
# Because performing a clean will also delete the engine build itself when using
# a source build, we simply delete the `Binaries` and `Intermediate` directories
shutil.rmtree(os.path.join(dir, 'Binaries'), ignore_errors=True)
shutil.rmtree(os.path.join(dir, 'Intermediate'), ignore_errors=True)
# If we are cleaning a project, also clean any plugins
if self.isProject(descriptor):
projectPlugins = glob.glob(os.path.join(dir, 'Plugins', '*'))
for pluginDir in projectPlugins:
self.cleanDescriptor(pluginDir) | [
"def",
"cleanDescriptor",
"(",
"self",
",",
"dir",
"=",
"os",
".",
"getcwd",
"(",
")",
")",
":",
"# Verify that an Unreal project or plugin exists in the specified directory",
"descriptor",
"=",
"self",
".",
"getDescriptor",
"(",
"dir",
")",
"# Because performing a clea... | Cleans the build artifacts for the Unreal project or plugin in the specified directory | [
"Cleans",
"the",
"build",
"artifacts",
"for",
"the",
"Unreal",
"project",
"or",
"plugin",
"in",
"the",
"specified",
"directory"
] | python | train |
qacafe/cdrouter.py | cdrouter/packages.py | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/packages.py#L218-L227 | def get(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Get a package.
:param id: Package ID as an int.
:return: :class:`packages.Package <packages.Package>` object
:rtype: packages.Package
"""
schema = PackageSchema()
resp = self.service.get_id(self.base, id)
return self.service.decode(schema, resp) | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"PackageSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"get_id",
"(",
"self",
".",
"base",
",",
"id",
")",
"return",
"self",
".... | Get a package.
:param id: Package ID as an int.
:return: :class:`packages.Package <packages.Package>` object
:rtype: packages.Package | [
"Get",
"a",
"package",
"."
] | python | train |
turicas/rows | rows/utils.py | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L727-L755 | def uncompressed_size(filename):
"""Return the uncompressed size for a file by executing commands
Note: due to a limitation in gzip format, uncompressed files greather than
4GiB will have a wrong value.
"""
quoted_filename = shlex.quote(filename)
# TODO: get filetype from file-magic, if available
if str(filename).lower().endswith(".xz"):
output = execute_command('xz --list "{}"'.format(quoted_filename))
compressed, uncompressed = regexp_sizes.findall(output)
value, unit = uncompressed.split()
value = float(value.replace(",", ""))
return int(value * MULTIPLIERS[unit])
elif str(filename).lower().endswith(".gz"):
# XXX: gzip only uses 32 bits to store uncompressed size, so if the
# uncompressed size is greater than 4GiB, the value returned will be
# incorrect.
output = execute_command('gzip --list "{}"'.format(quoted_filename))
lines = [line.split() for line in output.splitlines()]
header, data = lines[0], lines[1]
gzip_data = dict(zip(header, data))
return int(gzip_data["uncompressed"])
else:
raise ValueError('Unrecognized file type for "{}".'.format(filename)) | [
"def",
"uncompressed_size",
"(",
"filename",
")",
":",
"quoted_filename",
"=",
"shlex",
".",
"quote",
"(",
"filename",
")",
"# TODO: get filetype from file-magic, if available",
"if",
"str",
"(",
"filename",
")",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\"... | Return the uncompressed size for a file by executing commands
Note: due to a limitation in gzip format, uncompressed files greather than
4GiB will have a wrong value. | [
"Return",
"the",
"uncompressed",
"size",
"for",
"a",
"file",
"by",
"executing",
"commands"
] | python | train |
iskandr/knnimpute | knnimpute/optimistic.py | https://github.com/iskandr/knnimpute/blob/9a1b8abed9ce6c07a606f3f28cf45333e84d62f4/knnimpute/optimistic.py#L21-L152 | def knn_impute_optimistic(
X,
missing_mask,
k,
verbose=False,
print_interval=100):
"""
Fill in the given incomplete matrix using k-nearest neighbor imputation.
This version assumes that most of the time the same neighbors will be
used so first performs the weighted average of a row's k-nearest neighbors
and checks afterward whether it was valid (due to possible missing values).
Has been observed to be a lot faster for 1/4 missing images matrix
with 1000 rows and ~9000 columns.
Parameters
----------
X : np.ndarray
Matrix to fill of shape (n_samples, n_features)
missing_mask : np.ndarray
Boolean array of same shape as X
k : int
verbose : bool
Modifies X by replacing its missing values with weighted averages of
similar rows. Returns the modified X.
"""
start_t = time.time()
n_rows, n_cols = X.shape
X_row_major, D, _ = knn_initialize(X, missing_mask, verbose=verbose)
D_sorted_indices = np.argsort(D, axis=1)
X_column_major = X_row_major.copy(order="F")
dot = np.dot
# preallocate array to prevent repeated creation in the following loops
neighbor_weights = np.ones(k, dtype=X.dtype)
missing_mask_column_major = np.asarray(missing_mask, order="F")
observed_mask_column_major = ~missing_mask_column_major
for i in range(n_rows):
missing_columns = np.where(missing_mask[i])[0]
if verbose and i % print_interval == 0:
print(
"Imputing row %d/%d with %d missing, elapsed time: %0.3f" % (
i + 1,
n_rows,
len(missing_columns),
time.time() - start_t))
n_missing_columns = len(missing_columns)
if n_missing_columns == 0:
continue
row_distances = D[i, :]
neighbor_indices = D_sorted_indices[i, :]
X_missing_columns = X_column_major[:, missing_columns]
# precompute these for the fast path where the k nearest neighbors
# are not missing the feature value we're currently trying to impute
k_nearest_indices = neighbor_indices[:k]
np.divide(1.0, row_distances[k_nearest_indices], out=neighbor_weights)
# optimistically impute all the columns from the k nearest neighbors
# we'll have to back-track for some of the columns for which
# one of the neighbors did not have a value
X_knn = X_missing_columns[k_nearest_indices, :]
weighted_average_of_neighboring_rows = dot(
X_knn.T,
neighbor_weights)
sum_weights = neighbor_weights.sum()
weighted_average_of_neighboring_rows /= sum_weights
imputed_values = weighted_average_of_neighboring_rows
observed_mask_missing_columns = observed_mask_column_major[:, missing_columns]
observed_mask_missing_columns_sorted = observed_mask_missing_columns[
neighbor_indices, :]
# We can determine the maximum number of other rows that must be
# inspected across all features missing for this row by
# looking at the column-wise running sums of the observed feature
# matrix.
observed_cumulative_sum = observed_mask_missing_columns_sorted.cumsum(axis=0)
sufficient_rows = (observed_cumulative_sum == k)
n_rows_needed = sufficient_rows.argmax(axis=0) + 1
max_rows_needed = n_rows_needed.max()
if max_rows_needed == k:
# if we never needed more than k rows then we're done after the
# optimistic averaging above, so go on to the next sample
X[i, missing_columns] = imputed_values
continue
# truncate all the sorted arrays to only include the necessary
# number of rows (should significantly speed up the "slow" path)
necessary_indices = neighbor_indices[:max_rows_needed]
d_sorted = row_distances[necessary_indices]
X_missing_columns_sorted = X_missing_columns[necessary_indices, :]
observed_mask_missing_columns_sorted = observed_mask_missing_columns_sorted[
:max_rows_needed, :]
for missing_column_idx in range(n_missing_columns):
# since all the arrays we're looking into have already been
# sliced out at the missing features, we need to address these
# features from 0..n_missing using missing_idx rather than j
if n_rows_needed[missing_column_idx] == k:
assert np.isfinite(imputed_values[missing_column_idx]), \
"Expected finite imputed value #%d (column #%d for row %d)" % (
missing_column_idx,
missing_columns[missing_column_idx],
i)
continue
row_mask = observed_mask_missing_columns_sorted[:, missing_column_idx]
sorted_column_values = X_missing_columns_sorted[:, missing_column_idx]
neighbor_distances = d_sorted[row_mask][:k]
# may not have enough values in a column for all k neighbors
k_or_less = len(neighbor_distances)
usable_weights = neighbor_weights[:k_or_less]
np.divide(
1.0,
neighbor_distances, out=usable_weights)
neighbor_values = sorted_column_values[row_mask][:k_or_less]
imputed_values[missing_column_idx] = (
dot(neighbor_values, usable_weights) / usable_weights.sum())
X[i, missing_columns] = imputed_values
return X | [
"def",
"knn_impute_optimistic",
"(",
"X",
",",
"missing_mask",
",",
"k",
",",
"verbose",
"=",
"False",
",",
"print_interval",
"=",
"100",
")",
":",
"start_t",
"=",
"time",
".",
"time",
"(",
")",
"n_rows",
",",
"n_cols",
"=",
"X",
".",
"shape",
"X_row_m... | Fill in the given incomplete matrix using k-nearest neighbor imputation.
This version assumes that most of the time the same neighbors will be
used so first performs the weighted average of a row's k-nearest neighbors
and checks afterward whether it was valid (due to possible missing values).
Has been observed to be a lot faster for 1/4 missing images matrix
with 1000 rows and ~9000 columns.
Parameters
----------
X : np.ndarray
Matrix to fill of shape (n_samples, n_features)
missing_mask : np.ndarray
Boolean array of same shape as X
k : int
verbose : bool
Modifies X by replacing its missing values with weighted averages of
similar rows. Returns the modified X. | [
"Fill",
"in",
"the",
"given",
"incomplete",
"matrix",
"using",
"k",
"-",
"nearest",
"neighbor",
"imputation",
"."
] | python | train |
decryptus/sonicprobe | sonicprobe/libs/workerpool.py | https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/workerpool.py#L237-L248 | def killall(self, wait = None):
"""
Kill all active workers.
@wait: Seconds to wait until last worker ends.
If None it waits forever.
"""
with self.tasks.mutex:
self.tasks.queue.clear()
self.count_lock.acquire()
self.kill(self.workers)
self.count_lock.release()
self.kill_event.wait(wait) | [
"def",
"killall",
"(",
"self",
",",
"wait",
"=",
"None",
")",
":",
"with",
"self",
".",
"tasks",
".",
"mutex",
":",
"self",
".",
"tasks",
".",
"queue",
".",
"clear",
"(",
")",
"self",
".",
"count_lock",
".",
"acquire",
"(",
")",
"self",
".",
"kil... | Kill all active workers.
@wait: Seconds to wait until last worker ends.
If None it waits forever. | [
"Kill",
"all",
"active",
"workers",
"."
] | python | train |
yymao/easyquery | easyquery.py | https://github.com/yymao/easyquery/blob/cd94c100e26f59042cd9ffb26d0a7b61cdcd457d/easyquery.py#L266-L282 | def count(self, table):
"""
Use the current Query object to count the number of entries in `table`
that satisfy `queries`.
Parameters
----------
table : NumPy structured array, astropy Table, etc.
Returns
-------
count : int
"""
if self._operator is None and self._operands is None:
return self._get_table_len(table)
return np.count_nonzero(self.mask(table)) | [
"def",
"count",
"(",
"self",
",",
"table",
")",
":",
"if",
"self",
".",
"_operator",
"is",
"None",
"and",
"self",
".",
"_operands",
"is",
"None",
":",
"return",
"self",
".",
"_get_table_len",
"(",
"table",
")",
"return",
"np",
".",
"count_nonzero",
"("... | Use the current Query object to count the number of entries in `table`
that satisfy `queries`.
Parameters
----------
table : NumPy structured array, astropy Table, etc.
Returns
-------
count : int | [
"Use",
"the",
"current",
"Query",
"object",
"to",
"count",
"the",
"number",
"of",
"entries",
"in",
"table",
"that",
"satisfy",
"queries",
"."
] | python | train |
santoshphilip/eppy | eppy/results/readhtml.py | https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/results/readhtml.py#L49-L64 | def table2matrix(table):
"""convert a table to a list of lists - a 2D matrix"""
if not is_simpletable(table):
raise NotSimpleTable("Not able read a cell in the table as a string")
rows = []
for tr in table('tr'):
row = []
for td in tr('td'):
td = tdbr2EOL(td) # convert any '<br>' in the td to line ending
try:
row.append(td.contents[0])
except IndexError:
row.append('')
rows.append(row)
return rows | [
"def",
"table2matrix",
"(",
"table",
")",
":",
"if",
"not",
"is_simpletable",
"(",
"table",
")",
":",
"raise",
"NotSimpleTable",
"(",
"\"Not able read a cell in the table as a string\"",
")",
"rows",
"=",
"[",
"]",
"for",
"tr",
"in",
"table",
"(",
"'tr'",
")",... | convert a table to a list of lists - a 2D matrix | [
"convert",
"a",
"table",
"to",
"a",
"list",
"of",
"lists",
"-",
"a",
"2D",
"matrix"
] | python | train |
evolbioinfo/pastml | pastml/ml.py | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/ml.py#L458-L473 | def check_marginal_likelihoods(tree, feature):
"""
Sanity check: combined bottom-up and top-down likelihood of each node of the tree must be the same.
:param tree: ete3.Tree, the tree of interest
:param feature: str, character for which the likelihood is calculated
:return: void, stores the node marginal likelihoods in the get_personalised_feature_name(feature, LH) feature.
"""
lh_feature = get_personalized_feature_name(feature, LH)
lh_sf_feature = get_personalized_feature_name(feature, LH_SF)
for node in tree.traverse():
if not node.is_root() and not (node.is_leaf() and node.dist == 0):
node_loglh = np.log10(getattr(node, lh_feature).sum()) - getattr(node, lh_sf_feature)
parent_loglh = np.log10(getattr(node.up, lh_feature).sum()) - getattr(node.up, lh_sf_feature)
assert (round(node_loglh, 2) == round(parent_loglh, 2)) | [
"def",
"check_marginal_likelihoods",
"(",
"tree",
",",
"feature",
")",
":",
"lh_feature",
"=",
"get_personalized_feature_name",
"(",
"feature",
",",
"LH",
")",
"lh_sf_feature",
"=",
"get_personalized_feature_name",
"(",
"feature",
",",
"LH_SF",
")",
"for",
"node",
... | Sanity check: combined bottom-up and top-down likelihood of each node of the tree must be the same.
:param tree: ete3.Tree, the tree of interest
:param feature: str, character for which the likelihood is calculated
:return: void, stores the node marginal likelihoods in the get_personalised_feature_name(feature, LH) feature. | [
"Sanity",
"check",
":",
"combined",
"bottom",
"-",
"up",
"and",
"top",
"-",
"down",
"likelihood",
"of",
"each",
"node",
"of",
"the",
"tree",
"must",
"be",
"the",
"same",
"."
] | python | train |
rwl/pylon | pyreto/continuous/experiment.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/continuous/experiment.py#L249-L258 | def reset(self):
""" Sets initial conditions for the experiment.
"""
self.stepid = 0
for task, agent in zip(self.tasks, self.agents):
task.reset()
agent.module.reset()
agent.history.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"stepid",
"=",
"0",
"for",
"task",
",",
"agent",
"in",
"zip",
"(",
"self",
".",
"tasks",
",",
"self",
".",
"agents",
")",
":",
"task",
".",
"reset",
"(",
")",
"agent",
".",
"module",
".",
"res... | Sets initial conditions for the experiment. | [
"Sets",
"initial",
"conditions",
"for",
"the",
"experiment",
"."
] | python | train |
Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/common/cloudstorageaccount.py | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/common/cloudstorageaccount.py#L51-L66 | def create_block_blob_service(self):
'''
Creates a BlockBlobService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.blob.blockblobservice.BlockBlobService`
'''
try:
from azure.storage.blob.blockblobservice import BlockBlobService
return BlockBlobService(self.account_name, self.account_key,
sas_token=self.sas_token,
is_emulated=self.is_emulated)
except ImportError:
raise Exception('The package azure-storage-blob is required. '
+ 'Please install it using "pip install azure-storage-blob"') | [
"def",
"create_block_blob_service",
"(",
"self",
")",
":",
"try",
":",
"from",
"azure",
".",
"storage",
".",
"blob",
".",
"blockblobservice",
"import",
"BlockBlobService",
"return",
"BlockBlobService",
"(",
"self",
".",
"account_name",
",",
"self",
".",
"account... | Creates a BlockBlobService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.blob.blockblobservice.BlockBlobService` | [
"Creates",
"a",
"BlockBlobService",
"object",
"with",
"the",
"settings",
"specified",
"in",
"the",
"CloudStorageAccount",
"."
] | python | train |
RJT1990/pyflux | pyflux/inference/bbvi.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/inference/bbvi.py#L115-L120 | def draw_normal(self):
"""
Draw parameters from a mean-field normal family
"""
means, scale = self.get_means_and_scales()
return np.random.normal(means,scale,size=[self.sims,means.shape[0]]).T | [
"def",
"draw_normal",
"(",
"self",
")",
":",
"means",
",",
"scale",
"=",
"self",
".",
"get_means_and_scales",
"(",
")",
"return",
"np",
".",
"random",
".",
"normal",
"(",
"means",
",",
"scale",
",",
"size",
"=",
"[",
"self",
".",
"sims",
",",
"means"... | Draw parameters from a mean-field normal family | [
"Draw",
"parameters",
"from",
"a",
"mean",
"-",
"field",
"normal",
"family"
] | python | train |
mozillazg/python-shanbay | shanbay/api.py | https://github.com/mozillazg/python-shanbay/blob/d505ba614dc13a36afce46969d13fc64e10dde0d/shanbay/api.py#L66-L74 | def examples(self, word_id, type=None,
url='https://api.shanbay.com/bdc/example/'):
"""获取单词的例句"""
params = {
'vocabulary_id': word_id
}
if type is not None:
params['type'] = type
return self._request(url, params=params).json() | [
"def",
"examples",
"(",
"self",
",",
"word_id",
",",
"type",
"=",
"None",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/example/'",
")",
":",
"params",
"=",
"{",
"'vocabulary_id'",
":",
"word_id",
"}",
"if",
"type",
"is",
"not",
"None",
":",
"params",
"["... | 获取单词的例句 | [
"获取单词的例句"
] | python | train |
Phyks/libbmc | libbmc/tools.py | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/tools.py#L16-L36 | def replace_all(text, replace_dict):
"""
Replace multiple strings in a text.
.. note::
Replacements are made successively, without any warranty on the order \
in which they are made.
:param text: Text to replace in.
:param replace_dict: Dictionary mapping strings to replace with their \
substitution.
:returns: Text after replacements.
>>> replace_all("foo bar foo thing", {"foo": "oof", "bar": "rab"})
'oof rab oof thing'
"""
for i, j in replace_dict.items():
text = text.replace(i, j)
return text | [
"def",
"replace_all",
"(",
"text",
",",
"replace_dict",
")",
":",
"for",
"i",
",",
"j",
"in",
"replace_dict",
".",
"items",
"(",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"i",
",",
"j",
")",
"return",
"text"
] | Replace multiple strings in a text.
.. note::
Replacements are made successively, without any warranty on the order \
in which they are made.
:param text: Text to replace in.
:param replace_dict: Dictionary mapping strings to replace with their \
substitution.
:returns: Text after replacements.
>>> replace_all("foo bar foo thing", {"foo": "oof", "bar": "rab"})
'oof rab oof thing' | [
"Replace",
"multiple",
"strings",
"in",
"a",
"text",
"."
] | python | train |
python-cmd2/cmd2 | cmd2/cmd2.py | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L3796-L3827 | def disable_command(self, command: str, message_to_print: str) -> None:
"""
Disable a command and overwrite its functions
:param command: the command being disabled
:param message_to_print: what to print when this command is run or help is called on it while disabled
The variable COMMAND_NAME can be used as a placeholder for the name of the
command being disabled.
ex: message_to_print = "{} is currently disabled".format(COMMAND_NAME)
"""
import functools
# If the commands is already disabled, then return
if command in self.disabled_commands:
return
# Make sure this is an actual command
command_function = self.cmd_func(command)
if command_function is None:
raise AttributeError("{} does not refer to a command".format(command))
help_func_name = HELP_FUNC_PREFIX + command
# Add the disabled command record
self.disabled_commands[command] = DisabledCommand(command_function=command_function,
help_function=getattr(self, help_func_name, None))
# Overwrite the command and help functions to print the message
new_func = functools.partial(self._report_disabled_command_usage,
message_to_print=message_to_print.replace(COMMAND_NAME, command))
setattr(self, self.cmd_func_name(command), new_func)
setattr(self, help_func_name, new_func) | [
"def",
"disable_command",
"(",
"self",
",",
"command",
":",
"str",
",",
"message_to_print",
":",
"str",
")",
"->",
"None",
":",
"import",
"functools",
"# If the commands is already disabled, then return",
"if",
"command",
"in",
"self",
".",
"disabled_commands",
":",... | Disable a command and overwrite its functions
:param command: the command being disabled
:param message_to_print: what to print when this command is run or help is called on it while disabled
The variable COMMAND_NAME can be used as a placeholder for the name of the
command being disabled.
ex: message_to_print = "{} is currently disabled".format(COMMAND_NAME) | [
"Disable",
"a",
"command",
"and",
"overwrite",
"its",
"functions",
":",
"param",
"command",
":",
"the",
"command",
"being",
"disabled",
":",
"param",
"message_to_print",
":",
"what",
"to",
"print",
"when",
"this",
"command",
"is",
"run",
"or",
"help",
"is",
... | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L206-L210 | def shakeshake2_equal_grad(x1, x2, dy):
"""Overriding gradient for shake-shake of 2 tensors."""
y = shakeshake2_py(x1, x2, equal=True)
dx = tf.gradients(ys=[y], xs=[x1, x2], grad_ys=[dy])
return dx | [
"def",
"shakeshake2_equal_grad",
"(",
"x1",
",",
"x2",
",",
"dy",
")",
":",
"y",
"=",
"shakeshake2_py",
"(",
"x1",
",",
"x2",
",",
"equal",
"=",
"True",
")",
"dx",
"=",
"tf",
".",
"gradients",
"(",
"ys",
"=",
"[",
"y",
"]",
",",
"xs",
"=",
"[",... | Overriding gradient for shake-shake of 2 tensors. | [
"Overriding",
"gradient",
"for",
"shake",
"-",
"shake",
"of",
"2",
"tensors",
"."
] | python | train |
relwell/corenlp-xml-lib | corenlp_xml/document.py | https://github.com/relwell/corenlp-xml-lib/blob/9b0f8c912ba3ecedd34473f74a9f2d033a75baf9/corenlp_xml/document.py#L386-L398 | def character_offset_begin(self):
"""
Lazy-loads character offset begin node
:getter: Returns the integer value of the beginning offset
:type: int
"""
if self._character_offset_begin is None:
offsets = self._element.xpath('CharacterOffsetBegin/text()')
if len(offsets) > 0:
self._character_offset_begin = int(offsets[0])
return self._character_offset_begin | [
"def",
"character_offset_begin",
"(",
"self",
")",
":",
"if",
"self",
".",
"_character_offset_begin",
"is",
"None",
":",
"offsets",
"=",
"self",
".",
"_element",
".",
"xpath",
"(",
"'CharacterOffsetBegin/text()'",
")",
"if",
"len",
"(",
"offsets",
")",
">",
... | Lazy-loads character offset begin node
:getter: Returns the integer value of the beginning offset
:type: int | [
"Lazy",
"-",
"loads",
"character",
"offset",
"begin",
"node"
] | python | train |
jbarlow83/OCRmyPDF | src/ocrmypdf/leptonica.py | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/leptonica.py#L402-L412 | def remove_colormap(self, removal_type):
"""Remove a palette (colormap); if no colormap, returns a copy of this
image
removal_type - any of lept.REMOVE_CMAP_*
"""
with _LeptonicaErrorTrap():
return Pix(
lept.pixRemoveColormapGeneral(self._cdata, removal_type, lept.L_COPY)
) | [
"def",
"remove_colormap",
"(",
"self",
",",
"removal_type",
")",
":",
"with",
"_LeptonicaErrorTrap",
"(",
")",
":",
"return",
"Pix",
"(",
"lept",
".",
"pixRemoveColormapGeneral",
"(",
"self",
".",
"_cdata",
",",
"removal_type",
",",
"lept",
".",
"L_COPY",
")... | Remove a palette (colormap); if no colormap, returns a copy of this
image
removal_type - any of lept.REMOVE_CMAP_* | [
"Remove",
"a",
"palette",
"(",
"colormap",
")",
";",
"if",
"no",
"colormap",
"returns",
"a",
"copy",
"of",
"this",
"image"
] | python | train |
saimn/sigal | sigal/video.py | https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/video.py#L38-L59 | def check_subprocess(cmd, source, outname):
"""Run the command to resize the video and remove the output file if the
processing fails.
"""
logger = logging.getLogger(__name__)
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except KeyboardInterrupt:
logger.debug('Process terminated, removing file %s', outname)
if os.path.isfile(outname):
os.remove(outname)
raise
if res.returncode:
logger.debug('STDOUT:\n %s', res.stdout.decode('utf8'))
logger.debug('STDERR:\n %s', res.stderr.decode('utf8'))
if os.path.isfile(outname):
logger.debug('Removing file %s', outname)
os.remove(outname)
raise SubprocessException('Failed to process ' + source) | [
"def",
"check_subprocess",
"(",
"cmd",
",",
"source",
",",
"outname",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"try",
":",
"res",
"=",
"subprocess",
".",
"run",
"(",
"cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE... | Run the command to resize the video and remove the output file if the
processing fails. | [
"Run",
"the",
"command",
"to",
"resize",
"the",
"video",
"and",
"remove",
"the",
"output",
"file",
"if",
"the",
"processing",
"fails",
"."
] | python | valid |
tensorflow/tensorboard | tensorboard/plugins/pr_curve/pr_curves_plugin.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/pr_curve/pr_curves_plugin.py#L314-L341 | def is_active(self):
"""Determines whether this plugin is active.
This plugin is active only if PR curve summary data is read by TensorBoard.
Returns:
Whether this plugin is active.
"""
if self._db_connection_provider:
# The plugin is active if one relevant tag can be found in the database.
db = self._db_connection_provider()
cursor = db.execute(
'''
SELECT 1
FROM Tags
WHERE Tags.plugin_name = ?
LIMIT 1
''',
(metadata.PLUGIN_NAME,))
return bool(list(cursor))
if not self._multiplexer:
return False
all_runs = self._multiplexer.PluginRunToTagToContent(metadata.PLUGIN_NAME)
# The plugin is active if any of the runs has a tag relevant to the plugin.
return any(six.itervalues(all_runs)) | [
"def",
"is_active",
"(",
"self",
")",
":",
"if",
"self",
".",
"_db_connection_provider",
":",
"# The plugin is active if one relevant tag can be found in the database.",
"db",
"=",
"self",
".",
"_db_connection_provider",
"(",
")",
"cursor",
"=",
"db",
".",
"execute",
... | Determines whether this plugin is active.
This plugin is active only if PR curve summary data is read by TensorBoard.
Returns:
Whether this plugin is active. | [
"Determines",
"whether",
"this",
"plugin",
"is",
"active",
"."
] | python | train |
pycontribs/pyrax | pyrax/object_storage.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/object_storage.py#L1649-L1656 | def move(self, new_container, new_obj_name=None, extra_info=None):
"""
Works just like copy_object, except that this object is deleted after a
successful copy. This means that this storage_object reference will no
longer be valid.
"""
return self.container.move_object(self, new_container,
new_obj_name=new_obj_name) | [
"def",
"move",
"(",
"self",
",",
"new_container",
",",
"new_obj_name",
"=",
"None",
",",
"extra_info",
"=",
"None",
")",
":",
"return",
"self",
".",
"container",
".",
"move_object",
"(",
"self",
",",
"new_container",
",",
"new_obj_name",
"=",
"new_obj_name",... | Works just like copy_object, except that this object is deleted after a
successful copy. This means that this storage_object reference will no
longer be valid. | [
"Works",
"just",
"like",
"copy_object",
"except",
"that",
"this",
"object",
"is",
"deleted",
"after",
"a",
"successful",
"copy",
".",
"This",
"means",
"that",
"this",
"storage_object",
"reference",
"will",
"no",
"longer",
"be",
"valid",
"."
] | python | train |
SBRG/ssbio | ssbio/protein/sequence/properties/kinetic_folding_rate.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/properties/kinetic_folding_rate.py#L23-L52 | def get_foldrate(seq, secstruct):
"""Submit sequence and structural class to FOLD-RATE calculator (http://www.iitm.ac.in/bioinfo/fold-rate/)
to calculate kinetic folding rate.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
secstruct (str): Structural class: `all-alpha``, ``all-beta``, ``mixed``, or ``unknown``
Returns:
float: Kinetic folding rate k_f
"""
seq = ssbio.protein.sequence.utils.cast_to_str(seq)
url = 'http://www.iitm.ac.in/bioinfo/cgi-bin/fold-rate/foldrateCalculator.pl'
values = {'sequence': seq, 'eqn': secstruct}
data = urlencode(values)
data = data.encode('ASCII')
response = urlopen(url, data)
result = str(response.read())
ind = str.find(result, 'The folding rate,')
result2 = result[ind:ind + 70]
ind1 = str.find(result2, '=')
ind2 = str.find(result2, '/sec')
rate = result2[ind1 + 2:ind2]
return rate | [
"def",
"get_foldrate",
"(",
"seq",
",",
"secstruct",
")",
":",
"seq",
"=",
"ssbio",
".",
"protein",
".",
"sequence",
".",
"utils",
".",
"cast_to_str",
"(",
"seq",
")",
"url",
"=",
"'http://www.iitm.ac.in/bioinfo/cgi-bin/fold-rate/foldrateCalculator.pl'",
"values",
... | Submit sequence and structural class to FOLD-RATE calculator (http://www.iitm.ac.in/bioinfo/fold-rate/)
to calculate kinetic folding rate.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
secstruct (str): Structural class: `all-alpha``, ``all-beta``, ``mixed``, or ``unknown``
Returns:
float: Kinetic folding rate k_f | [
"Submit",
"sequence",
"and",
"structural",
"class",
"to",
"FOLD",
"-",
"RATE",
"calculator",
"(",
"http",
":",
"//",
"www",
".",
"iitm",
".",
"ac",
".",
"in",
"/",
"bioinfo",
"/",
"fold",
"-",
"rate",
"/",
")",
"to",
"calculate",
"kinetic",
"folding",
... | python | train |
gwastro/pycbc-glue | pycbc_glue/ligolw/ligolw.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ligolw.py#L290-L297 | def appendData(self, content):
"""
Add characters to the element's pcdata.
"""
if self.pcdata is not None:
self.pcdata += content
else:
self.pcdata = content | [
"def",
"appendData",
"(",
"self",
",",
"content",
")",
":",
"if",
"self",
".",
"pcdata",
"is",
"not",
"None",
":",
"self",
".",
"pcdata",
"+=",
"content",
"else",
":",
"self",
".",
"pcdata",
"=",
"content"
] | Add characters to the element's pcdata. | [
"Add",
"characters",
"to",
"the",
"element",
"s",
"pcdata",
"."
] | python | train |
nugget/python-insteonplm | insteonplm/plm.py | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L188-L203 | def start_all_linking(self, mode, group):
"""Put the IM into All-Linking mode.
Puts the IM into All-Linking mode for 4 minutes.
Parameters:
mode: 0 | 1 | 3 | 255
0 - PLM is responder
1 - PLM is controller
3 - Device that initiated All-Linking is Controller
255 = Delete All-Link
group: All-Link group number (0 - 255)
"""
msg = StartAllLinking(mode, group)
self.send_msg(msg) | [
"def",
"start_all_linking",
"(",
"self",
",",
"mode",
",",
"group",
")",
":",
"msg",
"=",
"StartAllLinking",
"(",
"mode",
",",
"group",
")",
"self",
".",
"send_msg",
"(",
"msg",
")"
] | Put the IM into All-Linking mode.
Puts the IM into All-Linking mode for 4 minutes.
Parameters:
mode: 0 | 1 | 3 | 255
0 - PLM is responder
1 - PLM is controller
3 - Device that initiated All-Linking is Controller
255 = Delete All-Link
group: All-Link group number (0 - 255) | [
"Put",
"the",
"IM",
"into",
"All",
"-",
"Linking",
"mode",
"."
] | python | train |
secynic/ipwhois | ipwhois/experimental.py | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/experimental.py#L113-L457 | def bulk_lookup_rdap(addresses=None, inc_raw=False, retry_count=3, depth=0,
excluded_entities=None, rate_limit_timeout=60,
socket_timeout=10, asn_timeout=240, proxy_openers=None):
"""
The function for bulk retrieving and parsing whois information for a list
of IP addresses via HTTP (RDAP). This bulk lookup method uses bulk
ASN Whois lookups first to retrieve the ASN for each IP. It then optimizes
RDAP queries to achieve the fastest overall time, accounting for
rate-limiting RIRs.
Args:
addresses (:obj:`list` of :obj:`str`): IP addresses to lookup.
inc_raw (:obj:`bool`, optional): Whether to include the raw whois
results in the returned dictionary. Defaults to False.
retry_count (:obj:`int`): The number of times to retry in case socket
errors, timeouts, connection resets, etc. are encountered.
Defaults to 3.
depth (:obj:`int`): How many levels deep to run queries when additional
referenced objects are found. Defaults to 0.
excluded_entities (:obj:`list` of :obj:`str`): Entity handles to not
perform lookups. Defaults to None.
rate_limit_timeout (:obj:`int`): The number of seconds to wait before
retrying when a rate limit notice is returned via rdap+json.
Defaults to 60.
socket_timeout (:obj:`int`): The default timeout for socket
connections in seconds. Defaults to 10.
asn_timeout (:obj:`int`): The default timeout for bulk ASN lookups in
seconds. Defaults to 240.
proxy_openers (:obj:`list` of :obj:`OpenerDirector`): Proxy openers
for single/rotating proxy support. Defaults to None.
Returns:
namedtuple:
:results (dict): IP address keys with the values as dictionaries
returned by IPWhois.lookup_rdap().
:stats (dict): Stats for the lookups:
::
{
'ip_input_total' (int) - The total number of addresses
originally provided for lookup via the addresses argument.
'ip_unique_total' (int) - The total number of unique addresses
found in the addresses argument.
'ip_lookup_total' (int) - The total number of addresses that
lookups were attempted for, excluding any that failed ASN
registry checks.
'lacnic' (dict) -
{
'failed' (list) - The addresses that failed to lookup.
Excludes any that failed initially, but succeeded after
futher retries.
'rate_limited' (list) - The addresses that encountered
rate-limiting. Unless an address is also in 'failed',
it eventually succeeded.
'total' (int) - The total number of addresses belonging to
this RIR that lookups were attempted for.
}
'ripencc' (dict) - Same as 'lacnic' above.
'apnic' (dict) - Same as 'lacnic' above.
'afrinic' (dict) - Same as 'lacnic' above.
'arin' (dict) - Same as 'lacnic' above.
'unallocated_addresses' (list) - The addresses that are
unallocated/failed ASN lookups. These can be addresses that
are not listed for one of the 5 RIRs (other). No attempt
was made to perform an RDAP lookup for these.
}
Raises:
ASNLookupError: The ASN bulk lookup failed, cannot proceed with bulk
RDAP lookup.
"""
if not isinstance(addresses, list):
raise ValueError('addresses must be a list of IP address strings')
# Initialize the dicts/lists
results = {}
failed_lookups_dict = {}
rated_lookups = []
stats = {
'ip_input_total': len(addresses),
'ip_unique_total': 0,
'ip_lookup_total': 0,
'lacnic': {'failed': [], 'rate_limited': [], 'total': 0},
'ripencc': {'failed': [], 'rate_limited': [], 'total': 0},
'apnic': {'failed': [], 'rate_limited': [], 'total': 0},
'afrinic': {'failed': [], 'rate_limited': [], 'total': 0},
'arin': {'failed': [], 'rate_limited': [], 'total': 0},
'unallocated_addresses': []
}
asn_parsed_results = {}
if proxy_openers is None:
proxy_openers = [None]
proxy_openers_copy = iter(proxy_openers)
# Make sure addresses is unique
unique_ip_list = list(unique_everseen(addresses))
# Get the unique count to return
stats['ip_unique_total'] = len(unique_ip_list)
# This is needed for iteration order
rir_keys_ordered = ['lacnic', 'ripencc', 'apnic', 'afrinic', 'arin']
# First query the ASN data for all IPs, can raise ASNLookupError, no catch
bulk_asn = get_bulk_asn_whois(unique_ip_list, timeout=asn_timeout)
# ASN results are returned as string, parse lines to list and remove first
asn_result_list = bulk_asn.split('\n')
del asn_result_list[0]
# We need to instantiate IPASN, which currently needs a Net object,
# IP doesn't matter here
net = Net('1.2.3.4')
ipasn = IPASN(net)
# Iterate each IP ASN result, and add valid RIR results to
# asn_parsed_results for RDAP lookups
for asn_result in asn_result_list:
temp = asn_result.split('|')
# Not a valid entry, move on to next
if len(temp) == 1:
continue
ip = temp[1].strip()
# We need this since ASN bulk lookup is returning duplicates
# This is an issue on the Cymru end
if ip in asn_parsed_results.keys(): # pragma: no cover
continue
try:
results = ipasn.parse_fields_whois(asn_result)
except ASNRegistryError: # pragma: no cover
continue
# Add valid IP ASN result to asn_parsed_results for RDAP lookup
asn_parsed_results[ip] = results
stats[results['asn_registry']]['total'] += 1
# Set the list of IPs that are not allocated/failed ASN lookup
stats['unallocated_addresses'] = list(k for k in addresses if k not in
asn_parsed_results)
# Set the total lookup count after unique IP and ASN result filtering
stats['ip_lookup_total'] = len(asn_parsed_results)
# Track the total number of LACNIC queries left. This is tracked in order
# to ensure the 9 priority LACNIC queries/min don't go into infinite loop
lacnic_total_left = stats['lacnic']['total']
# Set the start time, this value is updated when the rate limit is reset
old_time = time.time()
# Rate limit tracking dict for all RIRs
rate_tracker = {
'lacnic': {'time': old_time, 'count': 0},
'ripencc': {'time': old_time, 'count': 0},
'apnic': {'time': old_time, 'count': 0},
'afrinic': {'time': old_time, 'count': 0},
'arin': {'time': old_time, 'count': 0}
}
# Iterate all of the IPs to perform RDAP lookups until none are left
while len(asn_parsed_results) > 0:
# Sequentially run through each RIR to minimize lookups in a row to
# the same RIR.
for rir in rir_keys_ordered:
# If there are still LACNIC IPs left to lookup and the rate limit
# hasn't been reached, skip to find a LACNIC IP to lookup
if (
rir != 'lacnic' and lacnic_total_left > 0 and
(rate_tracker['lacnic']['count'] != 9 or
(time.time() - rate_tracker['lacnic']['time']
) >= rate_limit_timeout
)
): # pragma: no cover
continue
# If the RIR rate limit has been reached and hasn't expired,
# move on to the next RIR
if (
rate_tracker[rir]['count'] == 9 and (
(time.time() - rate_tracker[rir]['time']
) < rate_limit_timeout)
): # pragma: no cover
continue
# If the RIR rate limit has expired, reset the count/timer
# and perform the lookup
elif ((time.time() - rate_tracker[rir]['time']
) >= rate_limit_timeout): # pragma: no cover
rate_tracker[rir]['count'] = 0
rate_tracker[rir]['time'] = time.time()
# Create a copy of the lookup IP dict so we can modify on
# successful/failed queries. Loop each IP until it matches the
# correct RIR in the parent loop, and attempt lookup
tmp_dict = asn_parsed_results.copy()
for ip, asn_data in tmp_dict.items():
# Check to see if IP matches parent loop RIR for lookup
if asn_data['asn_registry'] == rir:
log.debug('Starting lookup for IP: {0} '
'RIR: {1}'.format(ip, rir))
# Add to count for rate-limit tracking only for LACNIC,
# since we have not seen aggressive rate-limiting from the
# other RIRs yet
if rir == 'lacnic':
rate_tracker[rir]['count'] += 1
# Get the next proxy opener to use, or None
try:
opener = next(proxy_openers_copy)
# Start at the beginning if all have been used
except StopIteration:
proxy_openers_copy = iter(proxy_openers)
opener = next(proxy_openers_copy)
# Instantiate the objects needed for the RDAP lookup
net = Net(ip, timeout=socket_timeout, proxy_opener=opener)
rdap = RDAP(net)
try:
# Perform the RDAP lookup. retry_count is set to 0
# here since we handle that in this function
results = rdap.lookup(
inc_raw=inc_raw, retry_count=0, asn_data=asn_data,
depth=depth, excluded_entities=excluded_entities
)
log.debug('Successful lookup for IP: {0} '
'RIR: {1}'.format(ip, rir))
# Lookup was successful, add to result. Set the nir
# key to None as this is not supported
# (yet - requires more queries)
results[ip] = results
results[ip]['nir'] = None
# Remove the IP from the lookup queue
del asn_parsed_results[ip]
# If this was LACNIC IP, reduce the total left count
if rir == 'lacnic':
lacnic_total_left -= 1
log.debug(
'{0} total lookups left, {1} LACNIC lookups left'
''.format(str(len(asn_parsed_results)),
str(lacnic_total_left))
)
# If this IP failed previously, remove it from the
# failed return dict
if (
ip in failed_lookups_dict.keys()
): # pragma: no cover
del failed_lookups_dict[ip]
# Break out of the IP list loop, we need to change to
# the next RIR
break
except HTTPLookupError: # pragma: no cover
log.debug('Failed lookup for IP: {0} '
'RIR: {1}'.format(ip, rir))
# Add the IP to the failed lookups dict if not there
if ip not in failed_lookups_dict.keys():
failed_lookups_dict[ip] = 1
# This IP has already failed at least once, increment
# the failure count until retry_count reached, then
# stop trying
else:
failed_lookups_dict[ip] += 1
if failed_lookups_dict[ip] == retry_count:
del asn_parsed_results[ip]
stats[rir]['failed'].append(ip)
if rir == 'lacnic':
lacnic_total_left -= 1
# Since this IP failed, we don't break to move to next
# RIR, we check the next IP for this RIR
continue
except HTTPRateLimitError: # pragma: no cover
# Add the IP to the rate-limited lookups dict if not
# there
if ip not in rated_lookups:
rated_lookups.append(ip)
stats[rir]['rate_limited'].append(ip)
log.debug('Rate limiting triggered for IP: {0} '
'RIR: {1}'.format(ip, rir))
# Since rate-limit was reached, reset the timer and
# max out the count
rate_tracker[rir]['time'] = time.time()
rate_tracker[rir]['count'] = 9
# Break out of the IP list loop, we need to change to
# the next RIR
break
return_tuple = namedtuple('return_tuple', ['results', 'stats'])
return return_tuple(results, stats) | [
"def",
"bulk_lookup_rdap",
"(",
"addresses",
"=",
"None",
",",
"inc_raw",
"=",
"False",
",",
"retry_count",
"=",
"3",
",",
"depth",
"=",
"0",
",",
"excluded_entities",
"=",
"None",
",",
"rate_limit_timeout",
"=",
"60",
",",
"socket_timeout",
"=",
"10",
","... | The function for bulk retrieving and parsing whois information for a list
of IP addresses via HTTP (RDAP). This bulk lookup method uses bulk
ASN Whois lookups first to retrieve the ASN for each IP. It then optimizes
RDAP queries to achieve the fastest overall time, accounting for
rate-limiting RIRs.
Args:
addresses (:obj:`list` of :obj:`str`): IP addresses to lookup.
inc_raw (:obj:`bool`, optional): Whether to include the raw whois
results in the returned dictionary. Defaults to False.
retry_count (:obj:`int`): The number of times to retry in case socket
errors, timeouts, connection resets, etc. are encountered.
Defaults to 3.
depth (:obj:`int`): How many levels deep to run queries when additional
referenced objects are found. Defaults to 0.
excluded_entities (:obj:`list` of :obj:`str`): Entity handles to not
perform lookups. Defaults to None.
rate_limit_timeout (:obj:`int`): The number of seconds to wait before
retrying when a rate limit notice is returned via rdap+json.
Defaults to 60.
socket_timeout (:obj:`int`): The default timeout for socket
connections in seconds. Defaults to 10.
asn_timeout (:obj:`int`): The default timeout for bulk ASN lookups in
seconds. Defaults to 240.
proxy_openers (:obj:`list` of :obj:`OpenerDirector`): Proxy openers
for single/rotating proxy support. Defaults to None.
Returns:
namedtuple:
:results (dict): IP address keys with the values as dictionaries
returned by IPWhois.lookup_rdap().
:stats (dict): Stats for the lookups:
::
{
'ip_input_total' (int) - The total number of addresses
originally provided for lookup via the addresses argument.
'ip_unique_total' (int) - The total number of unique addresses
found in the addresses argument.
'ip_lookup_total' (int) - The total number of addresses that
lookups were attempted for, excluding any that failed ASN
registry checks.
'lacnic' (dict) -
{
'failed' (list) - The addresses that failed to lookup.
Excludes any that failed initially, but succeeded after
futher retries.
'rate_limited' (list) - The addresses that encountered
rate-limiting. Unless an address is also in 'failed',
it eventually succeeded.
'total' (int) - The total number of addresses belonging to
this RIR that lookups were attempted for.
}
'ripencc' (dict) - Same as 'lacnic' above.
'apnic' (dict) - Same as 'lacnic' above.
'afrinic' (dict) - Same as 'lacnic' above.
'arin' (dict) - Same as 'lacnic' above.
'unallocated_addresses' (list) - The addresses that are
unallocated/failed ASN lookups. These can be addresses that
are not listed for one of the 5 RIRs (other). No attempt
was made to perform an RDAP lookup for these.
}
Raises:
ASNLookupError: The ASN bulk lookup failed, cannot proceed with bulk
RDAP lookup. | [
"The",
"function",
"for",
"bulk",
"retrieving",
"and",
"parsing",
"whois",
"information",
"for",
"a",
"list",
"of",
"IP",
"addresses",
"via",
"HTTP",
"(",
"RDAP",
")",
".",
"This",
"bulk",
"lookup",
"method",
"uses",
"bulk",
"ASN",
"Whois",
"lookups",
"fir... | python | train |
cytoscape/py2cytoscape | py2cytoscape/cyrest/network.py | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/network.py#L600-L617 | def load_url(self, url=None, verbose=False):
"""
Load a new network from a URL that points to a network file type (e.g.
SIF, XGMML, etc.). Use network import url to load networks from Excel or
csv files. This command will create a new network collection if no current
network collection is selected, otherwise it will add the network to the
current collection. The SUIDs of the new networks and views are returned.
:param url (string): Select a URL that points to a network format file.
This command does not support csv or Excel files. Use network import
url for that.
:param verbose: print more
:returns: { SUIDs of the new networks and views }
"""
PARAMS=set_param(["url"],[url])
response=api(url=self.__url+"/load url", PARAMS=PARAMS, method="POST", verbose=verbose)
return response | [
"def",
"load_url",
"(",
"self",
",",
"url",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"PARAMS",
"=",
"set_param",
"(",
"[",
"\"url\"",
"]",
",",
"[",
"url",
"]",
")",
"response",
"=",
"api",
"(",
"url",
"=",
"self",
".",
"__url",
"+",
... | Load a new network from a URL that points to a network file type (e.g.
SIF, XGMML, etc.). Use network import url to load networks from Excel or
csv files. This command will create a new network collection if no current
network collection is selected, otherwise it will add the network to the
current collection. The SUIDs of the new networks and views are returned.
:param url (string): Select a URL that points to a network format file.
This command does not support csv or Excel files. Use network import
url for that.
:param verbose: print more
:returns: { SUIDs of the new networks and views } | [
"Load",
"a",
"new",
"network",
"from",
"a",
"URL",
"that",
"points",
"to",
"a",
"network",
"file",
"type",
"(",
"e",
".",
"g",
".",
"SIF",
"XGMML",
"etc",
".",
")",
".",
"Use",
"network",
"import",
"url",
"to",
"load",
"networks",
"from",
"Excel",
... | python | train |
shmir/PyIxExplorer | ixexplorer/ixe_app.py | https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L197-L204 | def wait_transmit(self, *ports):
""" Wait for traffic end on ports.
:param ports: list of ports to wait for, if empty wait for all ports.
"""
port_list = self.set_ports_list(*ports)
self.api.call_rc('ixCheckTransmitDone {}'.format(port_list)) | [
"def",
"wait_transmit",
"(",
"self",
",",
"*",
"ports",
")",
":",
"port_list",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"ports",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixCheckTransmitDone {}'",
".",
"format",
"(",
"port_list",
")",
")"
] | Wait for traffic end on ports.
:param ports: list of ports to wait for, if empty wait for all ports. | [
"Wait",
"for",
"traffic",
"end",
"on",
"ports",
"."
] | python | train |
inveniosoftware/invenio-oauth2server | invenio_oauth2server/models.py | https://github.com/inveniosoftware/invenio-oauth2server/blob/7033d3495c1a2b830e101e43918e92a37bbb49f2/invenio_oauth2server/models.py#L278-L285 | def get_users(self):
"""Get number of users."""
no_users = Token.query.filter_by(
client_id=self.client_id,
is_personal=False,
is_internal=False
).count()
return no_users | [
"def",
"get_users",
"(",
"self",
")",
":",
"no_users",
"=",
"Token",
".",
"query",
".",
"filter_by",
"(",
"client_id",
"=",
"self",
".",
"client_id",
",",
"is_personal",
"=",
"False",
",",
"is_internal",
"=",
"False",
")",
".",
"count",
"(",
")",
"retu... | Get number of users. | [
"Get",
"number",
"of",
"users",
"."
] | python | train |
openpermissions/koi | koi/commands.py | https://github.com/openpermissions/koi/blob/d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281/koi/commands.py#L331-L336 | def cli(main, conf_dir=None, commands_dir=None):
"""Convenience function for initialising a Command CLI
For parameter definitions see :class:`.Command`
"""
return Command(main, conf_dir=conf_dir, commands_dir=commands_dir)() | [
"def",
"cli",
"(",
"main",
",",
"conf_dir",
"=",
"None",
",",
"commands_dir",
"=",
"None",
")",
":",
"return",
"Command",
"(",
"main",
",",
"conf_dir",
"=",
"conf_dir",
",",
"commands_dir",
"=",
"commands_dir",
")",
"(",
")"
] | Convenience function for initialising a Command CLI
For parameter definitions see :class:`.Command` | [
"Convenience",
"function",
"for",
"initialising",
"a",
"Command",
"CLI"
] | python | train |
angr/angr | angr/procedures/stubs/format_parser.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/procedures/stubs/format_parser.py#L517-L525 | def _sim_atoi_inner(self, str_addr, region, base=10, read_length=None):
"""
Return the result of invoking the atoi simprocedure on `str_addr`.
"""
from .. import SIM_PROCEDURES
strtol = SIM_PROCEDURES['libc']['strtol']
return strtol.strtol_inner(str_addr, self.state, region, base, True, read_length=read_length) | [
"def",
"_sim_atoi_inner",
"(",
"self",
",",
"str_addr",
",",
"region",
",",
"base",
"=",
"10",
",",
"read_length",
"=",
"None",
")",
":",
"from",
".",
".",
"import",
"SIM_PROCEDURES",
"strtol",
"=",
"SIM_PROCEDURES",
"[",
"'libc'",
"]",
"[",
"'strtol'",
... | Return the result of invoking the atoi simprocedure on `str_addr`. | [
"Return",
"the",
"result",
"of",
"invoking",
"the",
"atoi",
"simprocedure",
"on",
"str_addr",
"."
] | python | train |
isambard-uob/ampal | src/ampal/base_ampal.py | https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/base_ampal.py#L605-L626 | def close_monomers(self, group, cutoff=4.0):
"""Returns a list of Monomers from within a cut off distance of the Monomer
Parameters
----------
group: BaseAmpal or Subclass
Group to be search for Monomers that are close to this Monomer.
cutoff: float
Distance cut off.
Returns
-------
nearby_residues: [Monomers]
List of Monomers within cut off distance.
"""
nearby_residues = []
for self_atom in self.atoms.values():
nearby_atoms = group.is_within(cutoff, self_atom)
for res_atom in nearby_atoms:
if res_atom.parent not in nearby_residues:
nearby_residues.append(res_atom.parent)
return nearby_residues | [
"def",
"close_monomers",
"(",
"self",
",",
"group",
",",
"cutoff",
"=",
"4.0",
")",
":",
"nearby_residues",
"=",
"[",
"]",
"for",
"self_atom",
"in",
"self",
".",
"atoms",
".",
"values",
"(",
")",
":",
"nearby_atoms",
"=",
"group",
".",
"is_within",
"("... | Returns a list of Monomers from within a cut off distance of the Monomer
Parameters
----------
group: BaseAmpal or Subclass
Group to be search for Monomers that are close to this Monomer.
cutoff: float
Distance cut off.
Returns
-------
nearby_residues: [Monomers]
List of Monomers within cut off distance. | [
"Returns",
"a",
"list",
"of",
"Monomers",
"from",
"within",
"a",
"cut",
"off",
"distance",
"of",
"the",
"Monomer"
] | python | train |
psd-tools/psd-tools | src/psd_tools/utils.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L28-L38 | def read_fmt(fmt, fp):
"""
Reads data from ``fp`` according to ``fmt``.
"""
fmt = str(">" + fmt)
fmt_size = struct.calcsize(fmt)
data = fp.read(fmt_size)
assert len(data) == fmt_size, 'read=%d, expected=%d' % (
len(data), fmt_size
)
return struct.unpack(fmt, data) | [
"def",
"read_fmt",
"(",
"fmt",
",",
"fp",
")",
":",
"fmt",
"=",
"str",
"(",
"\">\"",
"+",
"fmt",
")",
"fmt_size",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"data",
"=",
"fp",
".",
"read",
"(",
"fmt_size",
")",
"assert",
"len",
"(",
"data",... | Reads data from ``fp`` according to ``fmt``. | [
"Reads",
"data",
"from",
"fp",
"according",
"to",
"fmt",
"."
] | python | train |
fastai/fastai | fastai/vision/data.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/data.py#L71-L75 | def normalize_funcs(mean:FloatTensor, std:FloatTensor, do_x:bool=True, do_y:bool=False)->Tuple[Callable,Callable]:
"Create normalize/denormalize func using `mean` and `std`, can specify `do_y` and `device`."
mean,std = tensor(mean),tensor(std)
return (partial(_normalize_batch, mean=mean, std=std, do_x=do_x, do_y=do_y),
partial(denormalize, mean=mean, std=std, do_x=do_x)) | [
"def",
"normalize_funcs",
"(",
"mean",
":",
"FloatTensor",
",",
"std",
":",
"FloatTensor",
",",
"do_x",
":",
"bool",
"=",
"True",
",",
"do_y",
":",
"bool",
"=",
"False",
")",
"->",
"Tuple",
"[",
"Callable",
",",
"Callable",
"]",
":",
"mean",
",",
"st... | Create normalize/denormalize func using `mean` and `std`, can specify `do_y` and `device`. | [
"Create",
"normalize",
"/",
"denormalize",
"func",
"using",
"mean",
"and",
"std",
"can",
"specify",
"do_y",
"and",
"device",
"."
] | python | train |
kislyuk/aegea | aegea/packages/github3/issues/issue.py | https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/issues/issue.py#L116-L128 | def assign(self, login):
"""Assigns user ``login`` to this issue. This is a short cut for
``issue.edit``.
:param str login: username of the person to assign this issue to
:returns: bool
"""
if not login:
return False
number = self.milestone.number if self.milestone else None
labels = [str(l) for l in self.labels]
return self.edit(self.title, self.body, login, self.state, number,
labels) | [
"def",
"assign",
"(",
"self",
",",
"login",
")",
":",
"if",
"not",
"login",
":",
"return",
"False",
"number",
"=",
"self",
".",
"milestone",
".",
"number",
"if",
"self",
".",
"milestone",
"else",
"None",
"labels",
"=",
"[",
"str",
"(",
"l",
")",
"f... | Assigns user ``login`` to this issue. This is a short cut for
``issue.edit``.
:param str login: username of the person to assign this issue to
:returns: bool | [
"Assigns",
"user",
"login",
"to",
"this",
"issue",
".",
"This",
"is",
"a",
"short",
"cut",
"for",
"issue",
".",
"edit",
"."
] | python | train |
celiao/tmdbsimple | tmdbsimple/movies.py | https://github.com/celiao/tmdbsimple/blob/ff17893110c99771d6398a62c35d36dd9735f4b9/tmdbsimple/movies.py#L253-L269 | def reviews(self, **kwargs):
"""
Get the reviews for a particular movie id.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('reviews')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | [
"def",
"reviews",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_id_path",
"(",
"'reviews'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs_to_values",
"(",
"respons... | Get the reviews for a particular movie id.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API. | [
"Get",
"the",
"reviews",
"for",
"a",
"particular",
"movie",
"id",
"."
] | python | test |
spyder-ide/spyder | spyder/widgets/calltip.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L200-L206 | def hideEvent(self, event):
""" Reimplemented to disconnect signal handlers and event filter.
"""
super(CallTipWidget, self).hideEvent(event)
self._text_edit.cursorPositionChanged.disconnect(
self._cursor_position_changed)
self._text_edit.removeEventFilter(self) | [
"def",
"hideEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"CallTipWidget",
",",
"self",
")",
".",
"hideEvent",
"(",
"event",
")",
"self",
".",
"_text_edit",
".",
"cursorPositionChanged",
".",
"disconnect",
"(",
"self",
".",
"_cursor_position_cha... | Reimplemented to disconnect signal handlers and event filter. | [
"Reimplemented",
"to",
"disconnect",
"signal",
"handlers",
"and",
"event",
"filter",
"."
] | python | train |
tensorforce/tensorforce | tensorforce/core/optimizers/tf_optimizer.py | https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/tf_optimizer.py#L53-L77 | def tf_step(self, time, variables, **kwargs):
"""
Keyword Args:
arguments: Dict of arguments for passing to fn_loss as **kwargs.
fn_loss: A callable taking arguments as kwargs and returning the loss op of the current model.
"""
arguments = kwargs["arguments"]
fn_loss = kwargs["fn_loss"]
loss = fn_loss(**arguments)
# Force loss value to be calculated.
with tf.control_dependencies(control_inputs=(loss,)):
# Trivial operation to enforce control dependency
previous_variables = [variable + 0.0 for variable in variables]
# The actual tensorflow minimize op.
with tf.control_dependencies(control_inputs=previous_variables):
applied = self.tf_optimizer.minimize(loss=loss, var_list=variables) # colocate_gradients_with_ops=True
# Return deltas after actually having change the variables.
with tf.control_dependencies(control_inputs=(applied,)):
return [
variable - previous_variable
for variable, previous_variable in zip(variables, previous_variables)
] | [
"def",
"tf_step",
"(",
"self",
",",
"time",
",",
"variables",
",",
"*",
"*",
"kwargs",
")",
":",
"arguments",
"=",
"kwargs",
"[",
"\"arguments\"",
"]",
"fn_loss",
"=",
"kwargs",
"[",
"\"fn_loss\"",
"]",
"loss",
"=",
"fn_loss",
"(",
"*",
"*",
"arguments... | Keyword Args:
arguments: Dict of arguments for passing to fn_loss as **kwargs.
fn_loss: A callable taking arguments as kwargs and returning the loss op of the current model. | [
"Keyword",
"Args",
":",
"arguments",
":",
"Dict",
"of",
"arguments",
"for",
"passing",
"to",
"fn_loss",
"as",
"**",
"kwargs",
".",
"fn_loss",
":",
"A",
"callable",
"taking",
"arguments",
"as",
"kwargs",
"and",
"returning",
"the",
"loss",
"op",
"of",
"the",... | python | valid |
softlayer/softlayer-python | SoftLayer/CLI/dns/zone_list.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/zone_list.py#L13-L30 | def cli(env):
"""List all zones."""
manager = SoftLayer.DNSManager(env.client)
zones = manager.list_zones()
table = formatting.Table(['id', 'zone', 'serial', 'updated'])
table.align['serial'] = 'c'
table.align['updated'] = 'c'
for zone in zones:
table.add_row([
zone['id'],
zone['name'],
zone['serial'],
zone['updateDate'],
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"DNSManager",
"(",
"env",
".",
"client",
")",
"zones",
"=",
"manager",
".",
"list_zones",
"(",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'zone'",
",",
... | List all zones. | [
"List",
"all",
"zones",
"."
] | python | train |
apple/turicreate | src/unity/python/turicreate/toolkits/activity_classifier/_activity_classifier.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/activity_classifier/_activity_classifier.py#L745-L795 | def classify(self, dataset, output_frequency='per_row'):
"""
Return a classification, for each ``prediction_window`` examples in the
``dataset``, using the trained activity classification model. The output
SFrame contains predictions as both class labels as well as probabilities
that the predicted value is the associated label.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include columns with the same
names as the features and session id used for model training, but
does not require a target column. Additional columns are ignored.
output_frequency : {'per_row', 'per_window'}, optional
The frequency of the predictions which is one of:
- 'per_row': Each prediction is returned ``prediction_window`` times.
- 'per_window': Return a single prediction for each
``prediction_window`` rows in ``dataset`` per ``session_id``.
Returns
-------
out : SFrame
An SFrame with model predictions i.e class labels and probabilities.
See Also
----------
create, evaluate, predict
Examples
----------
>>> classes = model.classify(data)
"""
_tkutl._check_categorical_option_type(
'output_frequency', output_frequency, ['per_window', 'per_row'])
id_target_map = self._id_target_map
preds = self.predict(
dataset, output_type='probability_vector', output_frequency=output_frequency)
if output_frequency == 'per_row':
return _SFrame({
'class': preds.apply(lambda p: id_target_map[_np.argmax(p)]),
'probability': preds.apply(_np.max)
})
elif output_frequency == 'per_window':
preds['class'] = preds['probability_vector'].apply(
lambda p: id_target_map[_np.argmax(p)])
preds['probability'] = preds['probability_vector'].apply(_np.max)
preds = preds.remove_column('probability_vector')
return preds | [
"def",
"classify",
"(",
"self",
",",
"dataset",
",",
"output_frequency",
"=",
"'per_row'",
")",
":",
"_tkutl",
".",
"_check_categorical_option_type",
"(",
"'output_frequency'",
",",
"output_frequency",
",",
"[",
"'per_window'",
",",
"'per_row'",
"]",
")",
"id_targ... | Return a classification, for each ``prediction_window`` examples in the
``dataset``, using the trained activity classification model. The output
SFrame contains predictions as both class labels as well as probabilities
that the predicted value is the associated label.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include columns with the same
names as the features and session id used for model training, but
does not require a target column. Additional columns are ignored.
output_frequency : {'per_row', 'per_window'}, optional
The frequency of the predictions which is one of:
- 'per_row': Each prediction is returned ``prediction_window`` times.
- 'per_window': Return a single prediction for each
``prediction_window`` rows in ``dataset`` per ``session_id``.
Returns
-------
out : SFrame
An SFrame with model predictions i.e class labels and probabilities.
See Also
----------
create, evaluate, predict
Examples
----------
>>> classes = model.classify(data) | [
"Return",
"a",
"classification",
"for",
"each",
"prediction_window",
"examples",
"in",
"the",
"dataset",
"using",
"the",
"trained",
"activity",
"classification",
"model",
".",
"The",
"output",
"SFrame",
"contains",
"predictions",
"as",
"both",
"class",
"labels",
"... | python | train |
apache/airflow | airflow/contrib/hooks/gcs_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcs_hook.py#L208-L221 | def exists(self, bucket_name, object_name):
"""
Checks for the existence of a file in Google Cloud Storage.
:param bucket_name: The Google cloud storage bucket where the object is.
:type bucket_name: str
:param object_name: The name of the blob_name to check in the Google cloud
storage bucket.
:type object_name: str
"""
client = self.get_conn()
bucket = client.get_bucket(bucket_name=bucket_name)
blob = bucket.blob(blob_name=object_name)
return blob.exists() | [
"def",
"exists",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
")",
":",
"client",
"=",
"self",
".",
"get_conn",
"(",
")",
"bucket",
"=",
"client",
".",
"get_bucket",
"(",
"bucket_name",
"=",
"bucket_name",
")",
"blob",
"=",
"bucket",
".",
"blob",... | Checks for the existence of a file in Google Cloud Storage.
:param bucket_name: The Google cloud storage bucket where the object is.
:type bucket_name: str
:param object_name: The name of the blob_name to check in the Google cloud
storage bucket.
:type object_name: str | [
"Checks",
"for",
"the",
"existence",
"of",
"a",
"file",
"in",
"Google",
"Cloud",
"Storage",
"."
] | python | test |
klmitch/policies | policies/instructions.py | https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/instructions.py#L961-L982 | def fold(self, elems):
"""
Perform constant folding. If the result of applying the
operator to the elements would be a fixed constant value,
returns the result of applying the operator to the operands.
Otherwise, returns an instance of ``Instructions`` containing
the instructions necessary to apply the operator.
:param elems: A list (or list-like object) containing the
elements.
:returns: A list of one element, containing the instructions
necessary to implement the operator.
"""
cond, if_true, if_false = elems
if isinstance(cond, Constant):
return [if_true if cond.value else if_false]
return [Instructions([cond, JumpIfNot(len(if_true) + 2), pop, if_true,
Jump(len(if_false) + 1), pop, if_false])] | [
"def",
"fold",
"(",
"self",
",",
"elems",
")",
":",
"cond",
",",
"if_true",
",",
"if_false",
"=",
"elems",
"if",
"isinstance",
"(",
"cond",
",",
"Constant",
")",
":",
"return",
"[",
"if_true",
"if",
"cond",
".",
"value",
"else",
"if_false",
"]",
"ret... | Perform constant folding. If the result of applying the
operator to the elements would be a fixed constant value,
returns the result of applying the operator to the operands.
Otherwise, returns an instance of ``Instructions`` containing
the instructions necessary to apply the operator.
:param elems: A list (or list-like object) containing the
elements.
:returns: A list of one element, containing the instructions
necessary to implement the operator. | [
"Perform",
"constant",
"folding",
".",
"If",
"the",
"result",
"of",
"applying",
"the",
"operator",
"to",
"the",
"elements",
"would",
"be",
"a",
"fixed",
"constant",
"value",
"returns",
"the",
"result",
"of",
"applying",
"the",
"operator",
"to",
"the",
"opera... | python | train |
etscrivner/nose-perfdump | perfdump/connection.py | https://github.com/etscrivner/nose-perfdump/blob/a203a68495d30346fab43fb903cb60cd29b17d49/perfdump/connection.py#L38-L72 | def connect(cls, dbname):
"""Create a new connection to the SQLite3 database.
:param dbname: The database name
:type dbname: str
"""
test_times_schema = """
CREATE TABLE IF NOT EXISTS test_times (
file text,
module text,
class text,
func text,
elapsed float
)
"""
setup_times_schema = """
CREATE TABLE IF NOT EXISTS setup_times (
file text,
module text,
class text,
func text,
elapsed float
)
"""
schemas = [test_times_schema,
setup_times_schema]
db_file = '{}.db'.format(dbname)
cls.connection = sqlite3.connect(db_file)
for s in schemas:
cls.connection.execute(s) | [
"def",
"connect",
"(",
"cls",
",",
"dbname",
")",
":",
"test_times_schema",
"=",
"\"\"\"\n CREATE TABLE IF NOT EXISTS test_times (\n file text,\n module text,\n class text,\n func text,\n elapsed float\n )\n \"\"\"",
"setup_time... | Create a new connection to the SQLite3 database.
:param dbname: The database name
:type dbname: str | [
"Create",
"a",
"new",
"connection",
"to",
"the",
"SQLite3",
"database",
"."
] | python | train |
pydata/numexpr | numexpr/necompiler.py | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L765-L834 | def evaluate(ex, local_dict=None, global_dict=None,
out=None, order='K', casting='safe', **kwargs):
"""Evaluate a simple array expression element-wise, using the new iterator.
ex is a string forming an expression, like "2*a+3*b". The values for "a"
and "b" will by default be taken from the calling function's frame
(through use of sys._getframe()). Alternatively, they can be specifed
using the 'local_dict' or 'global_dict' arguments.
Parameters
----------
local_dict : dictionary, optional
A dictionary that replaces the local operands in current frame.
global_dict : dictionary, optional
A dictionary that replaces the global operands in current frame.
out : NumPy array, optional
An existing array where the outcome is going to be stored. Care is
required so that this array has the same shape and type than the
actual outcome of the computation. Useful for avoiding unnecessary
new array allocations.
order : {'C', 'F', 'A', or 'K'}, optional
Controls the iteration order for operands. 'C' means C order, 'F'
means Fortran order, 'A' means 'F' order if all the arrays are
Fortran contiguous, 'C' order otherwise, and 'K' means as close to
the order the array elements appear in memory as possible. For
efficient computations, typically 'K'eep order (the default) is
desired.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur when making a copy or
buffering. Setting this to 'unsafe' is not recommended, as it can
adversely affect accumulations.
* 'no' means the data types should not be cast at all.
* 'equiv' means only byte-order changes are allowed.
* 'safe' means only casts which can preserve values are allowed.
* 'same_kind' means only safe casts or casts within a kind,
like float64 to float32, are allowed.
* 'unsafe' means any data conversions may be done.
"""
global _numexpr_last
if not isinstance(ex, (str, unicode)):
raise ValueError("must specify expression as a string")
# Get the names for this expression
context = getContext(kwargs, frame_depth=1)
expr_key = (ex, tuple(sorted(context.items())))
if expr_key not in _names_cache:
_names_cache[expr_key] = getExprNames(ex, context)
names, ex_uses_vml = _names_cache[expr_key]
arguments = getArguments(names, local_dict, global_dict)
# Create a signature
signature = [(name, getType(arg)) for (name, arg) in
zip(names, arguments)]
# Look up numexpr if possible.
numexpr_key = expr_key + (tuple(signature),)
try:
compiled_ex = _numexpr_cache[numexpr_key]
except KeyError:
compiled_ex = _numexpr_cache[numexpr_key] = NumExpr(ex, signature, **context)
kwargs = {'out': out, 'order': order, 'casting': casting,
'ex_uses_vml': ex_uses_vml}
_numexpr_last = dict(ex=compiled_ex, argnames=names, kwargs=kwargs)
with evaluate_lock:
return compiled_ex(*arguments, **kwargs) | [
"def",
"evaluate",
"(",
"ex",
",",
"local_dict",
"=",
"None",
",",
"global_dict",
"=",
"None",
",",
"out",
"=",
"None",
",",
"order",
"=",
"'K'",
",",
"casting",
"=",
"'safe'",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_numexpr_last",
"if",
"not"... | Evaluate a simple array expression element-wise, using the new iterator.
ex is a string forming an expression, like "2*a+3*b". The values for "a"
and "b" will by default be taken from the calling function's frame
(through use of sys._getframe()). Alternatively, they can be specifed
using the 'local_dict' or 'global_dict' arguments.
Parameters
----------
local_dict : dictionary, optional
A dictionary that replaces the local operands in current frame.
global_dict : dictionary, optional
A dictionary that replaces the global operands in current frame.
out : NumPy array, optional
An existing array where the outcome is going to be stored. Care is
required so that this array has the same shape and type than the
actual outcome of the computation. Useful for avoiding unnecessary
new array allocations.
order : {'C', 'F', 'A', or 'K'}, optional
Controls the iteration order for operands. 'C' means C order, 'F'
means Fortran order, 'A' means 'F' order if all the arrays are
Fortran contiguous, 'C' order otherwise, and 'K' means as close to
the order the array elements appear in memory as possible. For
efficient computations, typically 'K'eep order (the default) is
desired.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur when making a copy or
buffering. Setting this to 'unsafe' is not recommended, as it can
adversely affect accumulations.
* 'no' means the data types should not be cast at all.
* 'equiv' means only byte-order changes are allowed.
* 'safe' means only casts which can preserve values are allowed.
* 'same_kind' means only safe casts or casts within a kind,
like float64 to float32, are allowed.
* 'unsafe' means any data conversions may be done. | [
"Evaluate",
"a",
"simple",
"array",
"expression",
"element",
"-",
"wise",
"using",
"the",
"new",
"iterator",
"."
] | python | train |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3181-L3192 | def isabs(self, path):
"""Return True if path is an absolute pathname."""
if self.filesystem.is_windows_fs:
path = self.splitdrive(path)[1]
path = make_string_path(path)
sep = self.filesystem._path_separator(path)
altsep = self.filesystem._alternative_path_separator(path)
if self.filesystem.is_windows_fs:
return len(path) > 0 and path[:1] in (sep, altsep)
else:
return (path.startswith(sep) or
altsep is not None and path.startswith(altsep)) | [
"def",
"isabs",
"(",
"self",
",",
"path",
")",
":",
"if",
"self",
".",
"filesystem",
".",
"is_windows_fs",
":",
"path",
"=",
"self",
".",
"splitdrive",
"(",
"path",
")",
"[",
"1",
"]",
"path",
"=",
"make_string_path",
"(",
"path",
")",
"sep",
"=",
... | Return True if path is an absolute pathname. | [
"Return",
"True",
"if",
"path",
"is",
"an",
"absolute",
"pathname",
"."
] | python | train |
mthh/smoomapy | smoomapy/core.py | https://github.com/mthh/smoomapy/blob/a603a62e76592e84509591fddcde8bfb1e826b84/smoomapy/core.py#L184-L219 | def make_regular_points_with_no_res(bounds, nb_points=10000):
"""
Return a regular grid of points within `bounds` with the specified
number of points (or a close approximate value).
Parameters
----------
bounds : 4-floats tuple
The bbox of the grid, as xmin, ymin, xmax, ymax.
nb_points : int, optionnal
The desired number of points (default: 10000)
Returns
-------
points : numpy.array
An array of coordinates
shape : 2-floats tuple
The number of points on each dimension (width, height)
"""
minlon, minlat, maxlon, maxlat = bounds
minlon, minlat, maxlon, maxlat = bounds
offset_lon = (maxlon - minlon) / 8
offset_lat = (maxlat - minlat) / 8
minlon -= offset_lon
maxlon += offset_lon
minlat -= offset_lat
maxlat += offset_lat
nb_x = int(nb_points**0.5)
nb_y = int(nb_points**0.5)
return (
np.linspace(minlon, maxlon, nb_x),
np.linspace(minlat, maxlat, nb_y),
(nb_y, nb_x)
) | [
"def",
"make_regular_points_with_no_res",
"(",
"bounds",
",",
"nb_points",
"=",
"10000",
")",
":",
"minlon",
",",
"minlat",
",",
"maxlon",
",",
"maxlat",
"=",
"bounds",
"minlon",
",",
"minlat",
",",
"maxlon",
",",
"maxlat",
"=",
"bounds",
"offset_lon",
"=",
... | Return a regular grid of points within `bounds` with the specified
number of points (or a close approximate value).
Parameters
----------
bounds : 4-floats tuple
The bbox of the grid, as xmin, ymin, xmax, ymax.
nb_points : int, optionnal
The desired number of points (default: 10000)
Returns
-------
points : numpy.array
An array of coordinates
shape : 2-floats tuple
The number of points on each dimension (width, height) | [
"Return",
"a",
"regular",
"grid",
"of",
"points",
"within",
"bounds",
"with",
"the",
"specified",
"number",
"of",
"points",
"(",
"or",
"a",
"close",
"approximate",
"value",
")",
"."
] | python | train |
crossbario/txaio-etcd | txaioetcd/_client_pg.py | https://github.com/crossbario/txaio-etcd/blob/c9aebff7f288a0b219bffc9d2579d22cf543baa5/txaioetcd/_client_pg.py#L173-L261 | def get(self,
key,
range_end=None,
count_only=None,
keys_only=None,
limit=None,
max_create_revision=None,
min_create_revision=None,
min_mod_revision=None,
revision=None,
serializable=None,
sort_order=None,
sort_target=None,
timeout=None):
"""
Range gets the keys in the range from the key-value store.
:param key: key is the first key for the range. If range_end is not given,
the request only looks up key.
:type key: bytes
:param range_end: range_end is the upper bound on the requested range
[key, range_end). If range_end is ``\\0``, the range is all keys ``\u003e=`` key.
If the range_end is one bit larger than the given key, then the range requests
get the all keys with the prefix (the given key). If both key and range_end
are ``\\0``, then range requests returns all keys.
:type range_end: bytes
:param prefix: If set, and no range_end is given, compute range_end from key prefix.
:type prefix: bool
:param count_only: count_only when set returns only the count of the keys in the range.
:type count_only: bool
:param keys_only: keys_only when set returns only the keys and not the values.
:type keys_only: bool
:param limit: limit is a limit on the number of keys returned for the request.
:type limit: int
:param max_create_revision: max_create_revision is the upper bound for returned
key create revisions; all keys with greater create revisions will be filtered away.
:type max_create_revision: int
:param max_mod_revision: max_mod_revision is the upper bound for returned key
mod revisions; all keys with greater mod revisions will be filtered away.
:type max_mod_revision: int
:param min_create_revision: min_create_revision is the lower bound for returned
key create revisions; all keys with lesser create trevisions will be filtered away.
:type min_create_revision: int
:param min_mod_revision: min_mod_revision is the lower bound for returned key
mod revisions; all keys with lesser mod revisions will be filtered away.
:type min_min_revision: int
:param revision: revision is the point-in-time of the key-value store to use for the
range. If revision is less or equal to zero, the range is over the newest
key-value store. If the revision has been compacted, ErrCompacted is returned as
a response.
:type revision: int
:param serializable: serializable sets the range request to use serializable
member-local reads. Range requests are linearizable by default; linearizable
requests have higher latency and lower throughput than serializable requests
but reflect the current consensus of the cluster. For better performance, in
exchange for possible stale reads, a serializable range request is served
locally without needing to reach consensus with other nodes in the cluster.
:type serializable: bool
:param sort_order: Sort order for returned KVs,
one of :class:`txaioetcd.OpGet.SORT_ORDERS`.
:type sort_order: str
:param sort_target: Sort target for sorting returned KVs,
one of :class:`txaioetcd.OpGet.SORT_TARGETS`.
:type sort_taget: str or None
:param timeout: Request timeout in seconds.
:type timeout: int or None
"""
def run(pg_txn):
pg_txn.execute("SELECT pgetcd.get(%s,%s)", (Binary(key), 10))
rows = pg_txn.fetchall()
res = "{0}".format(rows[0][0])
return res
return self._pool.runInteraction(run) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"range_end",
"=",
"None",
",",
"count_only",
"=",
"None",
",",
"keys_only",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"max_create_revision",
"=",
"None",
",",
"min_create_revision",
"=",
"None",
",",
"min_mo... | Range gets the keys in the range from the key-value store.
:param key: key is the first key for the range. If range_end is not given,
the request only looks up key.
:type key: bytes
:param range_end: range_end is the upper bound on the requested range
[key, range_end). If range_end is ``\\0``, the range is all keys ``\u003e=`` key.
If the range_end is one bit larger than the given key, then the range requests
get the all keys with the prefix (the given key). If both key and range_end
are ``\\0``, then range requests returns all keys.
:type range_end: bytes
:param prefix: If set, and no range_end is given, compute range_end from key prefix.
:type prefix: bool
:param count_only: count_only when set returns only the count of the keys in the range.
:type count_only: bool
:param keys_only: keys_only when set returns only the keys and not the values.
:type keys_only: bool
:param limit: limit is a limit on the number of keys returned for the request.
:type limit: int
:param max_create_revision: max_create_revision is the upper bound for returned
key create revisions; all keys with greater create revisions will be filtered away.
:type max_create_revision: int
:param max_mod_revision: max_mod_revision is the upper bound for returned key
mod revisions; all keys with greater mod revisions will be filtered away.
:type max_mod_revision: int
:param min_create_revision: min_create_revision is the lower bound for returned
key create revisions; all keys with lesser create trevisions will be filtered away.
:type min_create_revision: int
:param min_mod_revision: min_mod_revision is the lower bound for returned key
mod revisions; all keys with lesser mod revisions will be filtered away.
:type min_min_revision: int
:param revision: revision is the point-in-time of the key-value store to use for the
range. If revision is less or equal to zero, the range is over the newest
key-value store. If the revision has been compacted, ErrCompacted is returned as
a response.
:type revision: int
:param serializable: serializable sets the range request to use serializable
member-local reads. Range requests are linearizable by default; linearizable
requests have higher latency and lower throughput than serializable requests
but reflect the current consensus of the cluster. For better performance, in
exchange for possible stale reads, a serializable range request is served
locally without needing to reach consensus with other nodes in the cluster.
:type serializable: bool
:param sort_order: Sort order for returned KVs,
one of :class:`txaioetcd.OpGet.SORT_ORDERS`.
:type sort_order: str
:param sort_target: Sort target for sorting returned KVs,
one of :class:`txaioetcd.OpGet.SORT_TARGETS`.
:type sort_taget: str or None
:param timeout: Request timeout in seconds.
:type timeout: int or None | [
"Range",
"gets",
"the",
"keys",
"in",
"the",
"range",
"from",
"the",
"key",
"-",
"value",
"store",
"."
] | python | train |
fastai/fastai | fastai/vision/transform.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L235-L246 | def _find_coeffs(orig_pts:Points, targ_pts:Points)->Tensor:
"Find 8 coeff mentioned [here](https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/)."
matrix = []
#The equations we'll need to solve.
for p1, p2 in zip(targ_pts, orig_pts):
matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]])
matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]])
A = FloatTensor(matrix)
B = FloatTensor(orig_pts).view(8, 1)
#The 8 scalars we seek are solution of AX = B
return _solve_func(B,A)[0][:,0] | [
"def",
"_find_coeffs",
"(",
"orig_pts",
":",
"Points",
",",
"targ_pts",
":",
"Points",
")",
"->",
"Tensor",
":",
"matrix",
"=",
"[",
"]",
"#The equations we'll need to solve.",
"for",
"p1",
",",
"p2",
"in",
"zip",
"(",
"targ_pts",
",",
"orig_pts",
")",
":"... | Find 8 coeff mentioned [here](https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/). | [
"Find",
"8",
"coeff",
"mentioned",
"[",
"here",
"]",
"(",
"https",
":",
"//",
"web",
".",
"archive",
".",
"org",
"/",
"web",
"/",
"20150222120106",
"/",
"xenia",
".",
"media",
".",
"mit",
".",
"edu",
"/",
"~cwren",
"/",
"interpolator",
"/",
")",
".... | python | train |
n8henrie/urlmon | urlmon/urlmon.py | https://github.com/n8henrie/urlmon/blob/ebd58358843d7414f708c818a5c5a96feadd176f/urlmon/urlmon.py#L54-L93 | def push(self, message, device=None, title=None, url=None, url_title=None,
priority=None, timestamp=None, sound=None):
"""Pushes the notification, returns the Requests response.
Arguments:
message -- your message
Keyword arguments:
device -- your user's device name to send the message directly to
that device, rather than all of the user's devices
title -- your message's title, otherwise your app's name is used
url -- a supplementary URL to show with your message
url_title -- a title for your supplementary URL, otherwise just the
URL is shown
priority -- send as --1 to always send as a quiet notification, 1
to display as high--priority and bypass the user's quiet hours,
or 2 to also require confirmation from the user
timestamp -- a Unix timestamp of your message's date and time to
display to the user, rather than the time your message is
received by our API
sound -- the name of one of the sounds supported by device clients
to override the user's default sound choice.
"""
api_url = 'https://api.pushover.net/1/messages.json'
payload = {
'token': self.api_token,
'user': self.user,
'message': message,
'device': device,
'title': title,
'url': url,
'url_title': url_title,
'priority': priority,
'timestamp': timestamp,
'sound': sound
}
return requests.post(api_url, params=payload) | [
"def",
"push",
"(",
"self",
",",
"message",
",",
"device",
"=",
"None",
",",
"title",
"=",
"None",
",",
"url",
"=",
"None",
",",
"url_title",
"=",
"None",
",",
"priority",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"sound",
"=",
"None",
")",
... | Pushes the notification, returns the Requests response.
Arguments:
message -- your message
Keyword arguments:
device -- your user's device name to send the message directly to
that device, rather than all of the user's devices
title -- your message's title, otherwise your app's name is used
url -- a supplementary URL to show with your message
url_title -- a title for your supplementary URL, otherwise just the
URL is shown
priority -- send as --1 to always send as a quiet notification, 1
to display as high--priority and bypass the user's quiet hours,
or 2 to also require confirmation from the user
timestamp -- a Unix timestamp of your message's date and time to
display to the user, rather than the time your message is
received by our API
sound -- the name of one of the sounds supported by device clients
to override the user's default sound choice. | [
"Pushes",
"the",
"notification",
"returns",
"the",
"Requests",
"response",
"."
] | python | train |
astropy/photutils | photutils/segmentation/properties.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L674-L683 | def min_value(self):
"""
The minimum pixel value of the ``data`` within the source
segment.
"""
if self._is_completely_masked:
return np.nan * self._data_unit
else:
return np.min(self.values) | [
"def",
"min_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_completely_masked",
":",
"return",
"np",
".",
"nan",
"*",
"self",
".",
"_data_unit",
"else",
":",
"return",
"np",
".",
"min",
"(",
"self",
".",
"values",
")"
] | The minimum pixel value of the ``data`` within the source
segment. | [
"The",
"minimum",
"pixel",
"value",
"of",
"the",
"data",
"within",
"the",
"source",
"segment",
"."
] | python | train |
docker/docker-py | docker/api/secret.py | https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/api/secret.py#L51-L65 | def inspect_secret(self, id):
"""
Retrieve secret metadata
Args:
id (string): Full ID of the secret to remove
Returns (dict): A dictionary of metadata
Raises:
:py:class:`docker.errors.NotFound`
if no secret with that ID exists
"""
url = self._url('/secrets/{0}', id)
return self._result(self._get(url), True) | [
"def",
"inspect_secret",
"(",
"self",
",",
"id",
")",
":",
"url",
"=",
"self",
".",
"_url",
"(",
"'/secrets/{0}'",
",",
"id",
")",
"return",
"self",
".",
"_result",
"(",
"self",
".",
"_get",
"(",
"url",
")",
",",
"True",
")"
] | Retrieve secret metadata
Args:
id (string): Full ID of the secret to remove
Returns (dict): A dictionary of metadata
Raises:
:py:class:`docker.errors.NotFound`
if no secret with that ID exists | [
"Retrieve",
"secret",
"metadata"
] | python | train |
rbaier/python-urltools | urltools/urltools.py | https://github.com/rbaier/python-urltools/blob/76bf599aeb4cb463df8e38367aa40a7d8ec7d9a1/urltools/urltools.py#L150-L175 | def construct(parts):
"""Construct a new URL from parts."""
url = ''
if parts.scheme:
if parts.scheme in SCHEMES:
url += parts.scheme + '://'
else:
url += parts.scheme + ':'
if parts.username and parts.password:
url += parts.username + ':' + parts.password + '@'
elif parts.username:
url += parts.username + '@'
if parts.subdomain:
url += parts.subdomain + '.'
url += parts.domain
if parts.tld:
url += '.' + parts.tld
if parts.port:
url += ':' + parts.port
if parts.path:
url += parts.path
if parts.query:
url += '?' + parts.query
if parts.fragment:
url += '#' + parts.fragment
return url | [
"def",
"construct",
"(",
"parts",
")",
":",
"url",
"=",
"''",
"if",
"parts",
".",
"scheme",
":",
"if",
"parts",
".",
"scheme",
"in",
"SCHEMES",
":",
"url",
"+=",
"parts",
".",
"scheme",
"+",
"'://'",
"else",
":",
"url",
"+=",
"parts",
".",
"scheme"... | Construct a new URL from parts. | [
"Construct",
"a",
"new",
"URL",
"from",
"parts",
"."
] | python | train |
pvizeli/ha-alpr | haalpr.py | https://github.com/pvizeli/ha-alpr/blob/93777c20f3caba3ee832c45ec022b08a2ee7efd6/haalpr.py#L29-L75 | def recognize_byte(self, image, timeout=10):
"""Process a byte image buffer."""
result = []
alpr = subprocess.Popen(
self._cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL
)
# send image
try:
# pylint: disable=unused-variable
stdout, stderr = alpr.communicate(input=image, timeout=10)
stdout = io.StringIO(str(stdout, 'utf-8'))
except subprocess.TimeoutExpired:
_LOGGER.error("Alpr process timeout!")
alpr.kill()
return None
tmp_res = {}
while True:
line = stdout.readline()
if not line:
if len(tmp_res) > 0:
result.append(tmp_res)
break
new_plate = self.__re_plate.search(line)
new_result = self.__re_result.search(line)
# found a new plate
if new_plate and len(tmp_res) > 0:
result.append(tmp_res)
tmp_res = {}
continue
# found plate result
if new_result:
try:
tmp_res[new_result.group(1)] = float(new_result.group(2))
except ValueError:
continue
_LOGGER.debug("Process alpr with result: %s", result)
return result | [
"def",
"recognize_byte",
"(",
"self",
",",
"image",
",",
"timeout",
"=",
"10",
")",
":",
"result",
"=",
"[",
"]",
"alpr",
"=",
"subprocess",
".",
"Popen",
"(",
"self",
".",
"_cmd",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"... | Process a byte image buffer. | [
"Process",
"a",
"byte",
"image",
"buffer",
"."
] | python | train |
qacafe/cdrouter.py | cdrouter/packages.py | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/packages.py#L320-L327 | def bulk_copy(self, ids):
"""Bulk copy a set of packages.
:param ids: Int list of package IDs.
:return: :class:`packages.Package <packages.Package>` list
"""
schema = PackageSchema()
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | [
"def",
"bulk_copy",
"(",
"self",
",",
"ids",
")",
":",
"schema",
"=",
"PackageSchema",
"(",
")",
"return",
"self",
".",
"service",
".",
"bulk_copy",
"(",
"self",
".",
"base",
",",
"self",
".",
"RESOURCE",
",",
"ids",
",",
"schema",
")"
] | Bulk copy a set of packages.
:param ids: Int list of package IDs.
:return: :class:`packages.Package <packages.Package>` list | [
"Bulk",
"copy",
"a",
"set",
"of",
"packages",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/transformer.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/transformer.py#L1808-L1823 | def transformer_tall_finetune_tied():
"""Tied means fine-tune CNN/DM summarization as LM."""
hparams = transformer_tall()
hparams.multiproblem_max_input_length = 750
hparams.multiproblem_max_target_length = 100
hparams.multiproblem_schedule_max_examples = 0
hparams.learning_rate_schedule = ("linear_warmup*constant*cosdecay")
hparams.learning_rate_constant = 5e-5
hparams.learning_rate_warmup_steps = 100
# Set train steps to learning_rate_decay_steps or less
hparams.learning_rate_decay_steps = 80000
hparams.multiproblem_target_eval_only = True
hparams.multiproblem_reweight_label_loss = True
hparams.multiproblem_label_weight = 1.0
hparams.optimizer = "true_adam"
return hparams | [
"def",
"transformer_tall_finetune_tied",
"(",
")",
":",
"hparams",
"=",
"transformer_tall",
"(",
")",
"hparams",
".",
"multiproblem_max_input_length",
"=",
"750",
"hparams",
".",
"multiproblem_max_target_length",
"=",
"100",
"hparams",
".",
"multiproblem_schedule_max_exam... | Tied means fine-tune CNN/DM summarization as LM. | [
"Tied",
"means",
"fine",
"-",
"tune",
"CNN",
"/",
"DM",
"summarization",
"as",
"LM",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/jinja2/filters.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L196-L203 | def do_title(s):
"""Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
"""
return ''.join(
[item[0].upper() + item[1:].lower()
for item in _word_beginning_split_re.split(soft_unicode(s))
if item]) | [
"def",
"do_title",
"(",
"s",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"item",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"item",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
"for",
"item",
"in",
"_word_beginning_split_re",
".",
"split",
... | Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase. | [
"Return",
"a",
"titlecased",
"version",
"of",
"the",
"value",
".",
"I",
".",
"e",
".",
"words",
"will",
"start",
"with",
"uppercase",
"letters",
"all",
"remaining",
"characters",
"are",
"lowercase",
"."
] | python | train |
christophertbrown/bioscripts | ctbBio/strip_align.py | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/strip_align.py#L19-L39 | def strip_msa_100(msa, threshold, plot = False):
"""
strip out columns of a MSA that represent gaps for X percent (threshold) of sequences
"""
msa = [seq for seq in parse_fasta(msa)]
columns = [[0, 0] for pos in msa[0][1]] # [[#bases, #gaps], [#bases, #gaps], ...]
for seq in msa:
for position, base in enumerate(seq[1]):
if base == '-' or base == '.':
columns[position][1] += 1
else:
columns[position][0] += 1
columns = [float(float(g)/float(g+b)*100) for b, g in columns] # convert to percent gaps
for seq in msa:
stripped = []
for position, base in enumerate(seq[1]):
if columns[position] < threshold:
stripped.append(base)
yield [seq[0], ''.join(stripped)]
if plot is not False:
plot_gaps(plot, columns) | [
"def",
"strip_msa_100",
"(",
"msa",
",",
"threshold",
",",
"plot",
"=",
"False",
")",
":",
"msa",
"=",
"[",
"seq",
"for",
"seq",
"in",
"parse_fasta",
"(",
"msa",
")",
"]",
"columns",
"=",
"[",
"[",
"0",
",",
"0",
"]",
"for",
"pos",
"in",
"msa",
... | strip out columns of a MSA that represent gaps for X percent (threshold) of sequences | [
"strip",
"out",
"columns",
"of",
"a",
"MSA",
"that",
"represent",
"gaps",
"for",
"X",
"percent",
"(",
"threshold",
")",
"of",
"sequences"
] | python | train |
usc-isi-i2/dig-sparkutil | digSparkUtil/fileUtil.py | https://github.com/usc-isi-i2/dig-sparkutil/blob/d39c6cf957025c170753b0e02e477fea20ee3f2a/digSparkUtil/fileUtil.py#L131-L151 | def _load_text_csv_file(self, filename, separator=',', **kwargs):
"""Return a pair RDD where key is taken from first column, remaining columns are named after their column id as string"""
rdd_input = self.sc.textFile(filename)
def load_csv_record(line):
input_stream = StringIO.StringIO(line)
reader = csv.reader(input_stream, delimiter=',')
# key in first column, remaining columns 1..n become dict key values
payload = reader.next()
key = payload[0]
rest = payload[1:]
# generate dict of "1": first value, "2": second value, ...
d = {}
for (cell,i) in izip(rest, range(1,1+len(rest))):
d[str(i)] = cell
# just in case, add "0": key
d["0"] = key
return (key, d)
rdd_parsed = rdd_input.map(load_csv_record)
return rdd_parsed | [
"def",
"_load_text_csv_file",
"(",
"self",
",",
"filename",
",",
"separator",
"=",
"','",
",",
"*",
"*",
"kwargs",
")",
":",
"rdd_input",
"=",
"self",
".",
"sc",
".",
"textFile",
"(",
"filename",
")",
"def",
"load_csv_record",
"(",
"line",
")",
":",
"i... | Return a pair RDD where key is taken from first column, remaining columns are named after their column id as string | [
"Return",
"a",
"pair",
"RDD",
"where",
"key",
"is",
"taken",
"from",
"first",
"column",
"remaining",
"columns",
"are",
"named",
"after",
"their",
"column",
"id",
"as",
"string"
] | python | train |
awacha/credolib | credolib/initialization.py | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/initialization.py#L17-L82 | def init_dirs(rootdir_or_loader, outputpath, saveto_dir='data',
auximages_dir='auximages', prefix='crd'):
"""Initialize the directiories.
Inputs:
rootdir_or_loader: depends on the type:
str:
the root directory of the SAXSCtrl/CCT
software, i.e. where the subfolders ``eval2d``, ``param``,
``images``, ``mask`` etc. reside.
sastool.classes2.Loader instance:
a fully initialized loader, which will be used to acquire
headers and exposures.
list:
a list of sastool.classes2.Loader instances, which will
be used to open headers and exposures. When opening something,
always the first item will be tried first, and if it fails with
FileNotFoundError, the second, third, etc. will be tried until
either the file can be opened or the last one fails.
outputpath: the directory where the produced files are
written. This is usually the working directory of
the IPython notebook.
saveto_dir: the subdirectory where averaged, united,
subtracted etc. datasets are written.
auximages_dir: the subdirectory where automatically produced
images reside.
Remarks:
If a single root directory is given, a list of four loaders will be
constructed in this order: CCT (processed), CCT (raw), SAXSCtrl (processed),
SAXSCtrl (raw). Raw and processed loaders are handled separately.
"""
ip = get_ipython()
if isinstance(rootdir_or_loader, str):
print("Initializing loaders for SAXSCtrl and CCT.", flush=True)
ip.user_ns['_loaders'] = [
credo_cct.Loader(rootdir_or_loader, processed=True, exposureclass=prefix),
credo_saxsctrl.Loader(rootdir_or_loader, processed=True, exposureclass=prefix),
credo_cct.Loader(rootdir_or_loader, processed=False, exposureclass=prefix),
credo_saxsctrl.Loader(rootdir_or_loader, processed=False, exposureclass=prefix),
]
print("Loaders initialized.", flush=True)
elif isinstance(rootdir_or_loader, Loader):
ip.user_ns['_loaders'] = [rootdir_or_loader]
elif isinstance(rootdir_or_loader, list) and all([isinstance(l, Loader) for l in rootdir_or_loader]):
ip.user_ns['_loaders'] = rootdir_or_loader[:]
else:
raise TypeError(rootdir_or_loader)
if not os.path.isdir(outputpath):
os.makedirs(outputpath)
print("Output files will be written to:", outputpath)
os.chdir(outputpath)
ip.user_ns['outputpath'] = outputpath
if not os.path.isdir(os.path.join(ip.user_ns['outputpath'], saveto_dir)):
os.mkdir(os.path.join(ip.user_ns['outputpath'], saveto_dir))
if not os.path.isdir(os.path.join(ip.user_ns['outputpath'], auximages_dir)):
os.mkdir(os.path.join(ip.user_ns['outputpath'], auximages_dir))
ip.user_ns['auximages_dir'] = os.path.join(outputpath, auximages_dir)
ip.user_ns['saveto_dir'] = os.path.join(outputpath, saveto_dir)
ip.user_ns['saveto_dir_rel'] = saveto_dir
ip.user_ns['auximages_dir_rel'] = auximages_dir
ip.user_ns['crd_prefix']=prefix
set_length_units('nm') | [
"def",
"init_dirs",
"(",
"rootdir_or_loader",
",",
"outputpath",
",",
"saveto_dir",
"=",
"'data'",
",",
"auximages_dir",
"=",
"'auximages'",
",",
"prefix",
"=",
"'crd'",
")",
":",
"ip",
"=",
"get_ipython",
"(",
")",
"if",
"isinstance",
"(",
"rootdir_or_loader"... | Initialize the directiories.
Inputs:
rootdir_or_loader: depends on the type:
str:
the root directory of the SAXSCtrl/CCT
software, i.e. where the subfolders ``eval2d``, ``param``,
``images``, ``mask`` etc. reside.
sastool.classes2.Loader instance:
a fully initialized loader, which will be used to acquire
headers and exposures.
list:
a list of sastool.classes2.Loader instances, which will
be used to open headers and exposures. When opening something,
always the first item will be tried first, and if it fails with
FileNotFoundError, the second, third, etc. will be tried until
either the file can be opened or the last one fails.
outputpath: the directory where the produced files are
written. This is usually the working directory of
the IPython notebook.
saveto_dir: the subdirectory where averaged, united,
subtracted etc. datasets are written.
auximages_dir: the subdirectory where automatically produced
images reside.
Remarks:
If a single root directory is given, a list of four loaders will be
constructed in this order: CCT (processed), CCT (raw), SAXSCtrl (processed),
SAXSCtrl (raw). Raw and processed loaders are handled separately. | [
"Initialize",
"the",
"directiories",
"."
] | python | train |
spotify/gordon | gordon/record_checker.py | https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/record_checker.py#L54-L94 | async def check_record(self, record, timeout=60):
"""Measures the time for a DNS record to become available.
Query a provided DNS server multiple times until the reply matches the
information in the record or until timeout is reached.
Args:
record (dict): DNS record as a dict with record properties.
timeout (int): Time threshold to query the DNS server.
"""
start_time = time.time()
name, rr_data, r_type, ttl = self._extract_record_data(record)
r_type_code = async_dns.types.get_code(r_type)
resolvable_record = False
retries = 0
sleep_time = 5
while not resolvable_record and \
timeout > retries * sleep_time:
retries += 1
resolver_res = await self._resolver.query(name, r_type_code)
possible_ans = resolver_res.an
resolvable_record = \
await self._check_resolver_ans(possible_ans, name,
rr_data, ttl, r_type_code)
if not resolvable_record:
await asyncio.sleep(sleep_time)
if not resolvable_record:
logging.info(
f'Sending metric record-checker-failed: {record}.')
else:
final_time = float(time.time() - start_time)
success_msg = (f'This record: {record} took {final_time} to '
'register.')
logging.info(success_msg) | [
"async",
"def",
"check_record",
"(",
"self",
",",
"record",
",",
"timeout",
"=",
"60",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"name",
",",
"rr_data",
",",
"r_type",
",",
"ttl",
"=",
"self",
".",
"_extract_record_data",
"(",
"record... | Measures the time for a DNS record to become available.
Query a provided DNS server multiple times until the reply matches the
information in the record or until timeout is reached.
Args:
record (dict): DNS record as a dict with record properties.
timeout (int): Time threshold to query the DNS server. | [
"Measures",
"the",
"time",
"for",
"a",
"DNS",
"record",
"to",
"become",
"available",
"."
] | python | train |
tradenity/python-sdk | tradenity/resources/discount_promotion.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/discount_promotion.py#L892-L913 | def update_discount_promotion_by_id(cls, discount_promotion_id, discount_promotion, **kwargs):
"""Update DiscountPromotion
Update attributes of DiscountPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_discount_promotion_by_id(discount_promotion_id, discount_promotion, async=True)
>>> result = thread.get()
:param async bool
:param str discount_promotion_id: ID of discountPromotion to update. (required)
:param DiscountPromotion discount_promotion: Attributes of discountPromotion to update. (required)
:return: DiscountPromotion
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_discount_promotion_by_id_with_http_info(discount_promotion_id, discount_promotion, **kwargs)
else:
(data) = cls._update_discount_promotion_by_id_with_http_info(discount_promotion_id, discount_promotion, **kwargs)
return data | [
"def",
"update_discount_promotion_by_id",
"(",
"cls",
",",
"discount_promotion_id",
",",
"discount_promotion",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
... | Update DiscountPromotion
Update attributes of DiscountPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_discount_promotion_by_id(discount_promotion_id, discount_promotion, async=True)
>>> result = thread.get()
:param async bool
:param str discount_promotion_id: ID of discountPromotion to update. (required)
:param DiscountPromotion discount_promotion: Attributes of discountPromotion to update. (required)
:return: DiscountPromotion
If the method is called asynchronously,
returns the request thread. | [
"Update",
"DiscountPromotion"
] | python | train |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/structure/keys.py | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/keys.py#L15-L18 | def set_primary_key(self, table, column):
"""Create a Primary Key constraint on a specific column when the table is already created."""
self.execute('ALTER TABLE {0} ADD PRIMARY KEY ({1})'.format(wrap(table), column))
self._printer('\tAdded primary key to {0} on column {1}'.format(wrap(table), column)) | [
"def",
"set_primary_key",
"(",
"self",
",",
"table",
",",
"column",
")",
":",
"self",
".",
"execute",
"(",
"'ALTER TABLE {0} ADD PRIMARY KEY ({1})'",
".",
"format",
"(",
"wrap",
"(",
"table",
")",
",",
"column",
")",
")",
"self",
".",
"_printer",
"(",
"'\\... | Create a Primary Key constraint on a specific column when the table is already created. | [
"Create",
"a",
"Primary",
"Key",
"constraint",
"on",
"a",
"specific",
"column",
"when",
"the",
"table",
"is",
"already",
"created",
"."
] | python | train |
mushkevych/scheduler | synergy/system/repeat_timer.py | https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/system/repeat_timer.py#L48-L52 | def cancel(self):
""" stops the timer. call_back function is not called """
self.event.clear()
if self.__timer is not None:
self.__timer.cancel() | [
"def",
"cancel",
"(",
"self",
")",
":",
"self",
".",
"event",
".",
"clear",
"(",
")",
"if",
"self",
".",
"__timer",
"is",
"not",
"None",
":",
"self",
".",
"__timer",
".",
"cancel",
"(",
")"
] | stops the timer. call_back function is not called | [
"stops",
"the",
"timer",
".",
"call_back",
"function",
"is",
"not",
"called"
] | python | train |
nwilming/ocupy | ocupy/utils.py | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/utils.py#L78-L88 | def calc_resize_factor(prediction, image_size):
"""
Calculates how much prediction.shape and image_size differ.
"""
resize_factor_x = prediction.shape[1] / float(image_size[1])
resize_factor_y = prediction.shape[0] / float(image_size[0])
if abs(resize_factor_x - resize_factor_y) > 1.0/image_size[1] :
raise RuntimeError("""The aspect ratio of the fixations does not
match with the prediction: %f vs. %f"""
%(resize_factor_y, resize_factor_x))
return (resize_factor_y, resize_factor_x) | [
"def",
"calc_resize_factor",
"(",
"prediction",
",",
"image_size",
")",
":",
"resize_factor_x",
"=",
"prediction",
".",
"shape",
"[",
"1",
"]",
"/",
"float",
"(",
"image_size",
"[",
"1",
"]",
")",
"resize_factor_y",
"=",
"prediction",
".",
"shape",
"[",
"0... | Calculates how much prediction.shape and image_size differ. | [
"Calculates",
"how",
"much",
"prediction",
".",
"shape",
"and",
"image_size",
"differ",
"."
] | python | train |
CellProfiler/centrosome | centrosome/cpmorphology.py | https://github.com/CellProfiler/centrosome/blob/7bd9350a2d4ae1b215b81eabcecfe560bbb1f32a/centrosome/cpmorphology.py#L3185-L3204 | def endpoints(image, mask=None):
'''Remove all pixels from an image except for endpoints
image - a skeletonized image
mask - a mask of pixels excluded from consideration
1 0 0 ? 0 0
0 1 0 -> 0 1 0
0 0 0 0 0 0
'''
global endpoints_table
if mask is None:
masked_image = image
else:
masked_image = image.astype(bool).copy()
masked_image[~mask] = False
result = table_lookup(masked_image, endpoints_table, False, 1)
if not mask is None:
result[~mask] = image[~mask]
return result | [
"def",
"endpoints",
"(",
"image",
",",
"mask",
"=",
"None",
")",
":",
"global",
"endpoints_table",
"if",
"mask",
"is",
"None",
":",
"masked_image",
"=",
"image",
"else",
":",
"masked_image",
"=",
"image",
".",
"astype",
"(",
"bool",
")",
".",
"copy",
"... | Remove all pixels from an image except for endpoints
image - a skeletonized image
mask - a mask of pixels excluded from consideration
1 0 0 ? 0 0
0 1 0 -> 0 1 0
0 0 0 0 0 0 | [
"Remove",
"all",
"pixels",
"from",
"an",
"image",
"except",
"for",
"endpoints",
"image",
"-",
"a",
"skeletonized",
"image",
"mask",
"-",
"a",
"mask",
"of",
"pixels",
"excluded",
"from",
"consideration",
"1",
"0",
"0",
"?",
"0",
"0",
"0",
"1",
"0",
"-",... | python | train |
chimera0/accel-brain-code | Reinforcement-Learning/pyqlearning/deep_q_learning.py | https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/deep_q_learning.py#L237-L244 | def get_alpha_value(self):
'''
getter
Learning rate.
'''
if isinstance(self.__alpha_value, float) is False:
raise TypeError("The type of __alpha_value must be float.")
return self.__alpha_value | [
"def",
"get_alpha_value",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"__alpha_value",
",",
"float",
")",
"is",
"False",
":",
"raise",
"TypeError",
"(",
"\"The type of __alpha_value must be float.\"",
")",
"return",
"self",
".",
"__alpha_value"
] | getter
Learning rate. | [
"getter",
"Learning",
"rate",
"."
] | python | train |
pgjones/quart | quart/blueprints.py | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L290-L305 | def add_app_template_global(self, func: Callable, name: Optional[str]=None) -> None:
"""Add an application wide template global.
This is designed to be used on the blueprint directly, and
has the same arguments as
:meth:`~quart.Quart.add_template_global`. An example usage,
.. code-block:: python
def global():
...
blueprint = Blueprint(__name__)
blueprint.add_app_template_global(global)
"""
self.record_once(lambda state: state.register_template_global(func, name)) | [
"def",
"add_app_template_global",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"record_once",
"(",
"lambda",
"state",
":",
"state",
".",
"register_template_globa... | Add an application wide template global.
This is designed to be used on the blueprint directly, and
has the same arguments as
:meth:`~quart.Quart.add_template_global`. An example usage,
.. code-block:: python
def global():
...
blueprint = Blueprint(__name__)
blueprint.add_app_template_global(global) | [
"Add",
"an",
"application",
"wide",
"template",
"global",
"."
] | python | train |
flashashen/flange | flange/iterutils.py | https://github.com/flashashen/flange/blob/67ebaf70e39887f65ce1163168d182a8e4c2774a/flange/iterutils.py#L701-L725 | def same(iterable, ref=_UNSET):
"""``same()`` returns ``True`` when all values in *iterable* are
equal to one another, or optionally a reference value,
*ref*. Similar to :func:`all` and :func:`any` in that it evaluates
an iterable and returns a :class:`bool`. ``same()`` returns
``True`` for empty iterables.
>>> same([])
True
>>> same([1])
True
>>> same(['a', 'a', 'a'])
True
>>> same(range(20))
False
>>> same([[], []])
True
>>> same([[], []], ref='test')
False
"""
iterator = iter(iterable)
if ref is _UNSET:
ref = next(iterator, ref)
return all(val == ref for val in iterator) | [
"def",
"same",
"(",
"iterable",
",",
"ref",
"=",
"_UNSET",
")",
":",
"iterator",
"=",
"iter",
"(",
"iterable",
")",
"if",
"ref",
"is",
"_UNSET",
":",
"ref",
"=",
"next",
"(",
"iterator",
",",
"ref",
")",
"return",
"all",
"(",
"val",
"==",
"ref",
... | ``same()`` returns ``True`` when all values in *iterable* are
equal to one another, or optionally a reference value,
*ref*. Similar to :func:`all` and :func:`any` in that it evaluates
an iterable and returns a :class:`bool`. ``same()`` returns
``True`` for empty iterables.
>>> same([])
True
>>> same([1])
True
>>> same(['a', 'a', 'a'])
True
>>> same(range(20))
False
>>> same([[], []])
True
>>> same([[], []], ref='test')
False | [
"same",
"()",
"returns",
"True",
"when",
"all",
"values",
"in",
"*",
"iterable",
"*",
"are",
"equal",
"to",
"one",
"another",
"or",
"optionally",
"a",
"reference",
"value",
"*",
"ref",
"*",
".",
"Similar",
"to",
":",
"func",
":",
"all",
"and",
":",
"... | python | train |
markuskiller/textblob-de | textblob_de/np_extractors.py | https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/np_extractors.py#L120-L146 | def _filter_extracted(self, extracted_list):
"""Filter insignificant words for key noun phrase extraction.
determiners, relative pronouns, reflexive pronouns
In general, pronouns are not useful, as you need context to know what they refer to.
Most of the pronouns, however, are filtered out by blob.noun_phrase method's
np length (>1) filter
:param list extracted_list: A list of noun phrases extracted from parser output.
"""
_filtered = []
for np in extracted_list:
_np = np.split()
if _np[0] in INSIGNIFICANT:
_np.pop(0)
try:
if _np[-1] in INSIGNIFICANT:
_np.pop(-1)
# e.g. 'welcher die ...'
if _np[0] in INSIGNIFICANT:
_np.pop(0)
except IndexError:
_np = []
if len(_np) > 0:
_filtered.append(" ".join(_np))
return _filtered | [
"def",
"_filter_extracted",
"(",
"self",
",",
"extracted_list",
")",
":",
"_filtered",
"=",
"[",
"]",
"for",
"np",
"in",
"extracted_list",
":",
"_np",
"=",
"np",
".",
"split",
"(",
")",
"if",
"_np",
"[",
"0",
"]",
"in",
"INSIGNIFICANT",
":",
"_np",
"... | Filter insignificant words for key noun phrase extraction.
determiners, relative pronouns, reflexive pronouns
In general, pronouns are not useful, as you need context to know what they refer to.
Most of the pronouns, however, are filtered out by blob.noun_phrase method's
np length (>1) filter
:param list extracted_list: A list of noun phrases extracted from parser output. | [
"Filter",
"insignificant",
"words",
"for",
"key",
"noun",
"phrase",
"extraction",
"."
] | python | train |
shoebot/shoebot | shoebot/data/geometry.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L374-L385 | def contains(self, *a):
""" Returns True if the given point or rectangle falls within the bounds.
"""
if len(a) == 2: a = [Point(a[0], a[1])]
if len(a) == 1:
a = a[0]
if isinstance(a, Point):
return a.x >= self.x and a.x <= self.x+self.width \
and a.y >= self.y and a.y <= self.y+self.height
if isinstance(a, Bounds):
return a.x >= self.x and a.x+a.width <= self.x+self.width \
and a.y >= self.y and a.y+a.height <= self.y+self.height | [
"def",
"contains",
"(",
"self",
",",
"*",
"a",
")",
":",
"if",
"len",
"(",
"a",
")",
"==",
"2",
":",
"a",
"=",
"[",
"Point",
"(",
"a",
"[",
"0",
"]",
",",
"a",
"[",
"1",
"]",
")",
"]",
"if",
"len",
"(",
"a",
")",
"==",
"1",
":",
"a",
... | Returns True if the given point or rectangle falls within the bounds. | [
"Returns",
"True",
"if",
"the",
"given",
"point",
"or",
"rectangle",
"falls",
"within",
"the",
"bounds",
"."
] | python | valid |
boriel/zxbasic | zxbparser.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L950-L953 | def p_statement_randomize(p):
""" statement : RANDOMIZE
"""
p[0] = make_sentence('RANDOMIZE', make_number(0, lineno=p.lineno(1), type_=TYPE.ulong)) | [
"def",
"p_statement_randomize",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"make_sentence",
"(",
"'RANDOMIZE'",
",",
"make_number",
"(",
"0",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"type_",
"=",
"TYPE",
".",
"ulong",
")",
")"... | statement : RANDOMIZE | [
"statement",
":",
"RANDOMIZE"
] | python | train |
SpriteLink/NIPAP | nipap-cli/nipap_cli/nipap_cli.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap-cli/nipap_cli/nipap_cli.py#L49-L80 | def setup_connection():
""" Set up the global pynipap connection object
"""
# get connection parameters, first from environment variables if they are
# defined, otherwise from .nipaprc
try:
con_params = {
'username': os.getenv('NIPAP_USERNAME') or cfg.get('global', 'username'),
'password': os.getenv('NIPAP_PASSWORD') or cfg.get('global', 'password'),
'hostname': os.getenv('NIPAP_HOST') or cfg.get('global', 'hostname'),
'port' : os.getenv('NIPAP_PORT') or cfg.get('global', 'port')
}
except (configparser.NoOptionError, configparser.NoSectionError) as exc:
print("ERROR:", str(exc), file=sys.stderr)
print("HINT: Please define the username, password, hostname and port in your .nipaprc under the section 'global' or provide them through the environment variables NIPAP_HOST, NIPAP_PORT, NIPAP_USERNAME and NIPAP_PASSWORD.", file=sys.stderr)
sys.exit(1)
# if we haven't got a password (from env var or config) we interactively
# prompt for one
if con_params['password'] is None:
import getpass
con_params['password'] = getpass.getpass()
# build XML-RPC URI
pynipap.xmlrpc_uri = "http://%(username)s:%(password)s@%(hostname)s:%(port)s" % con_params
ao = pynipap.AuthOptions({
'authoritative_source': 'nipap',
'username': os.getenv('NIPAP_IMPERSONATE_USERNAME') or con_params['username'],
'full_name': os.getenv('NIPAP_IMPERSONATE_FULL_NAME'),
}) | [
"def",
"setup_connection",
"(",
")",
":",
"# get connection parameters, first from environment variables if they are",
"# defined, otherwise from .nipaprc",
"try",
":",
"con_params",
"=",
"{",
"'username'",
":",
"os",
".",
"getenv",
"(",
"'NIPAP_USERNAME'",
")",
"or",
"cfg"... | Set up the global pynipap connection object | [
"Set",
"up",
"the",
"global",
"pynipap",
"connection",
"object"
] | python | train |
tcalmant/ipopo | pelix/rsa/edef.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/edef.py#L468-L478 | def write(self, endpoints, filename):
# type: (List[EndpointDescription], str) -> None
"""
Writes the given endpoint descriptions to the given file
:param endpoints: A list of EndpointDescription beans
:param filename: Name of the file where to write the XML
:raise IOError: Error writing the file
"""
with open(filename, "w") as filep:
filep.write(self.to_string(endpoints)) | [
"def",
"write",
"(",
"self",
",",
"endpoints",
",",
"filename",
")",
":",
"# type: (List[EndpointDescription], str) -> None",
"with",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"filep",
":",
"filep",
".",
"write",
"(",
"self",
".",
"to_string",
"(",
"... | Writes the given endpoint descriptions to the given file
:param endpoints: A list of EndpointDescription beans
:param filename: Name of the file where to write the XML
:raise IOError: Error writing the file | [
"Writes",
"the",
"given",
"endpoint",
"descriptions",
"to",
"the",
"given",
"file"
] | python | train |
inasafe/inasafe | safe/common/parameters/resource_parameter_widget.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/parameters/resource_parameter_widget.py#L37-L43 | def get_parameter(self):
"""Obtain the parameter object from the current widget state.
:returns: A BooleanParameter from the current state of widget
"""
self._parameter.value = self._input.value()
return self._parameter | [
"def",
"get_parameter",
"(",
"self",
")",
":",
"self",
".",
"_parameter",
".",
"value",
"=",
"self",
".",
"_input",
".",
"value",
"(",
")",
"return",
"self",
".",
"_parameter"
] | Obtain the parameter object from the current widget state.
:returns: A BooleanParameter from the current state of widget | [
"Obtain",
"the",
"parameter",
"object",
"from",
"the",
"current",
"widget",
"state",
"."
] | python | train |
rbarrois/throttle | throttle/storage/django.py | https://github.com/rbarrois/throttle/blob/cc00e6b446f3938c81826ee258975ebdc12511a2/throttle/storage/django.py#L25-L29 | def cache(self):
"""Memoize access to the cache backend."""
if self._cache is None:
self._cache = django_cache.get_cache(self.cache_name)
return self._cache | [
"def",
"cache",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cache",
"is",
"None",
":",
"self",
".",
"_cache",
"=",
"django_cache",
".",
"get_cache",
"(",
"self",
".",
"cache_name",
")",
"return",
"self",
".",
"_cache"
] | Memoize access to the cache backend. | [
"Memoize",
"access",
"to",
"the",
"cache",
"backend",
"."
] | python | train |
icio/evil | evil/__init__.py | https://github.com/icio/evil/blob/6f12d16652951fb60ac238cef203eaa585ec0a28/evil/__init__.py#L140-L161 | def expr_tokenizer(expr, operator_tokens):
"""expr_tokenizer yields the components ("tokens") forming the expression.
Tokens are split by whitespace which is never considered a token in its
own right. operator_tokens should likely include "(" and ")" and strictly
the expression. This means that the word 'test' will be split into ['t',
'e', 'st'] if 'e' is an operator.
:param expr: The expression to break into tokens.
:param operator_tokens: A list of operators to extract as tokens.
"""
operator_tokens.sort(key=len, reverse=True)
for m in re.finditer(
r"""(\s+) | # Whitespace
({0}) | # Operators
(.+?)(?={0}|\s|$) # Patterns
""".format("|".join(re.escape(op) for op in operator_tokens)),
expr, re.X
):
token = m.group(2) or m.group(3)
if token:
yield token | [
"def",
"expr_tokenizer",
"(",
"expr",
",",
"operator_tokens",
")",
":",
"operator_tokens",
".",
"sort",
"(",
"key",
"=",
"len",
",",
"reverse",
"=",
"True",
")",
"for",
"m",
"in",
"re",
".",
"finditer",
"(",
"r\"\"\"(\\s+) | # Whitespace\n ... | expr_tokenizer yields the components ("tokens") forming the expression.
Tokens are split by whitespace which is never considered a token in its
own right. operator_tokens should likely include "(" and ")" and strictly
the expression. This means that the word 'test' will be split into ['t',
'e', 'st'] if 'e' is an operator.
:param expr: The expression to break into tokens.
:param operator_tokens: A list of operators to extract as tokens. | [
"expr_tokenizer",
"yields",
"the",
"components",
"(",
"tokens",
")",
"forming",
"the",
"expression",
"."
] | python | train |
wummel/linkchecker | linkcheck/plugins/viruscheck.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/plugins/viruscheck.py#L86-L110 | def new_scansock (self):
"""Return a connected socket for sending scan data to it."""
port = None
try:
self.sock.sendall("STREAM")
port = None
for dummy in range(60):
data = self.sock.recv(self.sock_rcvbuf)
i = data.find("PORT")
if i != -1:
port = int(data[i+5:])
break
except socket.error:
self.sock.close()
raise
if port is None:
raise ClamavError(_("clamd is not ready for stream scanning"))
sockinfo = get_sockinfo(self.host, port=port)
wsock = create_socket(socket.AF_INET, socket.SOCK_STREAM)
try:
wsock.connect(sockinfo[0][4])
except socket.error:
wsock.close()
raise
return wsock | [
"def",
"new_scansock",
"(",
"self",
")",
":",
"port",
"=",
"None",
"try",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"\"STREAM\"",
")",
"port",
"=",
"None",
"for",
"dummy",
"in",
"range",
"(",
"60",
")",
":",
"data",
"=",
"self",
".",
"sock",
... | Return a connected socket for sending scan data to it. | [
"Return",
"a",
"connected",
"socket",
"for",
"sending",
"scan",
"data",
"to",
"it",
"."
] | python | train |
goller/hashring | src/hashring/hashring.py | https://github.com/goller/hashring/blob/9bee95074f7d853b6aa656968dfd359d02b3b710/src/hashring/hashring.py#L150-L157 | def gen_key(self, key):
"""Given a string key it returns a long value,
this long value represents a place on the hash ring.
md5 is currently used because it mixes well.
"""
b_key = self._hash_digest(key)
return self._hash_val(b_key, lambda x: x) | [
"def",
"gen_key",
"(",
"self",
",",
"key",
")",
":",
"b_key",
"=",
"self",
".",
"_hash_digest",
"(",
"key",
")",
"return",
"self",
".",
"_hash_val",
"(",
"b_key",
",",
"lambda",
"x",
":",
"x",
")"
] | Given a string key it returns a long value,
this long value represents a place on the hash ring.
md5 is currently used because it mixes well. | [
"Given",
"a",
"string",
"key",
"it",
"returns",
"a",
"long",
"value",
"this",
"long",
"value",
"represents",
"a",
"place",
"on",
"the",
"hash",
"ring",
"."
] | python | valid |
phareous/insteonlocal | insteonlocal/Hub.py | https://github.com/phareous/insteonlocal/blob/a4544a17d143fb285852cb873e862c270d55dd00/insteonlocal/Hub.py#L1072-L1091 | def check_success(self, device_id, sent_cmd1, sent_cmd2):
"""Check if last command succeeded by checking buffer"""
device_id = device_id.upper()
self.logger.info('check_success: for device %s cmd1 %s cmd2 %s',
device_id, sent_cmd1, sent_cmd2)
sleep(2)
status = self.get_buffer_status(device_id)
check_id = status.get('id_from', '')
cmd1 = status.get('cmd1', '')
cmd2 = status.get('cmd2', '')
if (check_id == device_id) and (cmd1 == sent_cmd1) and (cmd2 == sent_cmd2):
self.logger.info("check_success: Response device %s cmd %s cmd2 %s SUCCESS",
check_id, cmd1, cmd2)
return True
self.logger.info("check_success: No valid response found for device %s cmd %s cmd2 %s",
device_id, sent_cmd1, sent_cmd2)
return False | [
"def",
"check_success",
"(",
"self",
",",
"device_id",
",",
"sent_cmd1",
",",
"sent_cmd2",
")",
":",
"device_id",
"=",
"device_id",
".",
"upper",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'check_success: for device %s cmd1 %s cmd2 %s'",
",",
"device_id... | Check if last command succeeded by checking buffer | [
"Check",
"if",
"last",
"command",
"succeeded",
"by",
"checking",
"buffer"
] | python | train |
pypa/pipenv | pipenv/vendor/requests/sessions.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L466-L535 | def request(self, method, url,
params=None, data=None, headers=None, cookies=None, files=None,
auth=None, timeout=None, allow_redirects=True, proxies=None,
hooks=None, stream=None, verify=None, cert=None, json=None):
"""Constructs a :class:`Request <Request>`, prepares it and sends it.
Returns :class:`Response <Response>` object.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query
string for the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the
:class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the
:class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the
:class:`Request`.
:param files: (optional) Dictionary of ``'filename': file-like-objects``
for multipart encoding upload.
:param auth: (optional) Auth tuple or callable to enable
Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Set to True by default.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
:param stream: (optional) whether to immediately download the response
content. Defaults to ``False``.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param cert: (optional) if String, path to ssl client cert file (.pem).
If Tuple, ('cert', 'key') pair.
:rtype: requests.Response
"""
# Create the Request.
req = Request(
method=method.upper(),
url=url,
headers=headers,
files=files,
data=data or {},
json=json,
params=params or {},
auth=auth,
cookies=cookies,
hooks=hooks,
)
prep = self.prepare_request(req)
proxies = proxies or {}
settings = self.merge_environment_settings(
prep.url, proxies, stream, verify, cert
)
# Send the request.
send_kwargs = {
'timeout': timeout,
'allow_redirects': allow_redirects,
}
send_kwargs.update(settings)
resp = self.send(prep, **send_kwargs)
return resp | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"cookies",
"=",
"None",
",",
"files",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"N... | Constructs a :class:`Request <Request>`, prepares it and sends it.
Returns :class:`Response <Response>` object.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query
string for the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the
:class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the
:class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the
:class:`Request`.
:param files: (optional) Dictionary of ``'filename': file-like-objects``
for multipart encoding upload.
:param auth: (optional) Auth tuple or callable to enable
Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Set to True by default.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
:param stream: (optional) whether to immediately download the response
content. Defaults to ``False``.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param cert: (optional) if String, path to ssl client cert file (.pem).
If Tuple, ('cert', 'key') pair.
:rtype: requests.Response | [
"Constructs",
"a",
":",
"class",
":",
"Request",
"<Request",
">",
"prepares",
"it",
"and",
"sends",
"it",
".",
"Returns",
":",
"class",
":",
"Response",
"<Response",
">",
"object",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/tilebus/block.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/block.py#L98-L110 | def set_name(self, name):
"""Set the module name to a 6 byte string
If the string is too short it is appended with space characters.
"""
if len(name) > 6:
raise ArgumentError("Name must be at most 6 characters long", name=name)
if len(name) < 6:
name += ' '*(6 - len(name))
self.name = name | [
"def",
"set_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"len",
"(",
"name",
")",
">",
"6",
":",
"raise",
"ArgumentError",
"(",
"\"Name must be at most 6 characters long\"",
",",
"name",
"=",
"name",
")",
"if",
"len",
"(",
"name",
")",
"<",
"6",
":... | Set the module name to a 6 byte string
If the string is too short it is appended with space characters. | [
"Set",
"the",
"module",
"name",
"to",
"a",
"6",
"byte",
"string"
] | python | train |
biocore/burrito-fillings | bfillings/cd_hit.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/cd_hit.py#L151-L159 | def _input_as_multiline_string(self, data):
"""Writes data to tempfile and sets -i parameter
data -- list of lines
"""
if data:
self.Parameters['-i']\
.on(super(CD_HIT,self)._input_as_multiline_string(data))
return '' | [
"def",
"_input_as_multiline_string",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
":",
"self",
".",
"Parameters",
"[",
"'-i'",
"]",
".",
"on",
"(",
"super",
"(",
"CD_HIT",
",",
"self",
")",
".",
"_input_as_multiline_string",
"(",
"data",
")",
")",
... | Writes data to tempfile and sets -i parameter
data -- list of lines | [
"Writes",
"data",
"to",
"tempfile",
"and",
"sets",
"-",
"i",
"parameter"
] | python | train |
rix0rrr/gcl | gcl/functions.py | https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/functions.py#L85-L98 | def has_key(tup, key):
"""has(tuple, string) -> bool
Return whether a given tuple has a key and the key is bound.
"""
if isinstance(tup, framework.TupleLike):
return tup.is_bound(key)
if isinstance(tup, dict):
return key in tup
if isinstance(tup, list):
if not isinstance(key, int):
raise ValueError('Key must be integer when checking list index')
return key < len(tup)
raise ValueError('Not a tuple-like object: %r' % tup) | [
"def",
"has_key",
"(",
"tup",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"tup",
",",
"framework",
".",
"TupleLike",
")",
":",
"return",
"tup",
".",
"is_bound",
"(",
"key",
")",
"if",
"isinstance",
"(",
"tup",
",",
"dict",
")",
":",
"return",
"k... | has(tuple, string) -> bool
Return whether a given tuple has a key and the key is bound. | [
"has",
"(",
"tuple",
"string",
")",
"-",
">",
"bool"
] | python | train |
rvswift/EB | EB/builder/utilities/classification.py | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/utilities/classification.py#L153-L171 | def calculate_ef_var(tpf, fpf):
"""
determine variance due to actives (efvar_a) decoys (efvar_d) and s2, the slope of the ROC curve tangent to the
fpf @ which the enrichment factor was calculated
:param tpf: float tpf @ which the enrichment factor was calculated
:param fpf: float fpf @ which the enrichment factor was calculated
:return efvara, efvard, s2: tuple
"""
efvara = (tpf * (1 - tpf))
efvard = (fpf * (1 - fpf))
ef = tpf / fpf
if fpf == 1:
return(0, 0, 0)
else:
s = ef * ( 1 + (np.log(ef)/np.log(fpf)))
s2 = s * s
return (efvara, efvard, s2) | [
"def",
"calculate_ef_var",
"(",
"tpf",
",",
"fpf",
")",
":",
"efvara",
"=",
"(",
"tpf",
"*",
"(",
"1",
"-",
"tpf",
")",
")",
"efvard",
"=",
"(",
"fpf",
"*",
"(",
"1",
"-",
"fpf",
")",
")",
"ef",
"=",
"tpf",
"/",
"fpf",
"if",
"fpf",
"==",
"1... | determine variance due to actives (efvar_a) decoys (efvar_d) and s2, the slope of the ROC curve tangent to the
fpf @ which the enrichment factor was calculated
:param tpf: float tpf @ which the enrichment factor was calculated
:param fpf: float fpf @ which the enrichment factor was calculated
:return efvara, efvard, s2: tuple | [
"determine",
"variance",
"due",
"to",
"actives",
"(",
"efvar_a",
")",
"decoys",
"(",
"efvar_d",
")",
"and",
"s2",
"the",
"slope",
"of",
"the",
"ROC",
"curve",
"tangent",
"to",
"the",
"fpf"
] | python | train |
materialsproject/pymatgen | pymatgen/io/abinit/utils.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/utils.py#L784-L789 | def as_condition(cls, obj):
"""Convert obj into :class:`Condition`"""
if isinstance(obj, cls):
return obj
else:
return cls(cmap=obj) | [
"def",
"as_condition",
"(",
"cls",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"cls",
")",
":",
"return",
"obj",
"else",
":",
"return",
"cls",
"(",
"cmap",
"=",
"obj",
")"
] | Convert obj into :class:`Condition` | [
"Convert",
"obj",
"into",
":",
"class",
":",
"Condition"
] | python | train |
softlayer/softlayer-python | SoftLayer/CLI/file/access/list.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/access/list.py#L21-L38 | def cli(env, columns, sortby, volume_id):
"""List ACLs."""
file_manager = SoftLayer.FileStorageManager(env.client)
access_list = file_manager.get_file_volume_access_list(
volume_id=volume_id)
table = formatting.Table(columns.columns)
table.sortby = sortby
for key, type_name in [('allowedVirtualGuests', 'VIRTUAL'),
('allowedHardware', 'HARDWARE'),
('allowedSubnets', 'SUBNET'),
('allowedIpAddresses', 'IP')]:
for obj in access_list.get(key, []):
obj['type'] = type_name
table.add_row([value or formatting.blank()
for value in columns.row(obj)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"columns",
",",
"sortby",
",",
"volume_id",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"access_list",
"=",
"file_manager",
".",
"get_file_volume_access_list",
"(",
"volu... | List ACLs. | [
"List",
"ACLs",
"."
] | python | train |
samirelanduk/quickplots | quickplots/charts.py | https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/charts.py#L164-L172 | def add_series(self, series):
"""Adds a :py:class:`.Series` to the chart.
:param Series series: The :py:class:`.Series` to add."""
if not isinstance(series, Series):
raise TypeError("'%s' is not a Series" % str(series))
self._all_series.append(series)
series._chart = self | [
"def",
"add_series",
"(",
"self",
",",
"series",
")",
":",
"if",
"not",
"isinstance",
"(",
"series",
",",
"Series",
")",
":",
"raise",
"TypeError",
"(",
"\"'%s' is not a Series\"",
"%",
"str",
"(",
"series",
")",
")",
"self",
".",
"_all_series",
".",
"ap... | Adds a :py:class:`.Series` to the chart.
:param Series series: The :py:class:`.Series` to add. | [
"Adds",
"a",
":",
"py",
":",
"class",
":",
".",
"Series",
"to",
"the",
"chart",
"."
] | python | train |
pycampers/zproc | zproc/state/state.py | https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/state.py#L522-L575 | def atomic(fn: Callable) -> Callable:
"""
Wraps a function, to create an atomic operation out of it.
This contract guarantees, that while an atomic ``fn`` is running -
- No one, except the "callee" may access the state.
- If an ``Exception`` occurs while the ``fn`` is running, the state remains unaffected.
- | If a signal is sent to the "callee", the ``fn`` remains unaffected.
| (The state is not left in an incoherent state.)
.. note::
- The first argument to the wrapped function *must* be a :py:class:`State` object.
- The wrapped ``fn`` receives a frozen version (snapshot) of state,
which is a ``dict`` object, not a :py:class:`State` object.
- It is not possible to call one atomic function from other.
Please read :ref:`atomicity` for a detailed explanation.
:param fn:
The function to be wrapped, as an atomic function.
:returns:
A wrapper function.
The wrapper function returns the value returned by the wrapped ``fn``.
>>> import zproc
>>>
>>> @zproc.atomic
... def increment(snapshot):
... return snapshot['count'] + 1
...
>>>
>>> ctx = zproc.Context()
>>> state = ctx.create_state({'count': 0})
>>>
>>> increment(state)
1
"""
msg = {
Msgs.cmd: Cmds.run_fn_atomically,
Msgs.info: serializer.dumps_fn(fn),
Msgs.args: (),
Msgs.kwargs: {},
}
@wraps(fn)
def wrapper(state: State, *args, **kwargs):
msg[Msgs.args] = args
msg[Msgs.kwargs] = kwargs
return state._s_request_reply(msg)
return wrapper | [
"def",
"atomic",
"(",
"fn",
":",
"Callable",
")",
"->",
"Callable",
":",
"msg",
"=",
"{",
"Msgs",
".",
"cmd",
":",
"Cmds",
".",
"run_fn_atomically",
",",
"Msgs",
".",
"info",
":",
"serializer",
".",
"dumps_fn",
"(",
"fn",
")",
",",
"Msgs",
".",
"ar... | Wraps a function, to create an atomic operation out of it.
This contract guarantees, that while an atomic ``fn`` is running -
- No one, except the "callee" may access the state.
- If an ``Exception`` occurs while the ``fn`` is running, the state remains unaffected.
- | If a signal is sent to the "callee", the ``fn`` remains unaffected.
| (The state is not left in an incoherent state.)
.. note::
- The first argument to the wrapped function *must* be a :py:class:`State` object.
- The wrapped ``fn`` receives a frozen version (snapshot) of state,
which is a ``dict`` object, not a :py:class:`State` object.
- It is not possible to call one atomic function from other.
Please read :ref:`atomicity` for a detailed explanation.
:param fn:
The function to be wrapped, as an atomic function.
:returns:
A wrapper function.
The wrapper function returns the value returned by the wrapped ``fn``.
>>> import zproc
>>>
>>> @zproc.atomic
... def increment(snapshot):
... return snapshot['count'] + 1
...
>>>
>>> ctx = zproc.Context()
>>> state = ctx.create_state({'count': 0})
>>>
>>> increment(state)
1 | [
"Wraps",
"a",
"function",
"to",
"create",
"an",
"atomic",
"operation",
"out",
"of",
"it",
"."
] | python | train |
Kyria/EsiPy | esipy/events.py | https://github.com/Kyria/EsiPy/blob/06407a0218a126678f80d8a7e8a67b9729327865/esipy/events.py#L19-L26 | def add_receiver(self, receiver):
""" Add a receiver to the list of receivers.
:param receiver: a callable variable
"""
if not callable(receiver):
raise TypeError("receiver must be callable")
self.event_receivers.append(receiver) | [
"def",
"add_receiver",
"(",
"self",
",",
"receiver",
")",
":",
"if",
"not",
"callable",
"(",
"receiver",
")",
":",
"raise",
"TypeError",
"(",
"\"receiver must be callable\"",
")",
"self",
".",
"event_receivers",
".",
"append",
"(",
"receiver",
")"
] | Add a receiver to the list of receivers.
:param receiver: a callable variable | [
"Add",
"a",
"receiver",
"to",
"the",
"list",
"of",
"receivers",
".",
":",
"param",
"receiver",
":",
"a",
"callable",
"variable"
] | python | train |
mapbox/cligj | cligj/features.py | https://github.com/mapbox/cligj/blob/1815692d99abfb4bc4b2d0411f67fa568f112c05/cligj/features.py#L175-L189 | def normalize_feature_objects(feature_objs):
"""Takes an iterable of GeoJSON-like Feature mappings or
an iterable of objects with a geo interface and
normalizes it to the former."""
for obj in feature_objs:
if hasattr(obj, "__geo_interface__") and \
'type' in obj.__geo_interface__.keys() and \
obj.__geo_interface__['type'] == 'Feature':
yield obj.__geo_interface__
elif isinstance(obj, dict) and 'type' in obj and \
obj['type'] == 'Feature':
yield obj
else:
raise ValueError("Did not recognize object {0}"
"as GeoJSON Feature".format(obj)) | [
"def",
"normalize_feature_objects",
"(",
"feature_objs",
")",
":",
"for",
"obj",
"in",
"feature_objs",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"__geo_interface__\"",
")",
"and",
"'type'",
"in",
"obj",
".",
"__geo_interface__",
".",
"keys",
"(",
")",
"and",
... | Takes an iterable of GeoJSON-like Feature mappings or
an iterable of objects with a geo interface and
normalizes it to the former. | [
"Takes",
"an",
"iterable",
"of",
"GeoJSON",
"-",
"like",
"Feature",
"mappings",
"or",
"an",
"iterable",
"of",
"objects",
"with",
"a",
"geo",
"interface",
"and",
"normalizes",
"it",
"to",
"the",
"former",
"."
] | python | train |
fastai/fastai | fastai/callback.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L29-L34 | def new(self, layer_groups:Collection[nn.Module], split_no_wd:bool=True):
"Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters."
opt_func = getattr(self, 'opt_func', self.opt.__class__)
res = self.create(opt_func, self.lr, layer_groups, wd=self.wd, true_wd=self.true_wd, bn_wd=self.bn_wd)
res.mom,res.beta = self.mom,self.beta
return res | [
"def",
"new",
"(",
"self",
",",
"layer_groups",
":",
"Collection",
"[",
"nn",
".",
"Module",
"]",
",",
"split_no_wd",
":",
"bool",
"=",
"True",
")",
":",
"opt_func",
"=",
"getattr",
"(",
"self",
",",
"'opt_func'",
",",
"self",
".",
"opt",
".",
"__cla... | Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters. | [
"Create",
"a",
"new",
"OptimWrapper",
"from",
"self",
"with",
"another",
"layer_groups",
"but",
"the",
"same",
"hyper",
"-",
"parameters",
"."
] | python | train |
wdecoster/NanoPlot | nanoplot/NanoPlot.py | https://github.com/wdecoster/NanoPlot/blob/d1601076731df2a07020316bd159b544f497a606/nanoplot/NanoPlot.py#L30-L106 | def main():
'''
Organization function
-setups logging
-gets inputdata
-calls plotting function
'''
args = get_args()
try:
utils.make_output_dir(args.outdir)
utils.init_logs(args)
args.format = nanoplotter.check_valid_format(args.format)
settings = vars(args)
settings["path"] = path.join(args.outdir, args.prefix)
sources = {
"fastq": args.fastq,
"bam": args.bam,
"cram": args.cram,
"fastq_rich": args.fastq_rich,
"fastq_minimal": args.fastq_minimal,
"summary": args.summary,
"fasta": args.fasta,
"ubam": args.ubam,
}
if args.pickle:
datadf = pickle.load(open(args.pickle, 'rb'))
else:
datadf = get_input(
source=[n for n, s in sources.items() if s][0],
files=[f for f in sources.values() if f][0],
threads=args.threads,
readtype=args.readtype,
combine="simple",
barcoded=args.barcoded)
if args.store:
pickle.dump(
obj=datadf,
file=open(settings["path"] + "NanoPlot-data.pickle", 'wb'))
if args.raw:
datadf.to_csv(settings["path"] + "NanoPlot-data.tsv.gz",
sep="\t",
index=False,
compression="gzip")
settings["statsfile"] = [make_stats(datadf, settings, suffix="")]
datadf, settings = filter_and_transform_data(datadf, settings)
if settings["filtered"]: # Bool set when filter was applied in filter_and_transform_data()
settings["statsfile"].append(make_stats(datadf, settings, suffix="_post_filtering"))
if args.barcoded:
barcodes = list(datadf["barcode"].unique())
plots = []
for barc in barcodes:
logging.info("Processing {}".format(barc))
settings["path"] = path.join(args.outdir, args.prefix + barc + "_")
dfbarc = datadf[datadf["barcode"] == barc]
if len(dfbarc) > 5:
settings["title"] = barc
plots.extend(
make_plots(dfbarc, settings)
)
else:
sys.stderr.write("Found barcode {} less than 5x, ignoring...\n".format(barc))
logging.info("Found barcode {} less than 5 times, ignoring".format(barc))
else:
plots = make_plots(datadf, settings)
make_report(plots, settings)
logging.info("Finished!")
except Exception as e:
logging.error(e, exc_info=True)
print("\n\n\nIf you read this then NanoPlot has crashed :-(")
print("Please try updating NanoPlot and see if that helps...\n")
print("If not, please report this issue at https://github.com/wdecoster/NanoPlot/issues")
print("If you could include the log file that would be really helpful.")
print("Thanks!\n\n\n")
raise | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
")",
"try",
":",
"utils",
".",
"make_output_dir",
"(",
"args",
".",
"outdir",
")",
"utils",
".",
"init_logs",
"(",
"args",
")",
"args",
".",
"format",
"=",
"nanoplotter",
".",
"check_valid_for... | Organization function
-setups logging
-gets inputdata
-calls plotting function | [
"Organization",
"function",
"-",
"setups",
"logging",
"-",
"gets",
"inputdata",
"-",
"calls",
"plotting",
"function"
] | python | train |
wandb/client | wandb/wandb_config.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/wandb_config.py#L154-L165 | def persist(self):
"""Stores the current configuration for pushing to W&B"""
# In dryrun mode, without wandb run, we don't
# save config on initial load, because the run directory
# may not be created yet (because we don't know if we're
# being used in a run context, or as an API).
# TODO: Defer saving somehow, maybe via an events system
path = self._config_path()
if path is None:
return
with open(path, "w") as conf_file:
conf_file.write(str(self)) | [
"def",
"persist",
"(",
"self",
")",
":",
"# In dryrun mode, without wandb run, we don't",
"# save config on initial load, because the run directory",
"# may not be created yet (because we don't know if we're",
"# being used in a run context, or as an API).",
"# TODO: Defer saving somehow, maybe... | Stores the current configuration for pushing to W&B | [
"Stores",
"the",
"current",
"configuration",
"for",
"pushing",
"to",
"W&B"
] | python | train |
Koed00/django-q | django_q/admin.py | https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/admin.py#L40-L44 | def retry_failed(FailAdmin, request, queryset):
"""Submit selected tasks back to the queue."""
for task in queryset:
async_task(task.func, *task.args or (), hook=task.hook, **task.kwargs or {})
task.delete() | [
"def",
"retry_failed",
"(",
"FailAdmin",
",",
"request",
",",
"queryset",
")",
":",
"for",
"task",
"in",
"queryset",
":",
"async_task",
"(",
"task",
".",
"func",
",",
"*",
"task",
".",
"args",
"or",
"(",
")",
",",
"hook",
"=",
"task",
".",
"hook",
... | Submit selected tasks back to the queue. | [
"Submit",
"selected",
"tasks",
"back",
"to",
"the",
"queue",
"."
] | python | train |
pantsbuild/pants | src/python/pants/reporting/json_reporter.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/reporting/json_reporter.py#L88-L101 | def do_handle_log(self, workunit, level, *msg_elements):
"""Implementation of Reporter callback."""
entry_info = {
'level': self._log_level_str[level],
'messages': self._render_messages(*msg_elements),
}
root_id = str(workunit.root().id)
current_stack = self._root_id_to_workunit_stack[root_id]
if current_stack:
current_stack[-1]['log_entries'].append(entry_info)
else:
self.results[root_id]['log_entries'].append(entry_info) | [
"def",
"do_handle_log",
"(",
"self",
",",
"workunit",
",",
"level",
",",
"*",
"msg_elements",
")",
":",
"entry_info",
"=",
"{",
"'level'",
":",
"self",
".",
"_log_level_str",
"[",
"level",
"]",
",",
"'messages'",
":",
"self",
".",
"_render_messages",
"(",
... | Implementation of Reporter callback. | [
"Implementation",
"of",
"Reporter",
"callback",
"."
] | python | train |
msmbuilder/osprey | osprey/plugins/plugin_pylearn2.py | https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plugins/plugin_pylearn2.py#L278-L298 | def load(self):
"""
Load the dataset using pylearn2.config.yaml_parse.
"""
from pylearn2.config import yaml_parse
from pylearn2.datasets import Dataset
dataset = yaml_parse.load(self.yaml_string)
assert isinstance(dataset, Dataset)
data = dataset.iterator(mode='sequential', num_batches=1,
data_specs=dataset.data_specs,
return_tuple=True).next()
if len(data) == 2:
X, y = data
y = np.squeeze(y)
if self.one_hot:
y = np.argmax(y, axis=1)
else:
X = data
y = None
return X, y | [
"def",
"load",
"(",
"self",
")",
":",
"from",
"pylearn2",
".",
"config",
"import",
"yaml_parse",
"from",
"pylearn2",
".",
"datasets",
"import",
"Dataset",
"dataset",
"=",
"yaml_parse",
".",
"load",
"(",
"self",
".",
"yaml_string",
")",
"assert",
"isinstance"... | Load the dataset using pylearn2.config.yaml_parse. | [
"Load",
"the",
"dataset",
"using",
"pylearn2",
".",
"config",
".",
"yaml_parse",
"."
] | python | valid |
BernardFW/bernard | src/bernard/platforms/facebook/platform.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L785-L801 | async def _send_generic_template(self, request: Request, stack: Stack):
"""
Generates and send a generic template.
"""
gt = stack.get_layer(GenericTemplate)
payload = await gt.serialize(request)
msg = {
'attachment': {
'type': 'template',
'payload': payload
}
}
await self._add_qr(stack, msg, request)
await self._send(request, msg, stack) | [
"async",
"def",
"_send_generic_template",
"(",
"self",
",",
"request",
":",
"Request",
",",
"stack",
":",
"Stack",
")",
":",
"gt",
"=",
"stack",
".",
"get_layer",
"(",
"GenericTemplate",
")",
"payload",
"=",
"await",
"gt",
".",
"serialize",
"(",
"request",... | Generates and send a generic template. | [
"Generates",
"and",
"send",
"a",
"generic",
"template",
"."
] | python | train |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/tails.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/tails.py#L97-L109 | async def open(self) -> 'Tails':
"""
Open reader handle and return current object.
:return: current object
"""
LOGGER.debug('Tails.open >>>')
self._reader_handle = await blob_storage.open_reader('default', self._tails_config_json)
LOGGER.debug('Tails.open <<<')
return self | [
"async",
"def",
"open",
"(",
"self",
")",
"->",
"'Tails'",
":",
"LOGGER",
".",
"debug",
"(",
"'Tails.open >>>'",
")",
"self",
".",
"_reader_handle",
"=",
"await",
"blob_storage",
".",
"open_reader",
"(",
"'default'",
",",
"self",
".",
"_tails_config_json",
"... | Open reader handle and return current object.
:return: current object | [
"Open",
"reader",
"handle",
"and",
"return",
"current",
"object",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.