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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/ordered_dict.py | python | OrderedDict.__repr__ | (self, _repr_running={}) | od.__repr__() <==> repr(od) | od.__repr__() <==> repr(od) | [
"od",
".",
"__repr__",
"()",
"<",
"==",
">",
"repr",
"(",
"od",
")"
] | def __repr__(self, _repr_running={}):
'od.__repr__() <==> repr(od)'
call_key = id(self), _get_ident()
if call_key in _repr_running:
return '...'
_repr_running[call_key] = 1
try:
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
finally:
del _repr_running[call_key] | [
"def",
"__repr__",
"(",
"self",
",",
"_repr_running",
"=",
"{",
"}",
")",
":",
"call_key",
"=",
"id",
"(",
"self",
")",
",",
"_get_ident",
"(",
")",
"if",
"call_key",
"in",
"_repr_running",
":",
"return",
"'...'",
"_repr_running",
"[",
"call_key",
"]",
... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/ordered_dict.py#L226-L237 | ||
vtraag/louvain-igraph | 124ea1be49ee74eec2eaca8006599d7fc5560db6 | src/louvain/VertexPartition.py | python | MutableVertexPartition.weight_from_comm | (self, v, comm) | return _c_louvain._MutableVertexPartition_weight_from_comm(self._partition, v, comm) | The total number of edges (or sum of weights) to node ``v`` from
community ``comm``.
See Also
--------
:func:`~VertexPartition.MutableVertexPartition.weight_to_comm` | The total number of edges (or sum of weights) to node ``v`` from
community ``comm``. | [
"The",
"total",
"number",
"of",
"edges",
"(",
"or",
"sum",
"of",
"weights",
")",
"to",
"node",
"v",
"from",
"community",
"comm",
"."
] | def weight_from_comm(self, v, comm):
""" The total number of edges (or sum of weights) to node ``v`` from
community ``comm``.
See Also
--------
:func:`~VertexPartition.MutableVertexPartition.weight_to_comm`
"""
return _c_louvain._MutableVertexPartition_weight_from_comm(self._partition, v, comm) | [
"def",
"weight_from_comm",
"(",
"self",
",",
"v",
",",
"comm",
")",
":",
"return",
"_c_louvain",
".",
"_MutableVertexPartition_weight_from_comm",
"(",
"self",
".",
"_partition",
",",
"v",
",",
"comm",
")"
] | https://github.com/vtraag/louvain-igraph/blob/124ea1be49ee74eec2eaca8006599d7fc5560db6/src/louvain/VertexPartition.py#L374-L382 | |
Cisco-Talos/moflow | ed71dfb0540d9e0d7a4c72f0881b58958d573728 | BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/service.py | python | RpcChannel.CallMethod | (self, method_descriptor, rpc_controller,
request, response_class, done) | Calls the method identified by the descriptor.
Call the given method of the remote service. The signature of this
procedure looks the same as Service.CallMethod(), but the requirements
are less strict in one important way: the request object doesn't have to
be of any specific class as long as its descriptor is method.input_type. | Calls the method identified by the descriptor. | [
"Calls",
"the",
"method",
"identified",
"by",
"the",
"descriptor",
"."
] | def CallMethod(self, method_descriptor, rpc_controller,
request, response_class, done):
"""Calls the method identified by the descriptor.
Call the given method of the remote service. The signature of this
procedure looks the same as Service.CallMethod(), but the requirements
are less strict in one important way: the request object doesn't have to
be of any specific class as long as its descriptor is method.input_type.
"""
raise NotImplementedError | [
"def",
"CallMethod",
"(",
"self",
",",
"method_descriptor",
",",
"rpc_controller",
",",
"request",
",",
"response_class",
",",
"done",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/service.py#L217-L226 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/incubate/fleet/collective/__init__.py | python | CollectiveOptimizer._transpile | (self, startup_program, main_program) | Transpile the programs to distributed programs. And add the variables. | Transpile the programs to distributed programs. And add the variables. | [
"Transpile",
"the",
"programs",
"to",
"distributed",
"programs",
".",
"And",
"add",
"the",
"variables",
"."
] | def _transpile(self, startup_program, main_program):
"""
Transpile the programs to distributed programs. And add the variables.
"""
worker_endpoints = fleet.worker_endpoints()
trainer_id = fleet.worker_index()
current_endpoint = fleet.worker_endpoints()[trainer_id]
worker_endpoints_env = ','.join(worker_endpoints)
trainers_num = fleet.worker_num()
if self.print_config:
print("worker_endpoints:{} trainers_num:{} current_endpoint:{} \
trainer_id:{}".format(worker_endpoints, trainers_num,
current_endpoint, trainer_id))
# call transpiler
config = dist_transpiler.DistributeTranspilerConfig()
config.mode = self._strategy.mode
config.collective_mode = self._strategy.collective_mode
config.nccl_comm_num = self._strategy.nccl_comm_num
config.use_hierarchical_allreduce = self._strategy.use_hierarchical_allreduce
config.hierarchical_allreduce_inter_nranks = self._strategy.hierarchical_allreduce_inter_nranks
t = dist_transpiler.DistributeTranspiler(config=config)
t.transpile(
trainer_id=trainer_id,
trainers=worker_endpoints_env,
startup_program=startup_program,
program=main_program,
current_endpoint=current_endpoint) | [
"def",
"_transpile",
"(",
"self",
",",
"startup_program",
",",
"main_program",
")",
":",
"worker_endpoints",
"=",
"fleet",
".",
"worker_endpoints",
"(",
")",
"trainer_id",
"=",
"fleet",
".",
"worker_index",
"(",
")",
"current_endpoint",
"=",
"fleet",
".",
"wor... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/collective/__init__.py#L324-L354 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/key.py | python | Key.get_contents_to_filename | (self, filename, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None,
res_download_handler=None,
response_headers=None) | Retrieve an object from S3 using the name of the Key object as the
key in S3. Store contents of the object to a file named by 'filename'.
See get_contents_to_file method for details about the
parameters.
:type filename: string
:param filename: The filename of where to put the file contents
:type headers: dict
:param headers: Any additional headers to send in the request
:type cb: function
:param cb: a callback function that will be called to report
progress on the upload. The callback should accept two
integer parameters, the first representing the number of
bytes that have been successfully transmitted to S3 and
the second representing the size of the to be transmitted
object.
:type num_cb: int
:param num_cb: (optional) If a callback is specified with the
cb parameter this parameter determines the granularity of
the callback by defining the maximum number of times the
callback will be called during the file transfer.
:type torrent: bool
:param torrent: If True, returns the contents of a torrent file
as a string.
:type res_upload_handler: ResumableDownloadHandler
:param res_download_handler: If provided, this handler will
perform the download.
:type response_headers: dict
:param response_headers: A dictionary containing HTTP
headers/values that will override any headers associated
with the stored object in the response. See
http://goo.gl/EWOPb for details.
:type version_id: str
:param version_id: The ID of a particular version of the object.
If this parameter is not supplied but the Key object has
a ``version_id`` attribute, that value will be used when
retrieving the object. You can set the Key object's
``version_id`` attribute to None to always grab the latest
version from a version-enabled bucket. | Retrieve an object from S3 using the name of the Key object as the
key in S3. Store contents of the object to a file named by 'filename'.
See get_contents_to_file method for details about the
parameters. | [
"Retrieve",
"an",
"object",
"from",
"S3",
"using",
"the",
"name",
"of",
"the",
"Key",
"object",
"as",
"the",
"key",
"in",
"S3",
".",
"Store",
"contents",
"of",
"the",
"object",
"to",
"a",
"file",
"named",
"by",
"filename",
".",
"See",
"get_contents_to_fi... | def get_contents_to_filename(self, filename, headers=None,
cb=None, num_cb=10,
torrent=False,
version_id=None,
res_download_handler=None,
response_headers=None):
"""
Retrieve an object from S3 using the name of the Key object as the
key in S3. Store contents of the object to a file named by 'filename'.
See get_contents_to_file method for details about the
parameters.
:type filename: string
:param filename: The filename of where to put the file contents
:type headers: dict
:param headers: Any additional headers to send in the request
:type cb: function
:param cb: a callback function that will be called to report
progress on the upload. The callback should accept two
integer parameters, the first representing the number of
bytes that have been successfully transmitted to S3 and
the second representing the size of the to be transmitted
object.
:type num_cb: int
:param num_cb: (optional) If a callback is specified with the
cb parameter this parameter determines the granularity of
the callback by defining the maximum number of times the
callback will be called during the file transfer.
:type torrent: bool
:param torrent: If True, returns the contents of a torrent file
as a string.
:type res_upload_handler: ResumableDownloadHandler
:param res_download_handler: If provided, this handler will
perform the download.
:type response_headers: dict
:param response_headers: A dictionary containing HTTP
headers/values that will override any headers associated
with the stored object in the response. See
http://goo.gl/EWOPb for details.
:type version_id: str
:param version_id: The ID of a particular version of the object.
If this parameter is not supplied but the Key object has
a ``version_id`` attribute, that value will be used when
retrieving the object. You can set the Key object's
``version_id`` attribute to None to always grab the latest
version from a version-enabled bucket.
"""
try:
with open(filename, 'wb') as fp:
self.get_contents_to_file(fp, headers, cb, num_cb,
torrent=torrent,
version_id=version_id,
res_download_handler=res_download_handler,
response_headers=response_headers)
except Exception:
os.remove(filename)
raise
# if last_modified date was sent from s3, try to set file's timestamp
if self.last_modified is not None:
try:
modified_tuple = email.utils.parsedate_tz(self.last_modified)
modified_stamp = int(email.utils.mktime_tz(modified_tuple))
os.utime(fp.name, (modified_stamp, modified_stamp))
except Exception:
pass | [
"def",
"get_contents_to_filename",
"(",
"self",
",",
"filename",
",",
"headers",
"=",
"None",
",",
"cb",
"=",
"None",
",",
"num_cb",
"=",
"10",
",",
"torrent",
"=",
"False",
",",
"version_id",
"=",
"None",
",",
"res_download_handler",
"=",
"None",
",",
"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/key.py#L1652-L1723 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol/numpy/random.py | python | shuffle | (x) | Modify a sequence in-place by shuffling its contents.
This function only shuffles the array along the first axis of a
multi-dimensional array. The order of sub-arrays is changed but
their contents remain the same.
Parameters
----------
x: _Symbol
The array or list to be shuffled.
Returns
-------
None
Examples
--------
>>> arr = np.arange(10)
>>> np.random.shuffle(arr)
>>> arr
array([5., 1., 0., 6., 7., 3., 9., 8., 4., 2.]) # random
Multi-dimensional arrays are only shuffled along the first axis:
>>> arr = np.arange(9).reshape((3, 3))
>>> np.random.shuffle(arr)
>>> arr
array([[6., 7., 8.], # random
[3., 4., 5.],
[0., 1., 2.]]) | Modify a sequence in-place by shuffling its contents. | [
"Modify",
"a",
"sequence",
"in",
"-",
"place",
"by",
"shuffling",
"its",
"contents",
"."
] | def shuffle(x):
"""
Modify a sequence in-place by shuffling its contents.
This function only shuffles the array along the first axis of a
multi-dimensional array. The order of sub-arrays is changed but
their contents remain the same.
Parameters
----------
x: _Symbol
The array or list to be shuffled.
Returns
-------
None
Examples
--------
>>> arr = np.arange(10)
>>> np.random.shuffle(arr)
>>> arr
array([5., 1., 0., 6., 7., 3., 9., 8., 4., 2.]) # random
Multi-dimensional arrays are only shuffled along the first axis:
>>> arr = np.arange(9).reshape((3, 3))
>>> np.random.shuffle(arr)
>>> arr
array([[6., 7., 8.], # random
[3., 4., 5.],
[0., 1., 2.]])
"""
_npi.shuffle(x, out=x) | [
"def",
"shuffle",
"(",
"x",
")",
":",
"_npi",
".",
"shuffle",
"(",
"x",
",",
"out",
"=",
"x",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/random.py#L995-L1028 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/framework/python/ops/arg_scope.py | python | add_arg_scope | (func) | return func_with_args | Decorates a function with args so it can be used within an arg_scope.
Args:
func: function to decorate.
Returns:
A tuple with the decorated function func_with_args(). | Decorates a function with args so it can be used within an arg_scope. | [
"Decorates",
"a",
"function",
"with",
"args",
"so",
"it",
"can",
"be",
"used",
"within",
"an",
"arg_scope",
"."
] | def add_arg_scope(func):
"""Decorates a function with args so it can be used within an arg_scope.
Args:
func: function to decorate.
Returns:
A tuple with the decorated function func_with_args().
"""
@functools.wraps(func)
def func_with_args(*args, **kwargs):
current_scope = _current_arg_scope()
current_args = kwargs
key_func = _key_op(func)
if key_func in current_scope:
current_args = current_scope[key_func].copy()
current_args.update(kwargs)
return func(*args, **current_args)
_add_op(func)
setattr(func_with_args, '_key_op', _key_op(func))
return func_with_args | [
"def",
"add_arg_scope",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"func_with_args",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"current_scope",
"=",
"_current_arg_scope",
"(",
")",
"current_args",
"=",
"kwa... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/framework/python/ops/arg_scope.py#L154-L174 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/plan/robotcspace.py | python | ClosedLoopRobotCSpace.closedLoop | (self,config=None,tol=None) | return max(abs(ei) for ei in e) <= tol | Returns true if the closed loop constraint has been met at config,
or if config==None, the robot's current configuration. | Returns true if the closed loop constraint has been met at config,
or if config==None, the robot's current configuration. | [
"Returns",
"true",
"if",
"the",
"closed",
"loop",
"constraint",
"has",
"been",
"met",
"at",
"config",
"or",
"if",
"config",
"==",
"None",
"the",
"robot",
"s",
"current",
"configuration",
"."
] | def closedLoop(self,config=None,tol=None):
"""Returns true if the closed loop constraint has been met at config,
or if config==None, the robot's current configuration."""
if config is not None: self.robot.setConfig(config)
e = self.solver.getResidual()
if tol==None: tol = self.tol
return max(abs(ei) for ei in e) <= tol | [
"def",
"closedLoop",
"(",
"self",
",",
"config",
"=",
"None",
",",
"tol",
"=",
"None",
")",
":",
"if",
"config",
"is",
"not",
"None",
":",
"self",
".",
"robot",
".",
"setConfig",
"(",
"config",
")",
"e",
"=",
"self",
".",
"solver",
".",
"getResidua... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/plan/robotcspace.py#L238-L244 | |
yujinrobot/yujin_ocs | 17337e5a2d0a0f3711c55e272e656eb59174d657 | yocs_ar_pair_approach/src/yocs_ar_pair_approach/node.py | python | Node.spin | (self) | Parse the set of /remocons/<name>_<uuid> connections. | Parse the set of /remocons/<name>_<uuid> connections. | [
"Parse",
"the",
"set",
"of",
"/",
"remocons",
"/",
"<name",
">",
"_<uuid",
">",
"connections",
"."
] | def spin(self):
'''
Parse the set of /remocons/<name>_<uuid> connections.
'''
rospy.spin()
if self._thread is not None:
self._thread.join() | [
"def",
"spin",
"(",
"self",
")",
":",
"rospy",
".",
"spin",
"(",
")",
"if",
"self",
".",
"_thread",
"is",
"not",
"None",
":",
"self",
".",
"_thread",
".",
"join",
"(",
")"
] | https://github.com/yujinrobot/yujin_ocs/blob/17337e5a2d0a0f3711c55e272e656eb59174d657/yocs_ar_pair_approach/src/yocs_ar_pair_approach/node.py#L259-L267 | ||
microsoft/clang | 86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5 | utils/check_cfc/check_cfc.py | python | remove_dir_from_path | (path_var, directory) | return os.pathsep.join(pathlist) | Remove the specified directory from path_var, a string representing
PATH | Remove the specified directory from path_var, a string representing
PATH | [
"Remove",
"the",
"specified",
"directory",
"from",
"path_var",
"a",
"string",
"representing",
"PATH"
] | def remove_dir_from_path(path_var, directory):
"""Remove the specified directory from path_var, a string representing
PATH"""
pathlist = path_var.split(os.pathsep)
norm_directory = os.path.normpath(os.path.normcase(directory))
pathlist = filter(lambda x: os.path.normpath(
os.path.normcase(x)) != norm_directory, pathlist)
return os.pathsep.join(pathlist) | [
"def",
"remove_dir_from_path",
"(",
"path_var",
",",
"directory",
")",
":",
"pathlist",
"=",
"path_var",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"norm_directory",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"normcase",
"("... | https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/utils/check_cfc/check_cfc.py#L93-L100 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/ticker.py | python | Ticker.Stop | (self) | Stop moving the text | Stop moving the text | [
"Stop",
"moving",
"the",
"text"
] | def Stop(self):
"""Stop moving the text"""
self.timer.Stop() | [
"def",
"Stop",
"(",
"self",
")",
":",
"self",
".",
"timer",
".",
"Stop",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ticker.py#L63-L65 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/web_perf/metrics/webrtc_rendering_stats.py | python | WebMediaPlayerMsRenderingStats._MapEventsToStream | (self, events) | return stream_to_events | Build a dictionary of events indexed by stream.
The events of interest have a 'Serial' argument which represents the
stream ID. The 'Serial' argument identifies the local or remote nature of
the stream with a least significant bit of 0 or 1 as well as the hash
value of the video track's URL. So stream::=hash(0|1} . The method will
then list the events of the same stream in a frame_distribution on stream
id. Practically speaking remote streams have an odd stream id and local
streams have a even stream id.
Args:
events: Telemetry WebMediaPlayerMs events.
Returns:
A dict of stream IDs mapped to events on that stream. | Build a dictionary of events indexed by stream. | [
"Build",
"a",
"dictionary",
"of",
"events",
"indexed",
"by",
"stream",
"."
] | def _MapEventsToStream(self, events):
"""Build a dictionary of events indexed by stream.
The events of interest have a 'Serial' argument which represents the
stream ID. The 'Serial' argument identifies the local or remote nature of
the stream with a least significant bit of 0 or 1 as well as the hash
value of the video track's URL. So stream::=hash(0|1} . The method will
then list the events of the same stream in a frame_distribution on stream
id. Practically speaking remote streams have an odd stream id and local
streams have a even stream id.
Args:
events: Telemetry WebMediaPlayerMs events.
Returns:
A dict of stream IDs mapped to events on that stream.
"""
stream_to_events = {}
for event in events:
if not self._IsEventValid(event):
# This is not a render event, skip it.
continue
stream = event.args[SERIAL]
events_for_stream = stream_to_events.setdefault(stream, [])
events_for_stream.append(event)
return stream_to_events | [
"def",
"_MapEventsToStream",
"(",
"self",
",",
"events",
")",
":",
"stream_to_events",
"=",
"{",
"}",
"for",
"event",
"in",
"events",
":",
"if",
"not",
"self",
".",
"_IsEventValid",
"(",
"event",
")",
":",
"# This is not a render event, skip it.",
"continue",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/web_perf/metrics/webrtc_rendering_stats.py#L68-L93 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/httplib2/python3/httplib2/__init__.py | python | _parse_www_authenticate | (headers, headername='www-authenticate') | return retval | Returns a dictionary of dictionaries, one dict
per auth_scheme. | Returns a dictionary of dictionaries, one dict
per auth_scheme. | [
"Returns",
"a",
"dictionary",
"of",
"dictionaries",
"one",
"dict",
"per",
"auth_scheme",
"."
] | def _parse_www_authenticate(headers, headername='www-authenticate'):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headername in headers:
try:
authenticate = headers[headername].strip()
www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
while authenticate:
# Break off the scheme at the beginning of the line
if headername == 'authentication-info':
(auth_scheme, the_rest) = ('digest', authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(r'\1', value) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval | [
"def",
"_parse_www_authenticate",
"(",
"headers",
",",
"headername",
"=",
"'www-authenticate'",
")",
":",
"retval",
"=",
"{",
"}",
"if",
"headername",
"in",
"headers",
":",
"try",
":",
"authenticate",
"=",
"headers",
"[",
"headername",
"]",
".",
"strip",
"("... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/python3/httplib2/__init__.py#L220-L247 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/site_compare/scrapers/chrome/chrome011010.py | python | Scrape | (urls, outdir, size, pos, timeout=20, **kwargs) | return chromebase.Scrape(urls, outdir, size, pos, timeout, kwargs) | Invoke a browser, send it to a series of URLs, and save its output.
Args:
urls: list of URLs to scrape
outdir: directory to place output
size: size of browser window to use
pos: position of browser window
timeout: amount of time to wait for page to load
kwargs: miscellaneous keyword args
Returns:
None if succeeded, else an error code | Invoke a browser, send it to a series of URLs, and save its output. | [
"Invoke",
"a",
"browser",
"send",
"it",
"to",
"a",
"series",
"of",
"URLs",
"and",
"save",
"its",
"output",
"."
] | def Scrape(urls, outdir, size, pos, timeout=20, **kwargs):
"""Invoke a browser, send it to a series of URLs, and save its output.
Args:
urls: list of URLs to scrape
outdir: directory to place output
size: size of browser window to use
pos: position of browser window
timeout: amount of time to wait for page to load
kwargs: miscellaneous keyword args
Returns:
None if succeeded, else an error code
"""
chromebase.GetChromeRenderPane = GetChromeRenderPane
return chromebase.Scrape(urls, outdir, size, pos, timeout, kwargs) | [
"def",
"Scrape",
"(",
"urls",
",",
"outdir",
",",
"size",
",",
"pos",
",",
"timeout",
"=",
"20",
",",
"*",
"*",
"kwargs",
")",
":",
"chromebase",
".",
"GetChromeRenderPane",
"=",
"GetChromeRenderPane",
"return",
"chromebase",
".",
"Scrape",
"(",
"urls",
... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/site_compare/scrapers/chrome/chrome011010.py#L19-L35 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/lib/type_check.py | python | mintypecode | (typechars,typeset='GDFgdf',default='d') | return l[0][1] | Return the character for the minimum-size type to which given types can
be safely cast.
The returned type character must represent the smallest size dtype such
that an array of the returned type can handle the data from an array of
all types in `typechars` (or if `typechars` is an array, then its
dtype.char).
Parameters
----------
typechars : list of str or array_like
If a list of strings, each string should represent a dtype.
If array_like, the character representation of the array dtype is used.
typeset : str or list of str, optional
The set of characters that the returned character is chosen from.
The default set is 'GDFgdf'.
default : str, optional
The default character, this is returned if none of the characters in
`typechars` matches a character in `typeset`.
Returns
-------
typechar : str
The character representing the minimum-size type that was found.
See Also
--------
dtype, sctype2char, maximum_sctype
Examples
--------
>>> np.mintypecode(['d', 'f', 'S'])
'd'
>>> x = np.array([1.1, 2-3.j])
>>> np.mintypecode(x)
'D'
>>> np.mintypecode('abceh', default='G')
'G' | Return the character for the minimum-size type to which given types can
be safely cast. | [
"Return",
"the",
"character",
"for",
"the",
"minimum",
"-",
"size",
"type",
"to",
"which",
"given",
"types",
"can",
"be",
"safely",
"cast",
"."
] | def mintypecode(typechars,typeset='GDFgdf',default='d'):
"""
Return the character for the minimum-size type to which given types can
be safely cast.
The returned type character must represent the smallest size dtype such
that an array of the returned type can handle the data from an array of
all types in `typechars` (or if `typechars` is an array, then its
dtype.char).
Parameters
----------
typechars : list of str or array_like
If a list of strings, each string should represent a dtype.
If array_like, the character representation of the array dtype is used.
typeset : str or list of str, optional
The set of characters that the returned character is chosen from.
The default set is 'GDFgdf'.
default : str, optional
The default character, this is returned if none of the characters in
`typechars` matches a character in `typeset`.
Returns
-------
typechar : str
The character representing the minimum-size type that was found.
See Also
--------
dtype, sctype2char, maximum_sctype
Examples
--------
>>> np.mintypecode(['d', 'f', 'S'])
'd'
>>> x = np.array([1.1, 2-3.j])
>>> np.mintypecode(x)
'D'
>>> np.mintypecode('abceh', default='G')
'G'
"""
typecodes = [(type(t) is type('') and t) or asarray(t).dtype.char\
for t in typechars]
intersection = [t for t in typecodes if t in typeset]
if not intersection:
return default
if 'F' in intersection and 'd' in intersection:
return 'D'
l = []
for t in intersection:
i = _typecodes_by_elsize.index(t)
l.append((i,t))
l.sort()
return l[0][1] | [
"def",
"mintypecode",
"(",
"typechars",
",",
"typeset",
"=",
"'GDFgdf'",
",",
"default",
"=",
"'d'",
")",
":",
"typecodes",
"=",
"[",
"(",
"type",
"(",
"t",
")",
"is",
"type",
"(",
"''",
")",
"and",
"t",
")",
"or",
"asarray",
"(",
"t",
")",
".",
... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/type_check.py#L16-L71 | |
yuxng/PoseCNN | 9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04 | lib/gt_synthesize_layer/minibatch.py | python | _get_label_blob | (roidb, intrinsic_matrix, data_out, num_classes, db_inds_syn, im_scales, extents, \
is_syn, db_inds_adapt, is_adapt, blob_height, blob_width) | return depth_blob, label_blob, meta_data_blob, vertex_target_blob, vertex_weight_blob, pose_blob, gt_boxes | build the label blob | build the label blob | [
"build",
"the",
"label",
"blob"
] | def _get_label_blob(roidb, intrinsic_matrix, data_out, num_classes, db_inds_syn, im_scales, extents, \
is_syn, db_inds_adapt, is_adapt, blob_height, blob_width):
""" build the label blob """
num_images = len(roidb)
processed_depth = []
processed_label = []
processed_meta_data = []
if cfg.TRAIN.VERTEX_REG_2D or cfg.TRAIN.VERTEX_REG_3D:
vertex_target_blob = np.zeros((num_images, blob_height, blob_width, 3 * num_classes), dtype=np.float32)
vertex_weight_blob = np.zeros((num_images, blob_height, blob_width, 3 * num_classes), dtype=np.float32)
pose_blob = np.zeros((0, 13), dtype=np.float32)
else:
vertex_target_blob = []
vertex_weight_blob = []
pose_blob = []
if not cfg.TRAIN.SEGMENTATION:
assert len(im_scales) == 1, "Single batch only"
assert len(roidb) == 1, "Single batch only"
if not cfg.TRAIN.SEGMENTATION:
assert len(im_scales) == 1, "Single batch only"
assert len(roidb) == 1, "Single batch only"
# gt boxes: (x1, y1, x2, y2, cls)
gt_boxes = np.zeros((0, 5), dtype=np.float32)
pose_blob = np.zeros((0, 13), dtype=np.float32)
else:
gt_boxes = []
for i in xrange(num_images):
im_scale = im_scales[i]
if is_adapt:
filename = cfg.TRAIN.ADAPT_ROOT + '{:06d}-depth.png'.format(db_inds_adapt[i])
im_depth = pad_im(cv2.imread(filename, cv2.IMREAD_UNCHANGED), 16)
meta_data = dict({'intrinsic_matrix': intrinsic_matrix, 'factor_depth': 1000.0})
else:
if is_syn:
if cfg.TRAIN.SYN_ONLINE:
meta_data = data_out[i]['meta_data']
meta_data['cls_indexes'] = meta_data['cls_indexes'].flatten()
im_depth = pad_im(data_out[i]['depth'], 16)
im = pad_im(data_out[i]['label'], 16)
else:
filename = cfg.TRAIN.SYNROOT + '{:06d}-meta.mat'.format(db_inds_syn[i])
meta_data = scipy.io.loadmat(filename)
meta_data['cls_indexes'] = meta_data['cls_indexes'].flatten()
filename = cfg.TRAIN.SYNROOT + '{:06d}-depth.png'.format(db_inds_syn[i])
im_depth = pad_im(cv2.imread(filename, cv2.IMREAD_UNCHANGED), 16)
# read label image
filename = cfg.TRAIN.SYNROOT + '{:06d}-label.png'.format(db_inds_syn[i])
im = pad_im(cv2.imread(filename, cv2.IMREAD_UNCHANGED), 16)
else:
meta_data = scipy.io.loadmat(roidb[i]['meta_data'])
meta_data['cls_indexes'] = meta_data['cls_indexes'].flatten()
if os.path.exists(roidb[i]['depth']):
im_depth = pad_im(cv2.imread(roidb[i]['depth'], cv2.IMREAD_UNCHANGED), 16)
else:
im_depth = np.zeros((blob_height, blob_width), dtype=np.float32)
# read label image
im = pad_im(cv2.imread(roidb[i]['label'], cv2.IMREAD_UNCHANGED), 16)
height = im_depth.shape[0]
width = im_depth.shape[1]
# mask the label image according to depth
if cfg.INPUT == 'DEPTH':
I = np.where(im_depth == 0)
if len(im.shape) == 2:
im[I[0], I[1]] = 0
else:
im[I[0], I[1], :] = 0
if roidb[i]['flipped']:
if len(im.shape) == 2:
im = im[:, ::-1]
else:
im = im[:, ::-1, :]
im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_NEAREST)
# process annotation if training for two classes
cls_indexes_old = []
if num_classes == 2 and roidb[i]['cls_index'] > 0:
I = np.where(im == roidb[i]['cls_index'])
im[:, :] = 0
im[I[0], I[1]] = 1
ind = np.where(meta_data['cls_indexes'] == roidb[i]['cls_index'])[0]
cls_indexes_old = ind
meta_data['cls_indexes'] = np.ones((len(ind),), dtype=np.float32)
if len(meta_data['poses'].shape) == 2:
meta_data['poses'] = np.reshape(meta_data['poses'], (3, 4, 1))
meta_data['poses'] = meta_data['poses'][:,:,ind]
meta_data['center'] = meta_data['center'][ind,:]
meta_data['box'] = meta_data['box'][ind,:]
# im_cls, im_labels = _process_label_image(im, roidb[i]['class_colors'], roidb[i]['class_weights'])
im_labels = im.copy()
processed_label.append(im_labels.astype(np.int32))
# bounding boxes
if not cfg.TRAIN.SEGMENTATION:
boxes = meta_data['box'].copy()
if roidb[i]['flipped']:
oldx1 = boxes[:, 0].copy()
oldx2 = boxes[:, 2].copy()
boxes[:, 0] = width - oldx2 - 1
boxes[:, 2] = width - oldx1 - 1
gt_box = np.concatenate((boxes * im_scales[0], meta_data['cls_indexes'][:, np.newaxis]), axis=1)
gt_boxes = np.concatenate((gt_boxes, gt_box), axis=0)
poses = meta_data['poses']
if len(poses.shape) == 2:
poses = np.reshape(poses, (3, 4, 1))
if roidb[i]['flipped']:
poses = _flip_poses(poses, meta_data['intrinsic_matrix'], width)
num = poses.shape[2]
qt = np.zeros((num, 13), dtype=np.float32)
for j in xrange(num):
R = poses[:, :3, j]
T = poses[:, 3, j]
qt[j, 0] = i
qt[j, 1] = meta_data['cls_indexes'][j]
qt[j, 2:6] = 0 # fill box later
qt[j, 6:10] = mat2quat(R)
qt[j, 10:] = T
pose_blob = np.concatenate((pose_blob, qt), axis=0)
# vertex regression targets and weights
if cfg.TRAIN.VERTEX_REG_2D or cfg.TRAIN.VERTEX_REG_3D:
poses = meta_data['poses']
if len(poses.shape) == 2:
poses = np.reshape(poses, (3, 4, 1))
if roidb[i]['flipped']:
poses = _flip_poses(poses, meta_data['intrinsic_matrix'], width)
if cfg.TRAIN.VERTEX_REG_3D:
vertmap = meta_data['vertmap']
if roidb[i]['flipped']:
vertmap = vertmap[:, ::-1, :]
vertmap = cv2.resize(vertmap, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR)
else:
vertmap = []
center = meta_data['center']
if roidb[i]['flipped']:
center[:, 0] = width - center[:, 0]
# check if mutiple same instances
cls_indexes = meta_data['cls_indexes']
if len(np.unique(cls_indexes)) < len(cls_indexes):
is_multi_instances = 1
# read mask image
mask = pad_im(cv2.imread(roidb[i]['mask'], cv2.IMREAD_UNCHANGED), 16)
else:
is_multi_instances = 0
mask = []
vertex_target_blob[i,:,:,:], vertex_weight_blob[i,:,:,:] = \
_generate_vertex_targets(im, meta_data['cls_indexes'], im_scale * center, poses, num_classes, vertmap, extents, \
mask, is_multi_instances, cls_indexes_old, \
vertex_target_blob[i,:,:,:], vertex_weight_blob[i,:,:,:])
num = poses.shape[2]
qt = np.zeros((num, 13), dtype=np.float32)
for j in xrange(num):
R = poses[:, :3, j]
T = poses[:, 3, j]
qt[j, 0] = i
qt[j, 1] = meta_data['cls_indexes'][j]
qt[j, 2:6] = 0 # fill box later
qt[j, 6:10] = mat2quat(R)
qt[j, 10:] = T
pose_blob = np.concatenate((pose_blob, qt), axis=0)
# voxelization
# points = voxelizer.backproject_camera(im_depth, meta_data)
# voxelizer.voxelized = False
# voxelizer.voxelize(points)
# RT_world = meta_data['rotation_translation_matrix']
# compute camera poses
# RT_live = meta_data['rotation_translation_matrix']
# pose_world2live = se3_mul(RT_live, se3_inverse(RT_world))
# pose_live2world = se3_inverse(pose_world2live)
# construct the meta data
"""
format of the meta_data
intrinsic matrix: meta_data[0 ~ 8]
inverse intrinsic matrix: meta_data[9 ~ 17]
pose_world2live: meta_data[18 ~ 29]
pose_live2world: meta_data[30 ~ 41]
voxel step size: meta_data[42, 43, 44]
voxel min value: meta_data[45, 46, 47]
"""
K = np.matrix(meta_data['intrinsic_matrix']) * im_scale
K[2, 2] = 1
Kinv = np.linalg.pinv(K)
mdata = np.zeros(48, dtype=np.float32)
mdata[0:9] = K.flatten()
mdata[9:18] = Kinv.flatten()
# mdata[18:30] = pose_world2live.flatten()
# mdata[30:42] = pose_live2world.flatten()
# mdata[42] = voxelizer.step_x
# mdata[43] = voxelizer.step_y
# mdata[44] = voxelizer.step_z
# mdata[45] = voxelizer.min_x
# mdata[46] = voxelizer.min_y
# mdata[47] = voxelizer.min_z
if cfg.FLIP_X:
mdata[0] = -1 * mdata[0]
mdata[9] = -1 * mdata[9]
mdata[11] = -1 * mdata[11]
processed_meta_data.append(mdata)
# depth
if roidb[i]['flipped']:
im_depth = im_depth[:, ::-1]
depth = im_depth.astype(np.float32, copy=True) / float(meta_data['factor_depth'])
depth = cv2.resize(depth, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR)
processed_depth.append(depth)
# construct the blobs
depth_blob = np.zeros((num_images, blob_height, blob_width, 1), dtype=np.float32)
meta_data_blob = np.zeros((num_images, 1, 1, 48), dtype=np.float32)
for i in xrange(num_images):
depth_blob[i,:,:,0] = processed_depth[i]
meta_data_blob[i,0,0,:] = processed_meta_data[i]
if is_adapt:
label_blob = -1 * np.ones((num_images, blob_height, blob_width), dtype=np.int32)
else:
label_blob = np.zeros((num_images, blob_height, blob_width), dtype=np.int32)
for i in xrange(num_images):
label_blob[i,:,:] = processed_label[i]
# filter bad boxes
if not cfg.TRAIN.SEGMENTATION:
gt_widths = gt_boxes[:, 2] - gt_boxes[:, 0] + 1.0
gt_heights = gt_boxes[:, 3] - gt_boxes[:, 1] + 1.0
ind = np.where((gt_widths > 0) & (gt_heights > 0))[0]
gt_boxes = gt_boxes[ind, :]
return depth_blob, label_blob, meta_data_blob, vertex_target_blob, vertex_weight_blob, pose_blob, gt_boxes | [
"def",
"_get_label_blob",
"(",
"roidb",
",",
"intrinsic_matrix",
",",
"data_out",
",",
"num_classes",
",",
"db_inds_syn",
",",
"im_scales",
",",
"extents",
",",
"is_syn",
",",
"db_inds_adapt",
",",
"is_adapt",
",",
"blob_height",
",",
"blob_width",
")",
":",
"... | https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/gt_synthesize_layer/minibatch.py#L270-L525 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/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/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/FS.py#L1796-L1800 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/SConf.py | python | SConfBuildTask.display_cached_string | (self, bi) | Logs the original builder messages, given the SConfBuildInfo instance
bi. | Logs the original builder messages, given the SConfBuildInfo instance
bi. | [
"Logs",
"the",
"original",
"builder",
"messages",
"given",
"the",
"SConfBuildInfo",
"instance",
"bi",
"."
] | def display_cached_string(self, bi):
"""
Logs the original builder messages, given the SConfBuildInfo instance
bi.
"""
if not isinstance(bi, SConfBuildInfo):
SCons.Warnings.warn(SConfWarning,
"The stored build information has an unexpected class: %s" % bi.__class__)
else:
self.display("The original builder output was:\n" +
(" |" + str(bi.string)).replace("\n", "\n |")) | [
"def",
"display_cached_string",
"(",
"self",
",",
"bi",
")",
":",
"if",
"not",
"isinstance",
"(",
"bi",
",",
"SConfBuildInfo",
")",
":",
"SCons",
".",
"Warnings",
".",
"warn",
"(",
"SConfWarning",
",",
"\"The stored build information has an unexpected class: %s\"",
... | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/SConf.py#L231-L241 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/psutil/psutil/_psosx.py | python | Process.get_ext_memory_info | (self) | return self._nt_ext_mem(rss, vms,
pfaults * _PAGESIZE,
pageins * _PAGESIZE) | Return a tuple with the process' RSS and VMS size. | Return a tuple with the process' RSS and VMS size. | [
"Return",
"a",
"tuple",
"with",
"the",
"process",
"RSS",
"and",
"VMS",
"size",
"."
] | def get_ext_memory_info(self):
"""Return a tuple with the process' RSS and VMS size."""
rss, vms, pfaults, pageins = _psutil_osx.get_process_memory_info(self.pid)
return self._nt_ext_mem(rss, vms,
pfaults * _PAGESIZE,
pageins * _PAGESIZE) | [
"def",
"get_ext_memory_info",
"(",
"self",
")",
":",
"rss",
",",
"vms",
",",
"pfaults",
",",
"pageins",
"=",
"_psutil_osx",
".",
"get_process_memory_info",
"(",
"self",
".",
"pid",
")",
"return",
"self",
".",
"_nt_ext_mem",
"(",
"rss",
",",
"vms",
",",
"... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/_psosx.py#L228-L233 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_model.py | python | GeneralFittingModel._create_multi_domain_function_using | (self, domain_functions: list) | Creates a new MultiDomainFunction using the provided functions corresponding to a domain each. | Creates a new MultiDomainFunction using the provided functions corresponding to a domain each. | [
"Creates",
"a",
"new",
"MultiDomainFunction",
"using",
"the",
"provided",
"functions",
"corresponding",
"to",
"a",
"domain",
"each",
"."
] | def _create_multi_domain_function_using(self, domain_functions: list) -> None:
"""Creates a new MultiDomainFunction using the provided functions corresponding to a domain each."""
self.fitting_context.simultaneous_fit_function = MultiDomainFunction()
for i, function in enumerate(domain_functions):
self.fitting_context.simultaneous_fit_function.add(function)
self.fitting_context.simultaneous_fit_function.setDomainIndex(i, i) | [
"def",
"_create_multi_domain_function_using",
"(",
"self",
",",
"domain_functions",
":",
"list",
")",
"->",
"None",
":",
"self",
".",
"fitting_context",
".",
"simultaneous_fit_function",
"=",
"MultiDomainFunction",
"(",
")",
"for",
"i",
",",
"function",
"in",
"enu... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_model.py#L177-L182 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/_pydecimal.py | python | Decimal.next_plus | (self, context=None) | return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
context) | Returns the smallest representable number larger than itself. | Returns the smallest representable number larger than itself. | [
"Returns",
"the",
"smallest",
"representable",
"number",
"larger",
"than",
"itself",
"."
] | def next_plus(self, context=None):
"""Returns the smallest representable number larger than itself."""
if context is None:
context = getcontext()
ans = self._check_nans(context=context)
if ans:
return ans
if self._isinfinity() == 1:
return _Infinity
if self._isinfinity() == -1:
return _dec_from_triple(1, '9'*context.prec, context.Etop())
context = context.copy()
context._set_rounding(ROUND_CEILING)
context._ignore_all_flags()
new_self = self._fix(context)
if new_self != self:
return new_self
return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
context) | [
"def",
"next_plus",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"getcontext",
"(",
")",
"ans",
"=",
"self",
".",
"_check_nans",
"(",
"context",
"=",
"context",
")",
"if",
"ans",
":",
"return... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pydecimal.py#L3521-L3542 | |
interpretml/interpret | 29466bffc04505fe4f836a83fcfebfd313ac8454 | python/interpret-core/interpret/api/templates.py | python | FeatureValueExplanation.visualize | (self, key=None) | Provides interactive visualizations.
Args:
key: Either a scalar or list
that indexes the internal object for sub-plotting.
If an overall visualization is requested, pass None.
Returns:
A Plotly figure. | Provides interactive visualizations. | [
"Provides",
"interactive",
"visualizations",
"."
] | def visualize(self, key=None):
""" Provides interactive visualizations.
Args:
key: Either a scalar or list
that indexes the internal object for sub-plotting.
If an overall visualization is requested, pass None.
Returns:
A Plotly figure.
"""
from ..visual.plot import (
plot_line,
plot_bar,
plot_horizontal_bar,
mli_plot_horizontal_bar,
is_multiclass_local_data_dict,
)
from ..visual.plot import (
get_sort_indexes,
get_explanation_index,
sort_take,
mli_sort_take,
plot_pairwise_heatmap,
)
data_dict = self.data(key)
if data_dict is None: # pragma: no cover
return None
# Handle overall graphs
if key is None:
data_dict = sort_take(
data_dict, sort_fn=lambda x: -abs(x), top_n=15, reverse_results=True
)
return plot_horizontal_bar(data_dict)
# Handle local instance graphs
if self.explanation_type == "local":
if isinstance(key, tuple) and len(key) == 2:
provider, key = key
# TODO: MLI should handle multiclass at a future date.
if "mli" == provider and "mli" in self.data(-1):
explanation_list = self.data(-1)["mli"]
explanation_index = get_explanation_index(
explanation_list, "local_feature_importance"
)
local_explanation = explanation_list[explanation_index]["value"]
scores = local_explanation["scores"]
perf = local_explanation["perf"]
sort_indexes = get_sort_indexes(
scores[key], sort_fn=lambda x: -abs(x), top_n=15
)
sorted_scores = mli_sort_take(
scores[key], sort_indexes, reverse_results=True
)
sorted_names = mli_sort_take(
self.feature_names, sort_indexes, reverse_results=True
)
instances = explanation_list[1]["value"]["dataset_x"]
return mli_plot_horizontal_bar(
sorted_scores,
sorted_names,
values=instances[key],
perf=perf[key],
)
else: # pragma: no cover
raise RuntimeError(
"Visual provider {} not supported".format(provider)
)
else:
is_multiclass = is_multiclass_local_data_dict(data_dict)
if is_multiclass:
# Sort by predicted class' abs feature values
pred_idx = data_dict["perf"]["predicted"]
sort_fn = lambda x: -abs(x[pred_idx])
else:
# Sort by abs feature values
sort_fn = lambda x: -abs(x)
data_dict = sort_take(
data_dict, sort_fn=sort_fn, top_n=15, reverse_results=True
)
return plot_horizontal_bar(data_dict, multiclass=is_multiclass)
# Handle global feature graphs
feature_type = self.feature_types[key]
title = self.feature_names[key]
if feature_type == "continuous":
return plot_line(data_dict, title=title)
elif feature_type == "categorical":
return plot_bar(data_dict, title=title)
elif feature_type == "interaction":
# TODO: Generalize this out.
xtitle = title.split(" x ")[0]
ytitle = title.split(" x ")[1]
return plot_pairwise_heatmap(
data_dict, title=title, xtitle=xtitle, ytitle=ytitle
)
# Handle everything else as invalid
raise Exception( # pragma: no cover
"Not supported configuration: {0}, {1}".format(
self.explanation_type, feature_type
)
) | [
"def",
"visualize",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"from",
".",
".",
"visual",
".",
"plot",
"import",
"(",
"plot_line",
",",
"plot_bar",
",",
"plot_horizontal_bar",
",",
"mli_plot_horizontal_bar",
",",
"is_multiclass_local_data_dict",
",",
")"... | https://github.com/interpretml/interpret/blob/29466bffc04505fe4f836a83fcfebfd313ac8454/python/interpret-core/interpret/api/templates.py#L64-L168 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/handlers.py | python | TimedRotatingFileHandler.computeRollover | (self, currentTime) | return result | Work out the rollover time based on the specified time. | Work out the rollover time based on the specified time. | [
"Work",
"out",
"the",
"rollover",
"time",
"based",
"on",
"the",
"specified",
"time",
"."
] | def computeRollover(self, currentTime):
"""
Work out the rollover time based on the specified time.
"""
result = currentTime + self.interval
# If we are rolling over at midnight or weekly, then the interval is already known.
# What we need to figure out is WHEN the next interval is. In other words,
# if you are rolling over at midnight, then your base interval is 1 day,
# but you want to start that one day clock at midnight, not now. So, we
# have to fudge the rolloverAt value in order to trigger the first rollover
# at the right time. After that, the regular interval will take care of
# the rest. Note that this code doesn't care about leap seconds. :)
if self.when == 'MIDNIGHT' or self.when.startswith('W'):
# This could be done with less code, but I wanted it to be clear
if self.utc:
t = time.gmtime(currentTime)
else:
t = time.localtime(currentTime)
currentHour = t[3]
currentMinute = t[4]
currentSecond = t[5]
currentDay = t[6]
# r is the number of seconds left between now and the next rotation
if self.atTime is None:
rotate_ts = _MIDNIGHT
else:
rotate_ts = ((self.atTime.hour * 60 + self.atTime.minute)*60 +
self.atTime.second)
r = rotate_ts - ((currentHour * 60 + currentMinute) * 60 +
currentSecond)
if r < 0:
# Rotate time is before the current time (for example when
# self.rotateAt is 13:45 and it now 14:15), rotation is
# tomorrow.
r += _MIDNIGHT
currentDay = (currentDay + 1) % 7
result = currentTime + r
# If we are rolling over on a certain day, add in the number of days until
# the next rollover, but offset by 1 since we just calculated the time
# until the next day starts. There are three cases:
# Case 1) The day to rollover is today; in this case, do nothing
# Case 2) The day to rollover is further in the interval (i.e., today is
# day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
# next rollover is simply 6 - 2 - 1, or 3.
# Case 3) The day to rollover is behind us in the interval (i.e., today
# is day 5 (Saturday) and rollover is on day 3 (Thursday).
# Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
# number of days left in the current week (1) plus the number
# of days in the next week until the rollover day (3).
# The calculations described in 2) and 3) above need to have a day added.
# This is because the above time calculation takes us to midnight on this
# day, i.e. the start of the next day.
if self.when.startswith('W'):
day = currentDay # 0 is Monday
if day != self.dayOfWeek:
if day < self.dayOfWeek:
daysToWait = self.dayOfWeek - day
else:
daysToWait = 6 - day + self.dayOfWeek + 1
newRolloverAt = result + (daysToWait * (60 * 60 * 24))
if not self.utc:
dstNow = t[-1]
dstAtRollover = time.localtime(newRolloverAt)[-1]
if dstNow != dstAtRollover:
if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
addend = -3600
else: # DST bows out before next rollover, so we need to add an hour
addend = 3600
newRolloverAt += addend
result = newRolloverAt
return result | [
"def",
"computeRollover",
"(",
"self",
",",
"currentTime",
")",
":",
"result",
"=",
"currentTime",
"+",
"self",
".",
"interval",
"# If we are rolling over at midnight or weekly, then the interval is already known.",
"# What we need to figure out is WHEN the next interval is. In othe... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/handlers.py#L256-L327 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | utils/lit/lit/llvm/subst.py | python | ToolSubst.__init__ | (self, key, command=None, pre=r'.-^/\<', post='-.', verbatim=False,
unresolved='warn', extra_args=None) | Construct a ToolSubst.
key: The text which is to be substituted.
command: The command to substitute when the key is matched. By default,
this will treat `key` as a tool name and search for it. If it is
a string, it is intereprted as an exact path. If it is an instance of
FindTool, the specified tool name is searched for on disk.
pre: If specified, the substitution will not find matches where
the character immediately preceding the word-boundary that begins
`key` is any of the characters in the string `pre`.
post: If specified, the substitution will not find matches where
the character immediately after the word-boundary that ends `key`
is any of the characters specified in the string `post`.
verbatim: If True, `key` is an exact regex that is passed to the
underlying substitution
unresolved: Action to take if the tool substitution cannot be
resolved. Valid values:
'warn' - log a warning but add the substitution anyway.
'fatal' - Exit the test suite and log a fatal error.
'break' - Don't add any of the substitutions from the current
group, and return a value indicating a failure.
'ignore' - Don't add the substitution, and don't log an error
extra_args: If specified, represents a list of arguments that will be
appended to the tool's substitution.
explicit_path: If specified, the exact path will be used as a substitution.
Otherwise, the tool will be searched for as if by calling which(tool) | Construct a ToolSubst. | [
"Construct",
"a",
"ToolSubst",
"."
] | def __init__(self, key, command=None, pre=r'.-^/\<', post='-.', verbatim=False,
unresolved='warn', extra_args=None):
"""Construct a ToolSubst.
key: The text which is to be substituted.
command: The command to substitute when the key is matched. By default,
this will treat `key` as a tool name and search for it. If it is
a string, it is intereprted as an exact path. If it is an instance of
FindTool, the specified tool name is searched for on disk.
pre: If specified, the substitution will not find matches where
the character immediately preceding the word-boundary that begins
`key` is any of the characters in the string `pre`.
post: If specified, the substitution will not find matches where
the character immediately after the word-boundary that ends `key`
is any of the characters specified in the string `post`.
verbatim: If True, `key` is an exact regex that is passed to the
underlying substitution
unresolved: Action to take if the tool substitution cannot be
resolved. Valid values:
'warn' - log a warning but add the substitution anyway.
'fatal' - Exit the test suite and log a fatal error.
'break' - Don't add any of the substitutions from the current
group, and return a value indicating a failure.
'ignore' - Don't add the substitution, and don't log an error
extra_args: If specified, represents a list of arguments that will be
appended to the tool's substitution.
explicit_path: If specified, the exact path will be used as a substitution.
Otherwise, the tool will be searched for as if by calling which(tool)
"""
self.unresolved = unresolved
self.extra_args = extra_args
self.key = key
self.command = command if command is not None else FindTool(key)
if verbatim:
self.regex = key
return
def not_in(chars, where=''):
if not chars:
return ''
pattern_str = '|'.join(re.escape(x) for x in chars)
return r'(?{}!({}))'.format(where, pattern_str)
def wordify(word):
match = wordifier.match(word)
introducer = match.group(1)
word = match.group(2)
return introducer + r'\b' + word + r'\b'
self.regex = not_in(pre, '<') + wordify(key) + not_in(post) | [
"def",
"__init__",
"(",
"self",
",",
"key",
",",
"command",
"=",
"None",
",",
"pre",
"=",
"r'.-^/\\<'",
",",
"post",
"=",
"'-.'",
",",
"verbatim",
"=",
"False",
",",
"unresolved",
"=",
"'warn'",
",",
"extra_args",
"=",
"None",
")",
":",
"self",
".",
... | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/utils/lit/lit/llvm/subst.py#L42-L99 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | SimRobotSensor.type | (self) | return _robotsim.SimRobotSensor_type(self) | r"""
type(SimRobotSensor self) -> std::string
Returns the type of the sensor. | r"""
type(SimRobotSensor self) -> std::string | [
"r",
"type",
"(",
"SimRobotSensor",
"self",
")",
"-",
">",
"std",
"::",
"string"
] | def type(self) -> "std::string":
r"""
type(SimRobotSensor self) -> std::string
Returns the type of the sensor.
"""
return _robotsim.SimRobotSensor_type(self) | [
"def",
"type",
"(",
"self",
")",
"->",
"\"std::string\"",
":",
"return",
"_robotsim",
".",
"SimRobotSensor_type",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L7149-L7157 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/feature_column/feature_column_v2.py | python | BucketizedColumn.get_config | (self) | return config | See 'FeatureColumn` base class. | See 'FeatureColumn` base class. | [
"See",
"FeatureColumn",
"base",
"class",
"."
] | def get_config(self):
"""See 'FeatureColumn` base class."""
from tensorflow.python.feature_column.serialization import serialize_feature_column # pylint: disable=g-import-not-at-top
config = dict(zip(self._fields, self))
config['source_column'] = serialize_feature_column(self.source_column)
return config | [
"def",
"get_config",
"(",
"self",
")",
":",
"from",
"tensorflow",
".",
"python",
".",
"feature_column",
".",
"serialization",
"import",
"serialize_feature_column",
"# pylint: disable=g-import-not-at-top",
"config",
"=",
"dict",
"(",
"zip",
"(",
"self",
".",
"_fields... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column_v2.py#L2866-L2871 | |
rodeofx/OpenWalter | 6116fbe3f04f1146c854afbfbdbe944feaee647e | walter/katana/WalterIn/walterVariantsMenu.py | python | VariantsMenu._getVariantList | (self, recursively=True) | return self.walterUSDExtern.getVariantsUsd().split('|') | Implementation of walterWidgets.BaseVariantsMenu. | Implementation of walterWidgets.BaseVariantsMenu. | [
"Implementation",
"of",
"walterWidgets",
".",
"BaseVariantsMenu",
"."
] | def _getVariantList(self, recursively=True):
"""Implementation of walterWidgets.BaseVariantsMenu."""
self.walterUSDExtern.setIdentifier(self.nodePath)
# Set the current variants from Katana parameters
arrayParameterPolicy = self.parent.getValuePolicy()
arraySize = arrayParameterPolicy.getArraySize()[0]
for i in range(0, arraySize):
child = arrayParameterPolicy.getArrayChild(i)
childValue = child.getValue()
self.walterUSDExtern.setVariantUsdFlat(childValue)
# Resize the parameters
self.walterUSDExtern.extractVariantsUsd()
arrayParameterPolicy.setArraySize(
[self.walterUSDExtern.getPrimsCount(), 1])
return self.walterUSDExtern.getVariantsUsd().split('|') | [
"def",
"_getVariantList",
"(",
"self",
",",
"recursively",
"=",
"True",
")",
":",
"self",
".",
"walterUSDExtern",
".",
"setIdentifier",
"(",
"self",
".",
"nodePath",
")",
"# Set the current variants from Katana parameters",
"arrayParameterPolicy",
"=",
"self",
".",
... | https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/katana/WalterIn/walterVariantsMenu.py#L72-L89 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListTextCtrl.Finish | (self) | Finish editing. | Finish editing. | [
"Finish",
"editing",
"."
] | def Finish(self):
""" Finish editing. """
try:
if not self._finished:
self._finished = True
self._owner.SetFocusIgnoringChildren()
self._owner.ResetTextControl()
except wx.PyDeadObjectError:
return | [
"def",
"Finish",
"(",
"self",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"_finished",
":",
"self",
".",
"_finished",
"=",
"True",
"self",
".",
"_owner",
".",
"SetFocusIgnoringChildren",
"(",
")",
"self",
".",
"_owner",
".",
"ResetTextControl",
"(",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L5843-L5852 | ||
yuxng/PoseCNN | 9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04 | lib/datasets/factory.py | python | get_imdb | (name) | return __sets[name]() | Get an imdb (image database) by name. | Get an imdb (image database) by name. | [
"Get",
"an",
"imdb",
"(",
"image",
"database",
")",
"by",
"name",
"."
] | def get_imdb(name):
"""Get an imdb (image database) by name."""
if not __sets.has_key(name):
raise KeyError('Unknown dataset: {}'.format(name))
return __sets[name]() | [
"def",
"get_imdb",
"(",
"name",
")",
":",
"if",
"not",
"__sets",
".",
"has_key",
"(",
"name",
")",
":",
"raise",
"KeyError",
"(",
"'Unknown dataset: {}'",
".",
"format",
"(",
"name",
")",
")",
"return",
"__sets",
"[",
"name",
"]",
"(",
")"
] | https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/datasets/factory.py#L112-L116 | |
chatopera/clause | dee31153d5ffdef33deedb6bff03e7806c296968 | var/assets/clients/gen-py/clause/Serving.py | python | Iface.myDicts | (self, request) | Parameters:
- request | Parameters:
- request | [
"Parameters",
":",
"-",
"request"
] | def myDicts(self, request):
"""
Parameters:
- request
"""
pass | [
"def",
"myDicts",
"(",
"self",
",",
"request",
")",
":",
"pass"
] | https://github.com/chatopera/clause/blob/dee31153d5ffdef33deedb6bff03e7806c296968/var/assets/clients/gen-py/clause/Serving.py#L116-L122 | ||
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/input.py | python | ValidateRulesInTarget | (target, target_dict, extra_sources_for_rules) | Ensures that the rules sections in target_dict are valid and consistent,
and determines which sources they apply to.
Arguments:
target: string, name of target.
target_dict: dict, target spec containing "rules" and "sources" lists.
extra_sources_for_rules: a list of keys to scan for rule matches in
addition to 'sources'. | Ensures that the rules sections in target_dict are valid and consistent,
and determines which sources they apply to. | [
"Ensures",
"that",
"the",
"rules",
"sections",
"in",
"target_dict",
"are",
"valid",
"and",
"consistent",
"and",
"determines",
"which",
"sources",
"they",
"apply",
"to",
"."
] | def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules):
"""Ensures that the rules sections in target_dict are valid and consistent,
and determines which sources they apply to.
Arguments:
target: string, name of target.
target_dict: dict, target spec containing "rules" and "sources" lists.
extra_sources_for_rules: a list of keys to scan for rule matches in
addition to 'sources'.
"""
# Dicts to map between values found in rules' 'rule_name' and 'extension'
# keys and the rule dicts themselves.
rule_names = {}
rule_extensions = {}
rules = target_dict.get('rules', [])
for rule in rules:
# Make sure that there's no conflict among rule names and extensions.
rule_name = rule['rule_name']
if rule_name in rule_names:
raise GypError('rule %s exists in duplicate, target %s' %
(rule_name, target))
rule_names[rule_name] = rule
rule_extension = rule['extension']
if rule_extension.startswith('.'):
rule_extension = rule_extension[1:]
if rule_extension in rule_extensions:
raise GypError(('extension %s associated with multiple rules, ' +
'target %s rules %s and %s') %
(rule_extension, target,
rule_extensions[rule_extension]['rule_name'],
rule_name))
rule_extensions[rule_extension] = rule
# Make sure rule_sources isn't already there. It's going to be
# created below if needed.
if 'rule_sources' in rule:
raise GypError(
'rule_sources must not exist in input, target %s rule %s' %
(target, rule_name))
rule_sources = []
source_keys = ['sources']
source_keys.extend(extra_sources_for_rules)
for source_key in source_keys:
for source in target_dict.get(source_key, []):
(source_root, source_extension) = os.path.splitext(source)
if source_extension.startswith('.'):
source_extension = source_extension[1:]
if source_extension == rule_extension:
rule_sources.append(source)
if len(rule_sources) > 0:
rule['rule_sources'] = rule_sources | [
"def",
"ValidateRulesInTarget",
"(",
"target",
",",
"target_dict",
",",
"extra_sources_for_rules",
")",
":",
"# Dicts to map between values found in rules' 'rule_name' and 'extension'",
"# keys and the rule dicts themselves.",
"rule_names",
"=",
"{",
"}",
"rule_extensions",
"=",
... | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/input.py#L2535-L2590 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/xdrlib.py | python | raise_conversion_error | (function) | return result | Wrap any raised struct.errors in a ConversionError. | Wrap any raised struct.errors in a ConversionError. | [
"Wrap",
"any",
"raised",
"struct",
".",
"errors",
"in",
"a",
"ConversionError",
"."
] | def raise_conversion_error(function):
""" Wrap any raised struct.errors in a ConversionError. """
@wraps(function)
def result(self, value):
try:
return function(self, value)
except struct.error as e:
raise ConversionError(e.args[0]) from None
return result | [
"def",
"raise_conversion_error",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"result",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"return",
"function",
"(",
"self",
",",
"value",
")",
"except",
"struct",
".",
"error",
"a... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xdrlib.py#L35-L44 | |
cyberbotics/webots | af7fa7d68dcf7b4550f1f2e132092b41e83698fc | scripts/image_tools/images/regular_image.py | python | RegularImage.set_pixel | (self, x, y, pixel) | Set pixel at the speficied position. | Set pixel at the speficied position. | [
"Set",
"pixel",
"at",
"the",
"speficied",
"position",
"."
] | def set_pixel(self, x, y, pixel):
"""Set pixel at the speficied position."""
assert x >= 0 and x < self.width
assert y >= 0 and y < self.height
self.im.putpixel((x, y), (int(pixel[0]), int(pixel[1]), int(pixel[2]))) | [
"def",
"set_pixel",
"(",
"self",
",",
"x",
",",
"y",
",",
"pixel",
")",
":",
"assert",
"x",
">=",
"0",
"and",
"x",
"<",
"self",
".",
"width",
"assert",
"y",
">=",
"0",
"and",
"y",
"<",
"self",
".",
"height",
"self",
".",
"im",
".",
"putpixel",
... | https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/scripts/image_tools/images/regular_image.py#L52-L56 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/dist_ratio.py | python | dist_ratio.is_atom_quasiconvex | (self) | return True | Is the atom quasiconvex? | Is the atom quasiconvex? | [
"Is",
"the",
"atom",
"quasiconvex?"
] | def is_atom_quasiconvex(self) -> bool:
"""Is the atom quasiconvex?
"""
return True | [
"def",
"is_atom_quasiconvex",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"True"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/dist_ratio.py#L64-L67 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/_strptime.py | python | TimeRE.__seqToRE | (self, to_convert, directive) | return '%s)' % regex | Convert a list to a regex string for matching a directive.
Want possible matching values to be from longest to shortest. This
prevents the possibility of a match occuring for a value that also
a substring of a larger value that should have matched (e.g., 'abc'
matching when 'abcdef' should have been the match). | Convert a list to a regex string for matching a directive. | [
"Convert",
"a",
"list",
"to",
"a",
"regex",
"string",
"for",
"matching",
"a",
"directive",
"."
] | def __seqToRE(self, to_convert, directive):
"""Convert a list to a regex string for matching a directive.
Want possible matching values to be from longest to shortest. This
prevents the possibility of a match occuring for a value that also
a substring of a larger value that should have matched (e.g., 'abc'
matching when 'abcdef' should have been the match).
"""
to_convert = sorted(to_convert, key=len, reverse=True)
for value in to_convert:
if value != '':
break
else:
return ''
regex = '|'.join(re_escape(stuff) for stuff in to_convert)
regex = '(?P<%s>%s' % (directive, regex)
return '%s)' % regex | [
"def",
"__seqToRE",
"(",
"self",
",",
"to_convert",
",",
"directive",
")",
":",
"to_convert",
"=",
"sorted",
"(",
"to_convert",
",",
"key",
"=",
"len",
",",
"reverse",
"=",
"True",
")",
"for",
"value",
"in",
"to_convert",
":",
"if",
"value",
"!=",
"''"... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/_strptime.py#L221-L238 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/closure_linter/closure_linter/tokenutil.py | python | Compare | (token1, token2) | Compares two tokens and determines their relative order.
Args:
token1: The first token to compare.
token2: The second token to compare.
Returns:
A negative integer, zero, or a positive integer as the first token is
before, equal, or after the second in the token stream. | Compares two tokens and determines their relative order. | [
"Compares",
"two",
"tokens",
"and",
"determines",
"their",
"relative",
"order",
"."
] | def Compare(token1, token2):
"""Compares two tokens and determines their relative order.
Args:
token1: The first token to compare.
token2: The second token to compare.
Returns:
A negative integer, zero, or a positive integer as the first token is
before, equal, or after the second in the token stream.
"""
if token2.line_number != token1.line_number:
return token1.line_number - token2.line_number
else:
return token1.start_index - token2.start_index | [
"def",
"Compare",
"(",
"token1",
",",
"token2",
")",
":",
"if",
"token2",
".",
"line_number",
"!=",
"token1",
".",
"line_number",
":",
"return",
"token1",
".",
"line_number",
"-",
"token2",
".",
"line_number",
"else",
":",
"return",
"token1",
".",
"start_i... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/tokenutil.py#L360-L374 | ||
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | lldb/third_party/Python/module/six/six.py | python | _import_module | (name) | return sys.modules[name] | Import module, returning the module after the last dot. | Import module, returning the module after the last dot. | [
"Import",
"module",
"returning",
"the",
"module",
"after",
"the",
"last",
"dot",
"."
] | def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name] | [
"def",
"_import_module",
"(",
"name",
")",
":",
"__import__",
"(",
"name",
")",
"return",
"sys",
".",
"modules",
"[",
"name",
"]"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/third_party/Python/module/six/six.py#L80-L83 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/sNMR/mrs.py | python | MRS.loadDir | (self, dirname) | Load several standard files from dir (old Borkum stage). | Load several standard files from dir (old Borkum stage). | [
"Load",
"several",
"standard",
"files",
"from",
"dir",
"(",
"old",
"Borkum",
"stage",
")",
"."
] | def loadDir(self, dirname):
"""Load several standard files from dir (old Borkum stage)."""
if not dirname[-1] == '/':
dirname += '/'
self.loadDataCube(dirname + 'datacube.dat')
self.loadErrorCube(dirname + 'errorcube.dat')
self.loadKernel(dirname)
self.loadZVector(dirname + 'zkernel.vec')
self.dirname = dirname | [
"def",
"loadDir",
"(",
"self",
",",
"dirname",
")",
":",
"if",
"not",
"dirname",
"[",
"-",
"1",
"]",
"==",
"'/'",
":",
"dirname",
"+=",
"'/'",
"self",
".",
"loadDataCube",
"(",
"dirname",
"+",
"'datacube.dat'",
")",
"self",
".",
"loadErrorCube",
"(",
... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/sNMR/mrs.py#L294-L302 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/driver_cbs.py | python | _cbs_gufunc | (func, total_method_name, **kwargs) | A text based parser of the CBS method string. Provided to handle "method/basis"
specification of the requested calculations. Also handles "simple" (i.e.
one-method and one-basis) calls.
Parameters
----------
func : function
Function to be called (energy, gradient, frequency or cbs).
total_method_name : str
String in a ``"method/basis"`` syntax. Simple calls (e.g. ``"blyp/sto-3g"``) are
bounced out of CBS. More complex calls (e.g. ``"mp2/cc-pv[tq]z"`` or
``"mp2/cc-pv[tq]z+D:ccsd(t)/cc-pvtz"``) are expanded by `_parse_cbs_gufunc_string()`
and pushed through :py:func:`~psi4.cbs`.
Returns
-------
tuple or float
Float, or if ``return_wfn`` is specified, a tuple of ``(value, wavefunction)``. | A text based parser of the CBS method string. Provided to handle "method/basis"
specification of the requested calculations. Also handles "simple" (i.e.
one-method and one-basis) calls. | [
"A",
"text",
"based",
"parser",
"of",
"the",
"CBS",
"method",
"string",
".",
"Provided",
"to",
"handle",
"method",
"/",
"basis",
"specification",
"of",
"the",
"requested",
"calculations",
".",
"Also",
"handles",
"simple",
"(",
"i",
".",
"e",
".",
"one",
... | def _cbs_gufunc(func, total_method_name, **kwargs):
"""
A text based parser of the CBS method string. Provided to handle "method/basis"
specification of the requested calculations. Also handles "simple" (i.e.
one-method and one-basis) calls.
Parameters
----------
func : function
Function to be called (energy, gradient, frequency or cbs).
total_method_name : str
String in a ``"method/basis"`` syntax. Simple calls (e.g. ``"blyp/sto-3g"``) are
bounced out of CBS. More complex calls (e.g. ``"mp2/cc-pv[tq]z"`` or
``"mp2/cc-pv[tq]z+D:ccsd(t)/cc-pvtz"``) are expanded by `_parse_cbs_gufunc_string()`
and pushed through :py:func:`~psi4.cbs`.
Returns
-------
tuple or float
Float, or if ``return_wfn`` is specified, a tuple of ``(value, wavefunction)``.
"""
# Catch kwarg issues for all methods
kwargs = p4util.kwargs_lower(kwargs)
return_wfn = kwargs.pop('return_wfn', False)
core.clean_variables()
ptype = kwargs.pop('ptype', None)
# Make sure the molecule the user provided is the active one
molecule = kwargs.pop('molecule', core.get_active_molecule())
molecule.update_geometry()
# Sanitize total_method_name
label = total_method_name
total_method_name = total_method_name.lower()
total_method_name = total_method_name.replace(' ', '')
# Split into components
method_list, basis_list = _parse_cbs_gufunc_string(total_method_name)
# Single energy call?
single_call = len(method_list) == 1
single_call &= '[' not in basis_list[0]
single_call &= ']' not in basis_list[0]
if single_call:
method_name = method_list[0]
basis = basis_list[0]
# Save some global variables so we can reset them later
optstash = p4util.OptionsState(['BASIS'])
core.set_global_option('BASIS', basis)
ptype_value, wfn = func(method_name, return_wfn=True, molecule=molecule, **kwargs)
if core.get_option("SCF", "DF_INTS_IO") != "SAVE":
core.clean()
optstash.restore()
if return_wfn:
return (ptype_value, wfn)
else:
return ptype_value
# Drop out for unsupported calls
if ptype not in ["energy", "gradient", "hessian"]:
raise ValidationError("%s: Cannot extrapolate or delta correct %s yet." % (ptype.title(), ptype))
# Catch kwarg issues for CBS methods only
user_dertype = kwargs.pop('dertype', None)
cbs_verbose = kwargs.pop('cbs_verbose', False)
# If we are not a single call, let CBS wrapper handle it!
cbs_kwargs = {}
cbs_kwargs['ptype'] = ptype
cbs_kwargs['return_wfn'] = True
cbs_kwargs['molecule'] = molecule
cbs_kwargs['verbose'] = cbs_verbose
if user_dertype != None:
cbs_kwargs['dertype'] = user_dertype
# Find method and basis
metadata = []
if method_list[0] in ['scf', 'hf', 'c4-scf', 'c4-hf']:
stage = {}
stage['wfn'] = method_list[0]
stage['basis'] = basis_list[0]
if 'scf_scheme' in kwargs:
stage['scheme'] = kwargs.pop('scf_scheme')
stage['stage'] = "scf"
stage['treatment'] = "scf"
else:
# _validate_cbs_inputs will produce scf stage automatically
stage = {}
stage['wfn'] = method_list[0]
stage['basis'] = basis_list[0]
if 'corl_scheme' in kwargs:
stage['scheme'] = kwargs.pop('corl_scheme')
stage['stage'] = "corl"
stage['treatment'] = "corl"
metadata.append(stage)
# "method/basis" syntax only allows for one delta correction
# via "method/basis+D:delta/basis". Maximum length of method_list is 2.
if len(method_list) == 2:
stage = {}
stage['wfn'] = method_list[1]
stage['basis'] = basis_list[1]
if 'delta_scheme' in kwargs:
stage['scheme'] = kwargs.pop('delta_scheme')
stage['stage'] = "delta1"
stage['treatment'] = "corl"
metadata.append(stage)
cbs_kwargs["cbs_metadata"] = metadata
ptype_value, wfn = cbs(func, label, **cbs_kwargs)
if return_wfn:
return (ptype_value, wfn)
else:
return ptype_value | [
"def",
"_cbs_gufunc",
"(",
"func",
",",
"total_method_name",
",",
"*",
"*",
"kwargs",
")",
":",
"# Catch kwarg issues for all methods",
"kwargs",
"=",
"p4util",
".",
"kwargs_lower",
"(",
"kwargs",
")",
"return_wfn",
"=",
"kwargs",
".",
"pop",
"(",
"'return_wfn'"... | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/driver_cbs.py#L1913-L2032 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Variables/EnumVariable.py | python | EnumVariable | (key, help, default, allowed_values, map={}, ignorecase=0) | return (key, help, default, validator, converter) | The input parameters describe an option with only certain values
allowed. They are returned with an appropriate converter and
validator appended. The result is usable for input to
Variables.Add().
'key' and 'default' are the values to be passed on to Variables.Add().
'help' will be appended by the allowed values automatically
'allowed_values' is a list of strings, which are allowed as values
for this option.
The 'map'-dictionary may be used for converting the input value
into canonical values (e.g. for aliases).
'ignorecase' defines the behaviour of the validator:
If ignorecase == 0, the validator/converter are case-sensitive.
If ignorecase == 1, the validator/converter are case-insensitive.
If ignorecase == 2, the validator/converter is case-insensitive and
the converted value will always be lower-case.
The 'validator' tests whether the value is in the list of allowed
values. The 'converter' converts input values according to the
given 'map'-dictionary (unmapped input values are returned
unchanged). | The input parameters describe an option with only certain values
allowed. They are returned with an appropriate converter and
validator appended. The result is usable for input to
Variables.Add(). | [
"The",
"input",
"parameters",
"describe",
"an",
"option",
"with",
"only",
"certain",
"values",
"allowed",
".",
"They",
"are",
"returned",
"with",
"an",
"appropriate",
"converter",
"and",
"validator",
"appended",
".",
"The",
"result",
"is",
"usable",
"for",
"in... | def EnumVariable(key, help, default, allowed_values, map={}, ignorecase=0):
"""
The input parameters describe an option with only certain values
allowed. They are returned with an appropriate converter and
validator appended. The result is usable for input to
Variables.Add().
'key' and 'default' are the values to be passed on to Variables.Add().
'help' will be appended by the allowed values automatically
'allowed_values' is a list of strings, which are allowed as values
for this option.
The 'map'-dictionary may be used for converting the input value
into canonical values (e.g. for aliases).
'ignorecase' defines the behaviour of the validator:
If ignorecase == 0, the validator/converter are case-sensitive.
If ignorecase == 1, the validator/converter are case-insensitive.
If ignorecase == 2, the validator/converter is case-insensitive and
the converted value will always be lower-case.
The 'validator' tests whether the value is in the list of allowed
values. The 'converter' converts input values according to the
given 'map'-dictionary (unmapped input values are returned
unchanged).
"""
help = '%s (%s)' % (help, '|'.join(allowed_values))
# define validator
if ignorecase >= 1:
validator = lambda key, val, env: \
_validator(key, val.lower(), env, allowed_values)
else:
validator = lambda key, val, env: \
_validator(key, val, env, allowed_values)
# define converter
if ignorecase == 2:
converter = lambda val: map.get(val.lower(), val).lower()
elif ignorecase == 1:
converter = lambda val: map.get(val.lower(), val)
else:
converter = lambda val: map.get(val, val)
return (key, help, default, validator, converter) | [
"def",
"EnumVariable",
"(",
"key",
",",
"help",
",",
"default",
",",
"allowed_values",
",",
"map",
"=",
"{",
"}",
",",
"ignorecase",
"=",
"0",
")",
":",
"help",
"=",
"'%s (%s)'",
"%",
"(",
"help",
",",
"'|'",
".",
"join",
"(",
"allowed_values",
")",
... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Variables/EnumVariable.py#L53-L97 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/training/saver.py | python | latest_checkpoint | (checkpoint_dir, latest_filename=None) | return None | Finds the filename of latest saved checkpoint file.
Args:
checkpoint_dir: Directory where the variables were saved.
latest_filename: Optional name for the protocol buffer file that
contains the list of most recent checkpoint filenames.
See the corresponding argument to `Saver.save()`.
Returns:
The full path to the latest checkpoint or `None` if no checkpoint was found. | Finds the filename of latest saved checkpoint file. | [
"Finds",
"the",
"filename",
"of",
"latest",
"saved",
"checkpoint",
"file",
"."
] | def latest_checkpoint(checkpoint_dir, latest_filename=None):
"""Finds the filename of latest saved checkpoint file.
Args:
checkpoint_dir: Directory where the variables were saved.
latest_filename: Optional name for the protocol buffer file that
contains the list of most recent checkpoint filenames.
See the corresponding argument to `Saver.save()`.
Returns:
The full path to the latest checkpoint or `None` if no checkpoint was found.
"""
# Pick the latest checkpoint based on checkpoint state.
ckpt = get_checkpoint_state(checkpoint_dir, latest_filename)
if ckpt and ckpt.model_checkpoint_path:
if file_io.get_matching_files(ckpt.model_checkpoint_path):
return ckpt.model_checkpoint_path
else:
logging.error("Couldn't match files for pattern %s",
ckpt.model_checkpoint_path)
return None | [
"def",
"latest_checkpoint",
"(",
"checkpoint_dir",
",",
"latest_filename",
"=",
"None",
")",
":",
"# Pick the latest checkpoint based on checkpoint state.",
"ckpt",
"=",
"get_checkpoint_state",
"(",
"checkpoint_dir",
",",
"latest_filename",
")",
"if",
"ckpt",
"and",
"ckpt... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/saver.py#L1142-L1163 | |
cocos-creator/engine-native | 984c4c9f5838253313b44ccd429bd8fac4ec8a6a | tools/bindings-generator/clang/cindex.py | python | SourceLocation.from_offset | (tu, file, offset) | return conf.lib.clang_getLocationForOffset(tu, file, offset) | Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file | Retrieve a SourceLocation from a given character offset. | [
"Retrieve",
"a",
"SourceLocation",
"from",
"a",
"given",
"character",
"offset",
"."
] | def from_offset(tu, file, offset):
"""Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file
"""
return conf.lib.clang_getLocationForOffset(tu, file, offset) | [
"def",
"from_offset",
"(",
"tu",
",",
"file",
",",
"offset",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getLocationForOffset",
"(",
"tu",
",",
"file",
",",
"offset",
")"
] | https://github.com/cocos-creator/engine-native/blob/984c4c9f5838253313b44ccd429bd8fac4ec8a6a/tools/bindings-generator/clang/cindex.py#L260-L267 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/xcodeproj_file.py | python | XCBuildPhase._AddPathToDict | (self, pbxbuildfile, path) | Adds path to the dict tracking paths belonging to this build phase.
If the path is already a member of this build phase, raises an exception. | Adds path to the dict tracking paths belonging to this build phase. | [
"Adds",
"path",
"to",
"the",
"dict",
"tracking",
"paths",
"belonging",
"to",
"this",
"build",
"phase",
"."
] | def _AddPathToDict(self, pbxbuildfile, path):
"""Adds path to the dict tracking paths belonging to this build phase.
If the path is already a member of this build phase, raises an exception.
"""
if path in self._files_by_path:
raise ValueError('Found multiple build files with path ' + path)
self._files_by_path[path] = pbxbuildfile | [
"def",
"_AddPathToDict",
"(",
"self",
",",
"pbxbuildfile",
",",
"path",
")",
":",
"if",
"path",
"in",
"self",
".",
"_files_by_path",
":",
"raise",
"ValueError",
"(",
"'Found multiple build files with path '",
"+",
"path",
")",
"self",
".",
"_files_by_path",
"[",... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/xcodeproj_file.py#L1778-L1786 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Text.mark_next | (self, index) | return self.tk.call(self._w, 'mark', 'next', index) or None | Return the name of the next mark after INDEX. | Return the name of the next mark after INDEX. | [
"Return",
"the",
"name",
"of",
"the",
"next",
"mark",
"after",
"INDEX",
"."
] | def mark_next(self, index):
"""Return the name of the next mark after INDEX."""
return self.tk.call(self._w, 'mark', 'next', index) or None | [
"def",
"mark_next",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'mark'",
",",
"'next'",
",",
"index",
")",
"or",
"None"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3064-L3066 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/dist/FreezeTool.py | python | Freezer.__loadModule | (self, mdef) | Adds the indicated module to the modulefinder. | Adds the indicated module to the modulefinder. | [
"Adds",
"the",
"indicated",
"module",
"to",
"the",
"modulefinder",
"."
] | def __loadModule(self, mdef):
""" Adds the indicated module to the modulefinder. """
if mdef.filename:
# If it has a filename, then we found it as a file on
# disk. In this case, the moduleName may not be accurate
# and useful, so load it as a file instead.
tempPath = None
if '.' not in mdef.moduleName:
# If we loaded a python file from the root, we need to
# temporarily add its directory to the module search
# path, so the modulefinder can find any sibling
# python files it imports as well.
tempPath = Filename(mdef.filename.getDirname()).toOsSpecific()
self.mf.path.append(tempPath)
pathname = mdef.filename.toOsSpecific()
ext = mdef.filename.getExtension()
if ext == 'pyc' or ext == 'pyo':
fp = open(pathname, 'rb')
stuff = ("", "rb", imp.PY_COMPILED)
self.mf.load_module(mdef.moduleName, fp, pathname, stuff)
else:
stuff = ("", "rb", imp.PY_SOURCE)
if mdef.text:
fp = io.StringIO(mdef.text)
else:
fp = open(pathname, 'rb')
self.mf.load_module(mdef.moduleName, fp, pathname, stuff)
if tempPath:
del self.mf.path[-1]
else:
# Otherwise, we can just import it normally.
self.mf.import_hook(mdef.moduleName) | [
"def",
"__loadModule",
"(",
"self",
",",
"mdef",
")",
":",
"if",
"mdef",
".",
"filename",
":",
"# If it has a filename, then we found it as a file on",
"# disk. In this case, the moduleName may not be accurate",
"# and useful, so load it as a file instead.",
"tempPath",
"=",
"No... | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/dist/FreezeTool.py#L1263-L1299 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | indentedBlock | (blockStatementExpr, indentStack, indent=True) | return smExpr.setName('indented block') | Helper method for defining space-delimited indentation blocks,
such as those used to define block statements in Python source code.
Parameters:
- blockStatementExpr - expression defining syntax of statement that
is repeated within the indented block
- indentStack - list created by caller to manage indentation stack
(multiple statementWithIndentedBlock expressions within a single
grammar should share a common indentStack)
- indent - boolean indicating whether block must be indented beyond
the current level; set to False for block of left-most
statements (default= ``True``)
A valid block must contain at least one ``blockStatement``.
Example::
data = '''
def A(z):
A1
B = 100
G = A2
A2
A3
B
def BB(a,b,c):
BB1
def BBA():
bba1
bba2
bba3
C
D
def spam(x,y):
def eggs(z):
pass
'''
indentStack = [1]
stmt = Forward()
identifier = Word(alphas, alphanums)
funcDecl = ("def" + identifier + Group("(" + Optional(delimitedList(identifier)) + ")") + ":")
func_body = indentedBlock(stmt, indentStack)
funcDef = Group(funcDecl + func_body)
rvalue = Forward()
funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
rvalue << (funcCall | identifier | Word(nums))
assignment = Group(identifier + "=" + rvalue)
stmt << (funcDef | assignment | identifier)
module_body = OneOrMore(stmt)
parseTree = module_body.parseString(data)
parseTree.pprint()
prints::
[['def',
'A',
['(', 'z', ')'],
':',
[['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
'B',
['def',
'BB',
['(', 'a', 'b', 'c', ')'],
':',
[['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
'C',
'D',
['def',
'spam',
['(', 'x', 'y', ')'],
':',
[[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] | Helper method for defining space-delimited indentation blocks,
such as those used to define block statements in Python source code. | [
"Helper",
"method",
"for",
"defining",
"space",
"-",
"delimited",
"indentation",
"blocks",
"such",
"as",
"those",
"used",
"to",
"define",
"block",
"statements",
"in",
"Python",
"source",
"code",
"."
] | def indentedBlock(blockStatementExpr, indentStack, indent=True):
"""Helper method for defining space-delimited indentation blocks,
such as those used to define block statements in Python source code.
Parameters:
- blockStatementExpr - expression defining syntax of statement that
is repeated within the indented block
- indentStack - list created by caller to manage indentation stack
(multiple statementWithIndentedBlock expressions within a single
grammar should share a common indentStack)
- indent - boolean indicating whether block must be indented beyond
the current level; set to False for block of left-most
statements (default= ``True``)
A valid block must contain at least one ``blockStatement``.
Example::
data = '''
def A(z):
A1
B = 100
G = A2
A2
A3
B
def BB(a,b,c):
BB1
def BBA():
bba1
bba2
bba3
C
D
def spam(x,y):
def eggs(z):
pass
'''
indentStack = [1]
stmt = Forward()
identifier = Word(alphas, alphanums)
funcDecl = ("def" + identifier + Group("(" + Optional(delimitedList(identifier)) + ")") + ":")
func_body = indentedBlock(stmt, indentStack)
funcDef = Group(funcDecl + func_body)
rvalue = Forward()
funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
rvalue << (funcCall | identifier | Word(nums))
assignment = Group(identifier + "=" + rvalue)
stmt << (funcDef | assignment | identifier)
module_body = OneOrMore(stmt)
parseTree = module_body.parseString(data)
parseTree.pprint()
prints::
[['def',
'A',
['(', 'z', ')'],
':',
[['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
'B',
['def',
'BB',
['(', 'a', 'b', 'c', ')'],
':',
[['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
'C',
'D',
['def',
'spam',
['(', 'x', 'y', ')'],
':',
[[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]
"""
backup_stack = indentStack[:]
def reset_stack():
indentStack[:] = backup_stack
def checkPeerIndent(s, l, t):
if l >= len(s): return
curCol = col(l, s)
if curCol != indentStack[-1]:
if curCol > indentStack[-1]:
raise ParseException(s, l, "illegal nesting")
raise ParseException(s, l, "not a peer entry")
def checkSubIndent(s, l, t):
curCol = col(l, s)
if curCol > indentStack[-1]:
indentStack.append(curCol)
else:
raise ParseException(s, l, "not a subentry")
def checkUnindent(s, l, t):
if l >= len(s): return
curCol = col(l, s)
if not(indentStack and curCol in indentStack):
raise ParseException(s, l, "not an unindent")
if curCol < indentStack[-1]:
indentStack.pop()
NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress(), stopOn=StringEnd())
INDENT = (Empty() + Empty().setParseAction(checkSubIndent)).setName('INDENT')
PEER = Empty().setParseAction(checkPeerIndent).setName('')
UNDENT = Empty().setParseAction(checkUnindent).setName('UNINDENT')
if indent:
smExpr = Group(Optional(NL)
+ INDENT
+ OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL), stopOn=StringEnd())
+ UNDENT)
else:
smExpr = Group(Optional(NL)
+ OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL), stopOn=StringEnd())
+ UNDENT)
smExpr.setFailAction(lambda a, b, c, d: reset_stack())
blockStatementExpr.ignore(_bslash + LineEnd())
return smExpr.setName('indented block') | [
"def",
"indentedBlock",
"(",
"blockStatementExpr",
",",
"indentStack",
",",
"indent",
"=",
"True",
")",
":",
"backup_stack",
"=",
"indentStack",
"[",
":",
"]",
"def",
"reset_stack",
"(",
")",
":",
"indentStack",
"[",
":",
"]",
"=",
"backup_stack",
"def",
"... | 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/pyparsing.py#L6231-L6355 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distro.py | python | LinuxDistribution.uname_attr | (self, attribute) | return self._uname_info.get(attribute, '') | Return a single named information item from the uname command
output data source of the OS distribution.
For details, see :func:`distro.uname_release_attr`. | [] | def uname_attr(self, attribute):
"""
Return a single named information item from the uname command
output data source of the OS distribution.
For details, see :func:`distro.uname_release_attr`.
"""
return self._uname_info.get(attribute, '') | [
"def",
"uname_attr",
"(",
"self",
",",
"attribute",
")",
":",
"return",
"self",
".",
"_uname_info",
".",
"get",
"(",
"attribute",
",",
"''",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distro.py#L1827-L1841 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_vendor/packaging/specifiers.py | python | BaseSpecifier.__eq__ | (self, other: object) | Returns a boolean representing whether or not the two Specifier like
objects are equal. | Returns a boolean representing whether or not the two Specifier like
objects are equal. | [
"Returns",
"a",
"boolean",
"representing",
"whether",
"or",
"not",
"the",
"two",
"Specifier",
"like",
"objects",
"are",
"equal",
"."
] | def __eq__(self, other: object) -> bool:
"""
Returns a boolean representing whether or not the two Specifier like
objects are equal.
""" | [
"def",
"__eq__",
"(",
"self",
",",
"other",
":",
"object",
")",
"->",
"bool",
":"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/packaging/specifiers.py#L54-L58 | ||
arkenthera/electron-vibrancy | 383153ef9ccb23a6c7517150d6bb0794dff3115e | scripts/cpplint.py | python | CheckForNonStandardConstructs | (filename, clean_lines, linenum,
nesting_state, error) | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. | [
"r",
"Logs",
"an",
"error",
"if",
"we",
"see",
"certain",
"non",
"-",
"ANSI",
"constructs",
"ignored",
"by",
"gcc",
"-",
"2",
"."
] | def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage class (static, extern, typedef, etc) should be first.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
% re.escape(base_classname),
line)
if (args and
args.group(1) != 'void' and
not Search(r'\bstd::initializer_list\b', args.group(1)) and
not Match(r'(const\s+)?%s(\s+const)?\s*(?:<\w+>\s*)?&'
% re.escape(base_classname), args.group(1).strip())):
error(filename, linenum, 'runtime/explicit', 5,
'Single-argument constructors should be marked explicit.') | [
"def",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Remove comments from the line, but leave in strings for now.",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"i... | https://github.com/arkenthera/electron-vibrancy/blob/383153ef9ccb23a6c7517150d6bb0794dff3115e/scripts/cpplint.py#L2320-L2425 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/numbers.py | python | Complex.__radd__ | (self, other) | other + self | other + self | [
"other",
"+",
"self"
] | def __radd__(self, other):
"""other + self"""
raise NotImplementedError | [
"def",
"__radd__",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/numbers.py#L78-L80 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/interpolate/_fitpack_impl.py | python | _intc_overflow | (x, msg=None) | return intc(x) | Cast the value to an intc and raise an OverflowError if the value
cannot fit. | Cast the value to an intc and raise an OverflowError if the value
cannot fit. | [
"Cast",
"the",
"value",
"to",
"an",
"intc",
"and",
"raise",
"an",
"OverflowError",
"if",
"the",
"value",
"cannot",
"fit",
"."
] | def _intc_overflow(x, msg=None):
"""Cast the value to an intc and raise an OverflowError if the value
cannot fit.
"""
if x > iinfo(intc).max:
if msg is None:
msg = '%r cannot fit into an intc' % x
raise OverflowError(msg)
return intc(x) | [
"def",
"_intc_overflow",
"(",
"x",
",",
"msg",
"=",
"None",
")",
":",
"if",
"x",
">",
"iinfo",
"(",
"intc",
")",
".",
"max",
":",
"if",
"msg",
"is",
"None",
":",
"msg",
"=",
"'%r cannot fit into an intc'",
"%",
"x",
"raise",
"OverflowError",
"(",
"ms... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/interpolate/_fitpack_impl.py#L40-L48 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap_external.py | python | SourceLoader.get_source | (self, fullname) | return decode_source(source_bytes) | Concrete implementation of InspectLoader.get_source. | Concrete implementation of InspectLoader.get_source. | [
"Concrete",
"implementation",
"of",
"InspectLoader",
".",
"get_source",
"."
] | def get_source(self, fullname):
"""Concrete implementation of InspectLoader.get_source."""
path = self.get_filename(fullname)
try:
source_bytes = self.get_data(path)
except OSError as exc:
raise ImportError('source not available through get_data()',
name=fullname) from exc
return decode_source(source_bytes) | [
"def",
"get_source",
"(",
"self",
",",
"fullname",
")",
":",
"path",
"=",
"self",
".",
"get_filename",
"(",
"fullname",
")",
"try",
":",
"source_bytes",
"=",
"self",
".",
"get_data",
"(",
"path",
")",
"except",
"OSError",
"as",
"exc",
":",
"raise",
"Im... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap_external.py#L775-L783 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py | python | UpdateIncludeState | (filename, include_state, io=codecs) | return True | Fill up the include_state with new includes found from the file.
Args:
filename: the name of the header to read.
include_state: an _IncludeState instance in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was succesfully added. False otherwise. | Fill up the include_state with new includes found from the file. | [
"Fill",
"up",
"the",
"include_state",
"with",
"new",
"includes",
"found",
"from",
"the",
"file",
"."
] | def UpdateIncludeState(filename, include_state, io=codecs):
"""Fill up the include_state with new includes found from the file.
Args:
filename: the name of the header to read.
include_state: an _IncludeState instance in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was succesfully added. False otherwise.
"""
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _RE_PATTERN_INCLUDE.search(clean_line)
if match:
include = match.group(2)
# The value formatting is cute, but not really used right now.
# What matters here is that the key is in include_state.
include_state.setdefault(include, '%s:%d' % (filename, linenum))
return True | [
"def",
"UpdateIncludeState",
"(",
"filename",
",",
"include_state",
",",
"io",
"=",
"codecs",
")",
":",
"headerfile",
"=",
"None",
"try",
":",
"headerfile",
"=",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"'utf8'",
",",
"'replace'",
")",
"excep... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py#L4454-L4480 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/browser.py | python | ModuleBrowserTreeItem.OnDoubleClick | (self) | Open a module in an editor window when double clicked. | Open a module in an editor window when double clicked. | [
"Open",
"a",
"module",
"in",
"an",
"editor",
"window",
"when",
"double",
"clicked",
"."
] | def OnDoubleClick(self):
"Open a module in an editor window when double clicked."
if os.path.normcase(self.file[-3:]) != ".py":
return
if not os.path.exists(self.file):
return
file_open(self.file) | [
"def",
"OnDoubleClick",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"normcase",
"(",
"self",
".",
"file",
"[",
"-",
"3",
":",
"]",
")",
"!=",
"\".py\"",
":",
"return",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"f... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/browser.py#L162-L168 | ||
ROCmSoftwarePlatform/hipCaffe | 4ec5d482515cce532348553b6db6d00d015675d5 | python/caffe/io.py | python | Transformer.set_transpose | (self, in_, order) | Set the input channel order for e.g. RGB to BGR conversion
as needed for the reference ImageNet model.
Parameters
----------
in_ : which input to assign this channel order
order : the order to transpose the dimensions | Set the input channel order for e.g. RGB to BGR conversion
as needed for the reference ImageNet model. | [
"Set",
"the",
"input",
"channel",
"order",
"for",
"e",
".",
"g",
".",
"RGB",
"to",
"BGR",
"conversion",
"as",
"needed",
"for",
"the",
"reference",
"ImageNet",
"model",
"."
] | def set_transpose(self, in_, order):
"""
Set the input channel order for e.g. RGB to BGR conversion
as needed for the reference ImageNet model.
Parameters
----------
in_ : which input to assign this channel order
order : the order to transpose the dimensions
"""
self.__check_input(in_)
if len(order) != len(self.inputs[in_]) - 1:
raise Exception('Transpose order needs to have the same number of '
'dimensions as the input.')
self.transpose[in_] = order | [
"def",
"set_transpose",
"(",
"self",
",",
"in_",
",",
"order",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"if",
"len",
"(",
"order",
")",
"!=",
"len",
"(",
"self",
".",
"inputs",
"[",
"in_",
"]",
")",
"-",
"1",
":",
"raise",
"Except... | https://github.com/ROCmSoftwarePlatform/hipCaffe/blob/4ec5d482515cce532348553b6db6d00d015675d5/python/caffe/io.py#L187-L201 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/utils.py | python | urldefragauth | (url) | return urlunparse((scheme, netloc, path, params, query, '')) | Given a url remove the fragment and the authentication part | Given a url remove the fragment and the authentication part | [
"Given",
"a",
"url",
"remove",
"the",
"fragment",
"and",
"the",
"authentication",
"part"
] | def urldefragauth(url):
"""
Given a url remove the fragment and the authentication part
"""
scheme, netloc, path, params, query, fragment = urlparse(url)
# see func:`prepend_scheme_if_needed`
if not netloc:
netloc, path = path, netloc
netloc = netloc.rsplit('@', 1)[-1]
return urlunparse((scheme, netloc, path, params, query, '')) | [
"def",
"urldefragauth",
"(",
"url",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
"=",
"urlparse",
"(",
"url",
")",
"# see func:`prepend_scheme_if_needed`",
"if",
"not",
"netloc",
":",
"netloc",
",",
"path",
... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/utils.py#L685-L697 | |
glotzerlab/hoomd-blue | f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a | hoomd/hpmc/tune/move_size.py | python | _InternalMoveSize._attached | (self) | return self._is_attached | bool: Whether or not the tuner is attached to a simulation. | bool: Whether or not the tuner is attached to a simulation. | [
"bool",
":",
"Whether",
"or",
"not",
"the",
"tuner",
"is",
"attached",
"to",
"a",
"simulation",
"."
] | def _attached(self):
"""bool: Whether or not the tuner is attached to a simulation."""
return self._is_attached | [
"def",
"_attached",
"(",
"self",
")",
":",
"return",
"self",
".",
"_is_attached"
] | https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/hpmc/tune/move_size.py#L175-L177 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/refactor.py | python | RefactoringTool.log_error | (self, msg, *args, **kwds) | Called when an error occurs. | Called when an error occurs. | [
"Called",
"when",
"an",
"error",
"occurs",
"."
] | def log_error(self, msg, *args, **kwds):
"""Called when an error occurs."""
raise | [
"def",
"log_error",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"raise"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/refactor.py#L255-L257 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/poolmanager.py | python | _default_key_normalizer | (key_class, request_context) | return key_class(**context) | Create a pool key out of a request context dictionary.
According to RFC 3986, both the scheme and host are case-insensitive.
Therefore, this function normalizes both before constructing the pool
key for an HTTPS request. If you wish to change this behaviour, provide
alternate callables to ``key_fn_by_scheme``.
:param key_class:
The class to use when constructing the key. This should be a namedtuple
with the ``scheme`` and ``host`` keys at a minimum.
:type key_class: namedtuple
:param request_context:
A dictionary-like object that contain the context for a request.
:type request_context: dict
:return: A namedtuple that can be used as a connection pool key.
:rtype: PoolKey | Create a pool key out of a request context dictionary. | [
"Create",
"a",
"pool",
"key",
"out",
"of",
"a",
"request",
"context",
"dictionary",
"."
] | def _default_key_normalizer(key_class, request_context):
"""
Create a pool key out of a request context dictionary.
According to RFC 3986, both the scheme and host are case-insensitive.
Therefore, this function normalizes both before constructing the pool
key for an HTTPS request. If you wish to change this behaviour, provide
alternate callables to ``key_fn_by_scheme``.
:param key_class:
The class to use when constructing the key. This should be a namedtuple
with the ``scheme`` and ``host`` keys at a minimum.
:type key_class: namedtuple
:param request_context:
A dictionary-like object that contain the context for a request.
:type request_context: dict
:return: A namedtuple that can be used as a connection pool key.
:rtype: PoolKey
"""
# Since we mutate the dictionary, make a copy first
context = request_context.copy()
context["scheme"] = context["scheme"].lower()
context["host"] = context["host"].lower()
# These are both dictionaries and need to be transformed into frozensets
for key in ("headers", "_proxy_headers", "_socks_options"):
if key in context and context[key] is not None:
context[key] = frozenset(context[key].items())
# The socket_options key may be a list and needs to be transformed into a
# tuple.
socket_opts = context.get("socket_options")
if socket_opts is not None:
context["socket_options"] = tuple(socket_opts)
# Map the kwargs to the names in the namedtuple - this is necessary since
# namedtuples can't have fields starting with '_'.
for key in list(context.keys()):
context["key_" + key] = context.pop(key)
# Default to ``None`` for keys missing from the context
for field in key_class._fields:
if field not in context:
context[field] = None
return key_class(**context) | [
"def",
"_default_key_normalizer",
"(",
"key_class",
",",
"request_context",
")",
":",
"# Since we mutate the dictionary, make a copy first",
"context",
"=",
"request_context",
".",
"copy",
"(",
")",
"context",
"[",
"\"scheme\"",
"]",
"=",
"context",
"[",
"\"scheme\"",
... | 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/urllib3/poolmanager.py#L78-L124 | |
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | src/third_party/protobuf/python/google/protobuf/service_reflection.py | python | _ServiceStubBuilder.__init__ | (self, service_descriptor) | Initializes an instance of the service stub class builder.
Args:
service_descriptor: ServiceDescriptor to use when constructing the
stub class. | Initializes an instance of the service stub class builder. | [
"Initializes",
"an",
"instance",
"of",
"the",
"service",
"stub",
"class",
"builder",
"."
] | def __init__(self, service_descriptor):
"""Initializes an instance of the service stub class builder.
Args:
service_descriptor: ServiceDescriptor to use when constructing the
stub class.
"""
self.descriptor = service_descriptor | [
"def",
"__init__",
"(",
"self",
",",
"service_descriptor",
")",
":",
"self",
".",
"descriptor",
"=",
"service_descriptor"
] | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/service_reflection.py#L242-L249 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge3.py | python | ExodusModel._get_trace | (omitted_frames=1) | return message | Return a compressed stack trace. | Return a compressed stack trace. | [
"Return",
"a",
"compressed",
"stack",
"trace",
"."
] | def _get_trace(omitted_frames=1):
"""Return a compressed stack trace."""
last_file = ''
message = ''
for frame in inspect.stack()[omitted_frames:]:
this_file = frame[1].split('/')[-1]
if this_file != last_file:
message += this_file + ':'
last_file = this_file
else:
message += ' ' * len(last_file) + ' '
message += frame[3] + ':' + str(frame[2])
message += '\n'
return message | [
"def",
"_get_trace",
"(",
"omitted_frames",
"=",
"1",
")",
":",
"last_file",
"=",
"''",
"message",
"=",
"''",
"for",
"frame",
"in",
"inspect",
".",
"stack",
"(",
")",
"[",
"omitted_frames",
":",
"]",
":",
"this_file",
"=",
"frame",
"[",
"1",
"]",
"."... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L919-L932 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/email/message.py | python | Message.__str__ | (self) | return self.as_string(unixfrom=True) | Return the entire formatted message as a string.
This includes the headers, body, and envelope header. | Return the entire formatted message as a string.
This includes the headers, body, and envelope header. | [
"Return",
"the",
"entire",
"formatted",
"message",
"as",
"a",
"string",
".",
"This",
"includes",
"the",
"headers",
"body",
"and",
"envelope",
"header",
"."
] | def __str__(self):
"""Return the entire formatted message as a string.
This includes the headers, body, and envelope header.
"""
return self.as_string(unixfrom=True) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"as_string",
"(",
"unixfrom",
"=",
"True",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/email/message.py#L118-L122 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/distutils/versionpredicate.py | python | VersionPredicate.__init__ | (self, versionPredicateStr) | Parse a version predicate string. | Parse a version predicate string. | [
"Parse",
"a",
"version",
"predicate",
"string",
"."
] | def __init__(self, versionPredicateStr):
"""Parse a version predicate string.
"""
# Fields:
# name: package name
# pred: list of (comparison string, StrictVersion)
versionPredicateStr = versionPredicateStr.strip()
if not versionPredicateStr:
raise ValueError("empty package restriction")
match = re_validPackage.match(versionPredicateStr)
if not match:
raise ValueError("bad package name in %r" % versionPredicateStr)
self.name, paren = match.groups()
paren = paren.strip()
if paren:
match = re_paren.match(paren)
if not match:
raise ValueError("expected parenthesized list: %r" % paren)
str = match.groups()[0]
self.pred = [splitUp(aPred) for aPred in str.split(",")]
if not self.pred:
raise ValueError("empty parenthesized list in %r"
% versionPredicateStr)
else:
self.pred = [] | [
"def",
"__init__",
"(",
"self",
",",
"versionPredicateStr",
")",
":",
"# Fields:",
"# name: package name",
"# pred: list of (comparison string, StrictVersion)",
"versionPredicateStr",
"=",
"versionPredicateStr",
".",
"strip",
"(",
")",
"if",
"not",
"versionPredicateSt... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/versionpredicate.py#L96-L121 | ||
francinexue/xuefu | b6ff79747a42e020588c0c0a921048e08fe4680c | api/ctpx/ctpmd.py | python | CtpMd.onRspSubMarketData | (self, SpecificInstrumentField, RspInfoField, requestId, final) | 订阅行情应答 | 订阅行情应答 | [
"订阅行情应答"
] | def onRspSubMarketData(self, SpecificInstrumentField, RspInfoField, requestId, final):
"""订阅行情应答"""
logger.info(u'订阅的instrumentID:{0},响应结果,错误码:[{1}],错误信息:【{2}]'.format(
SpecificInstrumentField.instrumentID, RspInfoField.errorID, RspInfoField.errorMsg.decode('gbk'))) | [
"def",
"onRspSubMarketData",
"(",
"self",
",",
"SpecificInstrumentField",
",",
"RspInfoField",
",",
"requestId",
",",
"final",
")",
":",
"logger",
".",
"info",
"(",
"u'订阅的instrumentID:{0},响应结果,错误码:[{1}],错误信息:【{2}]'.format(",
"",
"",
"",
"SpecificInstrumentField",
".",
... | https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctpmd.py#L74-L77 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/linalg/basic.py | python | solve | (a, b, sym_pos=False, lower=False, overwrite_a=False,
overwrite_b=False, debug=None, check_finite=True, assume_a='gen',
transposed=False) | return x | Solves the linear equation set ``a * x = b`` for the unknown ``x``
for square ``a`` matrix.
If the data matrix is known to be a particular type then supplying the
corresponding string to ``assume_a`` key chooses the dedicated solver.
The available options are
=================== ========
generic matrix 'gen'
symmetric 'sym'
hermitian 'her'
positive definite 'pos'
=================== ========
If omitted, ``'gen'`` is the default structure.
The datatype of the arrays define which solver is called regardless
of the values. In other words, even when the complex array entries have
precisely zero imaginary parts, the complex solver will be called based
on the data type of the array.
Parameters
----------
a : (N, N) array_like
Square input data
b : (N, NRHS) array_like
Input data for the right hand side.
sym_pos : bool, optional
Assume `a` is symmetric and positive definite. This key is deprecated
and assume_a = 'pos' keyword is recommended instead. The functionality
is the same. It will be removed in the future.
lower : bool, optional
If True, only the data contained in the lower triangle of `a`. Default
is to use upper triangle. (ignored for ``'gen'``)
overwrite_a : bool, optional
Allow overwriting data in `a` (may enhance performance).
Default is False.
overwrite_b : bool, optional
Allow overwriting data in `b` (may enhance performance).
Default is False.
check_finite : bool, optional
Whether to check that the input matrices contain only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
assume_a : str, optional
Valid entries are explained above.
transposed: bool, optional
If True, ``a^T x = b`` for real matrices, raises `NotImplementedError`
for complex matrices (only for True).
Returns
-------
x : (N, NRHS) ndarray
The solution array.
Raises
------
ValueError
If size mismatches detected or input a is not square.
LinAlgError
If the matrix is singular.
LinAlgWarning
If an ill-conditioned input a is detected.
NotImplementedError
If transposed is True and input a is a complex matrix.
Examples
--------
Given `a` and `b`, solve for `x`:
>>> a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
>>> b = np.array([2, 4, -1])
>>> from scipy import linalg
>>> x = linalg.solve(a, b)
>>> x
array([ 2., -2., 9.])
>>> np.dot(a, x) == b
array([ True, True, True], dtype=bool)
Notes
-----
If the input b matrix is a 1D array with N elements, when supplied
together with an NxN input a, it is assumed as a valid column vector
despite the apparent size mismatch. This is compatible with the
numpy.dot() behavior and the returned result is still 1D array.
The generic, symmetric, hermitian and positive definite solutions are
obtained via calling ?GESV, ?SYSV, ?HESV, and ?POSV routines of
LAPACK respectively. | Solves the linear equation set ``a * x = b`` for the unknown ``x``
for square ``a`` matrix. | [
"Solves",
"the",
"linear",
"equation",
"set",
"a",
"*",
"x",
"=",
"b",
"for",
"the",
"unknown",
"x",
"for",
"square",
"a",
"matrix",
"."
] | def solve(a, b, sym_pos=False, lower=False, overwrite_a=False,
overwrite_b=False, debug=None, check_finite=True, assume_a='gen',
transposed=False):
"""
Solves the linear equation set ``a * x = b`` for the unknown ``x``
for square ``a`` matrix.
If the data matrix is known to be a particular type then supplying the
corresponding string to ``assume_a`` key chooses the dedicated solver.
The available options are
=================== ========
generic matrix 'gen'
symmetric 'sym'
hermitian 'her'
positive definite 'pos'
=================== ========
If omitted, ``'gen'`` is the default structure.
The datatype of the arrays define which solver is called regardless
of the values. In other words, even when the complex array entries have
precisely zero imaginary parts, the complex solver will be called based
on the data type of the array.
Parameters
----------
a : (N, N) array_like
Square input data
b : (N, NRHS) array_like
Input data for the right hand side.
sym_pos : bool, optional
Assume `a` is symmetric and positive definite. This key is deprecated
and assume_a = 'pos' keyword is recommended instead. The functionality
is the same. It will be removed in the future.
lower : bool, optional
If True, only the data contained in the lower triangle of `a`. Default
is to use upper triangle. (ignored for ``'gen'``)
overwrite_a : bool, optional
Allow overwriting data in `a` (may enhance performance).
Default is False.
overwrite_b : bool, optional
Allow overwriting data in `b` (may enhance performance).
Default is False.
check_finite : bool, optional
Whether to check that the input matrices contain only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
assume_a : str, optional
Valid entries are explained above.
transposed: bool, optional
If True, ``a^T x = b`` for real matrices, raises `NotImplementedError`
for complex matrices (only for True).
Returns
-------
x : (N, NRHS) ndarray
The solution array.
Raises
------
ValueError
If size mismatches detected or input a is not square.
LinAlgError
If the matrix is singular.
LinAlgWarning
If an ill-conditioned input a is detected.
NotImplementedError
If transposed is True and input a is a complex matrix.
Examples
--------
Given `a` and `b`, solve for `x`:
>>> a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
>>> b = np.array([2, 4, -1])
>>> from scipy import linalg
>>> x = linalg.solve(a, b)
>>> x
array([ 2., -2., 9.])
>>> np.dot(a, x) == b
array([ True, True, True], dtype=bool)
Notes
-----
If the input b matrix is a 1D array with N elements, when supplied
together with an NxN input a, it is assumed as a valid column vector
despite the apparent size mismatch. This is compatible with the
numpy.dot() behavior and the returned result is still 1D array.
The generic, symmetric, hermitian and positive definite solutions are
obtained via calling ?GESV, ?SYSV, ?HESV, and ?POSV routines of
LAPACK respectively.
"""
# Flags for 1D or nD right hand side
b_is_1D = False
a1 = atleast_2d(_asarray_validated(a, check_finite=check_finite))
b1 = atleast_1d(_asarray_validated(b, check_finite=check_finite))
n = a1.shape[0]
overwrite_a = overwrite_a or _datacopied(a1, a)
overwrite_b = overwrite_b or _datacopied(b1, b)
if a1.shape[0] != a1.shape[1]:
raise ValueError('Input a needs to be a square matrix.')
if n != b1.shape[0]:
# Last chance to catch 1x1 scalar a and 1D b arrays
if not (n == 1 and b1.size != 0):
raise ValueError('Input b has to have same number of rows as '
'input a')
# accommodate empty arrays
if b1.size == 0:
return np.asfortranarray(b1.copy())
# regularize 1D b arrays to 2D
if b1.ndim == 1:
if n == 1:
b1 = b1[None, :]
else:
b1 = b1[:, None]
b_is_1D = True
# Backwards compatibility - old keyword.
if sym_pos:
assume_a = 'pos'
if assume_a not in ('gen', 'sym', 'her', 'pos'):
raise ValueError('{} is not a recognized matrix structure'
''.format(assume_a))
# Deprecate keyword "debug"
if debug is not None:
warn('Use of the "debug" keyword is deprecated '
'and this keyword will be removed in future '
'versions of SciPy.', DeprecationWarning, stacklevel=2)
# Get the correct lamch function.
# The LAMCH functions only exists for S and D
# So for complex values we have to convert to real/double.
if a1.dtype.char in 'fF': # single precision
lamch = get_lapack_funcs('lamch', dtype='f')
else:
lamch = get_lapack_funcs('lamch', dtype='d')
# Currently we do not have the other forms of the norm calculators
# lansy, lanpo, lanhe.
# However, in any case they only reduce computations slightly...
lange = get_lapack_funcs('lange', (a1,))
# Since the I-norm and 1-norm are the same for symmetric matrices
# we can collect them all in this one call
# Note however, that when issuing 'gen' and form!='none', then
# the I-norm should be used
if transposed:
trans = 1
norm = 'I'
if np.iscomplexobj(a1):
raise NotImplementedError('scipy.linalg.solve can currently '
'not solve a^T x = b or a^H x = b '
'for complex matrices.')
else:
trans = 0
norm = '1'
anorm = lange(norm, a1)
# Generalized case 'gesv'
if assume_a == 'gen':
gecon, getrf, getrs = get_lapack_funcs(('gecon', 'getrf', 'getrs'),
(a1, b1))
lu, ipvt, info = getrf(a1, overwrite_a=overwrite_a)
_solve_check(n, info)
x, info = getrs(lu, ipvt, b1,
trans=trans, overwrite_b=overwrite_b)
_solve_check(n, info)
rcond, info = gecon(lu, anorm, norm=norm)
# Hermitian case 'hesv'
elif assume_a == 'her':
hecon, hesv, hesv_lw = get_lapack_funcs(('hecon', 'hesv',
'hesv_lwork'), (a1, b1))
lwork = _compute_lwork(hesv_lw, n, lower)
lu, ipvt, x, info = hesv(a1, b1, lwork=lwork,
lower=lower,
overwrite_a=overwrite_a,
overwrite_b=overwrite_b)
_solve_check(n, info)
rcond, info = hecon(lu, ipvt, anorm)
# Symmetric case 'sysv'
elif assume_a == 'sym':
sycon, sysv, sysv_lw = get_lapack_funcs(('sycon', 'sysv',
'sysv_lwork'), (a1, b1))
lwork = _compute_lwork(sysv_lw, n, lower)
lu, ipvt, x, info = sysv(a1, b1, lwork=lwork,
lower=lower,
overwrite_a=overwrite_a,
overwrite_b=overwrite_b)
_solve_check(n, info)
rcond, info = sycon(lu, ipvt, anorm)
# Positive definite case 'posv'
else:
pocon, posv = get_lapack_funcs(('pocon', 'posv'),
(a1, b1))
lu, x, info = posv(a1, b1, lower=lower,
overwrite_a=overwrite_a,
overwrite_b=overwrite_b)
_solve_check(n, info)
rcond, info = pocon(lu, anorm)
_solve_check(n, info, lamch, rcond)
if b_is_1D:
x = x.ravel()
return x | [
"def",
"solve",
"(",
"a",
",",
"b",
",",
"sym_pos",
"=",
"False",
",",
"lower",
"=",
"False",
",",
"overwrite_a",
"=",
"False",
",",
"overwrite_b",
"=",
"False",
",",
"debug",
"=",
"None",
",",
"check_finite",
"=",
"True",
",",
"assume_a",
"=",
"'gen... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/linalg/basic.py#L42-L258 | |
apache/mesos | 97d9a4063332aae3825d78de71611657e05cf5e2 | src/python/interface/src/mesos/interface/__init__.py | python | SchedulerDriver.launchTasks | (self, offerIds, tasks, filters=None) | Launches the given set of tasks. Any remaining resources (i.e.,
those that are not used by the launched tasks or their executors)
will be considered declined. Note that this includes resources
used by tasks that the framework attempted to launch but failed
(with TASK_ERROR) due to a malformed task description. The
specified filters are applied on all unused resources (see
mesos.proto for a description of Filters). Available resources
are aggregated when multiple offers are provided. Note that all
offers must belong to the same slave. Invoking this function with
an empty collection of tasks declines offers in their entirety
(see Scheduler.declineOffer). Note that passing a single offer
is also supported. | Launches the given set of tasks. Any remaining resources (i.e.,
those that are not used by the launched tasks or their executors)
will be considered declined. Note that this includes resources
used by tasks that the framework attempted to launch but failed
(with TASK_ERROR) due to a malformed task description. The
specified filters are applied on all unused resources (see
mesos.proto for a description of Filters). Available resources
are aggregated when multiple offers are provided. Note that all
offers must belong to the same slave. Invoking this function with
an empty collection of tasks declines offers in their entirety
(see Scheduler.declineOffer). Note that passing a single offer
is also supported. | [
"Launches",
"the",
"given",
"set",
"of",
"tasks",
".",
"Any",
"remaining",
"resources",
"(",
"i",
".",
"e",
".",
"those",
"that",
"are",
"not",
"used",
"by",
"the",
"launched",
"tasks",
"or",
"their",
"executors",
")",
"will",
"be",
"considered",
"declin... | def launchTasks(self, offerIds, tasks, filters=None):
"""
Launches the given set of tasks. Any remaining resources (i.e.,
those that are not used by the launched tasks or their executors)
will be considered declined. Note that this includes resources
used by tasks that the framework attempted to launch but failed
(with TASK_ERROR) due to a malformed task description. The
specified filters are applied on all unused resources (see
mesos.proto for a description of Filters). Available resources
are aggregated when multiple offers are provided. Note that all
offers must belong to the same slave. Invoking this function with
an empty collection of tasks declines offers in their entirety
(see Scheduler.declineOffer). Note that passing a single offer
is also supported.
""" | [
"def",
"launchTasks",
"(",
"self",
",",
"offerIds",
",",
"tasks",
",",
"filters",
"=",
"None",
")",
":"
] | https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/src/python/interface/src/mesos/interface/__init__.py#L192-L206 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/platform/flags.py | python | DEFINE_float | (flag_name, default_value, docstring) | Defines a flag of type 'float'.
Args:
flag_name: The name of the flag as a string.
default_value: The default value the flag should take as a float.
docstring: A helpful message explaining the use of the flag. | Defines a flag of type 'float'. | [
"Defines",
"a",
"flag",
"of",
"type",
"float",
"."
] | def DEFINE_float(flag_name, default_value, docstring):
"""Defines a flag of type 'float'.
Args:
flag_name: The name of the flag as a string.
default_value: The default value the flag should take as a float.
docstring: A helpful message explaining the use of the flag.
"""
_define_helper(flag_name, default_value, docstring, float) | [
"def",
"DEFINE_float",
"(",
"flag_name",
",",
"default_value",
",",
"docstring",
")",
":",
"_define_helper",
"(",
"flag_name",
",",
"default_value",
",",
"docstring",
",",
"float",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/platform/flags.py#L129-L137 | ||
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | examples/Kaleidoscope/MCJIT/cached/genk-timing.py | python | generateKScript | (filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript) | Generate a random Kaleidoscope script based on the given parameters | Generate a random Kaleidoscope script based on the given parameters | [
"Generate",
"a",
"random",
"Kaleidoscope",
"script",
"based",
"on",
"the",
"given",
"parameters"
] | def generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript):
""" Generate a random Kaleidoscope script based on the given parameters """
print "Generating " + filename
print(" %d functions, %d elements per function, %d functions between execution" %
(numFuncs, elementsPerFunc, funcsBetweenExec))
print(" Call weighting = %f" % callWeighting)
script = KScriptGenerator(filename)
script.setCallWeighting(callWeighting)
script.writeComment("===========================================================================")
script.writeComment("Auto-generated script")
script.writeComment(" %d functions, %d elements per function, %d functions between execution"
% (numFuncs, elementsPerFunc, funcsBetweenExec))
script.writeComment(" call weighting = %f" % callWeighting)
script.writeComment("===========================================================================")
script.writeEmptyLine()
script.writePredefinedFunctions()
funcsSinceLastExec = 0
for i in range(numFuncs):
script.writeFunction(elementsPerFunc)
funcsSinceLastExec += 1
if funcsSinceLastExec == funcsBetweenExec:
script.writeFunctionCall()
funcsSinceLastExec = 0
# Always end with a function call
if funcsSinceLastExec > 0:
script.writeFunctionCall()
script.writeEmptyLine()
script.writeFinalFunctionCounts()
funcsCalled = len(script.calledFunctions)
print " Called %d of %d functions, %d total" % (funcsCalled, numFuncs, script.totalCallsExecuted)
timingScript.writeTimingCall(filename, numFuncs, funcsCalled, script.totalCallsExecuted) | [
"def",
"generateKScript",
"(",
"filename",
",",
"numFuncs",
",",
"elementsPerFunc",
",",
"funcsBetweenExec",
",",
"callWeighting",
",",
"timingScript",
")",
":",
"print",
"\"Generating \"",
"+",
"filename",
"print",
"(",
"\" %d functions, %d elements per function, %d fun... | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/examples/Kaleidoscope/MCJIT/cached/genk-timing.py#L174-L204 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetLdflags | (self, config, gyp_to_build_path, expand_special,
manifest_base_name, is_executable) | return ldflags, manifest_files | Returns the flags that need to be added to link commands, and the
manifest files. | Returns the flags that need to be added to link commands, and the
manifest files. | [
"Returns",
"the",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
"link",
"commands",
"and",
"the",
"manifest",
"files",
"."
] | def GetLdflags(self, config, gyp_to_build_path, expand_special,
manifest_base_name, is_executable):
"""Returns the flags that need to be added to link commands, and the
manifest files."""
config = self._RealConfig(config)
ldflags = []
ld = self._GetWrapper(self, self.msvs_settings[config],
'VCLinkerTool', append=ldflags)
self._GetDefFileAsLdflags(self.spec, ldflags, gyp_to_build_path)
ld('GenerateDebugInformation', map={'true': '/DEBUG'})
ld('TargetMachine', map={'1': 'X86', '17': 'X64'}, prefix='/MACHINE:')
ldflags.extend(self._GetAdditionalLibraryDirectories(
'VCLinkerTool', config, gyp_to_build_path))
ld('DelayLoadDLLs', prefix='/DELAYLOAD:')
out = self.GetOutputName(config, expand_special)
if out:
ldflags.append('/OUT:' + out)
ld('AdditionalOptions', prefix='')
ld('SubSystem', map={'1': 'CONSOLE', '2': 'WINDOWS'}, prefix='/SUBSYSTEM:')
ld('LinkIncremental', map={'1': ':NO', '2': ''}, prefix='/INCREMENTAL')
ld('FixedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/FIXED')
ld('RandomizedBaseAddress',
map={'1': ':NO', '2': ''}, prefix='/DYNAMICBASE')
ld('DataExecutionPrevention',
map={'1': ':NO', '2': ''}, prefix='/NXCOMPAT')
ld('OptimizeReferences', map={'1': 'NOREF', '2': 'REF'}, prefix='/OPT:')
ld('EnableCOMDATFolding', map={'1': 'NOICF', '2': 'ICF'}, prefix='/OPT:')
ld('LinkTimeCodeGeneration', map={'1': '/LTCG'})
ld('IgnoreDefaultLibraryNames', prefix='/NODEFAULTLIB:')
ld('ResourceOnlyDLL', map={'true': '/NOENTRY'})
ld('EntryPointSymbol', prefix='/ENTRY:')
# TODO(scottmg): This should sort of be somewhere else (not really a flag).
ld('AdditionalDependencies', prefix='')
# TODO(scottmg): These too.
ldflags.extend(('kernel32.lib', 'user32.lib', 'gdi32.lib', 'winspool.lib',
'comdlg32.lib', 'advapi32.lib', 'shell32.lib', 'ole32.lib',
'oleaut32.lib', 'uuid.lib', 'odbc32.lib', 'DelayImp.lib'))
# If the base address is not specifically controlled, DYNAMICBASE should
# be on by default.
base_flags = filter(lambda x: 'DYNAMICBASE' in x or x == '/FIXED',
ldflags)
if not base_flags:
ldflags.append('/DYNAMICBASE')
# If the NXCOMPAT flag has not been specified, default to on. Despite the
# documentation that says this only defaults to on when the subsystem is
# Vista or greater (which applies to the linker), the IDE defaults it on
# unless it's explicitly off.
if not filter(lambda x: 'NXCOMPAT' in x, ldflags):
ldflags.append('/NXCOMPAT')
have_def_file = filter(lambda x: x.startswith('/DEF:'), ldflags)
manifest_flags, intermediate_manifest_file = self._GetLdManifestFlags(
config, manifest_base_name, is_executable and not have_def_file)
ldflags.extend(manifest_flags)
manifest_files = self._GetAdditionalManifestFiles(config, gyp_to_build_path)
manifest_files.append(intermediate_manifest_file)
return ldflags, manifest_files | [
"def",
"GetLdflags",
"(",
"self",
",",
"config",
",",
"gyp_to_build_path",
",",
"expand_special",
",",
"manifest_base_name",
",",
"is_executable",
")",
":",
"config",
"=",
"self",
".",
"_RealConfig",
"(",
"config",
")",
"ldflags",
"=",
"[",
"]",
"ld",
"=",
... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/msvs_emulation.py#L373-L432 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/calendar.py | python | TextCalendar.pryear | (self, theyear, w=0, l=0, c=6, m=3) | Print a year's calendar. | Print a year's calendar. | [
"Print",
"a",
"year",
"s",
"calendar",
"."
] | def pryear(self, theyear, w=0, l=0, c=6, m=3):
"""Print a year's calendar."""
print(self.formatyear(theyear, w, l, c, m), end='') | [
"def",
"pryear",
"(",
"self",
",",
"theyear",
",",
"w",
"=",
"0",
",",
"l",
"=",
"0",
",",
"c",
"=",
"6",
",",
"m",
"=",
"3",
")",
":",
"print",
"(",
"self",
".",
"formatyear",
"(",
"theyear",
",",
"w",
",",
"l",
",",
"c",
",",
"m",
")",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/calendar.py#L405-L407 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/cli/autocompletion.py | python | autocomplete | () | Entry Point for completion of main and subcommand options. | Entry Point for completion of main and subcommand options. | [
"Entry",
"Point",
"for",
"completion",
"of",
"main",
"and",
"subcommand",
"options",
"."
] | def autocomplete():
# type: () -> None
"""Entry Point for completion of main and subcommand options.
"""
# Don't complete if user hasn't sourced bash_completion file.
if 'PIP_AUTO_COMPLETE' not in os.environ:
return
cwords = os.environ['COMP_WORDS'].split()[1:]
cword = int(os.environ['COMP_CWORD'])
try:
current = cwords[cword - 1]
except IndexError:
current = ''
parser = create_main_parser()
subcommands = list(commands_dict)
options = []
# subcommand
subcommand_name = None # type: Optional[str]
for word in cwords:
if word in subcommands:
subcommand_name = word
break
# subcommand options
if subcommand_name is not None:
# special case: 'help' subcommand has no options
if subcommand_name == 'help':
sys.exit(1)
# special case: list locally installed dists for show and uninstall
should_list_installed = (
subcommand_name in ['show', 'uninstall'] and
not current.startswith('-')
)
if should_list_installed:
installed = []
lc = current.lower()
for dist in get_installed_distributions(local_only=True):
if dist.key.startswith(lc) and dist.key not in cwords[1:]:
installed.append(dist.key)
# if there are no dists installed, fall back to option completion
if installed:
for dist in installed:
print(dist)
sys.exit(1)
subcommand = create_command(subcommand_name)
for opt in subcommand.parser.option_list_all:
if opt.help != optparse.SUPPRESS_HELP:
for opt_str in opt._long_opts + opt._short_opts:
options.append((opt_str, opt.nargs))
# filter out previously specified options from available options
prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
options = [(x, v) for (x, v) in options if x not in prev_opts]
# filter options by current input
options = [(k, v) for k, v in options if k.startswith(current)]
# get completion type given cwords and available subcommand options
completion_type = get_path_completion_type(
cwords, cword, subcommand.parser.option_list_all,
)
# get completion files and directories if ``completion_type`` is
# ``<file>``, ``<dir>`` or ``<path>``
if completion_type:
paths = auto_complete_paths(current, completion_type)
options = [(path, 0) for path in paths]
for option in options:
opt_label = option[0]
# append '=' to options which require args
if option[1] and option[0][:2] == "--":
opt_label += '='
print(opt_label)
else:
# show main parser options only when necessary
opts = [i.option_list for i in parser.option_groups]
opts.append(parser.option_list)
flattened_opts = chain.from_iterable(opts)
if current.startswith('-'):
for opt in flattened_opts:
if opt.help != optparse.SUPPRESS_HELP:
subcommands += opt._long_opts + opt._short_opts
else:
# get completion type given cwords and all available options
completion_type = get_path_completion_type(cwords, cword,
flattened_opts)
if completion_type:
subcommands = list(auto_complete_paths(current,
completion_type))
print(' '.join([x for x in subcommands if x.startswith(current)]))
sys.exit(1) | [
"def",
"autocomplete",
"(",
")",
":",
"# type: () -> None",
"# Don't complete if user hasn't sourced bash_completion file.",
"if",
"'PIP_AUTO_COMPLETE'",
"not",
"in",
"os",
".",
"environ",
":",
"return",
"cwords",
"=",
"os",
".",
"environ",
"[",
"'COMP_WORDS'",
"]",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/cli/autocompletion.py#L18-L110 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/concurrent/futures/_base.py | python | Future.exception | (self, timeout=None) | Return the exception raised by the call that the future represents.
Args:
timeout: The number of seconds to wait for the exception if the
future isn't done. If None, then there is no limit on the wait
time.
Returns:
The exception raised by the call that the future represents or None
if the call completed without raising.
Raises:
CancelledError: If the future was cancelled.
TimeoutError: If the future didn't finish executing before the given
timeout. | Return the exception raised by the call that the future represents. | [
"Return",
"the",
"exception",
"raised",
"by",
"the",
"call",
"that",
"the",
"future",
"represents",
"."
] | def exception(self, timeout=None):
"""Return the exception raised by the call that the future represents.
Args:
timeout: The number of seconds to wait for the exception if the
future isn't done. If None, then there is no limit on the wait
time.
Returns:
The exception raised by the call that the future represents or None
if the call completed without raising.
Raises:
CancelledError: If the future was cancelled.
TimeoutError: If the future didn't finish executing before the given
timeout.
"""
with self._condition:
if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
raise CancelledError()
elif self._state == FINISHED:
return self._exception
self._condition.wait(timeout)
if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
raise CancelledError()
elif self._state == FINISHED:
return self._exception
else:
raise TimeoutError() | [
"def",
"exception",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"with",
"self",
".",
"_condition",
":",
"if",
"self",
".",
"_state",
"in",
"[",
"CANCELLED",
",",
"CANCELLED_AND_NOTIFIED",
"]",
":",
"raise",
"CancelledError",
"(",
")",
"elif",
"se... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/concurrent/futures/_base.py#L439-L470 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/gradientbutton.py | python | GradientButton.SetTopEndColour | (self, colour) | Sets the top end colour for the gradient shading.
:param `colour`: a valid :class:`Colour` object. | Sets the top end colour for the gradient shading. | [
"Sets",
"the",
"top",
"end",
"colour",
"for",
"the",
"gradient",
"shading",
"."
] | def SetTopEndColour(self, colour):
"""
Sets the top end colour for the gradient shading.
:param `colour`: a valid :class:`Colour` object.
"""
self._topEndColour = colour
self.Refresh() | [
"def",
"SetTopEndColour",
"(",
"self",
",",
"colour",
")",
":",
"self",
".",
"_topEndColour",
"=",
"colour",
"self",
".",
"Refresh",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/gradientbutton.py#L567-L575 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | example/ssd/config/utils.py | python | config_as_dict | (cfg) | return ret | convert raw configuration to unified dictionary | convert raw configuration to unified dictionary | [
"convert",
"raw",
"configuration",
"to",
"unified",
"dictionary"
] | def config_as_dict(cfg):
""" convert raw configuration to unified dictionary """
ret = cfg.__dict__.copy()
# random cropping params
del ret['rand_crop_samplers']
assert isinstance(cfg.rand_crop_samplers, list)
ret = merge_dict(ret, zip_namedtuple(cfg.rand_crop_samplers))
num_crop_sampler = len(cfg.rand_crop_samplers)
ret['num_crop_sampler'] = num_crop_sampler # must specify the #
ret['rand_crop_prob'] = 1.0 / (num_crop_sampler + 1) * num_crop_sampler
# random padding params
del ret['rand_pad']
ret = merge_dict(ret, cfg.rand_pad._asdict())
# color jitter
del ret['color_jitter']
ret = merge_dict(ret, cfg.color_jitter._asdict())
return ret | [
"def",
"config_as_dict",
"(",
"cfg",
")",
":",
"ret",
"=",
"cfg",
".",
"__dict__",
".",
"copy",
"(",
")",
"# random cropping params",
"del",
"ret",
"[",
"'rand_crop_samplers'",
"]",
"assert",
"isinstance",
"(",
"cfg",
".",
"rand_crop_samplers",
",",
"list",
... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/ssd/config/utils.py#L92-L108 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/amber2lmp/dump2trj.py | python | Convert_files | () | Handle the whole conversion process | Handle the whole conversion process | [
"Handle",
"the",
"whole",
"conversion",
"process"
] | def Convert_files():
'Handle the whole conversion process'
print
print 'Welcome to dump2trj, a program to convert Lammps position dump files to\nAmber trajectory format!'
print
Basename_list = Find_dump_files()
for Basename in Basename_list:
t = Trajectory()
if t.Read_dump(Basename):
t.Write_trj(Basename)
del t
print | [
"def",
"Convert_files",
"(",
")",
":",
"print",
"print",
"'Welcome to dump2trj, a program to convert Lammps position dump files to\\nAmber trajectory format!'",
"print",
"Basename_list",
"=",
"Find_dump_files",
"(",
")",
"for",
"Basename",
"in",
"Basename_list",
":",
"t",
"="... | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/amber2lmp/dump2trj.py#L14-L28 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/stats/_multivariate.py | python | matrix_normal_gen.__call__ | (self, mean=None, rowcov=1, colcov=1, seed=None) | return matrix_normal_frozen(mean, rowcov, colcov, seed=seed) | Create a frozen matrix normal distribution.
See `matrix_normal_frozen` for more information. | Create a frozen matrix normal distribution. | [
"Create",
"a",
"frozen",
"matrix",
"normal",
"distribution",
"."
] | def __call__(self, mean=None, rowcov=1, colcov=1, seed=None):
"""
Create a frozen matrix normal distribution.
See `matrix_normal_frozen` for more information.
"""
return matrix_normal_frozen(mean, rowcov, colcov, seed=seed) | [
"def",
"__call__",
"(",
"self",
",",
"mean",
"=",
"None",
",",
"rowcov",
"=",
"1",
",",
"colcov",
"=",
"1",
",",
"seed",
"=",
"None",
")",
":",
"return",
"matrix_normal_frozen",
"(",
"mean",
",",
"rowcov",
",",
"colcov",
",",
"seed",
"=",
"seed",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/_multivariate.py#L931-L938 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/model/trajectory.py | python | Trajectory.insert | (self,time) | Inserts a milestone and keyframe at the given time. Returns the index of the new
milestone, or if a milestone already exists, then it returns that milestone index.
If the path is empty, the milestone is set to an empty list []. | Inserts a milestone and keyframe at the given time. Returns the index of the new
milestone, or if a milestone already exists, then it returns that milestone index. | [
"Inserts",
"a",
"milestone",
"and",
"keyframe",
"at",
"the",
"given",
"time",
".",
"Returns",
"the",
"index",
"of",
"the",
"new",
"milestone",
"or",
"if",
"a",
"milestone",
"already",
"exists",
"then",
"it",
"returns",
"that",
"milestone",
"index",
"."
] | def insert(self,time):
"""Inserts a milestone and keyframe at the given time. Returns the index of the new
milestone, or if a milestone already exists, then it returns that milestone index.
If the path is empty, the milestone is set to an empty list []."""
if len(self.times) == 0:
self.times = [time]
self.milestones = [[]]
return 0
if time <= self.times[0]:
if time < self.times[0]:
self.times.insert(0,time)
self.milestones.insert(0,self.milestones[0][:])
return 0
elif time >= self.times[-1]:
if time > self.times[-1]:
self.times.append(time)
self.milestones.append(self.milestones[-1][:])
return len(self.times)-1
else:
i,u = self.getSegment(time)
assert i >= 0,"getSegment returned -1? something must be wrong with the times"
if u == 0:
return i
elif u == 1:
return i+1
else:
q = self.interpolate_state(self.milestones[i],self.milestones[i+1],u,self.times[i+1]-self.times[i])
self.times.insert(i,time)
self.milestones.insert(i,q)
return i | [
"def",
"insert",
"(",
"self",
",",
"time",
")",
":",
"if",
"len",
"(",
"self",
".",
"times",
")",
"==",
"0",
":",
"self",
".",
"times",
"=",
"[",
"time",
"]",
"self",
".",
"milestones",
"=",
"[",
"[",
"]",
"]",
"return",
"0",
"if",
"time",
"<... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/trajectory.py#L267-L297 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py | python | IPv6Address.teredo | (self) | return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
IPv4Address(~self._ip & 0xFFFFFFFF)) | Tuple of embedded teredo IPs.
Returns:
Tuple of the (server, client) IPs or None if the address
doesn't appear to be a teredo address (doesn't start with
2001::/32) | Tuple of embedded teredo IPs. | [
"Tuple",
"of",
"embedded",
"teredo",
"IPs",
"."
] | def teredo(self):
"""Tuple of embedded teredo IPs.
Returns:
Tuple of the (server, client) IPs or None if the address
doesn't appear to be a teredo address (doesn't start with
2001::/32)
"""
if (self._ip >> 96) != 0x20010000:
return None
return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
IPv4Address(~self._ip & 0xFFFFFFFF)) | [
"def",
"teredo",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_ip",
">>",
"96",
")",
"!=",
"0x20010000",
":",
"return",
"None",
"return",
"(",
"IPv4Address",
"(",
"(",
"self",
".",
"_ip",
">>",
"64",
")",
"&",
"0xFFFFFFFF",
")",
",",
"IPv4Addres... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ipaddress.py#L2023-L2035 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/distributions/util.py | python | prefer_static_shape | (x) | return prefer_static_value(array_ops.shape(x)) | Return static shape of tensor `x` if available, else `tf.shape(x)`.
Args:
x: `Tensor` (already converted).
Returns:
Numpy array (if static shape is obtainable), else `Tensor`. | Return static shape of tensor `x` if available, else `tf.shape(x)`. | [
"Return",
"static",
"shape",
"of",
"tensor",
"x",
"if",
"available",
"else",
"tf",
".",
"shape",
"(",
"x",
")",
"."
] | def prefer_static_shape(x):
"""Return static shape of tensor `x` if available, else `tf.shape(x)`.
Args:
x: `Tensor` (already converted).
Returns:
Numpy array (if static shape is obtainable), else `Tensor`.
"""
return prefer_static_value(array_ops.shape(x)) | [
"def",
"prefer_static_shape",
"(",
"x",
")",
":",
"return",
"prefer_static_value",
"(",
"array_ops",
".",
"shape",
"(",
"x",
")",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/distributions/util.py#L760-L769 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/games/dynamic_routing_to_mean_field_game.py | python | DerivedNPlayerPolicyFromMeanFieldPolicy.action_probabilities | (self,
state: dynamic_routing.DynamicRoutingGameState,
player_id=None) | return self._mfg_policy.action_probabilities(mfg_state) | Returns the mean field action to apply in the N player state.
Args:
state: An N player dynamic routing game state.
player_id: the player id for which we want an action. Should be given to
the function.
Returns:
A `dict` of `{action: probability}` for the specified player in the
supplied state. | Returns the mean field action to apply in the N player state. | [
"Returns",
"the",
"mean",
"field",
"action",
"to",
"apply",
"in",
"the",
"N",
"player",
"state",
"."
] | def action_probabilities(self,
state: dynamic_routing.DynamicRoutingGameState,
player_id=None) -> Dict[int, float]:
"""Returns the mean field action to apply in the N player state.
Args:
state: An N player dynamic routing game state.
player_id: the player id for which we want an action. Should be given to
the function.
Returns:
A `dict` of `{action: probability}` for the specified player in the
supplied state.
"""
assert player_id is not None
mfg_state = self._convert_state_to_mean_field_state(state, player_id)
# Due to memoization, action_probabilities should not change mfg_state. In
# case action_probabilities changes mfg_state, then mfg_state.clone() should
# be passed to the function.
return self._mfg_policy.action_probabilities(mfg_state) | [
"def",
"action_probabilities",
"(",
"self",
",",
"state",
":",
"dynamic_routing",
".",
"DynamicRoutingGameState",
",",
"player_id",
"=",
"None",
")",
"->",
"Dict",
"[",
"int",
",",
"float",
"]",
":",
"assert",
"player_id",
"is",
"not",
"None",
"mfg_state",
"... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/games/dynamic_routing_to_mean_field_game.py#L113-L132 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/learn/python/learn/utils/export.py | python | classification_signature_fn_with_prob | (
examples, unused_features, predictions) | return default_signature, {} | Classification signature from given examples and predicted probabilities.
Args:
examples: `Tensor`.
unused_features: `dict` of `Tensor`s.
predictions: `Tensor` of predicted probabilities or dict that contains the
probabilities tensor as in {'probabilities', `Tensor`}.
Returns:
Tuple of default classification signature and empty named signatures.
Raises:
ValueError: If examples is `None`. | Classification signature from given examples and predicted probabilities. | [
"Classification",
"signature",
"from",
"given",
"examples",
"and",
"predicted",
"probabilities",
"."
] | def classification_signature_fn_with_prob(
examples, unused_features, predictions):
"""Classification signature from given examples and predicted probabilities.
Args:
examples: `Tensor`.
unused_features: `dict` of `Tensor`s.
predictions: `Tensor` of predicted probabilities or dict that contains the
probabilities tensor as in {'probabilities', `Tensor`}.
Returns:
Tuple of default classification signature and empty named signatures.
Raises:
ValueError: If examples is `None`.
"""
if examples is None:
raise ValueError('examples cannot be None when using this signature fn.')
if isinstance(predictions, dict):
default_signature = exporter.classification_signature(
examples, scores_tensor=predictions['probabilities'])
else:
default_signature = exporter.classification_signature(
examples, scores_tensor=predictions)
return default_signature, {} | [
"def",
"classification_signature_fn_with_prob",
"(",
"examples",
",",
"unused_features",
",",
"predictions",
")",
":",
"if",
"examples",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'examples cannot be None when using this signature fn.'",
")",
"if",
"isinstance",
"(",... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/utils/export.py#L139-L164 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/index/collector.py | python | _remove_duplicate_links | (links) | return list(OrderedDict.fromkeys(links)) | Return a list of links, with duplicates removed and ordering preserved. | [] | def _remove_duplicate_links(links):
# type: (Iterable[Link]) -> List[Link]
"""
Return a list of links, with duplicates removed and ordering preserved.
"""
# We preserve the ordering when removing duplicates because we can.
return list(OrderedDict.fromkeys(links)) | [
"def",
"_remove_duplicate_links",
"(",
"links",
")",
":",
"# type: (Iterable[Link]) -> List[Link]",
"# We preserve the ordering when removing duplicates because we can.",
"return",
"list",
"(",
"OrderedDict",
".",
"fromkeys",
"(",
"links",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/index/collector.py#L917-L929 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/procrouting/proc.py | python | select_olccd_property | (name, **kwargs) | Function selecting the algorithm for an OLCCD property call
and directing to specified or best-performance default modules. | Function selecting the algorithm for an OLCCD property call
and directing to specified or best-performance default modules. | [
"Function",
"selecting",
"the",
"algorithm",
"for",
"an",
"OLCCD",
"property",
"call",
"and",
"directing",
"to",
"specified",
"or",
"best",
"-",
"performance",
"default",
"modules",
"."
] | def select_olccd_property(name, **kwargs):
"""Function selecting the algorithm for an OLCCD property call
and directing to specified or best-performance default modules.
"""
reference = core.get_option('SCF', 'REFERENCE')
mtd_type = core.get_global_option('CC_TYPE')
module = core.get_global_option('QC_MODULE')
# Considering only [df]occ
func = None
if reference in ['RHF', 'UHF', 'ROHF', 'RKS', 'UKS']:
if mtd_type == 'DF':
if module in ['', 'OCC']:
func = run_dfocc_property
if func is None:
raise ManagedMethodError(['select_olccd_property', name, 'CC_TYPE', mtd_type, reference, module])
if kwargs.pop('probe', False):
return
else:
return func(name, **kwargs) | [
"def",
"select_olccd_property",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"reference",
"=",
"core",
".",
"get_option",
"(",
"'SCF'",
",",
"'REFERENCE'",
")",
"mtd_type",
"=",
"core",
".",
"get_global_option",
"(",
"'CC_TYPE'",
")",
"module",
"=",
"co... | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/procrouting/proc.py#L344-L366 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/traced_module/node.py | python | TensorNode.dtype | (self) | return self._dtype | r"""Get the dtype of this Node. | r"""Get the dtype of this Node. | [
"r",
"Get",
"the",
"dtype",
"of",
"this",
"Node",
"."
] | def dtype(self):
r"""Get the dtype of this Node."""
return self._dtype | [
"def",
"dtype",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dtype"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/traced_module/node.py#L276-L278 | |
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Modules/Scripted/DICOMLib/DICOMPlugin.py | python | DICOMPlugin.defaultSeriesNodeName | (self,seriesUID) | return name | Generate a name suitable for use as a mrml node name based
on the series level data in the database | Generate a name suitable for use as a mrml node name based
on the series level data in the database | [
"Generate",
"a",
"name",
"suitable",
"for",
"use",
"as",
"a",
"mrml",
"node",
"name",
"based",
"on",
"the",
"series",
"level",
"data",
"in",
"the",
"database"
] | def defaultSeriesNodeName(self,seriesUID):
"""Generate a name suitable for use as a mrml node name based
on the series level data in the database"""
instanceFilePaths = slicer.dicomDatabase.filesForSeries(seriesUID)
if len(instanceFilePaths) == 0:
return "Unnamed Series"
seriesDescription = slicer.dicomDatabase.fileValue(instanceFilePaths[0],self.tags['seriesDescription'])
seriesNumber = slicer.dicomDatabase.fileValue(instanceFilePaths[0],self.tags['seriesNumber'])
name = seriesDescription
if seriesDescription == "":
name = "Unnamed Series"
if seriesNumber != "":
name = seriesNumber + ": " + name
return name | [
"def",
"defaultSeriesNodeName",
"(",
"self",
",",
"seriesUID",
")",
":",
"instanceFilePaths",
"=",
"slicer",
".",
"dicomDatabase",
".",
"filesForSeries",
"(",
"seriesUID",
")",
"if",
"len",
"(",
"instanceFilePaths",
")",
"==",
"0",
":",
"return",
"\"Unnamed Seri... | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/DICOMLib/DICOMPlugin.py#L149-L162 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/setup.py | python | visibility_define | (config) | Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string). | Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string). | [
"Return",
"the",
"define",
"value",
"to",
"use",
"for",
"NPY_VISIBILITY_HIDDEN",
"(",
"may",
"be",
"empty",
"string",
")",
"."
] | def visibility_define(config):
"""Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string)."""
if config.check_compiler_gcc4():
return '__attribute__((visibility("hidden")))'
else:
return '' | [
"def",
"visibility_define",
"(",
"config",
")",
":",
"if",
"config",
".",
"check_compiler_gcc4",
"(",
")",
":",
"return",
"'__attribute__((visibility(\"hidden\")))'",
"else",
":",
"return",
"''"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/setup.py#L384-L390 | ||
lightvector/KataGo | 20d34784703c5b4000643d3ccc43bb37d418f3b5 | python/sgfmill/sgf.py | python | Node.set_setup_stones | (self, black, white, empty=None) | Set Add Black / Add White / Add Empty properties.
black, white, empty -- list or set of pairs (row, col)
Removes any existing AB/AW/AE properties from the node. | Set Add Black / Add White / Add Empty properties. | [
"Set",
"Add",
"Black",
"/",
"Add",
"White",
"/",
"Add",
"Empty",
"properties",
"."
] | def set_setup_stones(self, black, white, empty=None):
"""Set Add Black / Add White / Add Empty properties.
black, white, empty -- list or set of pairs (row, col)
Removes any existing AB/AW/AE properties from the node.
"""
if 'AB' in self._property_map:
del self._property_map['AB']
if 'AW' in self._property_map:
del self._property_map['AW']
if 'AE' in self._property_map:
del self._property_map['AE']
if black:
self.set('AB', black)
if white:
self.set('AW', white)
if empty:
self.set('AE', empty) | [
"def",
"set_setup_stones",
"(",
"self",
",",
"black",
",",
"white",
",",
"empty",
"=",
"None",
")",
":",
"if",
"'AB'",
"in",
"self",
".",
"_property_map",
":",
"del",
"self",
".",
"_property_map",
"[",
"'AB'",
"]",
"if",
"'AW'",
"in",
"self",
".",
"_... | https://github.com/lightvector/KataGo/blob/20d34784703c5b4000643d3ccc43bb37d418f3b5/python/sgfmill/sgf.py#L280-L299 | ||
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/vqs/base.py | python | variables | (self) | return flax.core.freeze({"params": self.parameters, **self.model_state}) | r"""The PyTreee containing the paramters and state of the model,
used when evaluating it. | r"""The PyTreee containing the paramters and state of the model,
used when evaluating it. | [
"r",
"The",
"PyTreee",
"containing",
"the",
"paramters",
"and",
"state",
"of",
"the",
"model",
"used",
"when",
"evaluating",
"it",
"."
] | def variables(self) -> PyTree:
r"""The PyTreee containing the paramters and state of the model,
used when evaluating it.
"""
return flax.core.freeze({"params": self.parameters, **self.model_state}) | [
"def",
"variables",
"(",
"self",
")",
"->",
"PyTree",
":",
"return",
"flax",
".",
"core",
".",
"freeze",
"(",
"{",
"\"params\"",
":",
"self",
".",
"parameters",
",",
"*",
"*",
"self",
".",
"model_state",
"}",
")"
] | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/vqs/base.py#L102-L106 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_gui.py | python | GuiDomain.screenshot | (self, viewID, filename, width=-1, height=-1) | screenshot(string, string, int, int) -> None
Save a screenshot for the given view to the given filename
at the next call to simulationStep.
The fileformat is guessed from the extension, the available
formats differ from platform to platform but should at least
include ps, svg and pdf, on linux probably gif, png and jpg as well.
Width and height of the image can be given as optional parameters. | screenshot(string, string, int, int) -> None | [
"screenshot",
"(",
"string",
"string",
"int",
"int",
")",
"-",
">",
"None"
] | def screenshot(self, viewID, filename, width=-1, height=-1):
"""screenshot(string, string, int, int) -> None
Save a screenshot for the given view to the given filename
at the next call to simulationStep.
The fileformat is guessed from the extension, the available
formats differ from platform to platform but should at least
include ps, svg and pdf, on linux probably gif, png and jpg as well.
Width and height of the image can be given as optional parameters.
"""
self._setCmd(tc.VAR_SCREENSHOT, viewID, "tsii", 3, filename, width, height) | [
"def",
"screenshot",
"(",
"self",
",",
"viewID",
",",
"filename",
",",
"width",
"=",
"-",
"1",
",",
"height",
"=",
"-",
"1",
")",
":",
"self",
".",
"_setCmd",
"(",
"tc",
".",
"VAR_SCREENSHOT",
",",
"viewID",
",",
"\"tsii\"",
",",
"3",
",",
"filenam... | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_gui.py#L93-L103 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/TaskGen.py | python | task_gen.get_name | (self) | If not set, the name is computed from the target name::
def build(bld):
x = bld(name='foo')
x.get_name() # foo
y = bld(target='bar')
y.get_name() # bar
:rtype: string
:return: name of this task generator | If not set, the name is computed from the target name:: | [
"If",
"not",
"set",
"the",
"name",
"is",
"computed",
"from",
"the",
"target",
"name",
"::"
] | def get_name(self):
"""
If not set, the name is computed from the target name::
def build(bld):
x = bld(name='foo')
x.get_name() # foo
y = bld(target='bar')
y.get_name() # bar
:rtype: string
:return: name of this task generator
"""
try:
return self._name
except AttributeError:
if isinstance(self.target, list):
lst = [str(x) for x in self.target]
name = self._name = ','.join(lst)
else:
name = self._name = str(self.target)
return name | [
"def",
"get_name",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_name",
"except",
"AttributeError",
":",
"if",
"isinstance",
"(",
"self",
".",
"target",
",",
"list",
")",
":",
"lst",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/TaskGen.py#L104-L125 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/mixture/gaussian_mixture.py | python | _compute_log_det_cholesky | (matrix_chol, covariance_type, n_features) | return log_det_chol | Compute the log-det of the cholesky decomposition of matrices.
Parameters
----------
matrix_chol : array-like,
Cholesky decompositions of the matrices.
'full' : shape of (n_components, n_features, n_features)
'tied' : shape of (n_features, n_features)
'diag' : shape of (n_components, n_features)
'spherical' : shape of (n_components,)
covariance_type : {'full', 'tied', 'diag', 'spherical'}
n_features : int
Number of features.
Returns
-------
log_det_precision_chol : array-like, shape (n_components,)
The determinant of the precision matrix for each component. | Compute the log-det of the cholesky decomposition of matrices. | [
"Compute",
"the",
"log",
"-",
"det",
"of",
"the",
"cholesky",
"decomposition",
"of",
"matrices",
"."
] | def _compute_log_det_cholesky(matrix_chol, covariance_type, n_features):
"""Compute the log-det of the cholesky decomposition of matrices.
Parameters
----------
matrix_chol : array-like,
Cholesky decompositions of the matrices.
'full' : shape of (n_components, n_features, n_features)
'tied' : shape of (n_features, n_features)
'diag' : shape of (n_components, n_features)
'spherical' : shape of (n_components,)
covariance_type : {'full', 'tied', 'diag', 'spherical'}
n_features : int
Number of features.
Returns
-------
log_det_precision_chol : array-like, shape (n_components,)
The determinant of the precision matrix for each component.
"""
if covariance_type == 'full':
n_components, _, _ = matrix_chol.shape
log_det_chol = (np.sum(np.log(
matrix_chol.reshape(
n_components, -1)[:, ::n_features + 1]), 1))
elif covariance_type == 'tied':
log_det_chol = (np.sum(np.log(np.diag(matrix_chol))))
elif covariance_type == 'diag':
log_det_chol = (np.sum(np.log(matrix_chol), axis=1))
else:
log_det_chol = n_features * (np.log(matrix_chol))
return log_det_chol | [
"def",
"_compute_log_det_cholesky",
"(",
"matrix_chol",
",",
"covariance_type",
",",
"n_features",
")",
":",
"if",
"covariance_type",
"==",
"'full'",
":",
"n_components",
",",
"_",
",",
"_",
"=",
"matrix_chol",
".",
"shape",
"log_det_chol",
"=",
"(",
"np",
"."... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/mixture/gaussian_mixture.py#L341-L378 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/algorithms/sfm/OpenSfM/opensfm/transformations.py | python | rotation_from_matrix | (matrix) | return angle, direction, point | Return rotation angle and axis from rotation matrix.
>>> angle = (numpy.random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> angle, direc, point = rotation_from_matrix(R0)
>>> R1 = rotation_matrix(angle, direc, point)
>>> is_same_transform(R0, R1)
True | Return rotation angle and axis from rotation matrix. | [
"Return",
"rotation",
"angle",
"and",
"axis",
"from",
"rotation",
"matrix",
"."
] | def rotation_from_matrix(matrix):
"""Return rotation angle and axis from rotation matrix.
>>> angle = (numpy.random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> angle, direc, point = rotation_from_matrix(R0)
>>> R1 = rotation_matrix(angle, direc, point)
>>> is_same_transform(R0, R1)
True
"""
R = numpy.array(matrix, dtype=numpy.float64, copy=False)
R33 = R[:3, :3]
# direction: unit eigenvector of R33 corresponding to eigenvalue of 1
w, W = numpy.linalg.eig(R33.T)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-6)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
direction = numpy.real(W[:, i[-1]]).squeeze()
# point: unit eigenvector of R33 corresponding to eigenvalue of 1
w, Q = numpy.linalg.eig(R)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-6)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
point = numpy.real(Q[:, i[-1]]).squeeze()
point /= point[3]
# rotation angle depending on direction
cosa = (numpy.trace(R33) - 1.0) / 2.0
if abs(direction[2]) > 1e-8:
sina = (R[1, 0] + (cosa-1.0)*direction[0]*direction[1]) / direction[2]
elif abs(direction[1]) > 1e-8:
sina = (R[0, 2] + (cosa-1.0)*direction[0]*direction[2]) / direction[1]
else:
sina = (R[2, 1] + (cosa-1.0)*direction[1]*direction[2]) / direction[0]
angle = math.atan2(sina, cosa)
return angle, direction, point | [
"def",
"rotation_from_matrix",
"(",
"matrix",
")",
":",
"R",
"=",
"numpy",
".",
"array",
"(",
"matrix",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"False",
")",
"R33",
"=",
"R",
"[",
":",
"3",
",",
":",
"3",
"]",
"# direction: un... | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/transformations.py#L339-L376 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/engine/training.py | python | _standardize_sample_or_class_weights | (x_weight, output_names, weight_type) | Maps `sample_weight` or `class_weight` to model outputs.
Arguments:
x_weight: User-provided `sample_weight` or `class_weight` argument.
output_names: List of output names (strings) in the model.
weight_type: A string used purely for exception printing.
Returns:
A list of `sample_weight` or `class_weight` where there are exactly
one element per model output.
Raises:
ValueError: In case of invalid user-provided argument. | Maps `sample_weight` or `class_weight` to model outputs. | [
"Maps",
"sample_weight",
"or",
"class_weight",
"to",
"model",
"outputs",
"."
] | def _standardize_sample_or_class_weights(x_weight, output_names, weight_type):
"""Maps `sample_weight` or `class_weight` to model outputs.
Arguments:
x_weight: User-provided `sample_weight` or `class_weight` argument.
output_names: List of output names (strings) in the model.
weight_type: A string used purely for exception printing.
Returns:
A list of `sample_weight` or `class_weight` where there are exactly
one element per model output.
Raises:
ValueError: In case of invalid user-provided argument.
"""
if x_weight is None or len(x_weight) == 0: # pylint: disable=g-explicit-length-test
return [None for _ in output_names]
if len(output_names) == 1:
if isinstance(x_weight, list) and len(x_weight) == 1:
return x_weight
if isinstance(x_weight, dict) and output_names[0] in x_weight:
return [x_weight[output_names[0]]]
else:
return [x_weight]
if isinstance(x_weight, list):
if len(x_weight) != len(output_names):
raise ValueError('Provided `' + weight_type + '` was a list of ' +
str(len(x_weight)) + ' elements, but the model has ' +
str(len(output_names)) + ' outputs. '
'You should provide one `' + weight_type + '`'
'array per model output.')
return x_weight
if isinstance(x_weight, dict):
x_weights = []
for name in output_names:
x_weights.append(x_weight.get(name))
return x_weights
else:
raise TypeError('The model has multiple outputs, so `' + weight_type + '` '
'should be either a list of a dict. '
'Provided `' + weight_type + '` type not understood: ' +
str(x_weight)) | [
"def",
"_standardize_sample_or_class_weights",
"(",
"x_weight",
",",
"output_names",
",",
"weight_type",
")",
":",
"if",
"x_weight",
"is",
"None",
"or",
"len",
"(",
"x_weight",
")",
"==",
"0",
":",
"# pylint: disable=g-explicit-length-test",
"return",
"[",
"None",
... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/engine/training.py#L147-L188 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/invert_ds.py | python | _invert_ds_tbe | () | return | Invert TBE register | Invert TBE register | [
"Invert",
"TBE",
"register"
] | def _invert_ds_tbe():
"""Invert TBE register"""
return | [
"def",
"_invert_ds_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/invert_ds.py#L36-L38 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/node/base.py | python | Node.IsTranslateable | (self) | Returns false if the node has contents that should not be translated,
otherwise returns false (even if the node has no contents). | Returns false if the node has contents that should not be translated,
otherwise returns false (even if the node has no contents). | [
"Returns",
"false",
"if",
"the",
"node",
"has",
"contents",
"that",
"should",
"not",
"be",
"translated",
"otherwise",
"returns",
"false",
"(",
"even",
"if",
"the",
"node",
"has",
"no",
"contents",
")",
"."
] | def IsTranslateable(self):
'''Returns false if the node has contents that should not be translated,
otherwise returns false (even if the node has no contents).
'''
if not 'translateable' in self.attrs:
return True
else:
return self.attrs['translateable'] == 'true' | [
"def",
"IsTranslateable",
"(",
"self",
")",
":",
"if",
"not",
"'translateable'",
"in",
"self",
".",
"attrs",
":",
"return",
"True",
"else",
":",
"return",
"self",
".",
"attrs",
"[",
"'translateable'",
"]",
"==",
"'true'"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/node/base.py#L407-L414 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/fromnumeric.py | python | argsort | (a, axis=-1, kind='quicksort', order=None) | return argsort(axis, kind, order) | Returns the indices that would sort an array.
Perform an indirect sort along the given axis using the algorithm specified
by the `kind` keyword. It returns an array of indices of the same shape as
`a` that index data along the given axis in sorted order.
Parameters
----------
a : array_like
Array to sort.
axis : int or None, optional
Axis along which to sort. The default is -1 (the last axis). If None,
the flattened array is used.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
order : list, optional
When `a` is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified.
Returns
-------
index_array : ndarray, int
Array of indices that sort `a` along the specified axis.
In other words, ``a[index_array]`` yields a sorted `a`.
See Also
--------
sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
argpartition : Indirect partial sort.
Notes
-----
See `sort` for notes on the different sorting algorithms.
As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
nan values. The enhanced sort order is documented in `sort`.
Examples
--------
One dimensional array:
>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])
Two-dimensional array:
>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
[2, 2]])
>>> np.argsort(x, axis=0)
array([[0, 1],
[1, 0]])
>>> np.argsort(x, axis=1)
array([[0, 1],
[0, 1]])
Sorting with keys:
>>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> x
array([(1, 0), (0, 1)],
dtype=[('x', '<i4'), ('y', '<i4')])
>>> np.argsort(x, order=('x','y'))
array([1, 0])
>>> np.argsort(x, order=('y','x'))
array([0, 1]) | Returns the indices that would sort an array. | [
"Returns",
"the",
"indices",
"that",
"would",
"sort",
"an",
"array",
"."
] | def argsort(a, axis=-1, kind='quicksort', order=None):
"""
Returns the indices that would sort an array.
Perform an indirect sort along the given axis using the algorithm specified
by the `kind` keyword. It returns an array of indices of the same shape as
`a` that index data along the given axis in sorted order.
Parameters
----------
a : array_like
Array to sort.
axis : int or None, optional
Axis along which to sort. The default is -1 (the last axis). If None,
the flattened array is used.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
order : list, optional
When `a` is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified.
Returns
-------
index_array : ndarray, int
Array of indices that sort `a` along the specified axis.
In other words, ``a[index_array]`` yields a sorted `a`.
See Also
--------
sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
argpartition : Indirect partial sort.
Notes
-----
See `sort` for notes on the different sorting algorithms.
As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
nan values. The enhanced sort order is documented in `sort`.
Examples
--------
One dimensional array:
>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])
Two-dimensional array:
>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
[2, 2]])
>>> np.argsort(x, axis=0)
array([[0, 1],
[1, 0]])
>>> np.argsort(x, axis=1)
array([[0, 1],
[0, 1]])
Sorting with keys:
>>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> x
array([(1, 0), (0, 1)],
dtype=[('x', '<i4'), ('y', '<i4')])
>>> np.argsort(x, order=('x','y'))
array([1, 0])
>>> np.argsort(x, order=('y','x'))
array([0, 1])
"""
try:
argsort = a.argsort
except AttributeError:
return _wrapit(a, 'argsort', axis, kind, order)
return argsort(axis, kind, order) | [
"def",
"argsort",
"(",
"a",
",",
"axis",
"=",
"-",
"1",
",",
"kind",
"=",
"'quicksort'",
",",
"order",
"=",
"None",
")",
":",
"try",
":",
"argsort",
"=",
"a",
".",
"argsort",
"except",
"AttributeError",
":",
"return",
"_wrapit",
"(",
"a",
",",
"'ar... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/fromnumeric.py#L792-L875 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/xml/sax/xmlreader.py | python | InputSource.setEncoding | (self, encoding) | Sets the character encoding of this InputSource.
The encoding must be a string acceptable for an XML encoding
declaration (see section 4.3.3 of the XML recommendation).
The encoding attribute of the InputSource is ignored if the
InputSource also contains a character stream. | Sets the character encoding of this InputSource. | [
"Sets",
"the",
"character",
"encoding",
"of",
"this",
"InputSource",
"."
] | def setEncoding(self, encoding):
"""Sets the character encoding of this InputSource.
The encoding must be a string acceptable for an XML encoding
declaration (see section 4.3.3 of the XML recommendation).
The encoding attribute of the InputSource is ignored if the
InputSource also contains a character stream."""
self.__encoding = encoding | [
"def",
"setEncoding",
"(",
"self",
",",
"encoding",
")",
":",
"self",
".",
"__encoding",
"=",
"encoding"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xml/sax/xmlreader.py#L228-L236 | ||
Tencent/TNN | 7acca99f54c55747b415a4c57677403eebc7b706 | third_party/flatbuffers/grpc/examples/python/greeter/models/HelloRequest.py | python | HelloRequest.GetRootAsHelloRequest | (cls, buf, offset=0) | return cls.GetRootAs(buf, offset) | This method is deprecated. Please switch to GetRootAs. | This method is deprecated. Please switch to GetRootAs. | [
"This",
"method",
"is",
"deprecated",
".",
"Please",
"switch",
"to",
"GetRootAs",
"."
] | def GetRootAsHelloRequest(cls, buf, offset=0):
"""This method is deprecated. Please switch to GetRootAs."""
return cls.GetRootAs(buf, offset) | [
"def",
"GetRootAsHelloRequest",
"(",
"cls",
",",
"buf",
",",
"offset",
"=",
"0",
")",
":",
"return",
"cls",
".",
"GetRootAs",
"(",
"buf",
",",
"offset",
")"
] | https://github.com/Tencent/TNN/blob/7acca99f54c55747b415a4c57677403eebc7b706/third_party/flatbuffers/grpc/examples/python/greeter/models/HelloRequest.py#L20-L22 | |
alibaba/graph-learn | 54cafee9db3054dc310a28b856be7f97c7d5aee9 | graphlearn/python/nn/subgraph.py | python | SubGraph.apply | (self, func) | return self | Applies the function `func` to all attributes. | Applies the function `func` to all attributes. | [
"Applies",
"the",
"function",
"func",
"to",
"all",
"attributes",
"."
] | def apply(self, func):
"""Applies the function `func` to all attributes.
"""
for k, v in self.__dict__.items():
if v is not None and k[:2] != '__' and k[-2:] != '__':
self.__dict__[k] = func(v)
return self | [
"def",
"apply",
"(",
"self",
",",
"func",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"not",
"None",
"and",
"k",
"[",
":",
"2",
"]",
"!=",
"'__'",
"and",
"k",
"[",
"-",
"2",
... | https://github.com/alibaba/graph-learn/blob/54cafee9db3054dc310a28b856be7f97c7d5aee9/graphlearn/python/nn/subgraph.py#L73-L79 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/linalg/linear_operator.py | python | LinearOperator._assert_non_singular | (self) | Private default implementation of _assert_non_singular. | Private default implementation of _assert_non_singular. | [
"Private",
"default",
"implementation",
"of",
"_assert_non_singular",
"."
] | def _assert_non_singular(self):
"""Private default implementation of _assert_non_singular."""
logging.warn(
"Using (possibly slow) default implementation of assert_non_singular."
" Requires conversion to a dense matrix and O(N^3) operations.")
if self._can_use_cholesky():
return self.assert_positive_definite()
else:
singular_values = linalg_ops.svd(
self._get_cached_dense_matrix(), compute_uv=False)
# TODO(langmore) Add .eig and .cond as methods.
cond = (math_ops.reduce_max(singular_values, axis=-1) /
math_ops.reduce_min(singular_values, axis=-1))
return check_ops.assert_less(
cond,
self._max_condition_number_to_be_non_singular(),
message="Singular matrix up to precision epsilon.")
raise NotImplementedError("assert_non_singular is not implemented.") | [
"def",
"_assert_non_singular",
"(",
"self",
")",
":",
"logging",
".",
"warn",
"(",
"\"Using (possibly slow) default implementation of assert_non_singular.\"",
"\" Requires conversion to a dense matrix and O(N^3) operations.\"",
")",
"if",
"self",
".",
"_can_use_cholesky",
"(",
"... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/linalg/linear_operator.py#L464-L481 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.