nwo
stringlengths 5
86
| sha
stringlengths 40
40
| path
stringlengths 4
189
| language
stringclasses 1
value | identifier
stringlengths 1
94
| parameters
stringlengths 2
4.03k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
11.5k
| docstring
stringlengths 1
33.2k
| docstring_summary
stringlengths 0
5.15k
| docstring_tokens
list | function
stringlengths 34
151k
| function_tokens
list | url
stringlengths 90
278
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pytorch/pytorch
|
7176c92687d3cc847cc046bf002269c6949a21c2
|
torch/profiler/profiler.py
|
python
|
_KinetoProfile.add_metadata_json
|
(self, key: str, value: str)
|
Adds a user defined metadata with a string key and a valid json value
into the trace file
|
Adds a user defined metadata with a string key and a valid json value
into the trace file
|
[
"Adds",
"a",
"user",
"defined",
"metadata",
"with",
"a",
"string",
"key",
"and",
"a",
"valid",
"json",
"value",
"into",
"the",
"trace",
"file"
] |
def add_metadata_json(self, key: str, value: str):
"""
Adds a user defined metadata with a string key and a valid json value
into the trace file
"""
torch.autograd._add_metadata_json(key, value)
|
[
"def",
"add_metadata_json",
"(",
"self",
",",
"key",
":",
"str",
",",
"value",
":",
"str",
")",
":",
"torch",
".",
"autograd",
".",
"_add_metadata_json",
"(",
"key",
",",
"value",
")"
] |
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/profiler/profiler.py#L167-L172
|
||
vslavik/poedit
|
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
|
deps/boost/tools/build/src/build/scanner.py
|
python
|
reset
|
()
|
Clear the module state. This is mainly for testing purposes.
|
Clear the module state. This is mainly for testing purposes.
|
[
"Clear",
"the",
"module",
"state",
".",
"This",
"is",
"mainly",
"for",
"testing",
"purposes",
"."
] |
def reset ():
""" Clear the module state. This is mainly for testing purposes.
"""
global __scanners, __rv_cache, __scanner_cache
# Maps registered scanner classes to relevant properties
__scanners = {}
# A cache of scanners.
# The key is: class_name.properties_tag, where properties_tag is the concatenation
# of all relevant properties, separated by '-'
__scanner_cache = {}
|
[
"def",
"reset",
"(",
")",
":",
"global",
"__scanners",
",",
"__rv_cache",
",",
"__scanner_cache",
"# Maps registered scanner classes to relevant properties",
"__scanners",
"=",
"{",
"}",
"# A cache of scanners.",
"# The key is: class_name.properties_tag, where properties_tag is the concatenation",
"# of all relevant properties, separated by '-'",
"__scanner_cache",
"=",
"{",
"}"
] |
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/scanner.py#L38-L49
|
||
google/swiftshader
|
8ccc63f045d5975fb67f9dfd3d2b8235b0526990
|
third_party/SPIRV-Tools/utils/generate_grammar_tables.py
|
python
|
generate_extension_enum
|
(extensions)
|
return ',\n'.join(['k' + extension for extension in extensions])
|
Returns enumeration containing extensions declared in the grammar.
|
Returns enumeration containing extensions declared in the grammar.
|
[
"Returns",
"enumeration",
"containing",
"extensions",
"declared",
"in",
"the",
"grammar",
"."
] |
def generate_extension_enum(extensions):
"""Returns enumeration containing extensions declared in the grammar."""
return ',\n'.join(['k' + extension for extension in extensions])
|
[
"def",
"generate_extension_enum",
"(",
"extensions",
")",
":",
"return",
"',\\n'",
".",
"join",
"(",
"[",
"'k'",
"+",
"extension",
"for",
"extension",
"in",
"extensions",
"]",
")"
] |
https://github.com/google/swiftshader/blob/8ccc63f045d5975fb67f9dfd3d2b8235b0526990/third_party/SPIRV-Tools/utils/generate_grammar_tables.py#L591-L593
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/_core.py
|
python
|
BookCtrlBase.IsVertical
|
(*args, **kwargs)
|
return _core_.BookCtrlBase_IsVertical(*args, **kwargs)
|
IsVertical(self) -> bool
|
IsVertical(self) -> bool
|
[
"IsVertical",
"(",
"self",
")",
"-",
">",
"bool"
] |
def IsVertical(*args, **kwargs):
"""IsVertical(self) -> bool"""
return _core_.BookCtrlBase_IsVertical(*args, **kwargs)
|
[
"def",
"IsVertical",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"BookCtrlBase_IsVertical",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13586-L13588
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/gtk/richtext.py
|
python
|
RichTextCtrl.DeleteSelection
|
(*args, **kwargs)
|
return _richtext.RichTextCtrl_DeleteSelection(*args, **kwargs)
|
DeleteSelection(self)
Remove the current selection.
|
DeleteSelection(self)
|
[
"DeleteSelection",
"(",
"self",
")"
] |
def DeleteSelection(*args, **kwargs):
"""
DeleteSelection(self)
Remove the current selection.
"""
return _richtext.RichTextCtrl_DeleteSelection(*args, **kwargs)
|
[
"def",
"DeleteSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_DeleteSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L3228-L3234
|
|
shader-slang/slang
|
b8982fcf43b86c1e39dcc3dd19bff2821633eda6
|
external/vulkan/registry/generator.py
|
python
|
OutputGenerator.beginFeature
|
(self, interface, emit)
|
Write interface for a feature and tag generated features as having been done.
- interface - element for the `<version>` / `<extension>` to generate
- emit - actually write to the header only when True
|
Write interface for a feature and tag generated features as having been done.
|
[
"Write",
"interface",
"for",
"a",
"feature",
"and",
"tag",
"generated",
"features",
"as",
"having",
"been",
"done",
"."
] |
def beginFeature(self, interface, emit):
"""Write interface for a feature and tag generated features as having been done.
- interface - element for the `<version>` / `<extension>` to generate
- emit - actually write to the header only when True"""
self.emit = emit
self.featureName = interface.get('name')
# If there's an additional 'protect' attribute in the feature, save it
self.featureExtraProtect = interface.get('protect')
|
[
"def",
"beginFeature",
"(",
"self",
",",
"interface",
",",
"emit",
")",
":",
"self",
".",
"emit",
"=",
"emit",
"self",
".",
"featureName",
"=",
"interface",
".",
"get",
"(",
"'name'",
")",
"# If there's an additional 'protect' attribute in the feature, save it",
"self",
".",
"featureExtraProtect",
"=",
"interface",
".",
"get",
"(",
"'protect'",
")"
] |
https://github.com/shader-slang/slang/blob/b8982fcf43b86c1e39dcc3dd19bff2821633eda6/external/vulkan/registry/generator.py#L674-L682
|
||
CGRU/cgru
|
1881a4128530e3d31ac6c25314c18314fc50c2c7
|
afanasy/python/af.py
|
python
|
Job.setName
|
(self, name)
|
Missing DocString
:param name:
:return:
|
Missing DocString
|
[
"Missing",
"DocString"
] |
def setName(self, name):
"""Missing DocString
:param name:
:return:
"""
if name is not None and len(name):
self.data["name"] = name
|
[
"def",
"setName",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"is",
"not",
"None",
"and",
"len",
"(",
"name",
")",
":",
"self",
".",
"data",
"[",
"\"name\"",
"]",
"=",
"name"
] |
https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/afanasy/python/af.py#L585-L592
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/scikit-learn/py3/sklearn/linear_model/_theil_sen.py
|
python
|
_spatial_median
|
(X, max_iter=300, tol=1.e-3)
|
return n_iter, spatial_median
|
Spatial median (L1 median).
The spatial median is member of a class of so-called M-estimators which
are defined by an optimization problem. Given a number of p points in an
n-dimensional space, the point x minimizing the sum of all distances to the
p other points is called spatial median.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and
n_features is the number of features.
max_iter : int, optional
Maximum number of iterations. Default is 300.
tol : float, optional
Stop the algorithm if spatial_median has converged. Default is 1.e-3.
Returns
-------
spatial_median : array, shape = [n_features]
Spatial median.
n_iter : int
Number of iterations needed.
References
----------
- On Computation of Spatial Median for Robust Data Mining, 2005
T. Kärkkäinen and S. Äyrämö
http://users.jyu.fi/~samiayr/pdf/ayramo_eurogen05.pdf
|
Spatial median (L1 median).
|
[
"Spatial",
"median",
"(",
"L1",
"median",
")",
"."
] |
def _spatial_median(X, max_iter=300, tol=1.e-3):
"""Spatial median (L1 median).
The spatial median is member of a class of so-called M-estimators which
are defined by an optimization problem. Given a number of p points in an
n-dimensional space, the point x minimizing the sum of all distances to the
p other points is called spatial median.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and
n_features is the number of features.
max_iter : int, optional
Maximum number of iterations. Default is 300.
tol : float, optional
Stop the algorithm if spatial_median has converged. Default is 1.e-3.
Returns
-------
spatial_median : array, shape = [n_features]
Spatial median.
n_iter : int
Number of iterations needed.
References
----------
- On Computation of Spatial Median for Robust Data Mining, 2005
T. Kärkkäinen and S. Äyrämö
http://users.jyu.fi/~samiayr/pdf/ayramo_eurogen05.pdf
"""
if X.shape[1] == 1:
return 1, np.median(X.ravel())
tol **= 2 # We are computing the tol on the squared norm
spatial_median_old = np.mean(X, axis=0)
for n_iter in range(max_iter):
spatial_median = _modified_weiszfeld_step(X, spatial_median_old)
if np.sum((spatial_median_old - spatial_median) ** 2) < tol:
break
else:
spatial_median_old = spatial_median
else:
warnings.warn("Maximum number of iterations {max_iter} reached in "
"spatial median for TheilSen regressor."
"".format(max_iter=max_iter), ConvergenceWarning)
return n_iter, spatial_median
|
[
"def",
"_spatial_median",
"(",
"X",
",",
"max_iter",
"=",
"300",
",",
"tol",
"=",
"1.e-3",
")",
":",
"if",
"X",
".",
"shape",
"[",
"1",
"]",
"==",
"1",
":",
"return",
"1",
",",
"np",
".",
"median",
"(",
"X",
".",
"ravel",
"(",
")",
")",
"tol",
"**=",
"2",
"# We are computing the tol on the squared norm",
"spatial_median_old",
"=",
"np",
".",
"mean",
"(",
"X",
",",
"axis",
"=",
"0",
")",
"for",
"n_iter",
"in",
"range",
"(",
"max_iter",
")",
":",
"spatial_median",
"=",
"_modified_weiszfeld_step",
"(",
"X",
",",
"spatial_median_old",
")",
"if",
"np",
".",
"sum",
"(",
"(",
"spatial_median_old",
"-",
"spatial_median",
")",
"**",
"2",
")",
"<",
"tol",
":",
"break",
"else",
":",
"spatial_median_old",
"=",
"spatial_median",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"Maximum number of iterations {max_iter} reached in \"",
"\"spatial median for TheilSen regressor.\"",
"\"\"",
".",
"format",
"(",
"max_iter",
"=",
"max_iter",
")",
",",
"ConvergenceWarning",
")",
"return",
"n_iter",
",",
"spatial_median"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/linear_model/_theil_sen.py#L77-L128
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/dataview.py
|
python
|
DataViewModelNotifier.Cleared
|
(*args, **kwargs)
|
return _dataview.DataViewModelNotifier_Cleared(*args, **kwargs)
|
Cleared(self) -> bool
Override this to be informed that all data has been cleared. The
control will read the visible data items from the model again.
|
Cleared(self) -> bool
|
[
"Cleared",
"(",
"self",
")",
"-",
">",
"bool"
] |
def Cleared(*args, **kwargs):
"""
Cleared(self) -> bool
Override this to be informed that all data has been cleared. The
control will read the visible data items from the model again.
"""
return _dataview.DataViewModelNotifier_Cleared(*args, **kwargs)
|
[
"def",
"Cleared",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewModelNotifier_Cleared",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L250-L257
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/utils.py
|
python
|
set_environ
|
(env_name, value)
|
Set the environment variable 'env_name' to 'value'
Save previous value, yield, and then restore the previous value stored in
the environment variable 'env_name'.
If 'value' is None, do nothing
|
Set the environment variable 'env_name' to 'value'
|
[
"Set",
"the",
"environment",
"variable",
"env_name",
"to",
"value"
] |
def set_environ(env_name, value):
"""Set the environment variable 'env_name' to 'value'
Save previous value, yield, and then restore the previous value stored in
the environment variable 'env_name'.
If 'value' is None, do nothing"""
value_changed = value is not None
if value_changed:
old_value = os.environ.get(env_name)
os.environ[env_name] = value
try:
yield
finally:
if value_changed:
if old_value is None:
del os.environ[env_name]
else:
os.environ[env_name] = old_value
|
[
"def",
"set_environ",
"(",
"env_name",
",",
"value",
")",
":",
"value_changed",
"=",
"value",
"is",
"not",
"None",
"if",
"value_changed",
":",
"old_value",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"env_name",
")",
"os",
".",
"environ",
"[",
"env_name",
"]",
"=",
"value",
"try",
":",
"yield",
"finally",
":",
"if",
"value_changed",
":",
"if",
"old_value",
"is",
"None",
":",
"del",
"os",
".",
"environ",
"[",
"env_name",
"]",
"else",
":",
"os",
".",
"environ",
"[",
"env_name",
"]",
"=",
"old_value"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/utils.py#L688-L706
|
||
tensorflow/io
|
92b44e180674a8af0e12e405530f7343e3e693e4
|
tensorflow_io/python/experimental/mongodb_writer_ops.py
|
python
|
MongoDBWriter.__init__
|
(self, uri, database, collection)
|
Initialize the dataset with the following parameters
Args:
uri: A string, representing the uri of the mongo server or replicaset.
To connect to a MongoDB server with username and password
based authentication, the following uri pattern can be used.
Ex: `"mongodb://mongoadmin:default_password@localhost:27017"`.
Connecting to a replica set is much like connecting to a
standalone MongoDB server. Simply specify the replica set name
using the `?replicaSet=myreplset` URI option.
Ex: "mongodb://host01:27017,host02:27017,host03:27017/?replicaSet=myreplset"
Connection to a secure cluster via CA certs can be achieved by setting
the respective TLS options to the URI.
Ex: "mongodb://host01:27017/?tls=true&sslCertificateAuthorityFile=/opt/ca.pem"
Additional information on writing uri's can be found here:
- [libmongoc uri docs](http://mongoc.org/libmongoc/current/mongoc_uri_t.html)
- [mongodb uri docs](https://docs.mongodb.com/manual/reference/connection-string/)
database: A string, representing the database in the standalone MongoDB
server or a replica set to connect to.
collection: A string, representing the collection from which the documents
have to be retrieved.
|
Initialize the dataset with the following parameters
|
[
"Initialize",
"the",
"dataset",
"with",
"the",
"following",
"parameters"
] |
def __init__(self, uri, database, collection):
"""Initialize the dataset with the following parameters
Args:
uri: A string, representing the uri of the mongo server or replicaset.
To connect to a MongoDB server with username and password
based authentication, the following uri pattern can be used.
Ex: `"mongodb://mongoadmin:default_password@localhost:27017"`.
Connecting to a replica set is much like connecting to a
standalone MongoDB server. Simply specify the replica set name
using the `?replicaSet=myreplset` URI option.
Ex: "mongodb://host01:27017,host02:27017,host03:27017/?replicaSet=myreplset"
Connection to a secure cluster via CA certs can be achieved by setting
the respective TLS options to the URI.
Ex: "mongodb://host01:27017/?tls=true&sslCertificateAuthorityFile=/opt/ca.pem"
Additional information on writing uri's can be found here:
- [libmongoc uri docs](http://mongoc.org/libmongoc/current/mongoc_uri_t.html)
- [mongodb uri docs](https://docs.mongodb.com/manual/reference/connection-string/)
database: A string, representing the database in the standalone MongoDB
server or a replica set to connect to.
collection: A string, representing the collection from which the documents
have to be retrieved.
"""
self.uri = uri
self.database = database
self.collection = collection
self.resource = core_ops.io_mongo_db_writable_init(
uri=self.uri,
database=self.database,
collection=self.collection,
)
|
[
"def",
"__init__",
"(",
"self",
",",
"uri",
",",
"database",
",",
"collection",
")",
":",
"self",
".",
"uri",
"=",
"uri",
"self",
".",
"database",
"=",
"database",
"self",
".",
"collection",
"=",
"collection",
"self",
".",
"resource",
"=",
"core_ops",
".",
"io_mongo_db_writable_init",
"(",
"uri",
"=",
"self",
".",
"uri",
",",
"database",
"=",
"self",
".",
"database",
",",
"collection",
"=",
"self",
".",
"collection",
",",
")"
] |
https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/experimental/mongodb_writer_ops.py#L51-L84
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/gtk/dataview.py
|
python
|
DataViewCtrl.PrependDateColumn
|
(*args, **kwargs)
|
return _dataview.DataViewCtrl_PrependDateColumn(*args, **kwargs)
|
PrependDateColumn(self, PyObject label_or_bitmap, unsigned int model_column,
int mode=DATAVIEW_CELL_ACTIVATABLE, int width=-1,
int align=ALIGN_NOT, int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn
|
PrependDateColumn(self, PyObject label_or_bitmap, unsigned int model_column,
int mode=DATAVIEW_CELL_ACTIVATABLE, int width=-1,
int align=ALIGN_NOT, int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn
|
[
"PrependDateColumn",
"(",
"self",
"PyObject",
"label_or_bitmap",
"unsigned",
"int",
"model_column",
"int",
"mode",
"=",
"DATAVIEW_CELL_ACTIVATABLE",
"int",
"width",
"=",
"-",
"1",
"int",
"align",
"=",
"ALIGN_NOT",
"int",
"flags",
"=",
"DATAVIEW_COL_RESIZABLE",
")",
"-",
">",
"DataViewColumn"
] |
def PrependDateColumn(*args, **kwargs):
"""
PrependDateColumn(self, PyObject label_or_bitmap, unsigned int model_column,
int mode=DATAVIEW_CELL_ACTIVATABLE, int width=-1,
int align=ALIGN_NOT, int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn
"""
return _dataview.DataViewCtrl_PrependDateColumn(*args, **kwargs)
|
[
"def",
"PrependDateColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewCtrl_PrependDateColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1622-L1628
|
|
apple/turicreate
|
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
|
src/python/turicreate/data_structures/sarray.py
|
python
|
SArray.__len__
|
(self)
|
return self.__proxy__.size()
|
Returns the length of the array
|
Returns the length of the array
|
[
"Returns",
"the",
"length",
"of",
"the",
"array"
] |
def __len__(self):
"""
Returns the length of the array
"""
return self.__proxy__.size()
|
[
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"self",
".",
"__proxy__",
".",
"size",
"(",
")"
] |
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sarray.py#L898-L902
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/caching.py
|
python
|
CodeLibraryCacheImpl.rebuild
|
(self, target_context, payload)
|
return target_context.codegen().unserialize_library(payload)
|
Returns the unserialized CodeLibrary
|
Returns the unserialized CodeLibrary
|
[
"Returns",
"the",
"unserialized",
"CodeLibrary"
] |
def rebuild(self, target_context, payload):
"""
Returns the unserialized CodeLibrary
"""
return target_context.codegen().unserialize_library(payload)
|
[
"def",
"rebuild",
"(",
"self",
",",
"target_context",
",",
"payload",
")",
":",
"return",
"target_context",
".",
"codegen",
"(",
")",
".",
"unserialize_library",
"(",
"payload",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/caching.py#L442-L446
|
|
pyne/pyne
|
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
|
pyne/alara.py
|
python
|
_find_dt
|
(idt, decay_times)
|
This function returns a string representing a time in decay times.
Parameters
----------
idt : string
Represents a time, input decay time
decay_times : list of strings
Decay times.
Returns
-------
string from decay_times list that mathches idt
|
This function returns a string representing a time in decay times.
|
[
"This",
"function",
"returns",
"a",
"string",
"representing",
"a",
"time",
"in",
"decay",
"times",
"."
] |
def _find_dt(idt, decay_times):
"""
This function returns a string representing a time in decay times.
Parameters
----------
idt : string
Represents a time, input decay time
decay_times : list of strings
Decay times.
Returns
-------
string from decay_times list that mathches idt
"""
# Check the existence of idt in decay_times list.
if idt in decay_times:
return idt
# Direct matching cannot be found. Convert units to [s] and compare.
else:
# convert idt to [s]
idt_s = _convert_unit_to_s(idt)
# Loop over decay times in decay_times list and compare to idt_s.
for dt in decay_times:
# Skip "shutdown" string in list.
if str_to_unicode(dt) == u'shutdown':
continue
# Convert to [s].
dt_s = _convert_unit_to_s(dt)
if idt_s == dt_s:
# idt_s matches dt_s. return original string, dt.
return dt
elif dt_s != 0.0 and (abs(idt_s - dt_s)/dt_s) < 1e-6:
return dt
# if idt doesn't match any string in decay_times list, raise an error.
raise ValueError(
'Decay time {0} not found in decay_times'.format(idt))
|
[
"def",
"_find_dt",
"(",
"idt",
",",
"decay_times",
")",
":",
"# Check the existence of idt in decay_times list.",
"if",
"idt",
"in",
"decay_times",
":",
"return",
"idt",
"# Direct matching cannot be found. Convert units to [s] and compare.",
"else",
":",
"# convert idt to [s]",
"idt_s",
"=",
"_convert_unit_to_s",
"(",
"idt",
")",
"# Loop over decay times in decay_times list and compare to idt_s.",
"for",
"dt",
"in",
"decay_times",
":",
"# Skip \"shutdown\" string in list.",
"if",
"str_to_unicode",
"(",
"dt",
")",
"==",
"u'shutdown'",
":",
"continue",
"# Convert to [s].",
"dt_s",
"=",
"_convert_unit_to_s",
"(",
"dt",
")",
"if",
"idt_s",
"==",
"dt_s",
":",
"# idt_s matches dt_s. return original string, dt.",
"return",
"dt",
"elif",
"dt_s",
"!=",
"0.0",
"and",
"(",
"abs",
"(",
"idt_s",
"-",
"dt_s",
")",
"/",
"dt_s",
")",
"<",
"1e-6",
":",
"return",
"dt",
"# if idt doesn't match any string in decay_times list, raise an error.",
"raise",
"ValueError",
"(",
"'Decay time {0} not found in decay_times'",
".",
"format",
"(",
"idt",
")",
")"
] |
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/alara.py#L1072-L1108
|
||
wujian16/Cornell-MOE
|
df299d1be882d2af9796d7a68b3f9505cac7a53e
|
moe/optimal_learning/python/python_version/optimization.py
|
python
|
MultistartOptimizer.optimize
|
(self, random_starts=None, **kwargs)
|
return best_point, function_value_list
|
Perform multistart optimization with self.optimizer.
.. Note:: comments copied from MultistartOptimizer::MultistartOptimize in gpp_optimization.hpp.
Performs multistart optimization with the specified Optimizer (instance variable) to optimize the specified
OptimizableInterface (objective function) over the specified DomainInterface. Optimizer behavior is controlled
by the specified ParameterStruct. See class docs and header docs of this file, section 2c and 3b, iii),
for more information.
The method allows you to specify what the current best is, so that if optimization cannot beat it, no improvement will be
reported. It will otherwise report the overall best improvement (through io_container) as well as the result of every
individual multistart run if desired (through function_values).
:param random_starts: points from which to multistart ``self.optimizer``; if None, points are chosen randomly
:type random_starts: array of float64 with shape (num_points, dim) or None
:return: (best point found, objective function values at the end of each optimization run)
:rtype: tuple: (array of float64 with shape (self.optimizer.dim), array of float64 with shape (self.num_multistarts))
|
Perform multistart optimization with self.optimizer.
|
[
"Perform",
"multistart",
"optimization",
"with",
"self",
".",
"optimizer",
"."
] |
def optimize(self, random_starts=None, **kwargs):
"""Perform multistart optimization with self.optimizer.
.. Note:: comments copied from MultistartOptimizer::MultistartOptimize in gpp_optimization.hpp.
Performs multistart optimization with the specified Optimizer (instance variable) to optimize the specified
OptimizableInterface (objective function) over the specified DomainInterface. Optimizer behavior is controlled
by the specified ParameterStruct. See class docs and header docs of this file, section 2c and 3b, iii),
for more information.
The method allows you to specify what the current best is, so that if optimization cannot beat it, no improvement will be
reported. It will otherwise report the overall best improvement (through io_container) as well as the result of every
individual multistart run if desired (through function_values).
:param random_starts: points from which to multistart ``self.optimizer``; if None, points are chosen randomly
:type random_starts: array of float64 with shape (num_points, dim) or None
:return: (best point found, objective function values at the end of each optimization run)
:rtype: tuple: (array of float64 with shape (self.optimizer.dim), array of float64 with shape (self.num_multistarts))
"""
# TODO(GH-59): Pass the best point, fcn value, etc. in thru an IOContainer-like structure.
if random_starts is None:
random_starts = self.optimizer.domain.generate_uniform_random_points_in_domain(self.num_multistarts, None)
best_function_value = -numpy.inf
best_point = random_starts[0, ...] # any point will do
function_value_list = numpy.empty(random_starts.shape[0])
results = []
for i, point in enumerate(random_starts):
self.optimizer.objective_function.current_point = point
self.optimizer.optimize(**kwargs)
function_value = self.optimizer.objective_function.compute_objective_function(**kwargs)
function_value_list[i] = function_value
if function_value > best_function_value:
best_function_value = function_value
best_point = self.optimizer.objective_function.current_point
return best_point, function_value_list
|
[
"def",
"optimize",
"(",
"self",
",",
"random_starts",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO(GH-59): Pass the best point, fcn value, etc. in thru an IOContainer-like structure.",
"if",
"random_starts",
"is",
"None",
":",
"random_starts",
"=",
"self",
".",
"optimizer",
".",
"domain",
".",
"generate_uniform_random_points_in_domain",
"(",
"self",
".",
"num_multistarts",
",",
"None",
")",
"best_function_value",
"=",
"-",
"numpy",
".",
"inf",
"best_point",
"=",
"random_starts",
"[",
"0",
",",
"...",
"]",
"# any point will do",
"function_value_list",
"=",
"numpy",
".",
"empty",
"(",
"random_starts",
".",
"shape",
"[",
"0",
"]",
")",
"results",
"=",
"[",
"]",
"for",
"i",
",",
"point",
"in",
"enumerate",
"(",
"random_starts",
")",
":",
"self",
".",
"optimizer",
".",
"objective_function",
".",
"current_point",
"=",
"point",
"self",
".",
"optimizer",
".",
"optimize",
"(",
"*",
"*",
"kwargs",
")",
"function_value",
"=",
"self",
".",
"optimizer",
".",
"objective_function",
".",
"compute_objective_function",
"(",
"*",
"*",
"kwargs",
")",
"function_value_list",
"[",
"i",
"]",
"=",
"function_value",
"if",
"function_value",
">",
"best_function_value",
":",
"best_function_value",
"=",
"function_value",
"best_point",
"=",
"self",
".",
"optimizer",
".",
"objective_function",
".",
"current_point",
"return",
"best_point",
",",
"function_value_list"
] |
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/python_version/optimization.py#L565-L606
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python/src/Lib/distutils/dist.py
|
python
|
Distribution.run_command
|
(self, command)
|
Do whatever it takes to run a command (including nothing at all,
if the command has already been run). Specifically: if we have
already created and run the command named by 'command', return
silently without doing anything. If the command named by 'command'
doesn't even have a command object yet, create one. Then invoke
'run()' on that command object (or an existing one).
|
Do whatever it takes to run a command (including nothing at all,
if the command has already been run). Specifically: if we have
already created and run the command named by 'command', return
silently without doing anything. If the command named by 'command'
doesn't even have a command object yet, create one. Then invoke
'run()' on that command object (or an existing one).
|
[
"Do",
"whatever",
"it",
"takes",
"to",
"run",
"a",
"command",
"(",
"including",
"nothing",
"at",
"all",
"if",
"the",
"command",
"has",
"already",
"been",
"run",
")",
".",
"Specifically",
":",
"if",
"we",
"have",
"already",
"created",
"and",
"run",
"the",
"command",
"named",
"by",
"command",
"return",
"silently",
"without",
"doing",
"anything",
".",
"If",
"the",
"command",
"named",
"by",
"command",
"doesn",
"t",
"even",
"have",
"a",
"command",
"object",
"yet",
"create",
"one",
".",
"Then",
"invoke",
"run",
"()",
"on",
"that",
"command",
"object",
"(",
"or",
"an",
"existing",
"one",
")",
"."
] |
def run_command(self, command):
"""Do whatever it takes to run a command (including nothing at all,
if the command has already been run). Specifically: if we have
already created and run the command named by 'command', return
silently without doing anything. If the command named by 'command'
doesn't even have a command object yet, create one. Then invoke
'run()' on that command object (or an existing one).
"""
# Already been here, done that? then return silently.
if self.have_run.get(command):
return
log.info("running %s", command)
cmd_obj = self.get_command_obj(command)
cmd_obj.ensure_finalized()
cmd_obj.run()
self.have_run[command] = 1
|
[
"def",
"run_command",
"(",
"self",
",",
"command",
")",
":",
"# Already been here, done that? then return silently.",
"if",
"self",
".",
"have_run",
".",
"get",
"(",
"command",
")",
":",
"return",
"log",
".",
"info",
"(",
"\"running %s\"",
",",
"command",
")",
"cmd_obj",
"=",
"self",
".",
"get_command_obj",
"(",
"command",
")",
"cmd_obj",
".",
"ensure_finalized",
"(",
")",
"cmd_obj",
".",
"run",
"(",
")",
"self",
".",
"have_run",
"[",
"command",
"]",
"=",
"1"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/dist.py#L957-L973
|
||
LLNL/lbann
|
26083e6c86050302ce33148aea70f62e61cacb92
|
scripts/plotting/load_events.py
|
python
|
yield_events
|
(filename)
|
Yield events from filename.
|
Yield events from filename.
|
[
"Yield",
"events",
"from",
"filename",
"."
] |
def yield_events(filename):
"""Yield events from filename."""
# If we can fit it in memory, prefer to read the entire file first.
if os.path.getsize(filename) < max_read_size:
return _yield_events_mem(filename)
else:
return _yield_events_read(filename)
|
[
"def",
"yield_events",
"(",
"filename",
")",
":",
"# If we can fit it in memory, prefer to read the entire file first.",
"if",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
"<",
"max_read_size",
":",
"return",
"_yield_events_mem",
"(",
"filename",
")",
"else",
":",
"return",
"_yield_events_read",
"(",
"filename",
")"
] |
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/scripts/plotting/load_events.py#L51-L57
|
||
openvinotoolkit/openvino
|
dedcbeafa8b84cccdc55ca64b8da516682b381c7
|
src/bindings/python/src/compatibility/ngraph/opset1/ops.py
|
python
|
group_convolution_backprop_data
|
(
data: NodeInput,
filters: NodeInput,
strides: List[int],
output_shape: Optional[NodeInput] = None,
pads_begin: Optional[List[int]] = None,
pads_end: Optional[List[int]] = None,
dilations: Optional[List[int]] = None,
auto_pad: str = "EXPLICIT",
output_padding: Optional[List[int]] = None,
name: Optional[str] = None,
)
|
return _get_node_factory_opset1().create("GroupConvolutionBackpropData", args, attributes)
|
Perform Group Convolution operation on data from input node.
:param data: The node producing input data.
:param filters: The node producing filter data.
:param strides: The distance (in pixels) to slide the filter on the feature map
over the axes.
:param output_shape: The node that specifies spatial shape of the output.
:param pads_begin: The number of pixels to add at the beginning along each axis.
:param pads_end: The number of pixels to add at the end along each axis.
:param dilations: The distance in width and height between elements (weights)
in the filter.
:param auto_pad: Describes how to perform padding. Possible values:
EXPLICIT: Pad dimensions are explicity specified
SAME_LOWER: Pad dimensions computed to match input shape
Ceil(num_dims/2) at the beginning and
Floor(num_dims/2) at the end
SAME_UPPER: Pad dimensions computed to match input shape
Floor(num_dims/2) at the beginning and
Ceil(num_dims/2) at the end
VALID: No padding
:param output_padding: The additional amount of paddings added per each spatial axis
in the output tensor.
:param name: Optional output node name.
:return: The new node performing a Group Convolution operation on tensor from input node.
|
Perform Group Convolution operation on data from input node.
|
[
"Perform",
"Group",
"Convolution",
"operation",
"on",
"data",
"from",
"input",
"node",
"."
] |
def group_convolution_backprop_data(
data: NodeInput,
filters: NodeInput,
strides: List[int],
output_shape: Optional[NodeInput] = None,
pads_begin: Optional[List[int]] = None,
pads_end: Optional[List[int]] = None,
dilations: Optional[List[int]] = None,
auto_pad: str = "EXPLICIT",
output_padding: Optional[List[int]] = None,
name: Optional[str] = None,
) -> Node:
"""Perform Group Convolution operation on data from input node.
:param data: The node producing input data.
:param filters: The node producing filter data.
:param strides: The distance (in pixels) to slide the filter on the feature map
over the axes.
:param output_shape: The node that specifies spatial shape of the output.
:param pads_begin: The number of pixels to add at the beginning along each axis.
:param pads_end: The number of pixels to add at the end along each axis.
:param dilations: The distance in width and height between elements (weights)
in the filter.
:param auto_pad: Describes how to perform padding. Possible values:
EXPLICIT: Pad dimensions are explicity specified
SAME_LOWER: Pad dimensions computed to match input shape
Ceil(num_dims/2) at the beginning and
Floor(num_dims/2) at the end
SAME_UPPER: Pad dimensions computed to match input shape
Floor(num_dims/2) at the beginning and
Ceil(num_dims/2) at the end
VALID: No padding
:param output_padding: The additional amount of paddings added per each spatial axis
in the output tensor.
:param name: Optional output node name.
:return: The new node performing a Group Convolution operation on tensor from input node.
"""
spatial_dim_count = len(strides)
if dilations is None:
dilations = [1] * spatial_dim_count
if output_padding is None:
output_padding = [0] * spatial_dim_count
attributes = {
"strides": strides,
"dilations": dilations,
"auto_pad": auto_pad.upper(),
"output_padding": output_padding,
}
args = as_nodes(data, filters)
if output_shape is not None:
args.append(as_node(output_shape))
else:
if pads_begin is None:
pads_begin = [0] * spatial_dim_count
if pads_end is None:
pads_end = [0] * spatial_dim_count
attributes["pads_begin"] = pads_begin
attributes["pads_end"] = pads_end
return _get_node_factory_opset1().create("GroupConvolutionBackpropData", args, attributes)
|
[
"def",
"group_convolution_backprop_data",
"(",
"data",
":",
"NodeInput",
",",
"filters",
":",
"NodeInput",
",",
"strides",
":",
"List",
"[",
"int",
"]",
",",
"output_shape",
":",
"Optional",
"[",
"NodeInput",
"]",
"=",
"None",
",",
"pads_begin",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
",",
"pads_end",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
",",
"dilations",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
",",
"auto_pad",
":",
"str",
"=",
"\"EXPLICIT\"",
",",
"output_padding",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"Node",
":",
"spatial_dim_count",
"=",
"len",
"(",
"strides",
")",
"if",
"dilations",
"is",
"None",
":",
"dilations",
"=",
"[",
"1",
"]",
"*",
"spatial_dim_count",
"if",
"output_padding",
"is",
"None",
":",
"output_padding",
"=",
"[",
"0",
"]",
"*",
"spatial_dim_count",
"attributes",
"=",
"{",
"\"strides\"",
":",
"strides",
",",
"\"dilations\"",
":",
"dilations",
",",
"\"auto_pad\"",
":",
"auto_pad",
".",
"upper",
"(",
")",
",",
"\"output_padding\"",
":",
"output_padding",
",",
"}",
"args",
"=",
"as_nodes",
"(",
"data",
",",
"filters",
")",
"if",
"output_shape",
"is",
"not",
"None",
":",
"args",
".",
"append",
"(",
"as_node",
"(",
"output_shape",
")",
")",
"else",
":",
"if",
"pads_begin",
"is",
"None",
":",
"pads_begin",
"=",
"[",
"0",
"]",
"*",
"spatial_dim_count",
"if",
"pads_end",
"is",
"None",
":",
"pads_end",
"=",
"[",
"0",
"]",
"*",
"spatial_dim_count",
"attributes",
"[",
"\"pads_begin\"",
"]",
"=",
"pads_begin",
"attributes",
"[",
"\"pads_end\"",
"]",
"=",
"pads_end",
"return",
"_get_node_factory_opset1",
"(",
")",
".",
"create",
"(",
"\"GroupConvolutionBackpropData\"",
",",
"args",
",",
"attributes",
")"
] |
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/opset1/ops.py#L1088-L1149
|
|
CRYTEK/CRYENGINE
|
232227c59a220cbbd311576f0fbeba7bb53b2a8c
|
Editor/Python/windows/Lib/site-packages/setuptools/package_index.py
|
python
|
PyPIConfig.find_credential
|
(self, url)
|
If the URL indicated appears to be a repository defined in this
config, return the credential for that repository.
|
If the URL indicated appears to be a repository defined in this
config, return the credential for that repository.
|
[
"If",
"the",
"URL",
"indicated",
"appears",
"to",
"be",
"a",
"repository",
"defined",
"in",
"this",
"config",
"return",
"the",
"credential",
"for",
"that",
"repository",
"."
] |
def find_credential(self, url):
"""
If the URL indicated appears to be a repository defined in this
config, return the credential for that repository.
"""
for repository, cred in self.creds_by_repository.items():
if url.startswith(repository):
return cred
|
[
"def",
"find_credential",
"(",
"self",
",",
"url",
")",
":",
"for",
"repository",
",",
"cred",
"in",
"self",
".",
"creds_by_repository",
".",
"items",
"(",
")",
":",
"if",
"url",
".",
"startswith",
"(",
"repository",
")",
":",
"return",
"cred"
] |
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/package_index.py#L1037-L1044
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/msw/stc.py
|
python
|
StyledTextCtrl.GetAllLinesVisible
|
(*args, **kwargs)
|
return _stc.StyledTextCtrl_GetAllLinesVisible(*args, **kwargs)
|
GetAllLinesVisible(self) -> bool
|
GetAllLinesVisible(self) -> bool
|
[
"GetAllLinesVisible",
"(",
"self",
")",
"-",
">",
"bool"
] |
def GetAllLinesVisible(*args, **kwargs):
"""GetAllLinesVisible(self) -> bool"""
return _stc.StyledTextCtrl_GetAllLinesVisible(*args, **kwargs)
|
[
"def",
"GetAllLinesVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetAllLinesVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L3954-L3956
|
|
BlzFans/wke
|
b0fa21158312e40c5fbd84682d643022b6c34a93
|
cygwin/lib/python2.6/decimal.py
|
python
|
Decimal.log10
|
(self, context=None)
|
return ans
|
Returns the base 10 logarithm of self.
|
Returns the base 10 logarithm of self.
|
[
"Returns",
"the",
"base",
"10",
"logarithm",
"of",
"self",
"."
] |
def log10(self, context=None):
"""Returns the base 10 logarithm of self."""
if context is None:
context = getcontext()
# log10(NaN) = NaN
ans = self._check_nans(context=context)
if ans:
return ans
# log10(0.0) == -Infinity
if not self:
return _NegativeInfinity
# log10(Infinity) = Infinity
if self._isinfinity() == 1:
return _Infinity
# log10(negative or -Infinity) raises InvalidOperation
if self._sign == 1:
return context._raise_error(InvalidOperation,
'log10 of a negative value')
# log10(10**n) = n
if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
# answer may need rounding
ans = Decimal(self._exp + len(self._int) - 1)
else:
# result is irrational, so necessarily inexact
op = _WorkRep(self)
c, e = op.int, op.exp
p = context.prec
# correctly rounded result: repeatedly increase precision
# until result is unambiguously roundable
places = p-self._log10_exp_bound()+2
while True:
coeff = _dlog10(c, e, places)
# assert len(str(abs(coeff)))-p >= 1
if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
break
places += 3
ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
context = context._shallow_copy()
rounding = context._set_rounding(ROUND_HALF_EVEN)
ans = ans._fix(context)
context.rounding = rounding
return ans
|
[
"def",
"log10",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"getcontext",
"(",
")",
"# log10(NaN) = NaN",
"ans",
"=",
"self",
".",
"_check_nans",
"(",
"context",
"=",
"context",
")",
"if",
"ans",
":",
"return",
"ans",
"# log10(0.0) == -Infinity",
"if",
"not",
"self",
":",
"return",
"_NegativeInfinity",
"# log10(Infinity) = Infinity",
"if",
"self",
".",
"_isinfinity",
"(",
")",
"==",
"1",
":",
"return",
"_Infinity",
"# log10(negative or -Infinity) raises InvalidOperation",
"if",
"self",
".",
"_sign",
"==",
"1",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
",",
"'log10 of a negative value'",
")",
"# log10(10**n) = n",
"if",
"self",
".",
"_int",
"[",
"0",
"]",
"==",
"'1'",
"and",
"self",
".",
"_int",
"[",
"1",
":",
"]",
"==",
"'0'",
"*",
"(",
"len",
"(",
"self",
".",
"_int",
")",
"-",
"1",
")",
":",
"# answer may need rounding",
"ans",
"=",
"Decimal",
"(",
"self",
".",
"_exp",
"+",
"len",
"(",
"self",
".",
"_int",
")",
"-",
"1",
")",
"else",
":",
"# result is irrational, so necessarily inexact",
"op",
"=",
"_WorkRep",
"(",
"self",
")",
"c",
",",
"e",
"=",
"op",
".",
"int",
",",
"op",
".",
"exp",
"p",
"=",
"context",
".",
"prec",
"# correctly rounded result: repeatedly increase precision",
"# until result is unambiguously roundable",
"places",
"=",
"p",
"-",
"self",
".",
"_log10_exp_bound",
"(",
")",
"+",
"2",
"while",
"True",
":",
"coeff",
"=",
"_dlog10",
"(",
"c",
",",
"e",
",",
"places",
")",
"# assert len(str(abs(coeff)))-p >= 1",
"if",
"coeff",
"%",
"(",
"5",
"*",
"10",
"**",
"(",
"len",
"(",
"str",
"(",
"abs",
"(",
"coeff",
")",
")",
")",
"-",
"p",
"-",
"1",
")",
")",
":",
"break",
"places",
"+=",
"3",
"ans",
"=",
"_dec_from_triple",
"(",
"int",
"(",
"coeff",
"<",
"0",
")",
",",
"str",
"(",
"abs",
"(",
"coeff",
")",
")",
",",
"-",
"places",
")",
"context",
"=",
"context",
".",
"_shallow_copy",
"(",
")",
"rounding",
"=",
"context",
".",
"_set_rounding",
"(",
"ROUND_HALF_EVEN",
")",
"ans",
"=",
"ans",
".",
"_fix",
"(",
"context",
")",
"context",
".",
"rounding",
"=",
"rounding",
"return",
"ans"
] |
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L3012-L3061
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/groupby/groupby.py
|
python
|
GroupBy.rolling
|
(self, *args, **kwargs)
|
return RollingGroupby(self, *args, **kwargs)
|
Return a rolling grouper, providing rolling functionality per group.
|
Return a rolling grouper, providing rolling functionality per group.
|
[
"Return",
"a",
"rolling",
"grouper",
"providing",
"rolling",
"functionality",
"per",
"group",
"."
] |
def rolling(self, *args, **kwargs):
"""
Return a rolling grouper, providing rolling functionality per group.
"""
from pandas.core.window import RollingGroupby
return RollingGroupby(self, *args, **kwargs)
|
[
"def",
"rolling",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"pandas",
".",
"core",
".",
"window",
"import",
"RollingGroupby",
"return",
"RollingGroupby",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/groupby/groupby.py#L1562-L1568
|
|
apache/arrow
|
af33dd1157eb8d7d9bfac25ebf61445b793b7943
|
dev/archery/archery/cli.py
|
python
|
build
|
(ctx, src, build_dir, force, targets, **kwargs)
|
Initialize a C++ build directory.
The build command creates a directory initialized with Arrow's cpp source
cmake and configuration. It can also optionally invoke the generator to
test the build (and used in scripts).
Note that archery will carry the caller environment. It will also not touch
an existing directory, one must use the `--force` option to remove the
existing directory.
Examples:
\b
# Initialize build with clang8 and avx2 support in directory `clang8-build`
\b
archery build --cc=clang-8 --cxx=clang++-8 --cxx-flags=-mavx2 clang8-build
\b
# Builds and run test
archery build --targets=all --targets=test build
|
Initialize a C++ build directory.
|
[
"Initialize",
"a",
"C",
"++",
"build",
"directory",
"."
] |
def build(ctx, src, build_dir, force, targets, **kwargs):
""" Initialize a C++ build directory.
The build command creates a directory initialized with Arrow's cpp source
cmake and configuration. It can also optionally invoke the generator to
test the build (and used in scripts).
Note that archery will carry the caller environment. It will also not touch
an existing directory, one must use the `--force` option to remove the
existing directory.
Examples:
\b
# Initialize build with clang8 and avx2 support in directory `clang8-build`
\b
archery build --cc=clang-8 --cxx=clang++-8 --cxx-flags=-mavx2 clang8-build
\b
# Builds and run test
archery build --targets=all --targets=test build
"""
# Arrow's cpp cmake configuration
conf = CppConfiguration(**kwargs)
# This is a closure around cmake invocation, e.g. calling `def.build()`
# yields a directory ready to be run with the generator
cmake_def = CppCMakeDefinition(src.cpp, conf)
# Create build directory
build = cmake_def.build(build_dir, force=force)
for target in targets:
build.run(target)
|
[
"def",
"build",
"(",
"ctx",
",",
"src",
",",
"build_dir",
",",
"force",
",",
"targets",
",",
"*",
"*",
"kwargs",
")",
":",
"# Arrow's cpp cmake configuration",
"conf",
"=",
"CppConfiguration",
"(",
"*",
"*",
"kwargs",
")",
"# This is a closure around cmake invocation, e.g. calling `def.build()`",
"# yields a directory ready to be run with the generator",
"cmake_def",
"=",
"CppCMakeDefinition",
"(",
"src",
".",
"cpp",
",",
"conf",
")",
"# Create build directory",
"build",
"=",
"cmake_def",
".",
"build",
"(",
"build_dir",
",",
"force",
"=",
"force",
")",
"for",
"target",
"in",
"targets",
":",
"build",
".",
"run",
"(",
"target",
")"
] |
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/cli.py#L211-L242
|
||
netket/netket
|
0d534e54ecbf25b677ea72af6b85947979420652
|
netket/jax/utils.py
|
python
|
tree_to_real
|
(pytree: PyTree)
|
return _tree_to_real(pytree), partial(
_tree_reassemble_complex, target=pytree, fun=_tree_to_real
)
|
Replace all complex leaves of a pytree with a tuple of 2 real leaves.
Args:
pytree: a pytree to convert to real
Returns:
A pair where the first element is the converted real pytree,
and the second element is a callable for converting back a real pytree
to a complex pytree of of the same structure as the input pytree.
|
Replace all complex leaves of a pytree with a tuple of 2 real leaves.
|
[
"Replace",
"all",
"complex",
"leaves",
"of",
"a",
"pytree",
"with",
"a",
"tuple",
"of",
"2",
"real",
"leaves",
"."
] |
def tree_to_real(pytree: PyTree) -> Tuple[PyTree, Callable]:
"""Replace all complex leaves of a pytree with a tuple of 2 real leaves.
Args:
pytree: a pytree to convert to real
Returns:
A pair where the first element is the converted real pytree,
and the second element is a callable for converting back a real pytree
to a complex pytree of of the same structure as the input pytree.
"""
return _tree_to_real(pytree), partial(
_tree_reassemble_complex, target=pytree, fun=_tree_to_real
)
|
[
"def",
"tree_to_real",
"(",
"pytree",
":",
"PyTree",
")",
"->",
"Tuple",
"[",
"PyTree",
",",
"Callable",
"]",
":",
"return",
"_tree_to_real",
"(",
"pytree",
")",
",",
"partial",
"(",
"_tree_reassemble_complex",
",",
"target",
"=",
"pytree",
",",
"fun",
"=",
"_tree_to_real",
")"
] |
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/jax/utils.py#L253-L266
|
|
kamyu104/LeetCode-Solutions
|
77605708a927ea3b85aee5a479db733938c7c211
|
Python/flip-game-ii.py
|
python
|
Solution3.canWin
|
(self, s)
|
return is_win
|
:type s: str
:rtype: bool
|
:type s: str
:rtype: bool
|
[
":",
"type",
"s",
":",
"str",
":",
"rtype",
":",
"bool"
] |
def canWin(self, s):
"""
:type s: str
:rtype: bool
"""
i, n = 0, len(s) - 1
is_win = False
while not is_win and i < n: # O(n) time
if s[i] == '+':
while not is_win and i < n and s[i+1] == '+': # O(c) time
# t(n, c) = c * (t(n, c-1) + n) + n = ...
# = c! * t(n, 0) + n * c! * (c + 1) * (1/0! + 1/1! + ... 1/c!)
# = n * c! + n * c! * (c + 1) * O(e) = O(c * n * c!)
is_win = not self.canWin(s[:i] + '--' + s[i+2:]) # O(n) space
i += 1
i += 1
return is_win
|
[
"def",
"canWin",
"(",
"self",
",",
"s",
")",
":",
"i",
",",
"n",
"=",
"0",
",",
"len",
"(",
"s",
")",
"-",
"1",
"is_win",
"=",
"False",
"while",
"not",
"is_win",
"and",
"i",
"<",
"n",
":",
"# O(n) time",
"if",
"s",
"[",
"i",
"]",
"==",
"'+'",
":",
"while",
"not",
"is_win",
"and",
"i",
"<",
"n",
"and",
"s",
"[",
"i",
"+",
"1",
"]",
"==",
"'+'",
":",
"# O(c) time",
"# t(n, c) = c * (t(n, c-1) + n) + n = ...",
"# = c! * t(n, 0) + n * c! * (c + 1) * (1/0! + 1/1! + ... 1/c!)",
"# = n * c! + n * c! * (c + 1) * O(e) = O(c * n * c!)",
"is_win",
"=",
"not",
"self",
".",
"canWin",
"(",
"s",
"[",
":",
"i",
"]",
"+",
"'--'",
"+",
"s",
"[",
"i",
"+",
"2",
":",
"]",
")",
"# O(n) space",
"i",
"+=",
"1",
"i",
"+=",
"1",
"return",
"is_win"
] |
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/flip-game-ii.py#L55-L71
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/gtk/html.py
|
python
|
HtmlParser.SetFS
|
(*args, **kwargs)
|
return _html.HtmlParser_SetFS(*args, **kwargs)
|
SetFS(self, FileSystem fs)
|
SetFS(self, FileSystem fs)
|
[
"SetFS",
"(",
"self",
"FileSystem",
"fs",
")"
] |
def SetFS(*args, **kwargs):
"""SetFS(self, FileSystem fs)"""
return _html.HtmlParser_SetFS(*args, **kwargs)
|
[
"def",
"SetFS",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlParser_SetFS",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L185-L187
|
|
cms-sw/cmssw
|
fd9de012d503d3405420bcbeec0ec879baa57cf2
|
Alignment/MuonAlignment/python/svgfig.py
|
python
|
Axes.SVG
|
(self, trans=None)
|
return SVG("g", *(xaxis.sub + yaxis.sub))
|
Apply the transformation "trans" and return an SVG object.
|
Apply the transformation "trans" and return an SVG object.
|
[
"Apply",
"the",
"transformation",
"trans",
"and",
"return",
"an",
"SVG",
"object",
"."
] |
def SVG(self, trans=None):
"""Apply the transformation "trans" and return an SVG object."""
atx, aty = self.atx, self.aty
if atx < self.xmin: atx = self.xmin
if atx > self.xmax: atx = self.xmax
if aty < self.ymin: aty = self.ymin
if aty > self.ymax: aty = self.ymax
xmargin = 0.1 * abs(self.ymin - self.ymax)
xexclude = atx - xmargin, atx + xmargin
ymargin = 0.1 * abs(self.xmin - self.xmax)
yexclude = aty - ymargin, aty + ymargin
if self.arrows != None and self.arrows != False:
xarrow_start = self.arrows + ".xstart"
xarrow_end = self.arrows + ".xend"
yarrow_start = self.arrows + ".ystart"
yarrow_end = self.arrows + ".yend"
else:
xarrow_start = xarrow_end = yarrow_start = yarrow_end = None
xaxis = XAxis(self.xmin, self.xmax, aty, self.xticks, self.xminiticks, self.xlabels, self.xlogbase, xarrow_start, xarrow_end, exclude=xexclude, text_attr=self.text_attr, **self.attr).SVG(trans)
yaxis = YAxis(self.ymin, self.ymax, atx, self.yticks, self.yminiticks, self.ylabels, self.ylogbase, yarrow_start, yarrow_end, exclude=yexclude, text_attr=self.text_attr, **self.attr).SVG(trans)
return SVG("g", *(xaxis.sub + yaxis.sub))
|
[
"def",
"SVG",
"(",
"self",
",",
"trans",
"=",
"None",
")",
":",
"atx",
",",
"aty",
"=",
"self",
".",
"atx",
",",
"self",
".",
"aty",
"if",
"atx",
"<",
"self",
".",
"xmin",
":",
"atx",
"=",
"self",
".",
"xmin",
"if",
"atx",
">",
"self",
".",
"xmax",
":",
"atx",
"=",
"self",
".",
"xmax",
"if",
"aty",
"<",
"self",
".",
"ymin",
":",
"aty",
"=",
"self",
".",
"ymin",
"if",
"aty",
">",
"self",
".",
"ymax",
":",
"aty",
"=",
"self",
".",
"ymax",
"xmargin",
"=",
"0.1",
"*",
"abs",
"(",
"self",
".",
"ymin",
"-",
"self",
".",
"ymax",
")",
"xexclude",
"=",
"atx",
"-",
"xmargin",
",",
"atx",
"+",
"xmargin",
"ymargin",
"=",
"0.1",
"*",
"abs",
"(",
"self",
".",
"xmin",
"-",
"self",
".",
"xmax",
")",
"yexclude",
"=",
"aty",
"-",
"ymargin",
",",
"aty",
"+",
"ymargin",
"if",
"self",
".",
"arrows",
"!=",
"None",
"and",
"self",
".",
"arrows",
"!=",
"False",
":",
"xarrow_start",
"=",
"self",
".",
"arrows",
"+",
"\".xstart\"",
"xarrow_end",
"=",
"self",
".",
"arrows",
"+",
"\".xend\"",
"yarrow_start",
"=",
"self",
".",
"arrows",
"+",
"\".ystart\"",
"yarrow_end",
"=",
"self",
".",
"arrows",
"+",
"\".yend\"",
"else",
":",
"xarrow_start",
"=",
"xarrow_end",
"=",
"yarrow_start",
"=",
"yarrow_end",
"=",
"None",
"xaxis",
"=",
"XAxis",
"(",
"self",
".",
"xmin",
",",
"self",
".",
"xmax",
",",
"aty",
",",
"self",
".",
"xticks",
",",
"self",
".",
"xminiticks",
",",
"self",
".",
"xlabels",
",",
"self",
".",
"xlogbase",
",",
"xarrow_start",
",",
"xarrow_end",
",",
"exclude",
"=",
"xexclude",
",",
"text_attr",
"=",
"self",
".",
"text_attr",
",",
"*",
"*",
"self",
".",
"attr",
")",
".",
"SVG",
"(",
"trans",
")",
"yaxis",
"=",
"YAxis",
"(",
"self",
".",
"ymin",
",",
"self",
".",
"ymax",
",",
"atx",
",",
"self",
".",
"yticks",
",",
"self",
".",
"yminiticks",
",",
"self",
".",
"ylabels",
",",
"self",
".",
"ylogbase",
",",
"yarrow_start",
",",
"yarrow_end",
",",
"exclude",
"=",
"yexclude",
",",
"text_attr",
"=",
"self",
".",
"text_attr",
",",
"*",
"*",
"self",
".",
"attr",
")",
".",
"SVG",
"(",
"trans",
")",
"return",
"SVG",
"(",
"\"g\"",
",",
"*",
"(",
"xaxis",
".",
"sub",
"+",
"yaxis",
".",
"sub",
")",
")"
] |
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/MuonAlignment/python/svgfig.py#L3093-L3117
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/scipy/pavement.py
|
python
|
wininst_name
|
(pyver)
|
return "scipy-%s.win32-py%s%s" % (FULLVERSION, pyver, ext)
|
Return the name of the installer built by wininst command.
|
Return the name of the installer built by wininst command.
|
[
"Return",
"the",
"name",
"of",
"the",
"installer",
"built",
"by",
"wininst",
"command",
"."
] |
def wininst_name(pyver):
"""Return the name of the installer built by wininst command."""
ext = '.exe'
return "scipy-%s.win32-py%s%s" % (FULLVERSION, pyver, ext)
|
[
"def",
"wininst_name",
"(",
"pyver",
")",
":",
"ext",
"=",
"'.exe'",
"return",
"\"scipy-%s.win32-py%s%s\"",
"%",
"(",
"FULLVERSION",
",",
"pyver",
",",
"ext",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/pavement.py#L383-L386
|
|
Polidea/SiriusObfuscator
|
b0e590d8130e97856afe578869b83a209e2b19be
|
SymbolExtractorAndRenamer/clang/docs/tools/dump_ast_matchers.py
|
python
|
esc
|
(text)
|
return text
|
Escape any html in the given text.
|
Escape any html in the given text.
|
[
"Escape",
"any",
"html",
"in",
"the",
"given",
"text",
"."
] |
def esc(text):
"""Escape any html in the given text."""
text = re.sub(r'&', '&', text)
text = re.sub(r'<', '<', text)
text = re.sub(r'>', '>', text)
def link_if_exists(m):
name = m.group(1)
url = 'http://clang.llvm.org/doxygen/classclang_1_1%s.html' % name
if url not in doxygen_probes:
try:
print 'Probing %s...' % url
urllib2.urlopen(url)
doxygen_probes[url] = True
except:
doxygen_probes[url] = False
if doxygen_probes[url]:
return r'Matcher<<a href="%s">%s</a>>' % (url, name)
else:
return m.group(0)
text = re.sub(
r'Matcher<([^\*&]+)>', link_if_exists, text)
return text
|
[
"def",
"esc",
"(",
"text",
")",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r'&'",
",",
"'&'",
",",
"text",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'<'",
",",
"'<'",
",",
"text",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'>'",
",",
"'>'",
",",
"text",
")",
"def",
"link_if_exists",
"(",
"m",
")",
":",
"name",
"=",
"m",
".",
"group",
"(",
"1",
")",
"url",
"=",
"'http://clang.llvm.org/doxygen/classclang_1_1%s.html'",
"%",
"name",
"if",
"url",
"not",
"in",
"doxygen_probes",
":",
"try",
":",
"print",
"'Probing %s...'",
"%",
"url",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"doxygen_probes",
"[",
"url",
"]",
"=",
"True",
"except",
":",
"doxygen_probes",
"[",
"url",
"]",
"=",
"False",
"if",
"doxygen_probes",
"[",
"url",
"]",
":",
"return",
"r'Matcher<<a href=\"%s\">%s</a>>'",
"%",
"(",
"url",
",",
"name",
")",
"else",
":",
"return",
"m",
".",
"group",
"(",
"0",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'Matcher<([^\\*&]+)>'",
",",
"link_if_exists",
",",
"text",
")",
"return",
"text"
] |
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/docs/tools/dump_ast_matchers.py#L34-L55
|
|
weolar/miniblink49
|
1c4678db0594a4abde23d3ebbcc7cd13c3170777
|
third_party/jinja2/filters.py
|
python
|
do_trim
|
(value)
|
return soft_unicode(value).strip()
|
Strip leading and trailing whitespace.
|
Strip leading and trailing whitespace.
|
[
"Strip",
"leading",
"and",
"trailing",
"whitespace",
"."
] |
def do_trim(value):
"""Strip leading and trailing whitespace."""
return soft_unicode(value).strip()
|
[
"def",
"do_trim",
"(",
"value",
")",
":",
"return",
"soft_unicode",
"(",
"value",
")",
".",
"strip",
"(",
")"
] |
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/filters.py#L547-L549
|
|
tzutalin/dlib-android
|
989627cb7fe81cd1d41d73434b0e91ce1dd2683f
|
tools/lint/cpplint.py
|
python
|
FileInfo.Split
|
(self)
|
return (project,) + os.path.splitext(rest)
|
Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
|
Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
|
[
"Splits",
"the",
"file",
"into",
"the",
"directory",
"basename",
"and",
"extension",
".",
"For",
"chrome",
"/",
"browser",
"/",
"browser",
".",
"cc",
"Split",
"()",
"would",
"return",
"(",
"chrome",
"/",
"browser",
"browser",
".",
"cc",
")",
"Returns",
":",
"A",
"tuple",
"of",
"(",
"directory",
"basename",
"extension",
")",
"."
] |
def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest)
|
[
"def",
"Split",
"(",
"self",
")",
":",
"googlename",
"=",
"self",
".",
"RepositoryName",
"(",
")",
"project",
",",
"rest",
"=",
"os",
".",
"path",
".",
"split",
"(",
"googlename",
")",
"return",
"(",
"project",
",",
")",
"+",
"os",
".",
"path",
".",
"splitext",
"(",
"rest",
")"
] |
https://github.com/tzutalin/dlib-android/blob/989627cb7fe81cd1d41d73434b0e91ce1dd2683f/tools/lint/cpplint.py#L1064-L1074
|
|
mindspore-ai/mindspore
|
fb8fd3338605bb34fa5cea054e535a8b1d753fab
|
mindspore/python/mindspore/ops/_op_impl/tbe/fake_quant_with_min_max_vars.py
|
python
|
_fake_quant_with_min_max_vars_tbe
|
()
|
return
|
FakeQuantWithMinMaxVar TBE register
|
FakeQuantWithMinMaxVar TBE register
|
[
"FakeQuantWithMinMaxVar",
"TBE",
"register"
] |
def _fake_quant_with_min_max_vars_tbe():
"""FakeQuantWithMinMaxVar TBE register"""
return
|
[
"def",
"_fake_quant_with_min_max_vars_tbe",
"(",
")",
":",
"return"
] |
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/fake_quant_with_min_max_vars.py#L37-L39
|
|
pytorch/pytorch
|
7176c92687d3cc847cc046bf002269c6949a21c2
|
torch/nn/quantized/functional.py
|
python
|
celu
|
(input: Tensor, scale: float, zero_point: int, alpha: float = 1.)
|
return torch.ops.quantized.celu(input, scale, zero_point, alpha)
|
r"""celu(input, scale, zero_point, alpha=1.) -> Tensor
Applies the quantized CELU function element-wise.
.. math::
\text{CELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x / \alpha) - 1))
Args:
input: quantized input
alpha: the :math:`\alpha` value for the CELU formulation. Default: 1.0
|
r"""celu(input, scale, zero_point, alpha=1.) -> Tensor
|
[
"r",
"celu",
"(",
"input",
"scale",
"zero_point",
"alpha",
"=",
"1",
".",
")",
"-",
">",
"Tensor"
] |
def celu(input: Tensor, scale: float, zero_point: int, alpha: float = 1.) -> Tensor:
r"""celu(input, scale, zero_point, alpha=1.) -> Tensor
Applies the quantized CELU function element-wise.
.. math::
\text{CELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x / \alpha) - 1))
Args:
input: quantized input
alpha: the :math:`\alpha` value for the CELU formulation. Default: 1.0
"""
if not input.is_quantized:
raise ValueError("Input to 'quantized.celu' must be quantized!")
return torch.ops.quantized.celu(input, scale, zero_point, alpha)
|
[
"def",
"celu",
"(",
"input",
":",
"Tensor",
",",
"scale",
":",
"float",
",",
"zero_point",
":",
"int",
",",
"alpha",
":",
"float",
"=",
"1.",
")",
"->",
"Tensor",
":",
"if",
"not",
"input",
".",
"is_quantized",
":",
"raise",
"ValueError",
"(",
"\"Input to 'quantized.celu' must be quantized!\"",
")",
"return",
"torch",
".",
"ops",
".",
"quantized",
".",
"celu",
"(",
"input",
",",
"scale",
",",
"zero_point",
",",
"alpha",
")"
] |
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/quantized/functional.py#L397-L411
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/stc.py
|
python
|
StyledTextCtrl.DelWordRightEnd
|
(*args, **kwargs)
|
return _stc.StyledTextCtrl_DelWordRightEnd(*args, **kwargs)
|
DelWordRightEnd(self)
Delete the word to the right of the caret, but not the trailing non-word characters.
|
DelWordRightEnd(self)
|
[
"DelWordRightEnd",
"(",
"self",
")"
] |
def DelWordRightEnd(*args, **kwargs):
"""
DelWordRightEnd(self)
Delete the word to the right of the caret, but not the trailing non-word characters.
"""
return _stc.StyledTextCtrl_DelWordRightEnd(*args, **kwargs)
|
[
"def",
"DelWordRightEnd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_DelWordRightEnd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L4628-L4634
|
|
mongodb/mongo-cxx-driver
|
eb86512b05be20d2f51d53ba9b860c709e0799b3
|
etc/clang_format.py
|
python
|
Repo.commit
|
(self, command)
|
return self._callgito(["commit"] + command)
|
git commit wrapper
|
git commit wrapper
|
[
"git",
"commit",
"wrapper"
] |
def commit(self, command):
"""git commit wrapper
"""
return self._callgito(["commit"] + command)
|
[
"def",
"commit",
"(",
"self",
",",
"command",
")",
":",
"return",
"self",
".",
"_callgito",
"(",
"[",
"\"commit\"",
"]",
"+",
"command",
")"
] |
https://github.com/mongodb/mongo-cxx-driver/blob/eb86512b05be20d2f51d53ba9b860c709e0799b3/etc/clang_format.py#L578-L581
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python/src/Lib/logging/__init__.py
|
python
|
LoggerAdapter.process
|
(self, msg, kwargs)
|
return msg, kwargs
|
Process the logging message and keyword arguments passed in to
a logging call to insert contextual information. You can either
manipulate the message itself, the keyword args or both. Return
the message and kwargs modified (or not) to suit your needs.
Normally, you'll only need to override this one method in a
LoggerAdapter subclass for your specific needs.
|
Process the logging message and keyword arguments passed in to
a logging call to insert contextual information. You can either
manipulate the message itself, the keyword args or both. Return
the message and kwargs modified (or not) to suit your needs.
|
[
"Process",
"the",
"logging",
"message",
"and",
"keyword",
"arguments",
"passed",
"in",
"to",
"a",
"logging",
"call",
"to",
"insert",
"contextual",
"information",
".",
"You",
"can",
"either",
"manipulate",
"the",
"message",
"itself",
"the",
"keyword",
"args",
"or",
"both",
".",
"Return",
"the",
"message",
"and",
"kwargs",
"modified",
"(",
"or",
"not",
")",
"to",
"suit",
"your",
"needs",
"."
] |
def process(self, msg, kwargs):
"""
Process the logging message and keyword arguments passed in to
a logging call to insert contextual information. You can either
manipulate the message itself, the keyword args or both. Return
the message and kwargs modified (or not) to suit your needs.
Normally, you'll only need to override this one method in a
LoggerAdapter subclass for your specific needs.
"""
kwargs["extra"] = self.extra
return msg, kwargs
|
[
"def",
"process",
"(",
"self",
",",
"msg",
",",
"kwargs",
")",
":",
"kwargs",
"[",
"\"extra\"",
"]",
"=",
"self",
".",
"extra",
"return",
"msg",
",",
"kwargs"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/logging/__init__.py#L1428-L1439
|
|
miyosuda/TensorFlowAndroidDemo
|
35903e0221aa5f109ea2dbef27f20b52e317f42d
|
jni-build/jni/include/tensorflow/python/framework/docs.py
|
python
|
Library.write_other_members
|
(self, f, catch_all=False)
|
Writes the leftover members to `f`.
Args:
f: File to write to.
catch_all: If true, document all missing symbols from any module.
Otherwise, document missing symbols from just this module.
|
Writes the leftover members to `f`.
|
[
"Writes",
"the",
"leftover",
"members",
"to",
"f",
"."
] |
def write_other_members(self, f, catch_all=False):
"""Writes the leftover members to `f`.
Args:
f: File to write to.
catch_all: If true, document all missing symbols from any module.
Otherwise, document missing symbols from just this module.
"""
if catch_all:
names = self._members.items()
else:
names = inspect.getmembers(self._module)
all_names = getattr(self._module, "__all__", None)
if all_names is not None:
names = [(n, m) for n, m in names if n in all_names]
leftovers = []
for name, _ in names:
if name in self._members and name not in self._documented:
leftovers.append(name)
if leftovers:
print("%s: undocumented members: %d" % (self._title, len(leftovers)))
print("\n## Other Functions and Classes", file=f)
for name in sorted(leftovers):
print(" %s" % name)
self._documented.add(name)
self._mentioned.add(name)
self._write_member_markdown_to_file(f, "###", *self._members[name])
|
[
"def",
"write_other_members",
"(",
"self",
",",
"f",
",",
"catch_all",
"=",
"False",
")",
":",
"if",
"catch_all",
":",
"names",
"=",
"self",
".",
"_members",
".",
"items",
"(",
")",
"else",
":",
"names",
"=",
"inspect",
".",
"getmembers",
"(",
"self",
".",
"_module",
")",
"all_names",
"=",
"getattr",
"(",
"self",
".",
"_module",
",",
"\"__all__\"",
",",
"None",
")",
"if",
"all_names",
"is",
"not",
"None",
":",
"names",
"=",
"[",
"(",
"n",
",",
"m",
")",
"for",
"n",
",",
"m",
"in",
"names",
"if",
"n",
"in",
"all_names",
"]",
"leftovers",
"=",
"[",
"]",
"for",
"name",
",",
"_",
"in",
"names",
":",
"if",
"name",
"in",
"self",
".",
"_members",
"and",
"name",
"not",
"in",
"self",
".",
"_documented",
":",
"leftovers",
".",
"append",
"(",
"name",
")",
"if",
"leftovers",
":",
"print",
"(",
"\"%s: undocumented members: %d\"",
"%",
"(",
"self",
".",
"_title",
",",
"len",
"(",
"leftovers",
")",
")",
")",
"print",
"(",
"\"\\n## Other Functions and Classes\"",
",",
"file",
"=",
"f",
")",
"for",
"name",
"in",
"sorted",
"(",
"leftovers",
")",
":",
"print",
"(",
"\" %s\"",
"%",
"name",
")",
"self",
".",
"_documented",
".",
"add",
"(",
"name",
")",
"self",
".",
"_mentioned",
".",
"add",
"(",
"name",
")",
"self",
".",
"_write_member_markdown_to_file",
"(",
"f",
",",
"\"###\"",
",",
"*",
"self",
".",
"_members",
"[",
"name",
"]",
")"
] |
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/docs.py#L529-L555
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/_controls.py
|
python
|
AnyButton.GetBitmapPressed
|
(*args, **kwargs)
|
return _controls_.AnyButton_GetBitmapPressed(*args, **kwargs)
|
GetBitmapPressed(self) -> Bitmap
|
GetBitmapPressed(self) -> Bitmap
|
[
"GetBitmapPressed",
"(",
"self",
")",
"-",
">",
"Bitmap"
] |
def GetBitmapPressed(*args, **kwargs):
"""GetBitmapPressed(self) -> Bitmap"""
return _controls_.AnyButton_GetBitmapPressed(*args, **kwargs)
|
[
"def",
"GetBitmapPressed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"AnyButton_GetBitmapPressed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L104-L106
|
|
intel/llvm
|
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
|
clang-tools-extra/clangd/quality/CompletionModelCodegen.py
|
python
|
boost_node
|
(n, label, next_label)
|
return "%s: return %sf;" % (label, n['score'])
|
Returns code snippet for a leaf/boost node.
|
Returns code snippet for a leaf/boost node.
|
[
"Returns",
"code",
"snippet",
"for",
"a",
"leaf",
"/",
"boost",
"node",
"."
] |
def boost_node(n, label, next_label):
"""Returns code snippet for a leaf/boost node."""
return "%s: return %sf;" % (label, n['score'])
|
[
"def",
"boost_node",
"(",
"n",
",",
"label",
",",
"next_label",
")",
":",
"return",
"\"%s: return %sf;\"",
"%",
"(",
"label",
",",
"n",
"[",
"'score'",
"]",
")"
] |
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang-tools-extra/clangd/quality/CompletionModelCodegen.py#L41-L43
|
|
SoarGroup/Soar
|
a1c5e249499137a27da60533c72969eef3b8ab6b
|
scons/scons-local-4.1.0/SCons/Subst.py
|
python
|
ListSubber.this_word
|
(self)
|
Arrange for the next word to append to the end of the
current last word in the result.
|
Arrange for the next word to append to the end of the
current last word in the result.
|
[
"Arrange",
"for",
"the",
"next",
"word",
"to",
"append",
"to",
"the",
"end",
"of",
"the",
"current",
"last",
"word",
"in",
"the",
"result",
"."
] |
def this_word(self):
"""Arrange for the next word to append to the end of the
current last word in the result."""
self.append = self.add_to_current_word
|
[
"def",
"this_word",
"(",
"self",
")",
":",
"self",
".",
"append",
"=",
"self",
".",
"add_to_current_word"
] |
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Subst.py#L646-L649
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/msw/_gdi.py
|
python
|
DC.GetBackground
|
(*args, **kwargs)
|
return _gdi_.DC_GetBackground(*args, **kwargs)
|
GetBackground(self) -> Brush
Gets the brush used for painting the background.
|
GetBackground(self) -> Brush
|
[
"GetBackground",
"(",
"self",
")",
"-",
">",
"Brush"
] |
def GetBackground(*args, **kwargs):
"""
GetBackground(self) -> Brush
Gets the brush used for painting the background.
"""
return _gdi_.DC_GetBackground(*args, **kwargs)
|
[
"def",
"GetBackground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_GetBackground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L4426-L4432
|
|
kit-cel/gr-radar
|
ceebb6d83280526f6e08a8aa0dde486db6898c81
|
docs/doxygen/swig_doc.py
|
python
|
make_func_entry
|
(func, name=None, description=None, params=None)
|
return make_entry(func, name=name, description=description, params=params)
|
Create a function docstring entry for a swig interface file.
func - a doxyxml object from which documentation will be extracted.
name - the name of the C object (defaults to func.name())
description - if this optional variable is set then it's value is
used as the description instead of extracting it from func.
params - a parameter list that overrides using func.params.
|
Create a function docstring entry for a swig interface file.
|
[
"Create",
"a",
"function",
"docstring",
"entry",
"for",
"a",
"swig",
"interface",
"file",
"."
] |
def make_func_entry(func, name=None, description=None, params=None):
"""
Create a function docstring entry for a swig interface file.
func - a doxyxml object from which documentation will be extracted.
name - the name of the C object (defaults to func.name())
description - if this optional variable is set then it's value is
used as the description instead of extracting it from func.
params - a parameter list that overrides using func.params.
"""
#if params is None:
# params = func.params
#params = [prm.declname for prm in params]
#if params:
# sig = "Params: (%s)" % ", ".join(params)
#else:
# sig = "Params: (NONE)"
#templ = "{description}\n\n" + sig
#return make_entry(func, name=name, templ=utoascii(templ),
# description=description)
return make_entry(func, name=name, description=description, params=params)
|
[
"def",
"make_func_entry",
"(",
"func",
",",
"name",
"=",
"None",
",",
"description",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"#if params is None:",
"# params = func.params",
"#params = [prm.declname for prm in params]",
"#if params:",
"# sig = \"Params: (%s)\" % \", \".join(params)",
"#else:",
"# sig = \"Params: (NONE)\"",
"#templ = \"{description}\\n\\n\" + sig",
"#return make_entry(func, name=name, templ=utoascii(templ),",
"# description=description)",
"return",
"make_entry",
"(",
"func",
",",
"name",
"=",
"name",
",",
"description",
"=",
"description",
",",
"params",
"=",
"params",
")"
] |
https://github.com/kit-cel/gr-radar/blob/ceebb6d83280526f6e08a8aa0dde486db6898c81/docs/doxygen/swig_doc.py#L145-L165
|
|
domino-team/openwrt-cc
|
8b181297c34d14d3ca521cc9f31430d561dbc688
|
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/bccache.py
|
python
|
BytecodeCache.get_cache_key
|
(self, name, filename=None)
|
return hash.hexdigest()
|
Returns the unique hash key for this template name.
|
Returns the unique hash key for this template name.
|
[
"Returns",
"the",
"unique",
"hash",
"key",
"for",
"this",
"template",
"name",
"."
] |
def get_cache_key(self, name, filename=None):
"""Returns the unique hash key for this template name."""
hash = sha1(name.encode('utf-8'))
if filename is not None:
filename = '|' + filename
if isinstance(filename, text_type):
filename = filename.encode('utf-8')
hash.update(filename)
return hash.hexdigest()
|
[
"def",
"get_cache_key",
"(",
"self",
",",
"name",
",",
"filename",
"=",
"None",
")",
":",
"hash",
"=",
"sha1",
"(",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"if",
"filename",
"is",
"not",
"None",
":",
"filename",
"=",
"'|'",
"+",
"filename",
"if",
"isinstance",
"(",
"filename",
",",
"text_type",
")",
":",
"filename",
"=",
"filename",
".",
"encode",
"(",
"'utf-8'",
")",
"hash",
".",
"update",
"(",
"filename",
")",
"return",
"hash",
".",
"hexdigest",
"(",
")"
] |
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/bccache.py#L166-L174
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/devicearray.py
|
python
|
DeviceNDArray.__array__
|
(self, dtype=None)
|
return self.copy_to_host().__array__(dtype)
|
:return: an `numpy.ndarray`, so copies to the host.
|
:return: an `numpy.ndarray`, so copies to the host.
|
[
":",
"return",
":",
"an",
"numpy",
".",
"ndarray",
"so",
"copies",
"to",
"the",
"host",
"."
] |
def __array__(self, dtype=None):
"""
:return: an `numpy.ndarray`, so copies to the host.
"""
return self.copy_to_host().__array__(dtype)
|
[
"def",
"__array__",
"(",
"self",
",",
"dtype",
"=",
"None",
")",
":",
"return",
"self",
".",
"copy_to_host",
"(",
")",
".",
"__array__",
"(",
"dtype",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/devicearray.py#L467-L471
|
|
tinyobjloader/tinyobjloader
|
8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93
|
deps/cpplint.py
|
python
|
RemoveMultiLineCommentsFromRange
|
(lines, begin, end)
|
Clears a range of lines for multi-line comments.
|
Clears a range of lines for multi-line comments.
|
[
"Clears",
"a",
"range",
"of",
"lines",
"for",
"multi",
"-",
"line",
"comments",
"."
] |
def RemoveMultiLineCommentsFromRange(lines, begin, end):
"""Clears a range of lines for multi-line comments."""
# Having // dummy comments makes the lines non-empty, so we will not get
# unnecessary blank line warnings later in the code.
for i in range(begin, end):
lines[i] = '/**/'
|
[
"def",
"RemoveMultiLineCommentsFromRange",
"(",
"lines",
",",
"begin",
",",
"end",
")",
":",
"# Having // dummy comments makes the lines non-empty, so we will not get",
"# unnecessary blank line warnings later in the code.",
"for",
"i",
"in",
"range",
"(",
"begin",
",",
"end",
")",
":",
"lines",
"[",
"i",
"]",
"=",
"'/**/'"
] |
https://github.com/tinyobjloader/tinyobjloader/blob/8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93/deps/cpplint.py#L1250-L1255
|
||
deepmind/streetlearn
|
ccf1d60b9c45154894d45a897748aee85d7eb69b
|
streetlearn/python/environment/instructions_base.py
|
python
|
InstructionsBase._add_coin_reward_to_pano
|
(self, pano_id)
|
Add coin reward to a pano, but only if that pano has no reward yet.
Args:
pano_id: centroid pano id.
|
Add coin reward to a pano, but only if that pano has no reward yet.
|
[
"Add",
"coin",
"reward",
"to",
"a",
"pano",
"but",
"only",
"if",
"that",
"pano",
"has",
"no",
"reward",
"yet",
"."
] |
def _add_coin_reward_to_pano(self, pano_id):
"""Add coin reward to a pano, but only if that pano has no reward yet.
Args:
pano_id: centroid pano id.
"""
if pano_id not in self._reward_pano_id_list:
self._reward_pano_id_list[pano_id] = self._reward_per_coin
self._reward_pano_id_to_family[pano_id] = pano_id
self._reward_family[pano_id] = {pano_id}
self._pano_id_to_color[pano_id] = self._colors['coin']
|
[
"def",
"_add_coin_reward_to_pano",
"(",
"self",
",",
"pano_id",
")",
":",
"if",
"pano_id",
"not",
"in",
"self",
".",
"_reward_pano_id_list",
":",
"self",
".",
"_reward_pano_id_list",
"[",
"pano_id",
"]",
"=",
"self",
".",
"_reward_per_coin",
"self",
".",
"_reward_pano_id_to_family",
"[",
"pano_id",
"]",
"=",
"pano_id",
"self",
".",
"_reward_family",
"[",
"pano_id",
"]",
"=",
"{",
"pano_id",
"}",
"self",
".",
"_pano_id_to_color",
"[",
"pano_id",
"]",
"=",
"self",
".",
"_colors",
"[",
"'coin'",
"]"
] |
https://github.com/deepmind/streetlearn/blob/ccf1d60b9c45154894d45a897748aee85d7eb69b/streetlearn/python/environment/instructions_base.py#L314-L324
|
||
windystrife/UnrealEngine_NVIDIAGameWorks
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/lib/win32timezone.py
|
python
|
TimeZoneDefinition._locate_day
|
(year, cutoff)
|
return result
|
Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION
structure or call to GetTimeZoneInformation and interprets it based on the given
year to identify the actual day.
This method is necessary because the SYSTEMTIME structure refers to a day by its
day of the week and week of the month (e.g. 4th saturday in March).
>>> SATURDAY = 6
>>> MARCH = 3
>>> st = SYSTEMTIME(2000, MARCH, SATURDAY, 4, 0, 0, 0, 0)
# according to my calendar, the 4th Saturday in March in 2009 was the 28th
>>> expected_date = datetime.datetime(2009, 3, 28)
>>> TimeZoneDefinition._locate_day(2009, st) == expected_date
True
|
Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION
structure or call to GetTimeZoneInformation and interprets it based on the given
year to identify the actual day.
|
[
"Takes",
"a",
"SYSTEMTIME",
"object",
"such",
"as",
"retrieved",
"from",
"a",
"TIME_ZONE_INFORMATION",
"structure",
"or",
"call",
"to",
"GetTimeZoneInformation",
"and",
"interprets",
"it",
"based",
"on",
"the",
"given",
"year",
"to",
"identify",
"the",
"actual",
"day",
"."
] |
def _locate_day(year, cutoff):
"""
Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION
structure or call to GetTimeZoneInformation and interprets it based on the given
year to identify the actual day.
This method is necessary because the SYSTEMTIME structure refers to a day by its
day of the week and week of the month (e.g. 4th saturday in March).
>>> SATURDAY = 6
>>> MARCH = 3
>>> st = SYSTEMTIME(2000, MARCH, SATURDAY, 4, 0, 0, 0, 0)
# according to my calendar, the 4th Saturday in March in 2009 was the 28th
>>> expected_date = datetime.datetime(2009, 3, 28)
>>> TimeZoneDefinition._locate_day(2009, st) == expected_date
True
"""
# MS stores Sunday as 0, Python datetime stores Monday as zero
target_weekday = (cutoff.day_of_week + 6) % 7
# For SYSTEMTIMEs relating to time zone inforamtion, cutoff.day
# is the week of the month
week_of_month = cutoff.day
# so the following is the first day of that week
day = (week_of_month - 1) * 7 + 1
result = datetime.datetime(year, cutoff.month, day,
cutoff.hour, cutoff.minute, cutoff.second, cutoff.millisecond)
# now the result is the correct week, but not necessarily the correct day of the week
days_to_go = (target_weekday - result.weekday()) % 7
result += datetime.timedelta(days_to_go)
# if we selected a day in the month following the target month,
# move back a week or two.
# This is necessary because Microsoft defines the fifth week in a month
# to be the last week in a month and adding the time delta might have
# pushed the result into the next month.
while result.month == cutoff.month + 1:
result -= datetime.timedelta(weeks = 1)
return result
|
[
"def",
"_locate_day",
"(",
"year",
",",
"cutoff",
")",
":",
"# MS stores Sunday as 0, Python datetime stores Monday as zero",
"target_weekday",
"=",
"(",
"cutoff",
".",
"day_of_week",
"+",
"6",
")",
"%",
"7",
"# For SYSTEMTIMEs relating to time zone inforamtion, cutoff.day",
"# is the week of the month",
"week_of_month",
"=",
"cutoff",
".",
"day",
"# so the following is the first day of that week",
"day",
"=",
"(",
"week_of_month",
"-",
"1",
")",
"*",
"7",
"+",
"1",
"result",
"=",
"datetime",
".",
"datetime",
"(",
"year",
",",
"cutoff",
".",
"month",
",",
"day",
",",
"cutoff",
".",
"hour",
",",
"cutoff",
".",
"minute",
",",
"cutoff",
".",
"second",
",",
"cutoff",
".",
"millisecond",
")",
"# now the result is the correct week, but not necessarily the correct day of the week",
"days_to_go",
"=",
"(",
"target_weekday",
"-",
"result",
".",
"weekday",
"(",
")",
")",
"%",
"7",
"result",
"+=",
"datetime",
".",
"timedelta",
"(",
"days_to_go",
")",
"# if we selected a day in the month following the target month,",
"# move back a week or two.",
"# This is necessary because Microsoft defines the fifth week in a month",
"# to be the last week in a month and adding the time delta might have",
"# pushed the result into the next month.",
"while",
"result",
".",
"month",
"==",
"cutoff",
".",
"month",
"+",
"1",
":",
"result",
"-=",
"datetime",
".",
"timedelta",
"(",
"weeks",
"=",
"1",
")",
"return",
"result"
] |
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/lib/win32timezone.py#L406-L443
|
|
hughperkins/tf-coriander
|
970d3df6c11400ad68405f22b0c42a52374e94ca
|
tensorflow/python/summary/event_accumulator.py
|
python
|
EventAccumulator.Scalars
|
(self, tag)
|
return self._scalars.Items(tag)
|
Given a summary tag, return all associated `ScalarEvent`s.
Args:
tag: A string tag associated with the events.
Raises:
KeyError: If the tag is not found.
Returns:
An array of `ScalarEvent`s.
|
Given a summary tag, return all associated `ScalarEvent`s.
|
[
"Given",
"a",
"summary",
"tag",
"return",
"all",
"associated",
"ScalarEvent",
"s",
"."
] |
def Scalars(self, tag):
"""Given a summary tag, return all associated `ScalarEvent`s.
Args:
tag: A string tag associated with the events.
Raises:
KeyError: If the tag is not found.
Returns:
An array of `ScalarEvent`s.
"""
return self._scalars.Items(tag)
|
[
"def",
"Scalars",
"(",
"self",
",",
"tag",
")",
":",
"return",
"self",
".",
"_scalars",
".",
"Items",
"(",
"tag",
")"
] |
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/summary/event_accumulator.py#L279-L291
|
|
Polidea/SiriusObfuscator
|
b0e590d8130e97856afe578869b83a209e2b19be
|
SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py
|
python
|
Token.cursor
|
(self)
|
return cursor
|
The Cursor this Token corresponds to.
|
The Cursor this Token corresponds to.
|
[
"The",
"Cursor",
"this",
"Token",
"corresponds",
"to",
"."
] |
def cursor(self):
"""The Cursor this Token corresponds to."""
cursor = Cursor()
conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
return cursor
|
[
"def",
"cursor",
"(",
"self",
")",
":",
"cursor",
"=",
"Cursor",
"(",
")",
"conf",
".",
"lib",
".",
"clang_annotateTokens",
"(",
"self",
".",
"_tu",
",",
"byref",
"(",
"self",
")",
",",
"1",
",",
"byref",
"(",
"cursor",
")",
")",
"return",
"cursor"
] |
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py#L3041-L3047
|
|
swift/swift
|
12d031cf8177fdec0137f9aa7e2912fa23c4416b
|
3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py
|
python
|
Dir.build
|
(self, **kw)
|
A null "builder" for directories.
|
A null "builder" for directories.
|
[
"A",
"null",
"builder",
"for",
"directories",
"."
] |
def build(self, **kw):
"""A null "builder" for directories."""
global MkdirBuilder
if self.builder is not MkdirBuilder:
SCons.Node.Node.build(self, **kw)
|
[
"def",
"build",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"global",
"MkdirBuilder",
"if",
"self",
".",
"builder",
"is",
"not",
"MkdirBuilder",
":",
"SCons",
".",
"Node",
".",
"Node",
".",
"build",
"(",
"self",
",",
"*",
"*",
"kw",
")"
] |
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py#L1767-L1771
|
||
googleapis/google-cloud-cpp
|
6b6de2af1a62972a1e0144e2d4d7c2448d956294
|
google/cloud/storage/benchmarks/storage_parallel_uploads_plots.py
|
python
|
load_benchmark_output
|
(file)
|
return df
|
Loads the output generated by storage_parallel_uploads_benchmark.
|
Loads the output generated by storage_parallel_uploads_benchmark.
|
[
"Loads",
"the",
"output",
"generated",
"by",
"storage_parallel_uploads_benchmark",
"."
] |
def load_benchmark_output(file):
"""Loads the output generated by storage_parallel_uploads_benchmark."""
df = pd.read_csv(file, comment="#", sep=",", header=0)
df["MiB"] = df.FileSize / 1024 / 1024
df["MiBs"] = df.MiB * 1000.0 / df.UploadTimeMs
df["MiBsPerShard"] = df.MiBs / df.ShardCount
return df
|
[
"def",
"load_benchmark_output",
"(",
"file",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"file",
",",
"comment",
"=",
"\"#\"",
",",
"sep",
"=",
"\",\"",
",",
"header",
"=",
"0",
")",
"df",
"[",
"\"MiB\"",
"]",
"=",
"df",
".",
"FileSize",
"/",
"1024",
"/",
"1024",
"df",
"[",
"\"MiBs\"",
"]",
"=",
"df",
".",
"MiB",
"*",
"1000.0",
"/",
"df",
".",
"UploadTimeMs",
"df",
"[",
"\"MiBsPerShard\"",
"]",
"=",
"df",
".",
"MiBs",
"/",
"df",
".",
"ShardCount",
"return",
"df"
] |
https://github.com/googleapis/google-cloud-cpp/blob/6b6de2af1a62972a1e0144e2d4d7c2448d956294/google/cloud/storage/benchmarks/storage_parallel_uploads_plots.py#L27-L33
|
|
lammps/lammps
|
b75c3065430a75b1b5543a10e10f46d9b4c91913
|
tools/i-pi/ipi/inputs/initializer.py
|
python
|
InputInitializer.write
|
(self, name="", indent="")
|
return ""
|
Overloads Input write() function so that we never write out
InputInitializer to restart files.
Returns:
An empty string.
|
Overloads Input write() function so that we never write out
InputInitializer to restart files.
|
[
"Overloads",
"Input",
"write",
"()",
"function",
"so",
"that",
"we",
"never",
"write",
"out",
"InputInitializer",
"to",
"restart",
"files",
"."
] |
def write(self, name="", indent=""):
"""Overloads Input write() function so that we never write out
InputInitializer to restart files.
Returns:
An empty string.
"""
return ""
|
[
"def",
"write",
"(",
"self",
",",
"name",
"=",
"\"\"",
",",
"indent",
"=",
"\"\"",
")",
":",
"return",
"\"\""
] |
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/inputs/initializer.py#L330-L338
|
|
BlzFans/wke
|
b0fa21158312e40c5fbd84682d643022b6c34a93
|
cygwin/lib/python2.6/robotparser.py
|
python
|
RobotFileParser.read
|
(self)
|
Reads the robots.txt URL and feeds it to the parser.
|
Reads the robots.txt URL and feeds it to the parser.
|
[
"Reads",
"the",
"robots",
".",
"txt",
"URL",
"and",
"feeds",
"it",
"to",
"the",
"parser",
"."
] |
def read(self):
"""Reads the robots.txt URL and feeds it to the parser."""
opener = URLopener()
f = opener.open(self.url)
lines = [line.strip() for line in f]
f.close()
self.errcode = opener.errcode
if self.errcode in (401, 403):
self.disallow_all = True
elif self.errcode >= 400:
self.allow_all = True
elif self.errcode == 200 and lines:
self.parse(lines)
|
[
"def",
"read",
"(",
"self",
")",
":",
"opener",
"=",
"URLopener",
"(",
")",
"f",
"=",
"opener",
".",
"open",
"(",
"self",
".",
"url",
")",
"lines",
"=",
"[",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"f",
"]",
"f",
".",
"close",
"(",
")",
"self",
".",
"errcode",
"=",
"opener",
".",
"errcode",
"if",
"self",
".",
"errcode",
"in",
"(",
"401",
",",
"403",
")",
":",
"self",
".",
"disallow_all",
"=",
"True",
"elif",
"self",
".",
"errcode",
">=",
"400",
":",
"self",
".",
"allow_all",
"=",
"True",
"elif",
"self",
".",
"errcode",
"==",
"200",
"and",
"lines",
":",
"self",
".",
"parse",
"(",
"lines",
")"
] |
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/robotparser.py#L54-L66
|
||
google/llvm-propeller
|
45c226984fe8377ebfb2ad7713c680d652ba678d
|
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
|
python
|
_VerboseLevel
|
()
|
return _cpplint_state.verbose_level
|
Returns the module's verbosity setting.
|
Returns the module's verbosity setting.
|
[
"Returns",
"the",
"module",
"s",
"verbosity",
"setting",
"."
] |
def _VerboseLevel():
"""Returns the module's verbosity setting."""
return _cpplint_state.verbose_level
|
[
"def",
"_VerboseLevel",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"verbose_level"
] |
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L981-L983
|
|
thalium/icebox
|
99d147d5b9269222225443ce171b4fd46d8985d4
|
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
|
python
|
xpathContext.xpathVariableLookup
|
(self, name)
|
return xpathObjectRet(ret)
|
Search in the Variable array of the context for the given
variable value.
|
Search in the Variable array of the context for the given
variable value.
|
[
"Search",
"in",
"the",
"Variable",
"array",
"of",
"the",
"context",
"for",
"the",
"given",
"variable",
"value",
"."
] |
def xpathVariableLookup(self, name):
"""Search in the Variable array of the context for the given
variable value. """
ret = libxml2mod.xmlXPathVariableLookup(self._o, name)
if ret is None:raise xpathError('xmlXPathVariableLookup() failed')
return xpathObjectRet(ret)
|
[
"def",
"xpathVariableLookup",
"(",
"self",
",",
"name",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathVariableLookup",
"(",
"self",
".",
"_o",
",",
"name",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"xpathError",
"(",
"'xmlXPathVariableLookup() failed'",
")",
"return",
"xpathObjectRet",
"(",
"ret",
")"
] |
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L6607-L6612
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
wx/lib/agw/ultimatelistctrl.py
|
python
|
UltimateListItem.GetBackgroundColour
|
(self)
|
return (self.HasAttributes() and [self._attr.GetBackgroundColour()] or [wx.NullColour])[0]
|
Returns the background colour.
|
Returns the background colour.
|
[
"Returns",
"the",
"background",
"colour",
"."
] |
def GetBackgroundColour(self):
""" Returns the background colour. """
return (self.HasAttributes() and [self._attr.GetBackgroundColour()] or [wx.NullColour])[0]
|
[
"def",
"GetBackgroundColour",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"HasAttributes",
"(",
")",
"and",
"[",
"self",
".",
"_attr",
".",
"GetBackgroundColour",
"(",
")",
"]",
"or",
"[",
"wx",
".",
"NullColour",
"]",
")",
"[",
"0",
"]"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L1807-L1810
|
|
PolygonTek/BlueshiftEngine
|
fbc374cbc391e1147c744649f405a66a27c35d89
|
Source/ThirdParty/freetype/src/tools/docmaker/sources.py
|
python
|
SourceProcessor.dump
|
( self )
|
Print all blocks in a processor.
|
Print all blocks in a processor.
|
[
"Print",
"all",
"blocks",
"in",
"a",
"processor",
"."
] |
def dump( self ):
"""Print all blocks in a processor."""
for b in self.blocks:
b.dump()
|
[
"def",
"dump",
"(",
"self",
")",
":",
"for",
"b",
"in",
"self",
".",
"blocks",
":",
"b",
".",
"dump",
"(",
")"
] |
https://github.com/PolygonTek/BlueshiftEngine/blob/fbc374cbc391e1147c744649f405a66a27c35d89/Source/ThirdParty/freetype/src/tools/docmaker/sources.py#L392-L395
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python3/src/Lib/distutils/command/install.py
|
python
|
install.create_path_file
|
(self)
|
Creates the .pth file
|
Creates the .pth file
|
[
"Creates",
"the",
".",
"pth",
"file"
] |
def create_path_file(self):
"""Creates the .pth file"""
filename = os.path.join(self.install_libbase,
self.path_file + ".pth")
if self.install_path_file:
self.execute(write_file,
(filename, [self.extra_dirs]),
"creating %s" % filename)
else:
self.warn("path file '%s' not created" % filename)
|
[
"def",
"create_path_file",
"(",
"self",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"install_libbase",
",",
"self",
".",
"path_file",
"+",
"\".pth\"",
")",
"if",
"self",
".",
"install_path_file",
":",
"self",
".",
"execute",
"(",
"write_file",
",",
"(",
"filename",
",",
"[",
"self",
".",
"extra_dirs",
"]",
")",
",",
"\"creating %s\"",
"%",
"filename",
")",
"else",
":",
"self",
".",
"warn",
"(",
"\"path file '%s' not created\"",
"%",
"filename",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/command/install.py#L586-L595
|
||
tkn-tub/ns3-gym
|
19bfe0a583e641142609939a090a09dfc63a095f
|
src/visualizer/visualizer/core.py
|
python
|
Node.set_svg_icon
|
(self, file_base_name, width=None, height=None, align_x=0.5, align_y=0.5)
|
!
Set a background SVG icon for the node.
@param file_base_name: base file name, including .svg
extension, of the svg file. Place the file in the folder
src/contrib/visualizer/resource.
@param width: scale to the specified width, in meters
@param height: scale to the specified height, in meters
@param align_x: horizontal alignment of the icon relative to
the node position, from 0 (icon fully to the left of the node)
to 1.0 (icon fully to the right of the node)
@param align_y: vertical alignment of the icon relative to the
node position, from 0 (icon fully to the top of the node) to
1.0 (icon fully to the bottom of the node)
@return a ValueError exception if invalid dimensions.
|
!
Set a background SVG icon for the node.
|
[
"!",
"Set",
"a",
"background",
"SVG",
"icon",
"for",
"the",
"node",
"."
] |
def set_svg_icon(self, file_base_name, width=None, height=None, align_x=0.5, align_y=0.5):
"""!
Set a background SVG icon for the node.
@param file_base_name: base file name, including .svg
extension, of the svg file. Place the file in the folder
src/contrib/visualizer/resource.
@param width: scale to the specified width, in meters
@param height: scale to the specified height, in meters
@param align_x: horizontal alignment of the icon relative to
the node position, from 0 (icon fully to the left of the node)
to 1.0 (icon fully to the right of the node)
@param align_y: vertical alignment of the icon relative to the
node position, from 0 (icon fully to the top of the node) to
1.0 (icon fully to the bottom of the node)
@return a ValueError exception if invalid dimensions.
"""
if width is None and height is None:
raise ValueError("either width or height must be given")
rsvg_handle = svgitem.rsvg_handle_factory(file_base_name)
x = self.canvas_item.props.center_x
y = self.canvas_item.props.center_y
self.svg_item = svgitem.SvgItem(x, y, rsvg_handle)
self.svg_item.props.parent = self.visualizer.canvas.get_root_item()
self.svg_item.props.pointer_events = GooCanvas.CanvasPointerEvents.NONE
self.svg_item.lower(None)
self.svg_item.props.visibility = GooCanvas.CanvasItemVisibility.VISIBLE_ABOVE_THRESHOLD
if width is not None:
self.svg_item.props.width = transform_distance_simulation_to_canvas(width)
if height is not None:
self.svg_item.props.height = transform_distance_simulation_to_canvas(height)
#threshold1 = 10.0/self.svg_item.props.height
#threshold2 = 10.0/self.svg_item.props.width
#self.svg_item.props.visibility_threshold = min(threshold1, threshold2)
self.svg_align_x = align_x
self.svg_align_y = align_y
self._update_svg_position(x, y)
self._update_appearance()
|
[
"def",
"set_svg_icon",
"(",
"self",
",",
"file_base_name",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"align_x",
"=",
"0.5",
",",
"align_y",
"=",
"0.5",
")",
":",
"if",
"width",
"is",
"None",
"and",
"height",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"either width or height must be given\"",
")",
"rsvg_handle",
"=",
"svgitem",
".",
"rsvg_handle_factory",
"(",
"file_base_name",
")",
"x",
"=",
"self",
".",
"canvas_item",
".",
"props",
".",
"center_x",
"y",
"=",
"self",
".",
"canvas_item",
".",
"props",
".",
"center_y",
"self",
".",
"svg_item",
"=",
"svgitem",
".",
"SvgItem",
"(",
"x",
",",
"y",
",",
"rsvg_handle",
")",
"self",
".",
"svg_item",
".",
"props",
".",
"parent",
"=",
"self",
".",
"visualizer",
".",
"canvas",
".",
"get_root_item",
"(",
")",
"self",
".",
"svg_item",
".",
"props",
".",
"pointer_events",
"=",
"GooCanvas",
".",
"CanvasPointerEvents",
".",
"NONE",
"self",
".",
"svg_item",
".",
"lower",
"(",
"None",
")",
"self",
".",
"svg_item",
".",
"props",
".",
"visibility",
"=",
"GooCanvas",
".",
"CanvasItemVisibility",
".",
"VISIBLE_ABOVE_THRESHOLD",
"if",
"width",
"is",
"not",
"None",
":",
"self",
".",
"svg_item",
".",
"props",
".",
"width",
"=",
"transform_distance_simulation_to_canvas",
"(",
"width",
")",
"if",
"height",
"is",
"not",
"None",
":",
"self",
".",
"svg_item",
".",
"props",
".",
"height",
"=",
"transform_distance_simulation_to_canvas",
"(",
"height",
")",
"#threshold1 = 10.0/self.svg_item.props.height",
"#threshold2 = 10.0/self.svg_item.props.width",
"#self.svg_item.props.visibility_threshold = min(threshold1, threshold2)",
"self",
".",
"svg_align_x",
"=",
"align_x",
"self",
".",
"svg_align_y",
"=",
"align_y",
"self",
".",
"_update_svg_position",
"(",
"x",
",",
"y",
")",
"self",
".",
"_update_appearance",
"(",
")"
] |
https://github.com/tkn-tub/ns3-gym/blob/19bfe0a583e641142609939a090a09dfc63a095f/src/visualizer/visualizer/core.py#L144-L188
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/req/req_file.py
|
python
|
get_file_content
|
(url, session)
|
return url, content
|
Gets the content of a file; it may be a filename, file: URL, or
http: URL. Returns (location, content). Content is unicode.
Respects # -*- coding: declarations on the retrieved files.
:param url: File path or url.
:param session: PipSession instance.
|
Gets the content of a file; it may be a filename, file: URL, or
|
[
"Gets",
"the",
"content",
"of",
"a",
"file",
";",
"it",
"may",
"be",
"a",
"filename",
"file",
":",
"URL",
"or"
] |
def get_file_content(url, session):
# type: (str, PipSession) -> Tuple[str, str]
"""Gets the content of a file; it may be a filename, file: URL, or
http: URL. Returns (location, content). Content is unicode.
Respects # -*- coding: declarations on the retrieved files.
:param url: File path or url.
:param session: PipSession instance.
"""
scheme = get_url_scheme(url)
if scheme in ['http', 'https']:
# FIXME: catch some errors
resp = session.get(url)
raise_for_status(resp)
return resp.url, resp.text
elif scheme == 'file':
url = url_to_path(url)
try:
with open(url, 'rb') as f:
content = auto_decode(f.read())
except OSError as exc:
raise InstallationError(
f'Could not open requirements file: {exc}'
)
return url, content
|
[
"def",
"get_file_content",
"(",
"url",
",",
"session",
")",
":",
"# type: (str, PipSession) -> Tuple[str, str]",
"scheme",
"=",
"get_url_scheme",
"(",
"url",
")",
"if",
"scheme",
"in",
"[",
"'http'",
",",
"'https'",
"]",
":",
"# FIXME: catch some errors",
"resp",
"=",
"session",
".",
"get",
"(",
"url",
")",
"raise_for_status",
"(",
"resp",
")",
"return",
"resp",
".",
"url",
",",
"resp",
".",
"text",
"elif",
"scheme",
"==",
"'file'",
":",
"url",
"=",
"url_to_path",
"(",
"url",
")",
"try",
":",
"with",
"open",
"(",
"url",
",",
"'rb'",
")",
"as",
"f",
":",
"content",
"=",
"auto_decode",
"(",
"f",
".",
"read",
"(",
")",
")",
"except",
"OSError",
"as",
"exc",
":",
"raise",
"InstallationError",
"(",
"f'Could not open requirements file: {exc}'",
")",
"return",
"url",
",",
"content"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/req/req_file.py#L1065-L1119
|
|
zhaoweicai/mscnn
|
534bcac5710a579d60827f192035f7eef6d8c585
|
python/caffe/draw.py
|
python
|
get_pooling_types_dict
|
()
|
return d
|
Get dictionary mapping pooling type number to type name
|
Get dictionary mapping pooling type number to type name
|
[
"Get",
"dictionary",
"mapping",
"pooling",
"type",
"number",
"to",
"type",
"name"
] |
def get_pooling_types_dict():
"""Get dictionary mapping pooling type number to type name
"""
desc = caffe_pb2.PoolingParameter.PoolMethod.DESCRIPTOR
d = {}
for k, v in desc.values_by_name.items():
d[v.number] = k
return d
|
[
"def",
"get_pooling_types_dict",
"(",
")",
":",
"desc",
"=",
"caffe_pb2",
".",
"PoolingParameter",
".",
"PoolMethod",
".",
"DESCRIPTOR",
"d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"desc",
".",
"values_by_name",
".",
"items",
"(",
")",
":",
"d",
"[",
"v",
".",
"number",
"]",
"=",
"k",
"return",
"d"
] |
https://github.com/zhaoweicai/mscnn/blob/534bcac5710a579d60827f192035f7eef6d8c585/python/caffe/draw.py#L36-L43
|
|
DLR-SC/tigl
|
d1c5901e948e33d10b1f9659ff3e22c4717b455f
|
bindings/python_internal/tigl3/occ_helpers/topology.py
|
python
|
read_brep
|
(filename)
|
return shape
|
Reads in a brep file
:return: The shape
|
Reads in a brep file
|
[
"Reads",
"in",
"a",
"brep",
"file"
] |
def read_brep(filename):
"""
Reads in a brep file
:return: The shape
"""
if not Path(filename).is_file():
print ("File not found: " + filename)
raise FileNotFoundError(filename)
b = BRep_Builder()
shape = TopoDS_Shape()
if not breptools_Read(shape, filename, b):
raise RuntimeError("Cannot read brep file: " + filename)
return shape
|
[
"def",
"read_brep",
"(",
"filename",
")",
":",
"if",
"not",
"Path",
"(",
"filename",
")",
".",
"is_file",
"(",
")",
":",
"print",
"(",
"\"File not found: \"",
"+",
"filename",
")",
"raise",
"FileNotFoundError",
"(",
"filename",
")",
"b",
"=",
"BRep_Builder",
"(",
")",
"shape",
"=",
"TopoDS_Shape",
"(",
")",
"if",
"not",
"breptools_Read",
"(",
"shape",
",",
"filename",
",",
"b",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot read brep file: \"",
"+",
"filename",
")",
"return",
"shape"
] |
https://github.com/DLR-SC/tigl/blob/d1c5901e948e33d10b1f9659ff3e22c4717b455f/bindings/python_internal/tigl3/occ_helpers/topology.py#L60-L74
|
|
francinexue/xuefu
|
b6ff79747a42e020588c0c0a921048e08fe4680c
|
ctpx/ctp3/ctptd.py
|
python
|
CtpTd.onRspQryMMOptionInstrCommRate
|
(self, MMOptionInstrCommRateField, RspInfoField, requestId, final)
|
请求查询做市商期权合约手续费响应
|
请求查询做市商期权合约手续费响应
|
[
"请求查询做市商期权合约手续费响应"
] |
def onRspQryMMOptionInstrCommRate(self, MMOptionInstrCommRateField, RspInfoField, requestId, final):
"""请求查询做市商期权合约手续费响应"""
pass
|
[
"def",
"onRspQryMMOptionInstrCommRate",
"(",
"self",
",",
"MMOptionInstrCommRateField",
",",
"RspInfoField",
",",
"requestId",
",",
"final",
")",
":",
"pass"
] |
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/ctpx/ctp3/ctptd.py#L302-L304
|
||
krishauser/Klampt
|
972cc83ea5befac3f653c1ba20f80155768ad519
|
Python/klampt/robotsim.py
|
python
|
SimRobotController.sendCommand
|
(self, name: str, args: str)
|
return _robotsim.SimRobotController_sendCommand(self, name, args)
|
r"""
Sends a custom string command to the controller.
Args:
name (str)
args (str)
|
r"""
Sends a custom string command to the controller.
|
[
"r",
"Sends",
"a",
"custom",
"string",
"command",
"to",
"the",
"controller",
"."
] |
def sendCommand(self, name: str, args: str) ->bool:
r"""
Sends a custom string command to the controller.
Args:
name (str)
args (str)
"""
return _robotsim.SimRobotController_sendCommand(self, name, args)
|
[
"def",
"sendCommand",
"(",
"self",
",",
"name",
":",
"str",
",",
"args",
":",
"str",
")",
"->",
"bool",
":",
"return",
"_robotsim",
".",
"SimRobotController_sendCommand",
"(",
"self",
",",
"name",
",",
"args",
")"
] |
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L7166-L7174
|
|
ablab/quast
|
5f6709528129a6ad266a6b24ef3f40b88f0fe04b
|
quast_libs/site_packages/simplejson/decoder.py
|
python
|
JSONDecoder.raw_decode
|
(self, s, idx=0, _w=WHITESPACE.match)
|
return obj, end
|
Decode a JSON document from ``s`` (a ``str`` or ``unicode``
beginning with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
Optionally, ``idx`` can be used to specify an offset in ``s`` where
the JSON document begins.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.
|
Decode a JSON document from ``s`` (a ``str`` or ``unicode``
beginning with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
Optionally, ``idx`` can be used to specify an offset in ``s`` where
the JSON document begins.
|
[
"Decode",
"a",
"JSON",
"document",
"from",
"s",
"(",
"a",
"str",
"or",
"unicode",
"beginning",
"with",
"a",
"JSON",
"document",
")",
"and",
"return",
"a",
"2",
"-",
"tuple",
"of",
"the",
"Python",
"representation",
"and",
"the",
"index",
"in",
"s",
"where",
"the",
"document",
"ended",
".",
"Optionally",
"idx",
"can",
"be",
"used",
"to",
"specify",
"an",
"offset",
"in",
"s",
"where",
"the",
"JSON",
"document",
"begins",
"."
] |
def raw_decode(self, s, idx=0, _w=WHITESPACE.match):
"""Decode a JSON document from ``s`` (a ``str`` or ``unicode``
beginning with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
Optionally, ``idx`` can be used to specify an offset in ``s`` where
the JSON document begins.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.
"""
try:
obj, end = self.scan_once(s, idx=_w(s, idx).end())
except StopIteration:
raise JSONDecodeError("No JSON object could be decoded", s, idx)
return obj, end
|
[
"def",
"raw_decode",
"(",
"self",
",",
"s",
",",
"idx",
"=",
"0",
",",
"_w",
"=",
"WHITESPACE",
".",
"match",
")",
":",
"try",
":",
"obj",
",",
"end",
"=",
"self",
".",
"scan_once",
"(",
"s",
",",
"idx",
"=",
"_w",
"(",
"s",
",",
"idx",
")",
".",
"end",
"(",
")",
")",
"except",
"StopIteration",
":",
"raise",
"JSONDecodeError",
"(",
"\"No JSON object could be decoded\"",
",",
"s",
",",
"idx",
")",
"return",
"obj",
",",
"end"
] |
https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/simplejson/decoder.py#L412-L427
|
|
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/tokenizer.py
|
python
|
Tokenizer.get_eol
|
(self)
|
return token.value
|
Read the next token and raise an exception if it isn't EOL or
EOF.
@raises dns.exception.SyntaxError:
@rtype: string
|
Read the next token and raise an exception if it isn't EOL or
EOF.
|
[
"Read",
"the",
"next",
"token",
"and",
"raise",
"an",
"exception",
"if",
"it",
"isn",
"t",
"EOL",
"or",
"EOF",
"."
] |
def get_eol(self):
"""Read the next token and raise an exception if it isn't EOL or
EOF.
@raises dns.exception.SyntaxError:
@rtype: string
"""
token = self.get()
if not token.is_eol_or_eof():
raise dns.exception.SyntaxError('expected EOL or EOF, got %d "%s"' % (token.ttype, token.value))
return token.value
|
[
"def",
"get_eol",
"(",
"self",
")",
":",
"token",
"=",
"self",
".",
"get",
"(",
")",
"if",
"not",
"token",
".",
"is_eol_or_eof",
"(",
")",
":",
"raise",
"dns",
".",
"exception",
".",
"SyntaxError",
"(",
"'expected EOL or EOF, got %d \"%s\"'",
"%",
"(",
"token",
".",
"ttype",
",",
"token",
".",
"value",
")",
")",
"return",
"token",
".",
"value"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/tokenizer.py#L530-L541
|
|
MhLiao/TextBoxes_plusplus
|
39d4898de1504c53a2ed3d67966a57b3595836d0
|
tools/extra/parse_log.py
|
python
|
write_csv
|
(output_filename, dict_list, delimiter, verbose=False)
|
Write a CSV file
|
Write a CSV file
|
[
"Write",
"a",
"CSV",
"file"
] |
def write_csv(output_filename, dict_list, delimiter, verbose=False):
"""Write a CSV file
"""
if not dict_list:
if verbose:
print('Not writing %s; no lines to write' % output_filename)
return
dialect = csv.excel
dialect.delimiter = delimiter
with open(output_filename, 'w') as f:
dict_writer = csv.DictWriter(f, fieldnames=dict_list[0].keys(),
dialect=dialect)
dict_writer.writeheader()
dict_writer.writerows(dict_list)
if verbose:
print 'Wrote %s' % output_filename
|
[
"def",
"write_csv",
"(",
"output_filename",
",",
"dict_list",
",",
"delimiter",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"not",
"dict_list",
":",
"if",
"verbose",
":",
"print",
"(",
"'Not writing %s; no lines to write'",
"%",
"output_filename",
")",
"return",
"dialect",
"=",
"csv",
".",
"excel",
"dialect",
".",
"delimiter",
"=",
"delimiter",
"with",
"open",
"(",
"output_filename",
",",
"'w'",
")",
"as",
"f",
":",
"dict_writer",
"=",
"csv",
".",
"DictWriter",
"(",
"f",
",",
"fieldnames",
"=",
"dict_list",
"[",
"0",
"]",
".",
"keys",
"(",
")",
",",
"dialect",
"=",
"dialect",
")",
"dict_writer",
".",
"writeheader",
"(",
")",
"dict_writer",
".",
"writerows",
"(",
"dict_list",
")",
"if",
"verbose",
":",
"print",
"'Wrote %s'",
"%",
"output_filename"
] |
https://github.com/MhLiao/TextBoxes_plusplus/blob/39d4898de1504c53a2ed3d67966a57b3595836d0/tools/extra/parse_log.py#L150-L168
|
||
cms-sw/cmssw
|
fd9de012d503d3405420bcbeec0ec879baa57cf2
|
PhysicsTools/Heppy/python/physicsutils/genutils.py
|
python
|
realGenMothers
|
(gp)
|
return ret
|
Get the mothers of a particle X going through intermediate X -> X' chains.
e.g. if Y -> X, X -> X' realGenMothers(X') = Y
|
Get the mothers of a particle X going through intermediate X -> X' chains.
e.g. if Y -> X, X -> X' realGenMothers(X') = Y
|
[
"Get",
"the",
"mothers",
"of",
"a",
"particle",
"X",
"going",
"through",
"intermediate",
"X",
"-",
">",
"X",
"chains",
".",
"e",
".",
"g",
".",
"if",
"Y",
"-",
">",
"X",
"X",
"-",
">",
"X",
"realGenMothers",
"(",
"X",
")",
"=",
"Y"
] |
def realGenMothers(gp):
"""Get the mothers of a particle X going through intermediate X -> X' chains.
e.g. if Y -> X, X -> X' realGenMothers(X') = Y"""
ret = []
for i in range(gp.numberOfMothers()):
mom = gp.mother(i)
if mom.pdgId() == gp.pdgId():
ret += realGenMothers(mom)
else:
ret.append(mom)
return ret
|
[
"def",
"realGenMothers",
"(",
"gp",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"gp",
".",
"numberOfMothers",
"(",
")",
")",
":",
"mom",
"=",
"gp",
".",
"mother",
"(",
"i",
")",
"if",
"mom",
".",
"pdgId",
"(",
")",
"==",
"gp",
".",
"pdgId",
"(",
")",
":",
"ret",
"+=",
"realGenMothers",
"(",
"mom",
")",
"else",
":",
"ret",
".",
"append",
"(",
"mom",
")",
"return",
"ret"
] |
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/Heppy/python/physicsutils/genutils.py#L100-L110
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/_controls.py
|
python
|
TreeCtrl.IsEmpty
|
(*args, **kwargs)
|
return _controls_.TreeCtrl_IsEmpty(*args, **kwargs)
|
IsEmpty(self) -> bool
|
IsEmpty(self) -> bool
|
[
"IsEmpty",
"(",
"self",
")",
"-",
">",
"bool"
] |
def IsEmpty(*args, **kwargs):
"""IsEmpty(self) -> bool"""
return _controls_.TreeCtrl_IsEmpty(*args, **kwargs)
|
[
"def",
"IsEmpty",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TreeCtrl_IsEmpty",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L5351-L5353
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/numeric.py
|
python
|
tensordot
|
(a, b, axes=2)
|
return res.reshape(olda + oldb)
|
Compute tensor dot product along specified axes.
Given two tensors, `a` and `b`, and an array_like object containing
two array_like objects, ``(a_axes, b_axes)``, sum the products of
`a`'s and `b`'s elements (components) over the axes specified by
``a_axes`` and ``b_axes``. The third argument can be a single non-negative
integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
of `a` and the first ``N`` dimensions of `b` are summed over.
Parameters
----------
a, b : array_like
Tensors to "dot".
axes : int or (2,) array_like
* integer_like
If an int N, sum over the last N axes of `a` and the first N axes
of `b` in order. The sizes of the corresponding axes must match.
* (2,) array_like
Or, a list of axes to be summed over, first sequence applying to `a`,
second to `b`. Both elements array_like must be of the same length.
Returns
-------
output : ndarray
The tensor dot product of the input.
See Also
--------
dot, einsum
Notes
-----
Three common use cases are:
* ``axes = 0`` : tensor product :math:`a\\otimes b`
* ``axes = 1`` : tensor dot product :math:`a\\cdot b`
* ``axes = 2`` : (default) tensor double contraction :math:`a:b`
When `axes` is integer_like, the sequence for evaluation will be: first
the -Nth axis in `a` and 0th axis in `b`, and the -1th axis in `a` and
Nth axis in `b` last.
When there is more than one axis to sum over - and they are not the last
(first) axes of `a` (`b`) - the argument `axes` should consist of
two sequences of the same length, with the first axis to sum over given
first in both sequences, the second axis second, and so forth.
The shape of the result consists of the non-contracted axes of the
first tensor, followed by the non-contracted axes of the second.
Examples
--------
A "traditional" example:
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
>>> c.shape
(5, 2)
>>> c
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])
>>> # A slower but equivalent way of computing the same...
>>> d = np.zeros((5,2))
>>> for i in range(5):
... for j in range(2):
... for k in range(3):
... for n in range(4):
... d[i,j] += a[k,n,i] * b[n,k,j]
>>> c == d
array([[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True]])
An extended example taking advantage of the overloading of + and \\*:
>>> a = np.array(range(1, 9))
>>> a.shape = (2, 2, 2)
>>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
>>> A.shape = (2, 2)
>>> a; A
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
array([['a', 'b'],
['c', 'd']], dtype=object)
>>> np.tensordot(a, A) # third argument default is 2 for double-contraction
array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
>>> np.tensordot(a, A, 1)
array([[['acc', 'bdd'],
['aaacccc', 'bbbdddd']],
[['aaaaacccccc', 'bbbbbdddddd'],
['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
>>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
array([[[[['a', 'b'],
['c', 'd']],
...
>>> np.tensordot(a, A, (0, 1))
array([[['abbbbb', 'cddddd'],
['aabbbbbb', 'ccdddddd']],
[['aaabbbbbbb', 'cccddddddd'],
['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
>>> np.tensordot(a, A, (2, 1))
array([[['abb', 'cdd'],
['aaabbbb', 'cccdddd']],
[['aaaaabbbbbb', 'cccccdddddd'],
['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
>>> np.tensordot(a, A, ((0, 1), (0, 1)))
array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
>>> np.tensordot(a, A, ((2, 1), (1, 0)))
array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
|
Compute tensor dot product along specified axes.
|
[
"Compute",
"tensor",
"dot",
"product",
"along",
"specified",
"axes",
"."
] |
def tensordot(a, b, axes=2):
"""
Compute tensor dot product along specified axes.
Given two tensors, `a` and `b`, and an array_like object containing
two array_like objects, ``(a_axes, b_axes)``, sum the products of
`a`'s and `b`'s elements (components) over the axes specified by
``a_axes`` and ``b_axes``. The third argument can be a single non-negative
integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
of `a` and the first ``N`` dimensions of `b` are summed over.
Parameters
----------
a, b : array_like
Tensors to "dot".
axes : int or (2,) array_like
* integer_like
If an int N, sum over the last N axes of `a` and the first N axes
of `b` in order. The sizes of the corresponding axes must match.
* (2,) array_like
Or, a list of axes to be summed over, first sequence applying to `a`,
second to `b`. Both elements array_like must be of the same length.
Returns
-------
output : ndarray
The tensor dot product of the input.
See Also
--------
dot, einsum
Notes
-----
Three common use cases are:
* ``axes = 0`` : tensor product :math:`a\\otimes b`
* ``axes = 1`` : tensor dot product :math:`a\\cdot b`
* ``axes = 2`` : (default) tensor double contraction :math:`a:b`
When `axes` is integer_like, the sequence for evaluation will be: first
the -Nth axis in `a` and 0th axis in `b`, and the -1th axis in `a` and
Nth axis in `b` last.
When there is more than one axis to sum over - and they are not the last
(first) axes of `a` (`b`) - the argument `axes` should consist of
two sequences of the same length, with the first axis to sum over given
first in both sequences, the second axis second, and so forth.
The shape of the result consists of the non-contracted axes of the
first tensor, followed by the non-contracted axes of the second.
Examples
--------
A "traditional" example:
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
>>> c.shape
(5, 2)
>>> c
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])
>>> # A slower but equivalent way of computing the same...
>>> d = np.zeros((5,2))
>>> for i in range(5):
... for j in range(2):
... for k in range(3):
... for n in range(4):
... d[i,j] += a[k,n,i] * b[n,k,j]
>>> c == d
array([[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True]])
An extended example taking advantage of the overloading of + and \\*:
>>> a = np.array(range(1, 9))
>>> a.shape = (2, 2, 2)
>>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
>>> A.shape = (2, 2)
>>> a; A
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
array([['a', 'b'],
['c', 'd']], dtype=object)
>>> np.tensordot(a, A) # third argument default is 2 for double-contraction
array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
>>> np.tensordot(a, A, 1)
array([[['acc', 'bdd'],
['aaacccc', 'bbbdddd']],
[['aaaaacccccc', 'bbbbbdddddd'],
['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
>>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
array([[[[['a', 'b'],
['c', 'd']],
...
>>> np.tensordot(a, A, (0, 1))
array([[['abbbbb', 'cddddd'],
['aabbbbbb', 'ccdddddd']],
[['aaabbbbbbb', 'cccddddddd'],
['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
>>> np.tensordot(a, A, (2, 1))
array([[['abb', 'cdd'],
['aaabbbb', 'cccdddd']],
[['aaaaabbbbbb', 'cccccdddddd'],
['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
>>> np.tensordot(a, A, ((0, 1), (0, 1)))
array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
>>> np.tensordot(a, A, ((2, 1), (1, 0)))
array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
"""
try:
iter(axes)
except Exception:
axes_a = list(range(-axes, 0))
axes_b = list(range(0, axes))
else:
axes_a, axes_b = axes
try:
na = len(axes_a)
axes_a = list(axes_a)
except TypeError:
axes_a = [axes_a]
na = 1
try:
nb = len(axes_b)
axes_b = list(axes_b)
except TypeError:
axes_b = [axes_b]
nb = 1
a, b = asarray(a), asarray(b)
as_ = a.shape
nda = a.ndim
bs = b.shape
ndb = b.ndim
equal = True
if na != nb:
equal = False
else:
for k in range(na):
if as_[axes_a[k]] != bs[axes_b[k]]:
equal = False
break
if axes_a[k] < 0:
axes_a[k] += nda
if axes_b[k] < 0:
axes_b[k] += ndb
if not equal:
raise ValueError("shape-mismatch for sum")
# Move the axes to sum over to the end of "a"
# and to the front of "b"
notin = [k for k in range(nda) if k not in axes_a]
newaxes_a = notin + axes_a
N2 = 1
for axis in axes_a:
N2 *= as_[axis]
newshape_a = (int(multiply.reduce([as_[ax] for ax in notin])), N2)
olda = [as_[axis] for axis in notin]
notin = [k for k in range(ndb) if k not in axes_b]
newaxes_b = axes_b + notin
N2 = 1
for axis in axes_b:
N2 *= bs[axis]
newshape_b = (N2, int(multiply.reduce([bs[ax] for ax in notin])))
oldb = [bs[axis] for axis in notin]
at = a.transpose(newaxes_a).reshape(newshape_a)
bt = b.transpose(newaxes_b).reshape(newshape_b)
res = dot(at, bt)
return res.reshape(olda + oldb)
|
[
"def",
"tensordot",
"(",
"a",
",",
"b",
",",
"axes",
"=",
"2",
")",
":",
"try",
":",
"iter",
"(",
"axes",
")",
"except",
"Exception",
":",
"axes_a",
"=",
"list",
"(",
"range",
"(",
"-",
"axes",
",",
"0",
")",
")",
"axes_b",
"=",
"list",
"(",
"range",
"(",
"0",
",",
"axes",
")",
")",
"else",
":",
"axes_a",
",",
"axes_b",
"=",
"axes",
"try",
":",
"na",
"=",
"len",
"(",
"axes_a",
")",
"axes_a",
"=",
"list",
"(",
"axes_a",
")",
"except",
"TypeError",
":",
"axes_a",
"=",
"[",
"axes_a",
"]",
"na",
"=",
"1",
"try",
":",
"nb",
"=",
"len",
"(",
"axes_b",
")",
"axes_b",
"=",
"list",
"(",
"axes_b",
")",
"except",
"TypeError",
":",
"axes_b",
"=",
"[",
"axes_b",
"]",
"nb",
"=",
"1",
"a",
",",
"b",
"=",
"asarray",
"(",
"a",
")",
",",
"asarray",
"(",
"b",
")",
"as_",
"=",
"a",
".",
"shape",
"nda",
"=",
"a",
".",
"ndim",
"bs",
"=",
"b",
".",
"shape",
"ndb",
"=",
"b",
".",
"ndim",
"equal",
"=",
"True",
"if",
"na",
"!=",
"nb",
":",
"equal",
"=",
"False",
"else",
":",
"for",
"k",
"in",
"range",
"(",
"na",
")",
":",
"if",
"as_",
"[",
"axes_a",
"[",
"k",
"]",
"]",
"!=",
"bs",
"[",
"axes_b",
"[",
"k",
"]",
"]",
":",
"equal",
"=",
"False",
"break",
"if",
"axes_a",
"[",
"k",
"]",
"<",
"0",
":",
"axes_a",
"[",
"k",
"]",
"+=",
"nda",
"if",
"axes_b",
"[",
"k",
"]",
"<",
"0",
":",
"axes_b",
"[",
"k",
"]",
"+=",
"ndb",
"if",
"not",
"equal",
":",
"raise",
"ValueError",
"(",
"\"shape-mismatch for sum\"",
")",
"# Move the axes to sum over to the end of \"a\"",
"# and to the front of \"b\"",
"notin",
"=",
"[",
"k",
"for",
"k",
"in",
"range",
"(",
"nda",
")",
"if",
"k",
"not",
"in",
"axes_a",
"]",
"newaxes_a",
"=",
"notin",
"+",
"axes_a",
"N2",
"=",
"1",
"for",
"axis",
"in",
"axes_a",
":",
"N2",
"*=",
"as_",
"[",
"axis",
"]",
"newshape_a",
"=",
"(",
"int",
"(",
"multiply",
".",
"reduce",
"(",
"[",
"as_",
"[",
"ax",
"]",
"for",
"ax",
"in",
"notin",
"]",
")",
")",
",",
"N2",
")",
"olda",
"=",
"[",
"as_",
"[",
"axis",
"]",
"for",
"axis",
"in",
"notin",
"]",
"notin",
"=",
"[",
"k",
"for",
"k",
"in",
"range",
"(",
"ndb",
")",
"if",
"k",
"not",
"in",
"axes_b",
"]",
"newaxes_b",
"=",
"axes_b",
"+",
"notin",
"N2",
"=",
"1",
"for",
"axis",
"in",
"axes_b",
":",
"N2",
"*=",
"bs",
"[",
"axis",
"]",
"newshape_b",
"=",
"(",
"N2",
",",
"int",
"(",
"multiply",
".",
"reduce",
"(",
"[",
"bs",
"[",
"ax",
"]",
"for",
"ax",
"in",
"notin",
"]",
")",
")",
")",
"oldb",
"=",
"[",
"bs",
"[",
"axis",
"]",
"for",
"axis",
"in",
"notin",
"]",
"at",
"=",
"a",
".",
"transpose",
"(",
"newaxes_a",
")",
".",
"reshape",
"(",
"newshape_a",
")",
"bt",
"=",
"b",
".",
"transpose",
"(",
"newaxes_b",
")",
".",
"reshape",
"(",
"newshape_b",
")",
"res",
"=",
"dot",
"(",
"at",
",",
"bt",
")",
"return",
"res",
".",
"reshape",
"(",
"olda",
"+",
"oldb",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/numeric.py#L914-L1103
|
|
ideawu/ssdb
|
f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4
|
deps/cpy/antlr3/tree.py
|
python
|
BaseTree.getChildIndex
|
(self)
|
return 0
|
BaseTree doesn't track child indexes.
|
BaseTree doesn't track child indexes.
|
[
"BaseTree",
"doesn",
"t",
"track",
"child",
"indexes",
"."
] |
def getChildIndex(self):
"""BaseTree doesn't track child indexes."""
return 0
|
[
"def",
"getChildIndex",
"(",
"self",
")",
":",
"return",
"0"
] |
https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/tree.py#L844-L847
|
|
benoitsteiner/tensorflow-opencl
|
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
|
tensorflow/python/ops/math_grad.py
|
python
|
_ProdGrad
|
(op, grad)
|
return array_ops.reshape(out, input_shape), None
|
Gradient for Prod.
|
Gradient for Prod.
|
[
"Gradient",
"for",
"Prod",
"."
] |
def _ProdGrad(op, grad):
"""Gradient for Prod."""
# The gradient can be expressed by dividing the product by each entry of the
# input tensor, but this approach can't deal with zeros in the input.
# Here, we avoid this problem by composing the output as a product of two
# cumprod operations.
input_shape = array_ops.shape(op.inputs[0])
# Reshape reduction indices for the case where the parameter is a scalar
reduction_indices = array_ops.reshape(op.inputs[1], [-1])
# Expand grad to full input shape
output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1])
tile_scaling = _safe_shape_div(input_shape, output_shape_kept_dims)
grad = array_ops.reshape(grad, output_shape_kept_dims)
grad = array_ops.tile(grad, tile_scaling)
# Pack all reduced dimensions into a single one, so we can perform the
# cumprod ops. If the reduction dims list is empty, it defaults to float32,
# so we need to cast here. We put all the shape-related ops on CPU to avoid
# copying back and forth, and since listdiff is CPU only.
with ops.device("/cpu:0"):
rank = array_ops.rank(op.inputs[0])
reduction_indices = (reduction_indices + rank) % rank
reduced = math_ops.cast(reduction_indices, dtypes.int32)
idx = math_ops.range(0, rank)
other, _ = array_ops.setdiff1d(idx, reduced)
perm = array_ops.concat([reduced, other], 0)
reduced_num = math_ops.reduce_prod(array_ops.gather(input_shape, reduced))
other_num = math_ops.reduce_prod(array_ops.gather(input_shape, other))
permuted = array_ops.transpose(op.inputs[0], perm)
permuted_shape = array_ops.shape(permuted)
reshaped = array_ops.reshape(permuted, (reduced_num, other_num))
# Calculate product, leaving out the current entry
left = math_ops.cumprod(reshaped, axis=0, exclusive=True)
right = math_ops.cumprod(reshaped, axis=0, exclusive=True, reverse=True)
y = array_ops.reshape(left * right, permuted_shape)
# Invert the transpose and reshape operations.
# Make sure to set the statically known shape information through a reshape.
out = grad * array_ops.transpose(y, array_ops.invert_permutation(perm))
return array_ops.reshape(out, input_shape), None
|
[
"def",
"_ProdGrad",
"(",
"op",
",",
"grad",
")",
":",
"# The gradient can be expressed by dividing the product by each entry of the",
"# input tensor, but this approach can't deal with zeros in the input.",
"# Here, we avoid this problem by composing the output as a product of two",
"# cumprod operations.",
"input_shape",
"=",
"array_ops",
".",
"shape",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
")",
"# Reshape reduction indices for the case where the parameter is a scalar",
"reduction_indices",
"=",
"array_ops",
".",
"reshape",
"(",
"op",
".",
"inputs",
"[",
"1",
"]",
",",
"[",
"-",
"1",
"]",
")",
"# Expand grad to full input shape",
"output_shape_kept_dims",
"=",
"math_ops",
".",
"reduced_shape",
"(",
"input_shape",
",",
"op",
".",
"inputs",
"[",
"1",
"]",
")",
"tile_scaling",
"=",
"_safe_shape_div",
"(",
"input_shape",
",",
"output_shape_kept_dims",
")",
"grad",
"=",
"array_ops",
".",
"reshape",
"(",
"grad",
",",
"output_shape_kept_dims",
")",
"grad",
"=",
"array_ops",
".",
"tile",
"(",
"grad",
",",
"tile_scaling",
")",
"# Pack all reduced dimensions into a single one, so we can perform the",
"# cumprod ops. If the reduction dims list is empty, it defaults to float32,",
"# so we need to cast here. We put all the shape-related ops on CPU to avoid",
"# copying back and forth, and since listdiff is CPU only.",
"with",
"ops",
".",
"device",
"(",
"\"/cpu:0\"",
")",
":",
"rank",
"=",
"array_ops",
".",
"rank",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
")",
"reduction_indices",
"=",
"(",
"reduction_indices",
"+",
"rank",
")",
"%",
"rank",
"reduced",
"=",
"math_ops",
".",
"cast",
"(",
"reduction_indices",
",",
"dtypes",
".",
"int32",
")",
"idx",
"=",
"math_ops",
".",
"range",
"(",
"0",
",",
"rank",
")",
"other",
",",
"_",
"=",
"array_ops",
".",
"setdiff1d",
"(",
"idx",
",",
"reduced",
")",
"perm",
"=",
"array_ops",
".",
"concat",
"(",
"[",
"reduced",
",",
"other",
"]",
",",
"0",
")",
"reduced_num",
"=",
"math_ops",
".",
"reduce_prod",
"(",
"array_ops",
".",
"gather",
"(",
"input_shape",
",",
"reduced",
")",
")",
"other_num",
"=",
"math_ops",
".",
"reduce_prod",
"(",
"array_ops",
".",
"gather",
"(",
"input_shape",
",",
"other",
")",
")",
"permuted",
"=",
"array_ops",
".",
"transpose",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
",",
"perm",
")",
"permuted_shape",
"=",
"array_ops",
".",
"shape",
"(",
"permuted",
")",
"reshaped",
"=",
"array_ops",
".",
"reshape",
"(",
"permuted",
",",
"(",
"reduced_num",
",",
"other_num",
")",
")",
"# Calculate product, leaving out the current entry",
"left",
"=",
"math_ops",
".",
"cumprod",
"(",
"reshaped",
",",
"axis",
"=",
"0",
",",
"exclusive",
"=",
"True",
")",
"right",
"=",
"math_ops",
".",
"cumprod",
"(",
"reshaped",
",",
"axis",
"=",
"0",
",",
"exclusive",
"=",
"True",
",",
"reverse",
"=",
"True",
")",
"y",
"=",
"array_ops",
".",
"reshape",
"(",
"left",
"*",
"right",
",",
"permuted_shape",
")",
"# Invert the transpose and reshape operations.",
"# Make sure to set the statically known shape information through a reshape.",
"out",
"=",
"grad",
"*",
"array_ops",
".",
"transpose",
"(",
"y",
",",
"array_ops",
".",
"invert_permutation",
"(",
"perm",
")",
")",
"return",
"array_ops",
".",
"reshape",
"(",
"out",
",",
"input_shape",
")",
",",
"None"
] |
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/math_grad.py#L113-L155
|
|
BlzFans/wke
|
b0fa21158312e40c5fbd84682d643022b6c34a93
|
cygwin/lib/python2.6/mailbox.py
|
python
|
_singlefileMailbox.iterkeys
|
(self)
|
Return an iterator over keys.
|
Return an iterator over keys.
|
[
"Return",
"an",
"iterator",
"over",
"keys",
"."
] |
def iterkeys(self):
"""Return an iterator over keys."""
self._lookup()
for key in self._toc.keys():
yield key
|
[
"def",
"iterkeys",
"(",
"self",
")",
":",
"self",
".",
"_lookup",
"(",
")",
"for",
"key",
"in",
"self",
".",
"_toc",
".",
"keys",
"(",
")",
":",
"yield",
"key"
] |
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mailbox.py#L546-L550
|
||
krishauser/Klampt
|
972cc83ea5befac3f653c1ba20f80155768ad519
|
Python/klampt/src/robotsim.py
|
python
|
RobotModelLink.getID
|
(self)
|
return _robotsim.RobotModelLink_getID(self)
|
r"""
getID(RobotModelLink self) -> int
Returns the ID of the robot link in its world.
.. note::
The world ID is not the same as the link's index, retrieved by
getIndex.
|
r"""
getID(RobotModelLink self) -> int
|
[
"r",
"getID",
"(",
"RobotModelLink",
"self",
")",
"-",
">",
"int"
] |
def getID(self) -> "int":
r"""
getID(RobotModelLink self) -> int
Returns the ID of the robot link in its world.
.. note::
The world ID is not the same as the link's index, retrieved by
getIndex.
"""
return _robotsim.RobotModelLink_getID(self)
|
[
"def",
"getID",
"(",
"self",
")",
"->",
"\"int\"",
":",
"return",
"_robotsim",
".",
"RobotModelLink_getID",
"(",
"self",
")"
] |
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L4043-L4056
|
|
apache/incubator-mxnet
|
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
|
python/mxnet/numpy/multiarray.py
|
python
|
shape
|
(a)
|
return _mx_nd_np.shape(a)
|
Return the shape of an array.
Parameters
----------
a : array_like
Input array.
Returns
-------
shape : tuple of ints
The elements of the shape tuple give the lengths of the
corresponding array dimensions.
See Also
--------
ndarray.shape : Equivalent array method.
Examples
--------
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
|
Return the shape of an array.
|
[
"Return",
"the",
"shape",
"of",
"an",
"array",
"."
] |
def shape(a):
"""
Return the shape of an array.
Parameters
----------
a : array_like
Input array.
Returns
-------
shape : tuple of ints
The elements of the shape tuple give the lengths of the
corresponding array dimensions.
See Also
--------
ndarray.shape : Equivalent array method.
Examples
--------
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
"""
return _mx_nd_np.shape(a)
|
[
"def",
"shape",
"(",
"a",
")",
":",
"return",
"_mx_nd_np",
".",
"shape",
"(",
"a",
")"
] |
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L2781-L2811
|
|
freeorion/freeorion
|
c266a40eccd3a99a17de8fe57c36ef6ba3771665
|
default/python/AI/target.py
|
python
|
TargetFleet.get_system
|
(self)
|
return TargetSystem(system_id)
|
Get current fleet location or target system if currently on starlane.
|
Get current fleet location or target system if currently on starlane.
|
[
"Get",
"current",
"fleet",
"location",
"or",
"target",
"system",
"if",
"currently",
"on",
"starlane",
"."
] |
def get_system(self) -> Optional[TargetSystem]:
"""
Get current fleet location or target system if currently on starlane.
"""
universe = fo.getUniverse()
fleet = universe.getFleet(self.id)
system_id = fleet.nextSystemID
if system_id == INVALID_ID: # fleet is not moving
system_id = fleet.systemID
return TargetSystem(system_id)
|
[
"def",
"get_system",
"(",
"self",
")",
"->",
"Optional",
"[",
"TargetSystem",
"]",
":",
"universe",
"=",
"fo",
".",
"getUniverse",
"(",
")",
"fleet",
"=",
"universe",
".",
"getFleet",
"(",
"self",
".",
"id",
")",
"system_id",
"=",
"fleet",
".",
"nextSystemID",
"if",
"system_id",
"==",
"INVALID_ID",
":",
"# fleet is not moving",
"system_id",
"=",
"fleet",
".",
"systemID",
"return",
"TargetSystem",
"(",
"system_id",
")"
] |
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/target.py#L103-L112
|
|
baidu-research/tensorflow-allreduce
|
66d5b855e90b0949e9fa5cca5599fd729a70e874
|
tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py
|
python
|
_prepare_memory
|
(memory, memory_sequence_length, check_inner_dims_defined)
|
return nest.map_structure(lambda m: _maybe_mask(m, seq_len_mask), memory)
|
Convert to tensor and possibly mask `memory`.
Args:
memory: `Tensor`, shaped `[batch_size, max_time, ...]`.
memory_sequence_length: `int32` `Tensor`, shaped `[batch_size]`.
check_inner_dims_defined: Python boolean. If `True`, the `memory`
argument's shape is checked to ensure all but the two outermost
dimensions are fully defined.
Returns:
A (possibly masked), checked, new `memory`.
Raises:
ValueError: If `check_inner_dims_defined` is `True` and not
`memory.shape[2:].is_fully_defined()`.
|
Convert to tensor and possibly mask `memory`.
|
[
"Convert",
"to",
"tensor",
"and",
"possibly",
"mask",
"memory",
"."
] |
def _prepare_memory(memory, memory_sequence_length, check_inner_dims_defined):
"""Convert to tensor and possibly mask `memory`.
Args:
memory: `Tensor`, shaped `[batch_size, max_time, ...]`.
memory_sequence_length: `int32` `Tensor`, shaped `[batch_size]`.
check_inner_dims_defined: Python boolean. If `True`, the `memory`
argument's shape is checked to ensure all but the two outermost
dimensions are fully defined.
Returns:
A (possibly masked), checked, new `memory`.
Raises:
ValueError: If `check_inner_dims_defined` is `True` and not
`memory.shape[2:].is_fully_defined()`.
"""
memory = nest.map_structure(
lambda m: ops.convert_to_tensor(m, name="memory"), memory)
if memory_sequence_length is not None:
memory_sequence_length = ops.convert_to_tensor(
memory_sequence_length, name="memory_sequence_length")
if check_inner_dims_defined:
def _check_dims(m):
if not m.get_shape()[2:].is_fully_defined():
raise ValueError("Expected memory %s to have fully defined inner dims, "
"but saw shape: %s" % (m.name, m.get_shape()))
nest.map_structure(_check_dims, memory)
if memory_sequence_length is None:
seq_len_mask = None
else:
seq_len_mask = array_ops.sequence_mask(
memory_sequence_length,
maxlen=array_ops.shape(nest.flatten(memory)[0])[1],
dtype=nest.flatten(memory)[0].dtype)
seq_len_batch_size = (
memory_sequence_length.shape[0].value
or array_ops.shape(memory_sequence_length)[0])
def _maybe_mask(m, seq_len_mask):
rank = m.get_shape().ndims
rank = rank if rank is not None else array_ops.rank(m)
extra_ones = array_ops.ones(rank - 2, dtype=dtypes.int32)
m_batch_size = m.shape[0].value or array_ops.shape(m)[0]
if memory_sequence_length is not None:
message = ("memory_sequence_length and memory tensor batch sizes do not "
"match.")
with ops.control_dependencies([
check_ops.assert_equal(
seq_len_batch_size, m_batch_size, message=message)]):
seq_len_mask = array_ops.reshape(
seq_len_mask,
array_ops.concat((array_ops.shape(seq_len_mask), extra_ones), 0))
return m * seq_len_mask
else:
return m
return nest.map_structure(lambda m: _maybe_mask(m, seq_len_mask), memory)
|
[
"def",
"_prepare_memory",
"(",
"memory",
",",
"memory_sequence_length",
",",
"check_inner_dims_defined",
")",
":",
"memory",
"=",
"nest",
".",
"map_structure",
"(",
"lambda",
"m",
":",
"ops",
".",
"convert_to_tensor",
"(",
"m",
",",
"name",
"=",
"\"memory\"",
")",
",",
"memory",
")",
"if",
"memory_sequence_length",
"is",
"not",
"None",
":",
"memory_sequence_length",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"memory_sequence_length",
",",
"name",
"=",
"\"memory_sequence_length\"",
")",
"if",
"check_inner_dims_defined",
":",
"def",
"_check_dims",
"(",
"m",
")",
":",
"if",
"not",
"m",
".",
"get_shape",
"(",
")",
"[",
"2",
":",
"]",
".",
"is_fully_defined",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected memory %s to have fully defined inner dims, \"",
"\"but saw shape: %s\"",
"%",
"(",
"m",
".",
"name",
",",
"m",
".",
"get_shape",
"(",
")",
")",
")",
"nest",
".",
"map_structure",
"(",
"_check_dims",
",",
"memory",
")",
"if",
"memory_sequence_length",
"is",
"None",
":",
"seq_len_mask",
"=",
"None",
"else",
":",
"seq_len_mask",
"=",
"array_ops",
".",
"sequence_mask",
"(",
"memory_sequence_length",
",",
"maxlen",
"=",
"array_ops",
".",
"shape",
"(",
"nest",
".",
"flatten",
"(",
"memory",
")",
"[",
"0",
"]",
")",
"[",
"1",
"]",
",",
"dtype",
"=",
"nest",
".",
"flatten",
"(",
"memory",
")",
"[",
"0",
"]",
".",
"dtype",
")",
"seq_len_batch_size",
"=",
"(",
"memory_sequence_length",
".",
"shape",
"[",
"0",
"]",
".",
"value",
"or",
"array_ops",
".",
"shape",
"(",
"memory_sequence_length",
")",
"[",
"0",
"]",
")",
"def",
"_maybe_mask",
"(",
"m",
",",
"seq_len_mask",
")",
":",
"rank",
"=",
"m",
".",
"get_shape",
"(",
")",
".",
"ndims",
"rank",
"=",
"rank",
"if",
"rank",
"is",
"not",
"None",
"else",
"array_ops",
".",
"rank",
"(",
"m",
")",
"extra_ones",
"=",
"array_ops",
".",
"ones",
"(",
"rank",
"-",
"2",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
")",
"m_batch_size",
"=",
"m",
".",
"shape",
"[",
"0",
"]",
".",
"value",
"or",
"array_ops",
".",
"shape",
"(",
"m",
")",
"[",
"0",
"]",
"if",
"memory_sequence_length",
"is",
"not",
"None",
":",
"message",
"=",
"(",
"\"memory_sequence_length and memory tensor batch sizes do not \"",
"\"match.\"",
")",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"check_ops",
".",
"assert_equal",
"(",
"seq_len_batch_size",
",",
"m_batch_size",
",",
"message",
"=",
"message",
")",
"]",
")",
":",
"seq_len_mask",
"=",
"array_ops",
".",
"reshape",
"(",
"seq_len_mask",
",",
"array_ops",
".",
"concat",
"(",
"(",
"array_ops",
".",
"shape",
"(",
"seq_len_mask",
")",
",",
"extra_ones",
")",
",",
"0",
")",
")",
"return",
"m",
"*",
"seq_len_mask",
"else",
":",
"return",
"m",
"return",
"nest",
".",
"map_structure",
"(",
"lambda",
"m",
":",
"_maybe_mask",
"(",
"m",
",",
"seq_len_mask",
")",
",",
"memory",
")"
] |
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py#L67-L122
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/msw/_misc.py
|
python
|
LogGui.__init__
|
(self, *args, **kwargs)
|
__init__(self) -> LogGui
|
__init__(self) -> LogGui
|
[
"__init__",
"(",
"self",
")",
"-",
">",
"LogGui"
] |
def __init__(self, *args, **kwargs):
"""__init__(self) -> LogGui"""
_misc_.LogGui_swiginit(self,_misc_.new_LogGui(*args, **kwargs))
|
[
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_misc_",
".",
"LogGui_swiginit",
"(",
"self",
",",
"_misc_",
".",
"new_LogGui",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L1758-L1760
|
||
giuspen/cherrytree
|
84712f206478fcf9acf30174009ad28c648c6344
|
pygtk2/modules/ctdb.py
|
python
|
CTDBHandler.write_db_node
|
(self, db, tree_iter, sequence, node_father_id, write_dict, exporting="", sel_range=None)
|
Write a node in DB
|
Write a node in DB
|
[
"Write",
"a",
"node",
"in",
"DB"
] |
def write_db_node(self, db, tree_iter, sequence, node_father_id, write_dict, exporting="", sel_range=None):
"""Write a node in DB"""
node_id = self.dad.treestore[tree_iter][3]
print "write node content, node_id", node_id, ", write_dict", write_dict
name = self.dad.treestore[tree_iter][1].decode(cons.STR_UTF8)
syntax = self.dad.treestore[tree_iter][4]
tags = self.dad.treestore[tree_iter][6].decode(cons.STR_UTF8)
# is_ro (bitfield)
is_ro = self.dad.treestore[tree_iter][9] << 1
if self.dad.treestore[tree_iter][7]:
is_ro |= 0x01
# is_richtxt (bitfield)
is_richtxt = 0x01 if syntax == cons.RICH_TEXT_ID else 0x00
if support.get_pango_is_bold(self.dad.treestore[tree_iter][10]):
is_richtxt |= 0x02
foreground = self.dad.treestore[tree_iter][11]
if foreground:
is_richtxt |= 0x04
is_richtxt |= exports.rgb_int24bit_from_str(foreground[1:]) << 3
ts_creation = self.dad.treestore[tree_iter][12]
ts_lastsave = self.dad.treestore[tree_iter][13]
if not self.db_tables_check_done:
self.db_tables_execute_check(db)
self.db_tables_check_done = True
if write_dict['buff']:
if not self.dad.treestore[tree_iter][2]:
# we are using db storage and the buffer was not created yet
if exporting: self.read_db_node_content(tree_iter, self.dad.db)
else: self.read_db_node_content(tree_iter, self.dad.db_old)
curr_buffer = self.dad.treestore[tree_iter][2]
if not sel_range:
start_iter = curr_buffer.get_start_iter()
end_iter = curr_buffer.get_end_iter()
else:
start_iter = curr_buffer.get_iter_at_offset(sel_range[0])
end_iter = curr_buffer.get_iter_at_offset(sel_range[1])
if (is_richtxt & 0x01):
# prepare xml dom node
if "dom" in dir(self): del self.dom
self.dom = xml.dom.minidom.Document()
dom_iter = self.dom.createElement("node")
self.dom.appendChild(dom_iter)
# init attributes
self.curr_attributes = {}
for tag_property in cons.TAG_PROPERTIES: self.curr_attributes[tag_property] = ""
# go!
curr_iter = start_iter.copy()
self.dad.xml_handler.rich_text_attributes_update(curr_iter, self.curr_attributes)
tag_found = curr_iter.forward_to_tag_toggle(None)
while tag_found:
self.dad.xml_handler.rich_txt_serialize(dom_iter, start_iter, curr_iter, self.curr_attributes, dom=self.dom)
if curr_iter.compare(end_iter) >= 0: break
else:
self.dad.xml_handler.rich_text_attributes_update(curr_iter, self.curr_attributes)
offset_old = curr_iter.get_offset()
start_iter.set_offset(offset_old)
tag_found = curr_iter.forward_to_tag_toggle(None)
if curr_iter.get_offset() == offset_old: break
else: self.dad.xml_handler.rich_txt_serialize(dom_iter, start_iter, curr_iter, self.curr_attributes, dom=self.dom)
# time for the objects
if write_dict['upd']:
db.execute('DELETE FROM codebox WHERE node_id=?', (node_id,))
db.execute('DELETE FROM grid WHERE node_id=?', (node_id,))
db.execute('DELETE FROM image WHERE node_id=?', (node_id,))
pixbuf_table_codebox_vector = self.dad.state_machine.get_embedded_pixbufs_tables_codeboxes(curr_buffer, sel_range=sel_range)
# pixbuf_table_codebox_vector is [ [ "pixbuf"/"table"/"codebox", [offset, pixbuf, alignment] ],... ]
codeboxes_tuples = []
tables_tuples = []
images_tuples = []
for element in pixbuf_table_codebox_vector:
if sel_range: element[1][0] -= sel_range[0]
if element[0] == "pixbuf": images_tuples.append(self.get_image_db_tuple(element[1], node_id))
elif element[0] == "table": tables_tuples.append(self.get_table_db_tuple(element[1], node_id))
elif element[0] == "codebox": codeboxes_tuples.append(self.get_codebox_db_tuple(element[1], node_id))
if codeboxes_tuples:
has_codebox = 1
db.executemany('INSERT INTO codebox VALUES(?,?,?,?,?,?,?,?,?,?)', codeboxes_tuples)
else: has_codebox = 0
if tables_tuples:
has_table = 1
db.executemany('INSERT INTO grid VALUES(?,?,?,?,?,?)', tables_tuples)
else: has_table = 0
if images_tuples:
has_image = 1
db.executemany('INSERT INTO image VALUES(?,?,?,?,?,?,?,?)', images_tuples)
else: has_image = 0
# retrieve xml text
txt = (self.dom.toxml()).decode(cons.STR_UTF8)
else:
# not richtext
has_codebox = 0
has_table = 0
has_image = 0
txt = (start_iter.get_text(end_iter)).decode(cons.STR_UTF8)
if write_dict['prop'] and write_dict['buff']:
if write_dict['upd']:
db.execute('DELETE FROM node WHERE node_id=?', (node_id,))
node_tuple = (node_id, name, txt, syntax, tags,
is_ro, is_richtxt, has_codebox, has_table, has_image,
0, ts_creation, ts_lastsave) # TODO remove the column 'level'
db.execute('INSERT INTO node VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)', node_tuple)
elif write_dict['buff']:
db.execute('UPDATE node SET txt=?, syntax=?, is_richtxt=?, has_codebox=?, has_table=?, has_image=?, ts_lastsave=? WHERE node_id=?', (txt, syntax, is_richtxt, has_codebox, has_table, has_image, ts_lastsave, node_id))
elif write_dict['prop']:
db.execute('UPDATE node SET name=?, syntax=?, tags=?, is_ro=?, is_richtxt=? WHERE node_id=?', (name, syntax, tags, is_ro, is_richtxt, node_id))
if write_dict['hier']:
if write_dict['upd']:
db.execute('DELETE FROM children WHERE node_id=?', (node_id,))
db.execute('INSERT INTO children VALUES(?,?,?)', (node_id, node_father_id, sequence))
if not write_dict['child']: return
# let's take care about the children
child_tree_iter = self.dad.treestore.iter_children(tree_iter)
child_sequence = 0
while child_tree_iter != None:
child_sequence += 1
self.write_db_node(db, child_tree_iter, child_sequence, node_id, write_dict, exporting)
child_tree_iter = self.dad.treestore.iter_next(child_tree_iter)
|
[
"def",
"write_db_node",
"(",
"self",
",",
"db",
",",
"tree_iter",
",",
"sequence",
",",
"node_father_id",
",",
"write_dict",
",",
"exporting",
"=",
"\"\"",
",",
"sel_range",
"=",
"None",
")",
":",
"node_id",
"=",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"3",
"]",
"print",
"\"write node content, node_id\"",
",",
"node_id",
",",
"\", write_dict\"",
",",
"write_dict",
"name",
"=",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"1",
"]",
".",
"decode",
"(",
"cons",
".",
"STR_UTF8",
")",
"syntax",
"=",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"4",
"]",
"tags",
"=",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"6",
"]",
".",
"decode",
"(",
"cons",
".",
"STR_UTF8",
")",
"# is_ro (bitfield)",
"is_ro",
"=",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"9",
"]",
"<<",
"1",
"if",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"7",
"]",
":",
"is_ro",
"|=",
"0x01",
"# is_richtxt (bitfield)",
"is_richtxt",
"=",
"0x01",
"if",
"syntax",
"==",
"cons",
".",
"RICH_TEXT_ID",
"else",
"0x00",
"if",
"support",
".",
"get_pango_is_bold",
"(",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"10",
"]",
")",
":",
"is_richtxt",
"|=",
"0x02",
"foreground",
"=",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"11",
"]",
"if",
"foreground",
":",
"is_richtxt",
"|=",
"0x04",
"is_richtxt",
"|=",
"exports",
".",
"rgb_int24bit_from_str",
"(",
"foreground",
"[",
"1",
":",
"]",
")",
"<<",
"3",
"ts_creation",
"=",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"12",
"]",
"ts_lastsave",
"=",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"13",
"]",
"if",
"not",
"self",
".",
"db_tables_check_done",
":",
"self",
".",
"db_tables_execute_check",
"(",
"db",
")",
"self",
".",
"db_tables_check_done",
"=",
"True",
"if",
"write_dict",
"[",
"'buff'",
"]",
":",
"if",
"not",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"2",
"]",
":",
"# we are using db storage and the buffer was not created yet",
"if",
"exporting",
":",
"self",
".",
"read_db_node_content",
"(",
"tree_iter",
",",
"self",
".",
"dad",
".",
"db",
")",
"else",
":",
"self",
".",
"read_db_node_content",
"(",
"tree_iter",
",",
"self",
".",
"dad",
".",
"db_old",
")",
"curr_buffer",
"=",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"2",
"]",
"if",
"not",
"sel_range",
":",
"start_iter",
"=",
"curr_buffer",
".",
"get_start_iter",
"(",
")",
"end_iter",
"=",
"curr_buffer",
".",
"get_end_iter",
"(",
")",
"else",
":",
"start_iter",
"=",
"curr_buffer",
".",
"get_iter_at_offset",
"(",
"sel_range",
"[",
"0",
"]",
")",
"end_iter",
"=",
"curr_buffer",
".",
"get_iter_at_offset",
"(",
"sel_range",
"[",
"1",
"]",
")",
"if",
"(",
"is_richtxt",
"&",
"0x01",
")",
":",
"# prepare xml dom node",
"if",
"\"dom\"",
"in",
"dir",
"(",
"self",
")",
":",
"del",
"self",
".",
"dom",
"self",
".",
"dom",
"=",
"xml",
".",
"dom",
".",
"minidom",
".",
"Document",
"(",
")",
"dom_iter",
"=",
"self",
".",
"dom",
".",
"createElement",
"(",
"\"node\"",
")",
"self",
".",
"dom",
".",
"appendChild",
"(",
"dom_iter",
")",
"# init attributes",
"self",
".",
"curr_attributes",
"=",
"{",
"}",
"for",
"tag_property",
"in",
"cons",
".",
"TAG_PROPERTIES",
":",
"self",
".",
"curr_attributes",
"[",
"tag_property",
"]",
"=",
"\"\"",
"# go!",
"curr_iter",
"=",
"start_iter",
".",
"copy",
"(",
")",
"self",
".",
"dad",
".",
"xml_handler",
".",
"rich_text_attributes_update",
"(",
"curr_iter",
",",
"self",
".",
"curr_attributes",
")",
"tag_found",
"=",
"curr_iter",
".",
"forward_to_tag_toggle",
"(",
"None",
")",
"while",
"tag_found",
":",
"self",
".",
"dad",
".",
"xml_handler",
".",
"rich_txt_serialize",
"(",
"dom_iter",
",",
"start_iter",
",",
"curr_iter",
",",
"self",
".",
"curr_attributes",
",",
"dom",
"=",
"self",
".",
"dom",
")",
"if",
"curr_iter",
".",
"compare",
"(",
"end_iter",
")",
">=",
"0",
":",
"break",
"else",
":",
"self",
".",
"dad",
".",
"xml_handler",
".",
"rich_text_attributes_update",
"(",
"curr_iter",
",",
"self",
".",
"curr_attributes",
")",
"offset_old",
"=",
"curr_iter",
".",
"get_offset",
"(",
")",
"start_iter",
".",
"set_offset",
"(",
"offset_old",
")",
"tag_found",
"=",
"curr_iter",
".",
"forward_to_tag_toggle",
"(",
"None",
")",
"if",
"curr_iter",
".",
"get_offset",
"(",
")",
"==",
"offset_old",
":",
"break",
"else",
":",
"self",
".",
"dad",
".",
"xml_handler",
".",
"rich_txt_serialize",
"(",
"dom_iter",
",",
"start_iter",
",",
"curr_iter",
",",
"self",
".",
"curr_attributes",
",",
"dom",
"=",
"self",
".",
"dom",
")",
"# time for the objects",
"if",
"write_dict",
"[",
"'upd'",
"]",
":",
"db",
".",
"execute",
"(",
"'DELETE FROM codebox WHERE node_id=?'",
",",
"(",
"node_id",
",",
")",
")",
"db",
".",
"execute",
"(",
"'DELETE FROM grid WHERE node_id=?'",
",",
"(",
"node_id",
",",
")",
")",
"db",
".",
"execute",
"(",
"'DELETE FROM image WHERE node_id=?'",
",",
"(",
"node_id",
",",
")",
")",
"pixbuf_table_codebox_vector",
"=",
"self",
".",
"dad",
".",
"state_machine",
".",
"get_embedded_pixbufs_tables_codeboxes",
"(",
"curr_buffer",
",",
"sel_range",
"=",
"sel_range",
")",
"# pixbuf_table_codebox_vector is [ [ \"pixbuf\"/\"table\"/\"codebox\", [offset, pixbuf, alignment] ],... ]",
"codeboxes_tuples",
"=",
"[",
"]",
"tables_tuples",
"=",
"[",
"]",
"images_tuples",
"=",
"[",
"]",
"for",
"element",
"in",
"pixbuf_table_codebox_vector",
":",
"if",
"sel_range",
":",
"element",
"[",
"1",
"]",
"[",
"0",
"]",
"-=",
"sel_range",
"[",
"0",
"]",
"if",
"element",
"[",
"0",
"]",
"==",
"\"pixbuf\"",
":",
"images_tuples",
".",
"append",
"(",
"self",
".",
"get_image_db_tuple",
"(",
"element",
"[",
"1",
"]",
",",
"node_id",
")",
")",
"elif",
"element",
"[",
"0",
"]",
"==",
"\"table\"",
":",
"tables_tuples",
".",
"append",
"(",
"self",
".",
"get_table_db_tuple",
"(",
"element",
"[",
"1",
"]",
",",
"node_id",
")",
")",
"elif",
"element",
"[",
"0",
"]",
"==",
"\"codebox\"",
":",
"codeboxes_tuples",
".",
"append",
"(",
"self",
".",
"get_codebox_db_tuple",
"(",
"element",
"[",
"1",
"]",
",",
"node_id",
")",
")",
"if",
"codeboxes_tuples",
":",
"has_codebox",
"=",
"1",
"db",
".",
"executemany",
"(",
"'INSERT INTO codebox VALUES(?,?,?,?,?,?,?,?,?,?)'",
",",
"codeboxes_tuples",
")",
"else",
":",
"has_codebox",
"=",
"0",
"if",
"tables_tuples",
":",
"has_table",
"=",
"1",
"db",
".",
"executemany",
"(",
"'INSERT INTO grid VALUES(?,?,?,?,?,?)'",
",",
"tables_tuples",
")",
"else",
":",
"has_table",
"=",
"0",
"if",
"images_tuples",
":",
"has_image",
"=",
"1",
"db",
".",
"executemany",
"(",
"'INSERT INTO image VALUES(?,?,?,?,?,?,?,?)'",
",",
"images_tuples",
")",
"else",
":",
"has_image",
"=",
"0",
"# retrieve xml text",
"txt",
"=",
"(",
"self",
".",
"dom",
".",
"toxml",
"(",
")",
")",
".",
"decode",
"(",
"cons",
".",
"STR_UTF8",
")",
"else",
":",
"# not richtext",
"has_codebox",
"=",
"0",
"has_table",
"=",
"0",
"has_image",
"=",
"0",
"txt",
"=",
"(",
"start_iter",
".",
"get_text",
"(",
"end_iter",
")",
")",
".",
"decode",
"(",
"cons",
".",
"STR_UTF8",
")",
"if",
"write_dict",
"[",
"'prop'",
"]",
"and",
"write_dict",
"[",
"'buff'",
"]",
":",
"if",
"write_dict",
"[",
"'upd'",
"]",
":",
"db",
".",
"execute",
"(",
"'DELETE FROM node WHERE node_id=?'",
",",
"(",
"node_id",
",",
")",
")",
"node_tuple",
"=",
"(",
"node_id",
",",
"name",
",",
"txt",
",",
"syntax",
",",
"tags",
",",
"is_ro",
",",
"is_richtxt",
",",
"has_codebox",
",",
"has_table",
",",
"has_image",
",",
"0",
",",
"ts_creation",
",",
"ts_lastsave",
")",
"# TODO remove the column 'level'",
"db",
".",
"execute",
"(",
"'INSERT INTO node VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)'",
",",
"node_tuple",
")",
"elif",
"write_dict",
"[",
"'buff'",
"]",
":",
"db",
".",
"execute",
"(",
"'UPDATE node SET txt=?, syntax=?, is_richtxt=?, has_codebox=?, has_table=?, has_image=?, ts_lastsave=? WHERE node_id=?'",
",",
"(",
"txt",
",",
"syntax",
",",
"is_richtxt",
",",
"has_codebox",
",",
"has_table",
",",
"has_image",
",",
"ts_lastsave",
",",
"node_id",
")",
")",
"elif",
"write_dict",
"[",
"'prop'",
"]",
":",
"db",
".",
"execute",
"(",
"'UPDATE node SET name=?, syntax=?, tags=?, is_ro=?, is_richtxt=? WHERE node_id=?'",
",",
"(",
"name",
",",
"syntax",
",",
"tags",
",",
"is_ro",
",",
"is_richtxt",
",",
"node_id",
")",
")",
"if",
"write_dict",
"[",
"'hier'",
"]",
":",
"if",
"write_dict",
"[",
"'upd'",
"]",
":",
"db",
".",
"execute",
"(",
"'DELETE FROM children WHERE node_id=?'",
",",
"(",
"node_id",
",",
")",
")",
"db",
".",
"execute",
"(",
"'INSERT INTO children VALUES(?,?,?)'",
",",
"(",
"node_id",
",",
"node_father_id",
",",
"sequence",
")",
")",
"if",
"not",
"write_dict",
"[",
"'child'",
"]",
":",
"return",
"# let's take care about the children",
"child_tree_iter",
"=",
"self",
".",
"dad",
".",
"treestore",
".",
"iter_children",
"(",
"tree_iter",
")",
"child_sequence",
"=",
"0",
"while",
"child_tree_iter",
"!=",
"None",
":",
"child_sequence",
"+=",
"1",
"self",
".",
"write_db_node",
"(",
"db",
",",
"child_tree_iter",
",",
"child_sequence",
",",
"node_id",
",",
"write_dict",
",",
"exporting",
")",
"child_tree_iter",
"=",
"self",
".",
"dad",
".",
"treestore",
".",
"iter_next",
"(",
"child_tree_iter",
")"
] |
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/ctdb.py#L268-L384
|
||
wlanjie/AndroidFFmpeg
|
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
|
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sched.py
|
python
|
scheduler.enter
|
(self, delay, priority, action, argument)
|
return self.enterabs(time, priority, action, argument)
|
A variant that specifies the time as a relative time.
This is actually the more commonly used interface.
|
A variant that specifies the time as a relative time.
|
[
"A",
"variant",
"that",
"specifies",
"the",
"time",
"as",
"a",
"relative",
"time",
"."
] |
def enter(self, delay, priority, action, argument):
"""A variant that specifies the time as a relative time.
This is actually the more commonly used interface.
"""
time = self.timefunc() + delay
return self.enterabs(time, priority, action, argument)
|
[
"def",
"enter",
"(",
"self",
",",
"delay",
",",
"priority",
",",
"action",
",",
"argument",
")",
":",
"time",
"=",
"self",
".",
"timefunc",
"(",
")",
"+",
"delay",
"return",
"self",
".",
"enterabs",
"(",
"time",
",",
"priority",
",",
"action",
",",
"argument",
")"
] |
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sched.py#L57-L64
|
|
rsocket/rsocket-cpp
|
45ed594ebd6701f40795c31ec922d784ec7fc921
|
build/fbcode_builder/utils.py
|
python
|
run_command
|
(*cmd, **kwargs)
|
The stdout of most fbcode_builder utilities is meant to be parsed.
|
The stdout of most fbcode_builder utilities is meant to be parsed.
|
[
"The",
"stdout",
"of",
"most",
"fbcode_builder",
"utilities",
"is",
"meant",
"to",
"be",
"parsed",
"."
] |
def run_command(*cmd, **kwargs):
"The stdout of most fbcode_builder utilities is meant to be parsed."
logging.debug("Running: {0} with {1}".format(cmd, kwargs))
kwargs["stdout"] = sys.stderr
subprocess.check_call(cmd, **kwargs)
|
[
"def",
"run_command",
"(",
"*",
"cmd",
",",
"*",
"*",
"kwargs",
")",
":",
"logging",
".",
"debug",
"(",
"\"Running: {0} with {1}\"",
".",
"format",
"(",
"cmd",
",",
"kwargs",
")",
")",
"kwargs",
"[",
"\"stdout\"",
"]",
"=",
"sys",
".",
"stderr",
"subprocess",
".",
"check_call",
"(",
"cmd",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/rsocket/rsocket-cpp/blob/45ed594ebd6701f40795c31ec922d784ec7fc921/build/fbcode_builder/utils.py#L25-L29
|
||
CRYTEK/CRYENGINE
|
232227c59a220cbbd311576f0fbeba7bb53b2a8c
|
Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/utils.py
|
python
|
default_user_agent
|
(name="python-requests")
|
return " ".join(['%s/%s' % (name, __version__),
'%s/%s' % (_implementation, _implementation_version),
'%s/%s' % (p_system, p_release)])
|
Return a string representing the default user agent.
|
Return a string representing the default user agent.
|
[
"Return",
"a",
"string",
"representing",
"the",
"default",
"user",
"agent",
"."
] |
def default_user_agent(name="python-requests"):
"""Return a string representing the default user agent."""
_implementation = platform.python_implementation()
if _implementation == 'CPython':
_implementation_version = platform.python_version()
elif _implementation == 'PyPy':
_implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major,
sys.pypy_version_info.minor,
sys.pypy_version_info.micro)
if sys.pypy_version_info.releaselevel != 'final':
_implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel])
elif _implementation == 'Jython':
_implementation_version = platform.python_version() # Complete Guess
elif _implementation == 'IronPython':
_implementation_version = platform.python_version() # Complete Guess
else:
_implementation_version = 'Unknown'
try:
p_system = platform.system()
p_release = platform.release()
except IOError:
p_system = 'Unknown'
p_release = 'Unknown'
return " ".join(['%s/%s' % (name, __version__),
'%s/%s' % (_implementation, _implementation_version),
'%s/%s' % (p_system, p_release)])
|
[
"def",
"default_user_agent",
"(",
"name",
"=",
"\"python-requests\"",
")",
":",
"_implementation",
"=",
"platform",
".",
"python_implementation",
"(",
")",
"if",
"_implementation",
"==",
"'CPython'",
":",
"_implementation_version",
"=",
"platform",
".",
"python_version",
"(",
")",
"elif",
"_implementation",
"==",
"'PyPy'",
":",
"_implementation_version",
"=",
"'%s.%s.%s'",
"%",
"(",
"sys",
".",
"pypy_version_info",
".",
"major",
",",
"sys",
".",
"pypy_version_info",
".",
"minor",
",",
"sys",
".",
"pypy_version_info",
".",
"micro",
")",
"if",
"sys",
".",
"pypy_version_info",
".",
"releaselevel",
"!=",
"'final'",
":",
"_implementation_version",
"=",
"''",
".",
"join",
"(",
"[",
"_implementation_version",
",",
"sys",
".",
"pypy_version_info",
".",
"releaselevel",
"]",
")",
"elif",
"_implementation",
"==",
"'Jython'",
":",
"_implementation_version",
"=",
"platform",
".",
"python_version",
"(",
")",
"# Complete Guess",
"elif",
"_implementation",
"==",
"'IronPython'",
":",
"_implementation_version",
"=",
"platform",
".",
"python_version",
"(",
")",
"# Complete Guess",
"else",
":",
"_implementation_version",
"=",
"'Unknown'",
"try",
":",
"p_system",
"=",
"platform",
".",
"system",
"(",
")",
"p_release",
"=",
"platform",
".",
"release",
"(",
")",
"except",
"IOError",
":",
"p_system",
"=",
"'Unknown'",
"p_release",
"=",
"'Unknown'",
"return",
"\" \"",
".",
"join",
"(",
"[",
"'%s/%s'",
"%",
"(",
"name",
",",
"__version__",
")",
",",
"'%s/%s'",
"%",
"(",
"_implementation",
",",
"_implementation_version",
")",
",",
"'%s/%s'",
"%",
"(",
"p_system",
",",
"p_release",
")",
"]",
")"
] |
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/utils.py#L540-L568
|
|
ros/geometry
|
63c3c7b404b8f390061bdadc5bc675e7ae5808be
|
tf/src/tf/transformations.py
|
python
|
random_rotation_matrix
|
(rand=None)
|
return quaternion_matrix(random_quaternion(rand))
|
Return uniform random rotation matrix.
rnd: array like
Three independent random variables that are uniformly distributed
between 0 and 1 for each returned quaternion.
>>> R = random_rotation_matrix()
>>> numpy.allclose(numpy.dot(R.T, R), numpy.identity(4))
True
|
Return uniform random rotation matrix.
|
[
"Return",
"uniform",
"random",
"rotation",
"matrix",
"."
] |
def random_rotation_matrix(rand=None):
"""Return uniform random rotation matrix.
rnd: array like
Three independent random variables that are uniformly distributed
between 0 and 1 for each returned quaternion.
>>> R = random_rotation_matrix()
>>> numpy.allclose(numpy.dot(R.T, R), numpy.identity(4))
True
"""
return quaternion_matrix(random_quaternion(rand))
|
[
"def",
"random_rotation_matrix",
"(",
"rand",
"=",
"None",
")",
":",
"return",
"quaternion_matrix",
"(",
"random_quaternion",
"(",
"rand",
")",
")"
] |
https://github.com/ros/geometry/blob/63c3c7b404b8f390061bdadc5bc675e7ae5808be/tf/src/tf/transformations.py#L1341-L1353
|
|
google/clif
|
cab24d6a105609a65c95a36a1712ae3c20c7b5df
|
clif/python/pytd2proto.py
|
python
|
_TypeEntry.get_last_cpp_type
|
(self)
|
return self._cpp_names[-1] if self._cpp_names else ''
|
Get the last registered C++ type, or an empty string if none.
|
Get the last registered C++ type, or an empty string if none.
|
[
"Get",
"the",
"last",
"registered",
"C",
"++",
"type",
"or",
"an",
"empty",
"string",
"if",
"none",
"."
] |
def get_last_cpp_type(self):
"""Get the last registered C++ type, or an empty string if none."""
return self._cpp_names[-1] if self._cpp_names else ''
|
[
"def",
"get_last_cpp_type",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cpp_names",
"[",
"-",
"1",
"]",
"if",
"self",
".",
"_cpp_names",
"else",
"''"
] |
https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/python/pytd2proto.py#L1215-L1217
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/command/check.py
|
python
|
check.check_restructuredtext
|
(self)
|
Checks if the long string fields are reST-compliant.
|
Checks if the long string fields are reST-compliant.
|
[
"Checks",
"if",
"the",
"long",
"string",
"fields",
"are",
"reST",
"-",
"compliant",
"."
] |
def check_restructuredtext(self):
"""Checks if the long string fields are reST-compliant."""
data = self.distribution.get_long_description()
for warning in self._check_rst_data(data):
line = warning[-1].get('line')
if line is None:
warning = warning[1]
else:
warning = '%s (line %s)' % (warning[1], line)
self.warn(warning)
|
[
"def",
"check_restructuredtext",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"distribution",
".",
"get_long_description",
"(",
")",
"for",
"warning",
"in",
"self",
".",
"_check_rst_data",
"(",
"data",
")",
":",
"line",
"=",
"warning",
"[",
"-",
"1",
"]",
".",
"get",
"(",
"'line'",
")",
"if",
"line",
"is",
"None",
":",
"warning",
"=",
"warning",
"[",
"1",
"]",
"else",
":",
"warning",
"=",
"'%s (line %s)'",
"%",
"(",
"warning",
"[",
"1",
"]",
",",
"line",
")",
"self",
".",
"warn",
"(",
"warning",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/command/check.py#L110-L119
|
||
timi-liuliang/echo
|
40a5a24d430eee4118314459ab7e03afcb3b8719
|
thirdparty/protobuf/python/google/protobuf/message.py
|
python
|
Message.ParseFromString
|
(self, serialized)
|
Parse serialized protocol buffer data into this message.
Like MergeFromString(), except we clear the object first and
do not return the value that MergeFromString returns.
|
Parse serialized protocol buffer data into this message.
|
[
"Parse",
"serialized",
"protocol",
"buffer",
"data",
"into",
"this",
"message",
"."
] |
def ParseFromString(self, serialized):
"""Parse serialized protocol buffer data into this message.
Like MergeFromString(), except we clear the object first and
do not return the value that MergeFromString returns.
"""
self.Clear()
self.MergeFromString(serialized)
|
[
"def",
"ParseFromString",
"(",
"self",
",",
"serialized",
")",
":",
"self",
".",
"Clear",
"(",
")",
"self",
".",
"MergeFromString",
"(",
"serialized",
")"
] |
https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/message.py#L179-L186
|
||
ValveSoftware/source-sdk-2013
|
0d8dceea4310fde5706b3ce1c70609d72a38efdf
|
mp/src/thirdparty/protobuf-2.3.0/python/mox.py
|
python
|
MockMethod._PopNextMethod
|
(self)
|
Pop the next method from our call queue.
|
Pop the next method from our call queue.
|
[
"Pop",
"the",
"next",
"method",
"from",
"our",
"call",
"queue",
"."
] |
def _PopNextMethod(self):
"""Pop the next method from our call queue."""
try:
return self._call_queue.popleft()
except IndexError:
raise UnexpectedMethodCallError(self, None)
|
[
"def",
"_PopNextMethod",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_call_queue",
".",
"popleft",
"(",
")",
"except",
"IndexError",
":",
"raise",
"UnexpectedMethodCallError",
"(",
"self",
",",
"None",
")"
] |
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/mp/src/thirdparty/protobuf-2.3.0/python/mox.py#L581-L586
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python/src/Tools/bgen/bgen/bgenVariable.py
|
python
|
Variable.mkvalueArgs
|
(self)
|
return self.type.mkvalueArgs(self.name)
|
Call the type's mkvalueArgs method.
|
Call the type's mkvalueArgs method.
|
[
"Call",
"the",
"type",
"s",
"mkvalueArgs",
"method",
"."
] |
def mkvalueArgs(self):
"""Call the type's mkvalueArgs method."""
return self.type.mkvalueArgs(self.name)
|
[
"def",
"mkvalueArgs",
"(",
"self",
")",
":",
"return",
"self",
".",
"type",
".",
"mkvalueArgs",
"(",
"self",
".",
"name",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Tools/bgen/bgen/bgenVariable.py#L103-L105
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/_controls.py
|
python
|
Slider.GetValue
|
(*args, **kwargs)
|
return _controls_.Slider_GetValue(*args, **kwargs)
|
GetValue(self) -> int
|
GetValue(self) -> int
|
[
"GetValue",
"(",
"self",
")",
"-",
">",
"int"
] |
def GetValue(*args, **kwargs):
"""GetValue(self) -> int"""
return _controls_.Slider_GetValue(*args, **kwargs)
|
[
"def",
"GetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"Slider_GetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L2840-L2842
|
|
benoitsteiner/tensorflow-opencl
|
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
|
tensorflow/contrib/learn/python/learn/monitors.py
|
python
|
BaseMonitor.epoch_begin
|
(self, epoch)
|
Begin epoch.
Args:
epoch: `int`, the epoch number.
Raises:
ValueError: if we've already begun an epoch, or `epoch` < 0.
|
Begin epoch.
|
[
"Begin",
"epoch",
"."
] |
def epoch_begin(self, epoch):
"""Begin epoch.
Args:
epoch: `int`, the epoch number.
Raises:
ValueError: if we've already begun an epoch, or `epoch` < 0.
"""
if self._current_epoch is not None:
raise ValueError("epoch_begin called twice without epoch_end.")
if epoch < 0:
raise ValueError("Invalid epoch %s." % epoch)
self._current_epoch = epoch
|
[
"def",
"epoch_begin",
"(",
"self",
",",
"epoch",
")",
":",
"if",
"self",
".",
"_current_epoch",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"epoch_begin called twice without epoch_end.\"",
")",
"if",
"epoch",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Invalid epoch %s.\"",
"%",
"epoch",
")",
"self",
".",
"_current_epoch",
"=",
"epoch"
] |
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/monitors.py#L129-L142
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
|
python
|
NumberCounter.init
|
(self, value)
|
Set an initial value.
|
Set an initial value.
|
[
"Set",
"an",
"initial",
"value",
"."
] |
def init(self, value):
"Set an initial value."
self.value = value
|
[
"def",
"init",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"value",
"=",
"value"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L3199-L3201
|
||
pichenettes/eurorack
|
11cc3a80f2c6d67ee024091c711dfce59a58cb59
|
tools/midi/midifile.py
|
python
|
PackInteger
|
(value, size=4)
|
return struct.pack('>%s' % {1: 'B', 2: 'H', 4: 'L'}[size], value)
|
Packs a python integer into a n-byte big endian byte sequence.
|
Packs a python integer into a n-byte big endian byte sequence.
|
[
"Packs",
"a",
"python",
"integer",
"into",
"a",
"n",
"-",
"byte",
"big",
"endian",
"byte",
"sequence",
"."
] |
def PackInteger(value, size=4):
"""Packs a python integer into a n-byte big endian byte sequence."""
return struct.pack('>%s' % {1: 'B', 2: 'H', 4: 'L'}[size], value)
|
[
"def",
"PackInteger",
"(",
"value",
",",
"size",
"=",
"4",
")",
":",
"return",
"struct",
".",
"pack",
"(",
"'>%s'",
"%",
"{",
"1",
":",
"'B'",
",",
"2",
":",
"'H'",
",",
"4",
":",
"'L'",
"}",
"[",
"size",
"]",
",",
"value",
")"
] |
https://github.com/pichenettes/eurorack/blob/11cc3a80f2c6d67ee024091c711dfce59a58cb59/tools/midi/midifile.py#L30-L32
|
|
microsoft/checkedc-clang
|
a173fefde5d7877b7750e7ce96dd08cf18baebf2
|
clang/bindings/python/clang/cindex.py
|
python
|
TokenKind.from_value
|
(value)
|
return result
|
Obtain a registered TokenKind instance from its value.
|
Obtain a registered TokenKind instance from its value.
|
[
"Obtain",
"a",
"registered",
"TokenKind",
"instance",
"from",
"its",
"value",
"."
] |
def from_value(value):
"""Obtain a registered TokenKind instance from its value."""
result = TokenKind._value_map.get(value, None)
if result is None:
raise ValueError('Unknown TokenKind: %d' % value)
return result
|
[
"def",
"from_value",
"(",
"value",
")",
":",
"result",
"=",
"TokenKind",
".",
"_value_map",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"result",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unknown TokenKind: %d'",
"%",
"value",
")",
"return",
"result"
] |
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/bindings/python/clang/cindex.py#L587-L594
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py
|
python
|
Session.put
|
(self, url, data=None, **kwargs)
|
return self.request('PUT', url, data=data, **kwargs)
|
r"""Sends a PUT request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
|
r"""Sends a PUT request. Returns :class:`Response` object.
|
[
"r",
"Sends",
"a",
"PUT",
"request",
".",
"Returns",
":",
"class",
":",
"Response",
"object",
"."
] |
def put(self, url, data=None, **kwargs):
r"""Sends a PUT request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('PUT', url, data=data, **kwargs)
|
[
"def",
"put",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"'PUT'",
",",
"url",
",",
"data",
"=",
"data",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py#L580-L590
|
|
krishauser/Klampt
|
972cc83ea5befac3f653c1ba20f80155768ad519
|
Python/python2_version/klampt/model/cartesian_trajectory.py
|
python
|
cartesian_interpolate_bisect
|
(robot,a,b,constraints,
startConfig='robot',endConfig=None,
delta=1e-2,
solver=None,
feasibilityTest=None,
growthTol=10)
|
return res
|
Resolves a continuous robot trajectory that interpolates between two
Cartesian points for a single link of a robot. The output path is only
a kinematic resolution. It has time domain [0,1].
Args:
robot (RobotModel or SubRobotModel): the robot.
a, b (list of floats): endpoints of the Cartesian trajectory. Assumed
derived from `config.getConfig(constraints)`
constraints: one or more link indices, link names, or ``IKObjective``'s
giving the manner in which the Cartesian space is defined.
Interpreted as follows:
* int or str: the specified link's entire pose is constrained
* IKObjective: the links, constraint types, local positions, and
local axes are used as constraints. The world space elements
are considered temporary and will change to match the Cartesian
trajectory.
* list of int, list of str, or list of IKObjective: concatenates
the specified constraints together.
startConfig (optional): either 'robot' (configuration taken from the
robot), a configuration, or `None` (any configuration)
endConfig (optional): same type as `startConfig`.
delta (float, optional): the maximum configuration space distance
between points on the output path
solver (IKSolver, optional): if provided, an IKSolver configured with
the desired parameters for IK constraint solving.
feasibilityTest (function, optional): a function f(q) that returns
`False` when a configuration q is infeasible.
growthTol (float, optional): the end path can be at most `growthTol`
times the length of the length between the start and goal
configurations.
Returns:
RobotTrajectory or None: a configuration space path that interpolates
the Cartesian path, or None if no solution can be found.
|
Resolves a continuous robot trajectory that interpolates between two
Cartesian points for a single link of a robot. The output path is only
a kinematic resolution. It has time domain [0,1].
|
[
"Resolves",
"a",
"continuous",
"robot",
"trajectory",
"that",
"interpolates",
"between",
"two",
"Cartesian",
"points",
"for",
"a",
"single",
"link",
"of",
"a",
"robot",
".",
"The",
"output",
"path",
"is",
"only",
"a",
"kinematic",
"resolution",
".",
"It",
"has",
"time",
"domain",
"[",
"0",
"1",
"]",
"."
] |
def cartesian_interpolate_bisect(robot,a,b,constraints,
startConfig='robot',endConfig=None,
delta=1e-2,
solver=None,
feasibilityTest=None,
growthTol=10):
"""Resolves a continuous robot trajectory that interpolates between two
Cartesian points for a single link of a robot. The output path is only
a kinematic resolution. It has time domain [0,1].
Args:
robot (RobotModel or SubRobotModel): the robot.
a, b (list of floats): endpoints of the Cartesian trajectory. Assumed
derived from `config.getConfig(constraints)`
constraints: one or more link indices, link names, or ``IKObjective``'s
giving the manner in which the Cartesian space is defined.
Interpreted as follows:
* int or str: the specified link's entire pose is constrained
* IKObjective: the links, constraint types, local positions, and
local axes are used as constraints. The world space elements
are considered temporary and will change to match the Cartesian
trajectory.
* list of int, list of str, or list of IKObjective: concatenates
the specified constraints together.
startConfig (optional): either 'robot' (configuration taken from the
robot), a configuration, or `None` (any configuration)
endConfig (optional): same type as `startConfig`.
delta (float, optional): the maximum configuration space distance
between points on the output path
solver (IKSolver, optional): if provided, an IKSolver configured with
the desired parameters for IK constraint solving.
feasibilityTest (function, optional): a function f(q) that returns
`False` when a configuration q is infeasible.
growthTol (float, optional): the end path can be at most `growthTol`
times the length of the length between the start and goal
configurations.
Returns:
RobotTrajectory or None: a configuration space path that interpolates
the Cartesian path, or None if no solution can be found.
"""
assert delta > 0,"Spatial resolution must be positive"
assert growthTol > 1,"Growth parameter must be in range [1,infty]"
constraints,startConfig,endConfig,solver = _make_canonical(robot,constraints,startConfig,endConfig,solver)
assert startConfig is not None,"Unable to cartesian bisection interpolate without a start configuration"
if endConfig is None:
#find an end point
robot.setConfig(startConfig)
if not solve_cartesian(b,constraints,solver):
print "cartesian_interpolate_bisect(): Error, could not find an end configuration to match final Cartesian coordinates"
return None
endConfig = robot.getConfig()
robot.setConfig(startConfig)
set_cartesian_constraints(a,constraints,solver)
if not solver.isSolved():
if not solver.solve():
print "Error, initial configuration cannot be solved to match initial Cartesian coordinates, residual",solver.getResidual()
return None
print "Warning, initial configuration does not match initial Cartesian coordinates, solving"
startConfig = robot.getConfig()
robot.setConfig(endConfig)
set_cartesian_constraints(b,constraints,solver)
if not solver.isSolved():
if not solver.solve():
print "cartesian_interpolate_bisect(): Error, final configuration cannot be solved to match final Cartesian coordinates, residual",solver.getResidual()
return None
print "Warning, final configuration does not match final Cartesian coordinates, solving"
endConfig = robot.getConfig()
if feasibilityTest is not None and not feasibilityTest(startConfig):
print "cartesian_interpolate_bisect(): Error: initial configuration is infeasible"
return None
if feasibilityTest is not None and not feasibilityTest(endConfig):
print "cartesian_interpolate_bisect(): Error: final configuration is infeasible"
return None
root = _BisectNode(a,b,0,1,startConfig,endConfig)
root.d = robot.distance(startConfig,endConfig)
dtotal = root.d
dorig = root.d
scalecond = 0.5*(2 - 2.0/growthTol)
q = deque()
q.append(root)
while len(q) > 0:
n = q.pop()
d0 = n.d
if d0 <= delta:
continue
m = config.interpolate(constraints,n.a,n.b,0.5)
qm = robot.interpolate(n.qa,n.qb,0.5)
um = (n.ua+n.ub)*0.5
robot.setConfig(qm)
solver.setBiasConfig(qm)
if not solve_cartesian(m,constraints,solver):
solver.setBiasConfig([])
print "cartesian_interpolate_bisect(): Failed to solve at point",um
return None
solver.setBiasConfig([])
d1 = robot.distance(n.qa,qm)
d2 = robot.distance(qm,n.qb)
#print d1,d2
#print qm,"->",robot.getConfig()
qm = robot.getConfig()
d1 = robot.distance(n.qa,qm)
d2 = robot.distance(qm,n.qb)
dtotal += d1+d2 - d0
if dtotal > dorig*growthTol or (d1 > scalecond*d0) or (d2 > scalecond*d0):
print "cartesian_interpolate_bisect(): Excessive growth condition reached",d0,d1,d2,"at point",um
print n.qa
print qm
print n.qb
return None
if feasibilityTest and not feasibilityTest(qm):
print "cartesian_interpolate_bisect(): Violation of feasibility test","at point",um
return None
n.left = _BisectNode(n.a,m,n.ua,um,n.qa,qm)
n.left.d = d1
n.right = _BisectNode(m,n.b,um,n.ub,qm,n.qb)
n.right.d = d2
if d1 < d2:
q.append(n.left)
q.append(n.right)
else:
q.append(n.right)
q.append(n.left)
#done resolving, now output path from left to right of tree
res = RobotTrajectory(robot,[0],[startConfig])
q = [root]
while len(q) > 0:
n = q.pop(-1)
if n.left is None:
#leaf node
res.times.append(n.ub)
res.milestones.append(n.qb)
else:
q.append(n.right)
q.append(n.left)
return res
|
[
"def",
"cartesian_interpolate_bisect",
"(",
"robot",
",",
"a",
",",
"b",
",",
"constraints",
",",
"startConfig",
"=",
"'robot'",
",",
"endConfig",
"=",
"None",
",",
"delta",
"=",
"1e-2",
",",
"solver",
"=",
"None",
",",
"feasibilityTest",
"=",
"None",
",",
"growthTol",
"=",
"10",
")",
":",
"assert",
"delta",
">",
"0",
",",
"\"Spatial resolution must be positive\"",
"assert",
"growthTol",
">",
"1",
",",
"\"Growth parameter must be in range [1,infty]\"",
"constraints",
",",
"startConfig",
",",
"endConfig",
",",
"solver",
"=",
"_make_canonical",
"(",
"robot",
",",
"constraints",
",",
"startConfig",
",",
"endConfig",
",",
"solver",
")",
"assert",
"startConfig",
"is",
"not",
"None",
",",
"\"Unable to cartesian bisection interpolate without a start configuration\"",
"if",
"endConfig",
"is",
"None",
":",
"#find an end point",
"robot",
".",
"setConfig",
"(",
"startConfig",
")",
"if",
"not",
"solve_cartesian",
"(",
"b",
",",
"constraints",
",",
"solver",
")",
":",
"print",
"\"cartesian_interpolate_bisect(): Error, could not find an end configuration to match final Cartesian coordinates\"",
"return",
"None",
"endConfig",
"=",
"robot",
".",
"getConfig",
"(",
")",
"robot",
".",
"setConfig",
"(",
"startConfig",
")",
"set_cartesian_constraints",
"(",
"a",
",",
"constraints",
",",
"solver",
")",
"if",
"not",
"solver",
".",
"isSolved",
"(",
")",
":",
"if",
"not",
"solver",
".",
"solve",
"(",
")",
":",
"print",
"\"Error, initial configuration cannot be solved to match initial Cartesian coordinates, residual\"",
",",
"solver",
".",
"getResidual",
"(",
")",
"return",
"None",
"print",
"\"Warning, initial configuration does not match initial Cartesian coordinates, solving\"",
"startConfig",
"=",
"robot",
".",
"getConfig",
"(",
")",
"robot",
".",
"setConfig",
"(",
"endConfig",
")",
"set_cartesian_constraints",
"(",
"b",
",",
"constraints",
",",
"solver",
")",
"if",
"not",
"solver",
".",
"isSolved",
"(",
")",
":",
"if",
"not",
"solver",
".",
"solve",
"(",
")",
":",
"print",
"\"cartesian_interpolate_bisect(): Error, final configuration cannot be solved to match final Cartesian coordinates, residual\"",
",",
"solver",
".",
"getResidual",
"(",
")",
"return",
"None",
"print",
"\"Warning, final configuration does not match final Cartesian coordinates, solving\"",
"endConfig",
"=",
"robot",
".",
"getConfig",
"(",
")",
"if",
"feasibilityTest",
"is",
"not",
"None",
"and",
"not",
"feasibilityTest",
"(",
"startConfig",
")",
":",
"print",
"\"cartesian_interpolate_bisect(): Error: initial configuration is infeasible\"",
"return",
"None",
"if",
"feasibilityTest",
"is",
"not",
"None",
"and",
"not",
"feasibilityTest",
"(",
"endConfig",
")",
":",
"print",
"\"cartesian_interpolate_bisect(): Error: final configuration is infeasible\"",
"return",
"None",
"root",
"=",
"_BisectNode",
"(",
"a",
",",
"b",
",",
"0",
",",
"1",
",",
"startConfig",
",",
"endConfig",
")",
"root",
".",
"d",
"=",
"robot",
".",
"distance",
"(",
"startConfig",
",",
"endConfig",
")",
"dtotal",
"=",
"root",
".",
"d",
"dorig",
"=",
"root",
".",
"d",
"scalecond",
"=",
"0.5",
"*",
"(",
"2",
"-",
"2.0",
"/",
"growthTol",
")",
"q",
"=",
"deque",
"(",
")",
"q",
".",
"append",
"(",
"root",
")",
"while",
"len",
"(",
"q",
")",
">",
"0",
":",
"n",
"=",
"q",
".",
"pop",
"(",
")",
"d0",
"=",
"n",
".",
"d",
"if",
"d0",
"<=",
"delta",
":",
"continue",
"m",
"=",
"config",
".",
"interpolate",
"(",
"constraints",
",",
"n",
".",
"a",
",",
"n",
".",
"b",
",",
"0.5",
")",
"qm",
"=",
"robot",
".",
"interpolate",
"(",
"n",
".",
"qa",
",",
"n",
".",
"qb",
",",
"0.5",
")",
"um",
"=",
"(",
"n",
".",
"ua",
"+",
"n",
".",
"ub",
")",
"*",
"0.5",
"robot",
".",
"setConfig",
"(",
"qm",
")",
"solver",
".",
"setBiasConfig",
"(",
"qm",
")",
"if",
"not",
"solve_cartesian",
"(",
"m",
",",
"constraints",
",",
"solver",
")",
":",
"solver",
".",
"setBiasConfig",
"(",
"[",
"]",
")",
"print",
"\"cartesian_interpolate_bisect(): Failed to solve at point\"",
",",
"um",
"return",
"None",
"solver",
".",
"setBiasConfig",
"(",
"[",
"]",
")",
"d1",
"=",
"robot",
".",
"distance",
"(",
"n",
".",
"qa",
",",
"qm",
")",
"d2",
"=",
"robot",
".",
"distance",
"(",
"qm",
",",
"n",
".",
"qb",
")",
"#print d1,d2",
"#print qm,\"->\",robot.getConfig()",
"qm",
"=",
"robot",
".",
"getConfig",
"(",
")",
"d1",
"=",
"robot",
".",
"distance",
"(",
"n",
".",
"qa",
",",
"qm",
")",
"d2",
"=",
"robot",
".",
"distance",
"(",
"qm",
",",
"n",
".",
"qb",
")",
"dtotal",
"+=",
"d1",
"+",
"d2",
"-",
"d0",
"if",
"dtotal",
">",
"dorig",
"*",
"growthTol",
"or",
"(",
"d1",
">",
"scalecond",
"*",
"d0",
")",
"or",
"(",
"d2",
">",
"scalecond",
"*",
"d0",
")",
":",
"print",
"\"cartesian_interpolate_bisect(): Excessive growth condition reached\"",
",",
"d0",
",",
"d1",
",",
"d2",
",",
"\"at point\"",
",",
"um",
"print",
"n",
".",
"qa",
"print",
"qm",
"print",
"n",
".",
"qb",
"return",
"None",
"if",
"feasibilityTest",
"and",
"not",
"feasibilityTest",
"(",
"qm",
")",
":",
"print",
"\"cartesian_interpolate_bisect(): Violation of feasibility test\"",
",",
"\"at point\"",
",",
"um",
"return",
"None",
"n",
".",
"left",
"=",
"_BisectNode",
"(",
"n",
".",
"a",
",",
"m",
",",
"n",
".",
"ua",
",",
"um",
",",
"n",
".",
"qa",
",",
"qm",
")",
"n",
".",
"left",
".",
"d",
"=",
"d1",
"n",
".",
"right",
"=",
"_BisectNode",
"(",
"m",
",",
"n",
".",
"b",
",",
"um",
",",
"n",
".",
"ub",
",",
"qm",
",",
"n",
".",
"qb",
")",
"n",
".",
"right",
".",
"d",
"=",
"d2",
"if",
"d1",
"<",
"d2",
":",
"q",
".",
"append",
"(",
"n",
".",
"left",
")",
"q",
".",
"append",
"(",
"n",
".",
"right",
")",
"else",
":",
"q",
".",
"append",
"(",
"n",
".",
"right",
")",
"q",
".",
"append",
"(",
"n",
".",
"left",
")",
"#done resolving, now output path from left to right of tree",
"res",
"=",
"RobotTrajectory",
"(",
"robot",
",",
"[",
"0",
"]",
",",
"[",
"startConfig",
"]",
")",
"q",
"=",
"[",
"root",
"]",
"while",
"len",
"(",
"q",
")",
">",
"0",
":",
"n",
"=",
"q",
".",
"pop",
"(",
"-",
"1",
")",
"if",
"n",
".",
"left",
"is",
"None",
":",
"#leaf node",
"res",
".",
"times",
".",
"append",
"(",
"n",
".",
"ub",
")",
"res",
".",
"milestones",
".",
"append",
"(",
"n",
".",
"qb",
")",
"else",
":",
"q",
".",
"append",
"(",
"n",
".",
"right",
")",
"q",
".",
"append",
"(",
"n",
".",
"left",
")",
"return",
"res"
] |
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/cartesian_trajectory.py#L230-L369
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py
|
python
|
JIRA.find_transitionid_by_name
|
(self, issue, transition_name)
|
return id
|
Get a transitionid available on the specified issue to the current user.
Look at https://developer.atlassian.com/static/rest/jira/6.1.html#d2e1074 for json reference
:param issue: ID or key of the issue to get the transitions from
:param trans_name: iname of transition we are looking for
|
Get a transitionid available on the specified issue to the current user.
|
[
"Get",
"a",
"transitionid",
"available",
"on",
"the",
"specified",
"issue",
"to",
"the",
"current",
"user",
"."
] |
def find_transitionid_by_name(self, issue, transition_name):
"""Get a transitionid available on the specified issue to the current user.
Look at https://developer.atlassian.com/static/rest/jira/6.1.html#d2e1074 for json reference
:param issue: ID or key of the issue to get the transitions from
:param trans_name: iname of transition we are looking for
"""
transitions_json = self.transitions(issue)
id = None
for transition in transitions_json:
if transition["name"].lower() == transition_name.lower():
id = transition["id"]
break
return id
|
[
"def",
"find_transitionid_by_name",
"(",
"self",
",",
"issue",
",",
"transition_name",
")",
":",
"transitions_json",
"=",
"self",
".",
"transitions",
"(",
"issue",
")",
"id",
"=",
"None",
"for",
"transition",
"in",
"transitions_json",
":",
"if",
"transition",
"[",
"\"name\"",
"]",
".",
"lower",
"(",
")",
"==",
"transition_name",
".",
"lower",
"(",
")",
":",
"id",
"=",
"transition",
"[",
"\"id\"",
"]",
"break",
"return",
"id"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py#L1496-L1511
|
|
google/tink
|
59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14
|
python/setup.py
|
python
|
_get_bazel_command
|
()
|
Finds the bazel command.
|
Finds the bazel command.
|
[
"Finds",
"the",
"bazel",
"command",
"."
] |
def _get_bazel_command():
"""Finds the bazel command."""
if spawn.find_executable('bazelisk'):
return 'bazelisk'
elif spawn.find_executable('bazel'):
return 'bazel'
raise FileNotFoundError('Could not find bazel executable. Please install '
'bazel to compile the Tink Python package.')
|
[
"def",
"_get_bazel_command",
"(",
")",
":",
"if",
"spawn",
".",
"find_executable",
"(",
"'bazelisk'",
")",
":",
"return",
"'bazelisk'",
"elif",
"spawn",
".",
"find_executable",
"(",
"'bazel'",
")",
":",
"return",
"'bazel'",
"raise",
"FileNotFoundError",
"(",
"'Could not find bazel executable. Please install '",
"'bazel to compile the Tink Python package.'",
")"
] |
https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/setup.py#L52-L59
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/imaplib.py
|
python
|
IMAP4.search
|
(self, charset, *criteria)
|
return self._untagged_response(typ, dat, name)
|
Search mailbox for matching messages.
(typ, [data]) = <instance>.search(charset, criterion, ...)
'data' is space separated list of matching message numbers.
If UTF8 is enabled, charset MUST be None.
|
Search mailbox for matching messages.
|
[
"Search",
"mailbox",
"for",
"matching",
"messages",
"."
] |
def search(self, charset, *criteria):
"""Search mailbox for matching messages.
(typ, [data]) = <instance>.search(charset, criterion, ...)
'data' is space separated list of matching message numbers.
If UTF8 is enabled, charset MUST be None.
"""
name = 'SEARCH'
if charset:
if self.utf8_enabled:
raise IMAP4.error("Non-None charset not valid in UTF8 mode")
typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria)
else:
typ, dat = self._simple_command(name, *criteria)
return self._untagged_response(typ, dat, name)
|
[
"def",
"search",
"(",
"self",
",",
"charset",
",",
"*",
"criteria",
")",
":",
"name",
"=",
"'SEARCH'",
"if",
"charset",
":",
"if",
"self",
".",
"utf8_enabled",
":",
"raise",
"IMAP4",
".",
"error",
"(",
"\"Non-None charset not valid in UTF8 mode\"",
")",
"typ",
",",
"dat",
"=",
"self",
".",
"_simple_command",
"(",
"name",
",",
"'CHARSET'",
",",
"charset",
",",
"*",
"criteria",
")",
"else",
":",
"typ",
",",
"dat",
"=",
"self",
".",
"_simple_command",
"(",
"name",
",",
"*",
"criteria",
")",
"return",
"self",
".",
"_untagged_response",
"(",
"typ",
",",
"dat",
",",
"name",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/imaplib.py#L709-L724
|
|
kamyu104/LeetCode-Solutions
|
77605708a927ea3b85aee5a479db733938c7c211
|
Python/design-excel-sum-formula.py
|
python
|
Excel.set
|
(self, r, c, v)
|
:type r: int
:type c: str
:type v: int
:rtype: void
|
:type r: int
:type c: str
:type v: int
:rtype: void
|
[
":",
"type",
"r",
":",
"int",
":",
"type",
"c",
":",
"str",
":",
"type",
"v",
":",
"int",
":",
"rtype",
":",
"void"
] |
def set(self, r, c, v):
"""
:type r: int
:type c: str
:type v: int
:rtype: void
"""
self.__reset_dependency(r, c)
self.__update_others(r, c, v)
|
[
"def",
"set",
"(",
"self",
",",
"r",
",",
"c",
",",
"v",
")",
":",
"self",
".",
"__reset_dependency",
"(",
"r",
",",
"c",
")",
"self",
".",
"__update_others",
"(",
"r",
",",
"c",
",",
"v",
")"
] |
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/design-excel-sum-formula.py#L22-L30
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.