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
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/amp/grad_scaler.py
python
GradScaler.scale
(self, var)
return super(GradScaler, self).scale(var)
Multiplies a Tensor by the scale factor and returns scaled outputs. If this instance of :class:`GradScaler` is not enabled, output are returned unmodified. Args: var (Tensor): The tensor to scale. Returns: The scaled tensor or original tensor. Examples: .. code-block:: python import paddle model = paddle.nn.Conv2D(3, 2, 3, bias_attr=True) optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) scaler = paddle.amp.GradScaler(init_loss_scaling=1024) data = paddle.rand([10, 3, 32, 32]) with paddle.amp.auto_cast(): conv = model(data) loss = paddle.mean(conv) scaled = scaler.scale(loss) # scale the loss scaled.backward() # do backward scaler.minimize(optimizer, scaled) # update parameters optimizer.clear_grad()
Multiplies a Tensor by the scale factor and returns scaled outputs. If this instance of :class:`GradScaler` is not enabled, output are returned unmodified.
[ "Multiplies", "a", "Tensor", "by", "the", "scale", "factor", "and", "returns", "scaled", "outputs", ".", "If", "this", "instance", "of", ":", "class", ":", "GradScaler", "is", "not", "enabled", "output", "are", "returned", "unmodified", "." ]
def scale(self, var): """ Multiplies a Tensor by the scale factor and returns scaled outputs. If this instance of :class:`GradScaler` is not enabled, output are returned unmodified. Args: var (Tensor): The tensor to scale. Returns: The scaled tensor or original tensor. Examples: .. code-block:: python import paddle model = paddle.nn.Conv2D(3, 2, 3, bias_attr=True) optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) scaler = paddle.amp.GradScaler(init_loss_scaling=1024) data = paddle.rand([10, 3, 32, 32]) with paddle.amp.auto_cast(): conv = model(data) loss = paddle.mean(conv) scaled = scaler.scale(loss) # scale the loss scaled.backward() # do backward scaler.minimize(optimizer, scaled) # update parameters optimizer.clear_grad() """ return super(GradScaler, self).scale(var)
[ "def", "scale", "(", "self", ",", "var", ")", ":", "return", "super", "(", "GradScaler", ",", "self", ")", ".", "scale", "(", "var", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/amp/grad_scaler.py#L91-L121
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/math_ops.py
python
reduce_any
(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None)
return gen_math_ops._any( input_tensor, _ReductionDims(input_tensor, axis, reduction_indices), keep_dims, name=name)
Computes the "logical or" of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `axis` has no entries, all dimensions are reduced, and a tensor with a single element is returned. For example: ```python x = tf.constant([[True, True], [False, False]]) tf.reduce_any(x) # True tf.reduce_any(x, 0) # [True, True] tf.reduce_any(x, 1) # [True, False] ``` Args: input_tensor: The boolean tensor to reduce. axis: The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor))`. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). reduction_indices: The old (deprecated) name for axis. Returns: The reduced tensor. @compatibility(numpy) Equivalent to np.any @end_compatibility
Computes the "logical or" of elements across dimensions of a tensor.
[ "Computes", "the", "logical", "or", "of", "elements", "across", "dimensions", "of", "a", "tensor", "." ]
def reduce_any(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None): """Computes the "logical or" of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `axis`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `axis`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `axis` has no entries, all dimensions are reduced, and a tensor with a single element is returned. For example: ```python x = tf.constant([[True, True], [False, False]]) tf.reduce_any(x) # True tf.reduce_any(x, 0) # [True, True] tf.reduce_any(x, 1) # [True, False] ``` Args: input_tensor: The boolean tensor to reduce. axis: The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor))`. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). reduction_indices: The old (deprecated) name for axis. Returns: The reduced tensor. @compatibility(numpy) Equivalent to np.any @end_compatibility """ return gen_math_ops._any( input_tensor, _ReductionDims(input_tensor, axis, reduction_indices), keep_dims, name=name)
[ "def", "reduce_any", "(", "input_tensor", ",", "axis", "=", "None", ",", "keep_dims", "=", "False", ",", "name", "=", "None", ",", "reduction_indices", "=", "None", ")", ":", "return", "gen_math_ops", ".", "_any", "(", "input_tensor", ",", "_ReductionDims", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/math_ops.py#L1581-L1625
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Tools/tex.py
python
tex.bibtopic
(self)
Additional .aux files from the bibtopic package
Additional .aux files from the bibtopic package
[ "Additional", ".", "aux", "files", "from", "the", "bibtopic", "package" ]
def bibtopic(self): """ Additional .aux files from the bibtopic package """ p = self.inputs[0].parent.get_bld() if os.path.exists(os.path.join(p.abspath(), 'btaux.aux')): self.aux_nodes += p.ant_glob('*[0-9].aux')
[ "def", "bibtopic", "(", "self", ")", ":", "p", "=", "self", ".", "inputs", "[", "0", "]", ".", "parent", ".", "get_bld", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "p", ".", "abspath", "(", ")"...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/tex.py#L258-L264
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/swift_build_support/swift_build_support/products/swiftdocc.py
python
SwiftDocC.product_source_name
(cls)
return "swift-docc"
product_source_name() -> str The name of the source code directory of this product.
product_source_name() -> str
[ "product_source_name", "()", "-", ">", "str" ]
def product_source_name(cls): """product_source_name() -> str The name of the source code directory of this product. """ return "swift-docc"
[ "def", "product_source_name", "(", "cls", ")", ":", "return", "\"swift-docc\"" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/swift_build_support/swift_build_support/products/swiftdocc.py#L34-L39
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/flip-game.py
python
Solution.generatePossibleNextMoves
(self, s)
return res
:type s: str :rtype: List[str]
:type s: str :rtype: List[str]
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "List", "[", "str", "]" ]
def generatePossibleNextMoves(self, s): """ :type s: str :rtype: List[str] """ res = [] i, n = 0, len(s) - 1 while i < n: # O(n) time if s[i] == '+': while i < n and s[i+1] == '+': # O(c) time res.append(s[:i] + '--' + s[i+2:]) # O(n) time and space i += 1 i += 1 return res
[ "def", "generatePossibleNextMoves", "(", "self", ",", "s", ")", ":", "res", "=", "[", "]", "i", ",", "n", "=", "0", ",", "len", "(", "s", ")", "-", "1", "while", "i", "<", "n", ":", "# O(n) time", "if", "s", "[", "i", "]", "==", "'+'", ":", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/flip-game.py#L5-L18
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/simple_httpclient.py
python
SimpleAsyncHTTPClient.initialize
( # type: ignore self, max_clients: int = 10, hostname_mapping: Optional[Dict[str, str]] = None, max_buffer_size: int = 104857600, resolver: Optional[Resolver] = None, defaults: Optional[Dict[str, Any]] = None, max_header_size: Optional[int] = None, max_body_size: Optional[int] = None, )
Creates a AsyncHTTPClient. Only a single AsyncHTTPClient instance exists per IOLoop in order to provide limitations on the number of pending connections. ``force_instance=True`` may be used to suppress this behavior. Note that because of this implicit reuse, unless ``force_instance`` is used, only the first call to the constructor actually uses its arguments. It is recommended to use the ``configure`` method instead of the constructor to ensure that arguments take effect. ``max_clients`` is the number of concurrent requests that can be in progress; when this limit is reached additional requests will be queued. Note that time spent waiting in this queue still counts against the ``request_timeout``. ``hostname_mapping`` is a dictionary mapping hostnames to IP addresses. It can be used to make local DNS changes when modifying system-wide settings like ``/etc/hosts`` is not possible or desirable (e.g. in unittests). ``max_buffer_size`` (default 100MB) is the number of bytes that can be read into memory at once. ``max_body_size`` (defaults to ``max_buffer_size``) is the largest response body that the client will accept. Without a ``streaming_callback``, the smaller of these two limits applies; with a ``streaming_callback`` only ``max_body_size`` does. .. versionchanged:: 4.2 Added the ``max_body_size`` argument.
Creates a AsyncHTTPClient.
[ "Creates", "a", "AsyncHTTPClient", "." ]
def initialize( # type: ignore self, max_clients: int = 10, hostname_mapping: Optional[Dict[str, str]] = None, max_buffer_size: int = 104857600, resolver: Optional[Resolver] = None, defaults: Optional[Dict[str, Any]] = None, max_header_size: Optional[int] = None, max_body_size: Optional[int] = None, ) -> None: """Creates a AsyncHTTPClient. Only a single AsyncHTTPClient instance exists per IOLoop in order to provide limitations on the number of pending connections. ``force_instance=True`` may be used to suppress this behavior. Note that because of this implicit reuse, unless ``force_instance`` is used, only the first call to the constructor actually uses its arguments. It is recommended to use the ``configure`` method instead of the constructor to ensure that arguments take effect. ``max_clients`` is the number of concurrent requests that can be in progress; when this limit is reached additional requests will be queued. Note that time spent waiting in this queue still counts against the ``request_timeout``. ``hostname_mapping`` is a dictionary mapping hostnames to IP addresses. It can be used to make local DNS changes when modifying system-wide settings like ``/etc/hosts`` is not possible or desirable (e.g. in unittests). ``max_buffer_size`` (default 100MB) is the number of bytes that can be read into memory at once. ``max_body_size`` (defaults to ``max_buffer_size``) is the largest response body that the client will accept. Without a ``streaming_callback``, the smaller of these two limits applies; with a ``streaming_callback`` only ``max_body_size`` does. .. versionchanged:: 4.2 Added the ``max_body_size`` argument. """ super().initialize(defaults=defaults) self.max_clients = max_clients self.queue = ( collections.deque() ) # type: Deque[Tuple[object, HTTPRequest, Callable[[HTTPResponse], None]]] self.active = ( {} ) # type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None]]] self.waiting = ( {} ) # type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None], object]] self.max_buffer_size = max_buffer_size self.max_header_size = max_header_size self.max_body_size = max_body_size # TCPClient could create a Resolver for us, but we have to do it # ourselves to support hostname_mapping. if resolver: self.resolver = resolver self.own_resolver = False else: self.resolver = Resolver() self.own_resolver = True if hostname_mapping is not None: self.resolver = OverrideResolver( resolver=self.resolver, mapping=hostname_mapping ) self.tcp_client = TCPClient(resolver=self.resolver)
[ "def", "initialize", "(", "# type: ignore", "self", ",", "max_clients", ":", "int", "=", "10", ",", "hostname_mapping", ":", "Optional", "[", "Dict", "[", "str", ",", "str", "]", "]", "=", "None", ",", "max_buffer_size", ":", "int", "=", "104857600", ","...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/simple_httpclient.py#L89-L157
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/email/parser.py
python
Parser.__init__
(self, _class=None, *, policy=compat32)
Parser of RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the textual representation of the message. The string must be formatted as a block of RFC 2822 headers and header continuation lines, optionally preceded by a `Unix-from' header. The header block is terminated either by the end of the string or by a blank line. _class is the class to instantiate for new message objects when they must be created. This class must have a constructor that can take zero arguments. Default is Message.Message. The policy keyword specifies a policy object that controls a number of aspects of the parser's operation. The default policy maintains backward compatibility.
Parser of RFC 2822 and MIME email messages.
[ "Parser", "of", "RFC", "2822", "and", "MIME", "email", "messages", "." ]
def __init__(self, _class=None, *, policy=compat32): """Parser of RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the textual representation of the message. The string must be formatted as a block of RFC 2822 headers and header continuation lines, optionally preceded by a `Unix-from' header. The header block is terminated either by the end of the string or by a blank line. _class is the class to instantiate for new message objects when they must be created. This class must have a constructor that can take zero arguments. Default is Message.Message. The policy keyword specifies a policy object that controls a number of aspects of the parser's operation. The default policy maintains backward compatibility. """ self._class = _class self.policy = policy
[ "def", "__init__", "(", "self", ",", "_class", "=", "None", ",", "*", ",", "policy", "=", "compat32", ")", ":", "self", ".", "_class", "=", "_class", "self", ".", "policy", "=", "policy" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/parser.py#L17-L39
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/third_party/Python/module/pexpect-2.4/FSM.py
python
FSM.__init__
(self, initial_state, memory=None)
This creates the FSM. You set the initial state here. The "memory" attribute is any object that you want to pass along to the action functions. It is not used by the FSM. For parsing you would typically pass a list to be used as a stack.
This creates the FSM. You set the initial state here. The "memory" attribute is any object that you want to pass along to the action functions. It is not used by the FSM. For parsing you would typically pass a list to be used as a stack.
[ "This", "creates", "the", "FSM", ".", "You", "set", "the", "initial", "state", "here", ".", "The", "memory", "attribute", "is", "any", "object", "that", "you", "want", "to", "pass", "along", "to", "the", "action", "functions", ".", "It", "is", "not", "...
def __init__(self, initial_state, memory=None): """This creates the FSM. You set the initial state here. The "memory" attribute is any object that you want to pass along to the action functions. It is not used by the FSM. For parsing you would typically pass a list to be used as a stack. """ # Map (input_symbol, current_state) --> (action, next_state). self.state_transitions = {} # Map (current_state) --> (action, next_state). self.state_transitions_any = {} self.default_transition = None self.input_symbol = None self.initial_state = initial_state self.current_state = self.initial_state self.next_state = None self.action = None self.memory = memory
[ "def", "__init__", "(", "self", ",", "initial_state", ",", "memory", "=", "None", ")", ":", "# Map (input_symbol, current_state) --> (action, next_state).", "self", ".", "state_transitions", "=", "{", "}", "# Map (current_state) --> (action, next_state).", "self", ".", "s...
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/FSM.py#L86-L103
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/util/fslike/path.py
python
Path.open
(self, mode="r")
return TextIOWrapper(handle)
Opens the file at this path; returns a file-like object.
Opens the file at this path; returns a file-like object.
[ "Opens", "the", "file", "at", "this", "path", ";", "returns", "a", "file", "-", "like", "object", "." ]
def open(self, mode="r"): """ Opens the file at this path; returns a file-like object. """ dmode = mode.replace("b", "") if dmode == "r": handle = self.fsobj.open_r(self.parts) elif dmode == "w": handle = self.fsobj.open_w(self.parts) elif dmode in ("r+", "rw"): handle = self.fsobj.open_rw(self.parts) elif dmode == "a": handle = self.fsobj.open_a(self.parts) elif dmode in ("a+", "ar"): handle = self.fsobj.open_ar(self.parts) else: raise UnsupportedOperation("unsupported open mode: " + mode) if "b" in mode: return handle return TextIOWrapper(handle)
[ "def", "open", "(", "self", ",", "mode", "=", "\"r\"", ")", ":", "dmode", "=", "mode", ".", "replace", "(", "\"b\"", ",", "\"\"", ")", "if", "dmode", "==", "\"r\"", ":", "handle", "=", "self", ".", "fsobj", ".", "open_r", "(", "self", ".", "parts...
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/fslike/path.py#L106-L132
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/transport.py
python
Rpc.__init__
(self, request)
Constructor. Args: request: Request associated with this RPC.
Constructor.
[ "Constructor", "." ]
def __init__(self, request): """Constructor. Args: request: Request associated with this RPC. """ self.__request = request self.__response = None self.__state = remote.RpcState.RUNNING self.__error_message = None self.__error_name = None
[ "def", "__init__", "(", "self", ",", "request", ")", ":", "self", ".", "__request", "=", "request", "self", ".", "__response", "=", "None", "self", ".", "__state", "=", "remote", ".", "RpcState", ".", "RUNNING", "self", ".", "__error_message", "=", "None...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/transport.py#L61-L71
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/demand/vehicles.py
python
VehicleTypes.select_by_mode
(self, id_mode=None, mode=None, is_sumoid=False, is_share=False)
Returns a list with all vehice ids from a given mode. If is_share is True then also a list with the respective shares for each type is returned.
Returns a list with all vehice ids from a given mode. If is_share is True then also a list with the respective shares for each type is returned.
[ "Returns", "a", "list", "with", "all", "vehice", "ids", "from", "a", "given", "mode", ".", "If", "is_share", "is", "True", "then", "also", "a", "list", "with", "the", "respective", "shares", "for", "each", "type", "is", "returned", "." ]
def select_by_mode(self, id_mode=None, mode=None, is_sumoid=False, is_share=False): """ Returns a list with all vehice ids from a given mode. If is_share is True then also a list with the respective shares for each type is returned. """ if id_mode is None: id_mode = MODES[mode] # print 'select_by_mode',id_mode, mode # print ' ids',self.get_ids() # print ' ids_mode',self.ids_mode[self.get_ids()] ids = self.select_ids(self.ids_mode.get_value() == id_mode) #print ' ids_type',self.ids_sumo[ids]# # print ' ids_mode',self.ids_mode.get_value() if is_sumoid: idval = self.ids_sumo[ids] else: idval = ids if is_share: return idval, self.shares_in_mode[ids] else: return idval
[ "def", "select_by_mode", "(", "self", ",", "id_mode", "=", "None", ",", "mode", "=", "None", ",", "is_sumoid", "=", "False", ",", "is_share", "=", "False", ")", ":", "if", "id_mode", "is", "None", ":", "id_mode", "=", "MODES", "[", "mode", "]", "# pr...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/vehicles.py#L1327-L1352
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py
python
Context.exp
(self, a)
return a.exp(context=self)
Returns e ** a. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.exp(Decimal('-Infinity')) Decimal('0') >>> c.exp(Decimal('-1')) Decimal('0.367879441') >>> c.exp(Decimal('0')) Decimal('1') >>> c.exp(Decimal('1')) Decimal('2.71828183') >>> c.exp(Decimal('0.693147181')) Decimal('2.00000000') >>> c.exp(Decimal('+Infinity')) Decimal('Infinity') >>> c.exp(10) Decimal('22026.4658')
Returns e ** a.
[ "Returns", "e", "**", "a", "." ]
def exp(self, a): """Returns e ** a. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.exp(Decimal('-Infinity')) Decimal('0') >>> c.exp(Decimal('-1')) Decimal('0.367879441') >>> c.exp(Decimal('0')) Decimal('1') >>> c.exp(Decimal('1')) Decimal('2.71828183') >>> c.exp(Decimal('0.693147181')) Decimal('2.00000000') >>> c.exp(Decimal('+Infinity')) Decimal('Infinity') >>> c.exp(10) Decimal('22026.4658') """ a =_convert_other(a, raiseit=True) return a.exp(context=self)
[ "def", "exp", "(", "self", ",", "a", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "exp", "(", "context", "=", "self", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py#L4265-L4287
microsoft/AirSim
8057725712c0cd46979135396381784075ffc0f3
PythonClient/airsim/client.py
python
MultirotorClient.moveByAngleRatesThrottleAsync
(self, roll_rate, pitch_rate, yaw_rate, throttle, duration, vehicle_name = '')
return self.client.call_async('moveByAngleRatesThrottle', roll_rate, -pitch_rate, -yaw_rate, throttle, duration, vehicle_name)
- Desired throttle is between 0.0 to 1.0 - Roll rate, pitch rate, and yaw rate set points are given in **radians**, in the body frame. - The body frame follows the Front Left Up (FLU) convention, and right-handedness. - Frame Convention: - X axis is along the **Front** direction of the quadrotor. | Clockwise rotation about this axis defines a positive **roll** angle. | Hence, rolling with a positive angle is equivalent to translating in the **right** direction, w.r.t. our FLU body frame. - Y axis is along the **Left** direction of the quadrotor. | Clockwise rotation about this axis defines a positive **pitch** angle. | Hence, pitching with a positive angle is equivalent to translating in the **front** direction, w.r.t. our FLU body frame. - Z axis is along the **Up** direction. | Clockwise rotation about this axis defines a positive **yaw** angle. | Hence, yawing with a positive angle is equivalent to rotated towards the **left** direction wrt our FLU body frame. Or in an anticlockwise fashion in the body XY / FL plane. Args: roll_rate (float): Desired roll rate, in radians / second pitch_rate (float): Desired pitch rate, in radians / second yaw_rate (float): Desired yaw rate, in radians / second throttle (float): Desired throttle (between 0.0 to 1.0) duration (float): Desired amount of time (seconds), to send this command for vehicle_name (str, optional): Name of the multirotor to send this command to Returns: msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
- Desired throttle is between 0.0 to 1.0 - Roll rate, pitch rate, and yaw rate set points are given in **radians**, in the body frame. - The body frame follows the Front Left Up (FLU) convention, and right-handedness.
[ "-", "Desired", "throttle", "is", "between", "0", ".", "0", "to", "1", ".", "0", "-", "Roll", "rate", "pitch", "rate", "and", "yaw", "rate", "set", "points", "are", "given", "in", "**", "radians", "**", "in", "the", "body", "frame", ".", "-", "The"...
def moveByAngleRatesThrottleAsync(self, roll_rate, pitch_rate, yaw_rate, throttle, duration, vehicle_name = ''): """ - Desired throttle is between 0.0 to 1.0 - Roll rate, pitch rate, and yaw rate set points are given in **radians**, in the body frame. - The body frame follows the Front Left Up (FLU) convention, and right-handedness. - Frame Convention: - X axis is along the **Front** direction of the quadrotor. | Clockwise rotation about this axis defines a positive **roll** angle. | Hence, rolling with a positive angle is equivalent to translating in the **right** direction, w.r.t. our FLU body frame. - Y axis is along the **Left** direction of the quadrotor. | Clockwise rotation about this axis defines a positive **pitch** angle. | Hence, pitching with a positive angle is equivalent to translating in the **front** direction, w.r.t. our FLU body frame. - Z axis is along the **Up** direction. | Clockwise rotation about this axis defines a positive **yaw** angle. | Hence, yawing with a positive angle is equivalent to rotated towards the **left** direction wrt our FLU body frame. Or in an anticlockwise fashion in the body XY / FL plane. Args: roll_rate (float): Desired roll rate, in radians / second pitch_rate (float): Desired pitch rate, in radians / second yaw_rate (float): Desired yaw rate, in radians / second throttle (float): Desired throttle (between 0.0 to 1.0) duration (float): Desired amount of time (seconds), to send this command for vehicle_name (str, optional): Name of the multirotor to send this command to Returns: msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join() """ return self.client.call_async('moveByAngleRatesThrottle', roll_rate, -pitch_rate, -yaw_rate, throttle, duration, vehicle_name)
[ "def", "moveByAngleRatesThrottleAsync", "(", "self", ",", "roll_rate", ",", "pitch_rate", ",", "yaw_rate", ",", "throttle", ",", "duration", ",", "vehicle_name", "=", "''", ")", ":", "return", "self", ".", "client", ".", "call_async", "(", "'moveByAngleRatesThro...
https://github.com/microsoft/AirSim/blob/8057725712c0cd46979135396381784075ffc0f3/PythonClient/airsim/client.py#L1459-L1492
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/multiprocessing/managers.py
python
BaseManager._number_of_objects
(self)
Return the number of shared objects
Return the number of shared objects
[ "Return", "the", "number", "of", "shared", "objects" ]
def _number_of_objects(self): ''' Return the number of shared objects ''' conn = self._Client(self._address, authkey=self._authkey) try: return dispatch(conn, None, 'number_of_objects') finally: conn.close()
[ "def", "_number_of_objects", "(", "self", ")", ":", "conn", "=", "self", ".", "_Client", "(", "self", ".", "_address", ",", "authkey", "=", "self", ".", "_authkey", ")", "try", ":", "return", "dispatch", "(", "conn", ",", "None", ",", "'number_of_objects...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/multiprocessing/managers.py#L588-L596
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Misc._report_exception
(self)
Internal function.
Internal function.
[ "Internal", "function", "." ]
def _report_exception(self): """Internal function.""" import sys exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback root = self._root() root.report_callback_exception(exc, val, tb)
[ "def", "_report_exception", "(", "self", ")", ":", "import", "sys", "exc", ",", "val", ",", "tb", "=", "sys", ".", "exc_type", ",", "sys", ".", "exc_value", ",", "sys", ".", "exc_traceback", "root", "=", "self", ".", "_root", "(", ")", "root", ".", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1231-L1236
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
armoryengine/CoinSelection.py
python
PySelectCoins
(unspentTxOutInfo, targetOutVal, minFee=0, numRand=10, margin=CENT)
return finalSelection
Intense algorithm for coin selection: computes about 30 different ways to select coins based on the desired target output and the min tx fee. Then ranks the various solutions and picks the best one
Intense algorithm for coin selection: computes about 30 different ways to select coins based on the desired target output and the min tx fee. Then ranks the various solutions and picks the best one
[ "Intense", "algorithm", "for", "coin", "selection", ":", "computes", "about", "30", "different", "ways", "to", "select", "coins", "based", "on", "the", "desired", "target", "output", "and", "the", "min", "tx", "fee", ".", "Then", "ranks", "the", "various", ...
def PySelectCoins(unspentTxOutInfo, targetOutVal, minFee=0, numRand=10, margin=CENT): """ Intense algorithm for coin selection: computes about 30 different ways to select coins based on the desired target output and the min tx fee. Then ranks the various solutions and picks the best one """ if sum([u.getValue() for u in unspentTxOutInfo]) < targetOutVal: return [] targExact = targetOutVal targMargin = targetOutVal+margin selectLists = [] # Start with the intelligent solutions with different sortings for sortMethod in range(8): diffSortList = PySortCoins(unspentTxOutInfo, sortMethod) selectLists.append(PySelectCoins_SingleInput_SingleValue( diffSortList, targExact, minFee )) selectLists.append(PySelectCoins_MultiInput_SingleValue( diffSortList, targExact, minFee )) selectLists.append(PySelectCoins_SingleInput_SingleValue( diffSortList, targMargin, minFee )) selectLists.append(PySelectCoins_MultiInput_SingleValue( diffSortList, targMargin, minFee )) selectLists.append(PySelectCoins_SingleInput_DoubleValue( diffSortList, targExact, minFee )) selectLists.append(PySelectCoins_MultiInput_DoubleValue( diffSortList, targExact, minFee )) selectLists.append(PySelectCoins_SingleInput_DoubleValue( diffSortList, targMargin, minFee )) selectLists.append(PySelectCoins_MultiInput_DoubleValue( diffSortList, targMargin, minFee )) # Throw in a couple random solutions, maybe we get lucky # But first, make a copy before in-place shuffling # NOTE: using list[:] like below, really causes a swig::vector<type> to freak out! #utxos = unspentTxOutInfo[:] #utxos = list(unspentTxOutInfo) for method in range(8,10): for i in range(numRand): utxos = PySortCoins(unspentTxOutInfo, method) selectLists.append(PySelectCoins_MultiInput_SingleValue(utxos, targExact, minFee)) selectLists.append(PySelectCoins_MultiInput_DoubleValue(utxos, targExact, minFee)) selectLists.append(PySelectCoins_MultiInput_SingleValue(utxos, targMargin, minFee)) selectLists.append(PySelectCoins_MultiInput_DoubleValue(utxos, targMargin, minFee)) # Now we define PyEvalCoinSelect as our sorting metric, and find the best solution scoreFunc = lambda ulist: PyEvalCoinSelect(ulist, targetOutVal, minFee) finalSelection = max(selectLists, key=scoreFunc) SCORES = getSelectCoinsScores(finalSelection, targetOutVal, minFee) if len(finalSelection)==0: return [] # If we selected a list that has only one or two inputs, and we have # other, tiny, unspent outputs from the same addresses, we should # throw one or two of them in to help clear them out. However, we # only do so if a plethora of conditions exist: # # First, we only consider doing this if the tx has <5 inputs already. # Also, we skip this process if the current tx doesn't have excessive # priority already -- we don't want to risk de-prioritizing a tx for # this purpose. # # Next we sort by LOWEST value, because we really benefit from this most # by clearing out tiny outputs. Along those lines, we don't even do # unless it has low priority -- don't want to take a high-priority utxo # and convert it to one that will be low-priority to start. # # Finally, we shouldn't do this if a high score was assigned to output # anonymity: this extra output may cause a tx with good output anonymity # to no longer possess this property IDEAL_NUM_INPUTS = 5 if len(finalSelection) < IDEAL_NUM_INPUTS and \ SCORES[IDX_OUTANONYM] == 0: utxoToScrAddr = lambda a: a.getRecipientScrAddr() getPriority = lambda a: a.getValue() * a.getNumConfirm() getUtxoID = lambda a: a.getTxHash() + int_to_binary(a.getTxOutIndex()) alreadyUsedAddr = set( [utxoToScrAddr(utxo) for utxo in finalSelection] ) utxoSmallToLarge = sorted(unspentTxOutInfo, key=getPriority) utxoSmToLgIDs = [getUtxoID(utxo) for utxo in utxoSmallToLarge] finalSelectIDs = [getUtxoID(utxo) for utxo in finalSelection] for other in utxoSmallToLarge: # Skip it if it is already selected if getUtxoID(other) in finalSelectIDs: continue # We only consider UTXOs that won't link any new addresses together if not utxoToScrAddr(other) in alreadyUsedAddr: continue # Avoid zero-conf inputs altogether if other.getNumConfirm() == 0: continue # Don't consider any inputs that are high priority already if getPriority(other) > ONE_BTC*144: continue finalSelection.append(other) if len(finalSelection)>=IDEAL_NUM_INPUTS: break return finalSelection
[ "def", "PySelectCoins", "(", "unspentTxOutInfo", ",", "targetOutVal", ",", "minFee", "=", "0", ",", "numRand", "=", "10", ",", "margin", "=", "CENT", ")", ":", "if", "sum", "(", "[", "u", ".", "getValue", "(", ")", "for", "u", "in", "unspentTxOutInfo",...
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/CoinSelection.py#L620-L719
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/motionplanning.py
python
CSpaceInterface.setFeasibilityPrior
(self, name, costPrior=0.0, feasibilityProbability=0.0, evidenceStrength=1.0)
return _motionplanning.CSpaceInterface_setFeasibilityPrior(self, name, costPrior, feasibilityProbability, evidenceStrength)
setFeasibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double feasibilityProbability=0.0, double evidenceStrength=1.0) setFeasibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double feasibilityProbability=0.0) setFeasibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0) setFeasibilityPrior(CSpaceInterface self, char const * name) Resets the data for a certain feasibility test. Default values give a data- gathering behavior.
setFeasibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double feasibilityProbability=0.0, double evidenceStrength=1.0) setFeasibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double feasibilityProbability=0.0) setFeasibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0) setFeasibilityPrior(CSpaceInterface self, char const * name)
[ "setFeasibilityPrior", "(", "CSpaceInterface", "self", "char", "const", "*", "name", "double", "costPrior", "=", "0", ".", "0", "double", "feasibilityProbability", "=", "0", ".", "0", "double", "evidenceStrength", "=", "1", ".", "0", ")", "setFeasibilityPrior", ...
def setFeasibilityPrior(self, name, costPrior=0.0, feasibilityProbability=0.0, evidenceStrength=1.0): """ setFeasibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double feasibilityProbability=0.0, double evidenceStrength=1.0) setFeasibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double feasibilityProbability=0.0) setFeasibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0) setFeasibilityPrior(CSpaceInterface self, char const * name) Resets the data for a certain feasibility test. Default values give a data- gathering behavior. """ return _motionplanning.CSpaceInterface_setFeasibilityPrior(self, name, costPrior, feasibilityProbability, evidenceStrength)
[ "def", "setFeasibilityPrior", "(", "self", ",", "name", ",", "costPrior", "=", "0.0", ",", "feasibilityProbability", "=", "0.0", ",", "evidenceStrength", "=", "1.0", ")", ":", "return", "_motionplanning", ".", "CSpaceInterface_setFeasibilityPrior", "(", "self", ",...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/motionplanning.py#L606-L619
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/image/image.py
python
ImageIter.read_image
(self, fname)
return img
Reads an input image `fname` and returns the decoded raw bytes. Example usage: ---------- >>> dataIter.read_image('Face.jpg') # returns decoded raw bytes.
Reads an input image `fname` and returns the decoded raw bytes.
[ "Reads", "an", "input", "image", "fname", "and", "returns", "the", "decoded", "raw", "bytes", "." ]
def read_image(self, fname): """Reads an input image `fname` and returns the decoded raw bytes. Example usage: ---------- >>> dataIter.read_image('Face.jpg') # returns decoded raw bytes. """ with open(os.path.join(self.path_root, fname), 'rb') as fin: img = fin.read() return img
[ "def", "read_image", "(", "self", ",", "fname", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path_root", ",", "fname", ")", ",", "'rb'", ")", "as", "fin", ":", "img", "=", "fin", ".", "read", "(", ")", "retu...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/image/image.py#L1225-L1234
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiMDIChildFrame.Maximize
(*args, **kwargs)
return _aui.AuiMDIChildFrame_Maximize(*args, **kwargs)
Maximize(self, bool maximize=True)
Maximize(self, bool maximize=True)
[ "Maximize", "(", "self", "bool", "maximize", "=", "True", ")" ]
def Maximize(*args, **kwargs): """Maximize(self, bool maximize=True)""" return _aui.AuiMDIChildFrame_Maximize(*args, **kwargs)
[ "def", "Maximize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiMDIChildFrame_Maximize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L1562-L1564
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/dockart.py
python
ModernDockArt.Init
(self)
Initializes the dock art.
Initializes the dock art.
[ "Initializes", "the", "dock", "art", "." ]
def Init(self): """ Initializes the dock art. """ AuiDefaultDockArt.Init(self) self._active_caption_colour = self._inactive_caption_colour self._active_caption_text_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_CAPTIONTEXT) self._inactive_caption_text_colour = self._active_caption_text_colour
[ "def", "Init", "(", "self", ")", ":", "AuiDefaultDockArt", ".", "Init", "(", "self", ")", "self", ".", "_active_caption_colour", "=", "self", ".", "_inactive_caption_colour", "self", ".", "_active_caption_text_colour", "=", "wx", ".", "SystemSettings", ".", "Get...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/dockart.py#L964-L971
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/pycparser/c_lexer.py
python
CLexer.t_pppragma_PPPRAGMA
(self, t)
return t
r'pragma
r'pragma
[ "r", "pragma" ]
def t_pppragma_PPPRAGMA(self, t): r'pragma' return t
[ "def", "t_pppragma_PPPRAGMA", "(", "self", ",", "t", ")", ":", "return", "t" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/pycparser/c_lexer.py#L332-L334
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/pylib/utils/emulator.py
python
DeleteAllTempAVDs
()
Delete all temporary AVDs which are created for tests. If the test exits abnormally and some temporary AVDs created when testing may be left in the system. Clean these AVDs.
Delete all temporary AVDs which are created for tests.
[ "Delete", "all", "temporary", "AVDs", "which", "are", "created", "for", "tests", "." ]
def DeleteAllTempAVDs(): """Delete all temporary AVDs which are created for tests. If the test exits abnormally and some temporary AVDs created when testing may be left in the system. Clean these AVDs. """ avds = android_commands.GetAVDs() if not avds: return for avd_name in avds: if 'run_tests_avd' in avd_name: cmd = ['android', '-s', 'delete', 'avd', '--name', avd_name] cmd_helper.RunCmd(cmd) logging.info('Delete AVD %s' % avd_name)
[ "def", "DeleteAllTempAVDs", "(", ")", ":", "avds", "=", "android_commands", ".", "GetAVDs", "(", ")", "if", "not", "avds", ":", "return", "for", "avd_name", "in", "avds", ":", "if", "'run_tests_avd'", "in", "avd_name", ":", "cmd", "=", "[", "'android'", ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/utils/emulator.py#L107-L120
OAID/Caffe-HRT
aae71e498ab842c6f92bcc23fc668423615a4d65
python/caffe/io.py
python
blobproto_to_array
(blob, return_diff=False)
Convert a blob proto to an array. In default, we will just return the data, unless return_diff is True, in which case we will return the diff.
Convert a blob proto to an array. In default, we will just return the data, unless return_diff is True, in which case we will return the diff.
[ "Convert", "a", "blob", "proto", "to", "an", "array", ".", "In", "default", "we", "will", "just", "return", "the", "data", "unless", "return_diff", "is", "True", "in", "which", "case", "we", "will", "return", "the", "diff", "." ]
def blobproto_to_array(blob, return_diff=False): """ Convert a blob proto to an array. In default, we will just return the data, unless return_diff is True, in which case we will return the diff. """ # Read the data into an array if return_diff: data = np.array(blob.diff) else: data = np.array(blob.data) # Reshape the array if blob.HasField('num') or blob.HasField('channels') or blob.HasField('height') or blob.HasField('width'): # Use legacy 4D shape return data.reshape(blob.num, blob.channels, blob.height, blob.width) else: return data.reshape(blob.shape.dim)
[ "def", "blobproto_to_array", "(", "blob", ",", "return_diff", "=", "False", ")", ":", "# Read the data into an array", "if", "return_diff", ":", "data", "=", "np", ".", "array", "(", "blob", ".", "diff", ")", "else", ":", "data", "=", "np", ".", "array", ...
https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/python/caffe/io.py#L18-L34
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/versioneer.py
python
run_command
( commands, args, cwd=None, verbose=False, hide_stderr=False, env=None )
return stdout, p.returncode
Call the given command(s).
Call the given command(s).
[ "Call", "the", "given", "command", "(", "s", ")", "." ]
def run_command( commands, args, cwd=None, verbose=False, hide_stderr=False, env=None ): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen( [c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), ) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode
[ "def", "run_command", "(", "commands", ",", "args", ",", "cwd", "=", "None", ",", "verbose", "=", "False", ",", "hide_stderr", "=", "False", ",", "env", "=", "None", ")", ":", "assert", "isinstance", "(", "commands", ",", "list", ")", "p", "=", "None...
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/versioneer.py#L392-L430
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/internal/decoder.py
python
_StructPackDecoder
(wire_type, format)
return _SimpleDecoder(wire_type, InnerDecode)
Return a constructor for a decoder for a fixed-width field. Args: wire_type: The field's wire type. format: The format string to pass to struct.unpack().
Return a constructor for a decoder for a fixed-width field.
[ "Return", "a", "constructor", "for", "a", "decoder", "for", "a", "fixed", "-", "width", "field", "." ]
def _StructPackDecoder(wire_type, format): """Return a constructor for a decoder for a fixed-width field. Args: wire_type: The field's wire type. format: The format string to pass to struct.unpack(). """ value_size = struct.calcsize(format) local_unpack = struct.unpack # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but # not enough to make a significant difference. # Note that we expect someone up-stack to catch struct.error and convert # it to _DecodeError -- this way we don't have to set up exception- # handling blocks every time we parse one value. def InnerDecode(buffer, pos): new_pos = pos + value_size result = local_unpack(format, buffer[pos:new_pos])[0] return (result, new_pos) return _SimpleDecoder(wire_type, InnerDecode)
[ "def", "_StructPackDecoder", "(", "wire_type", ",", "format", ")", ":", "value_size", "=", "struct", ".", "calcsize", "(", "format", ")", "local_unpack", "=", "struct", ".", "unpack", "# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but", "# not ...
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/decoder.py#L254-L276
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
models/AI-Model-Zoo/caffe-xilinx/python/caffe/coord_map.py
python
coord_map
(fn)
Define the coordinate mapping by its - axis - scale: output coord[i * scale] <- input_coord[i] - shift: output coord[i] <- output_coord[i + shift] s.t. the identity mapping, as for pointwise layers like ReLu, is defined by (None, 1, 0) since it is independent of axis and does not transform coords.
Define the coordinate mapping by its - axis - scale: output coord[i * scale] <- input_coord[i] - shift: output coord[i] <- output_coord[i + shift] s.t. the identity mapping, as for pointwise layers like ReLu, is defined by (None, 1, 0) since it is independent of axis and does not transform coords.
[ "Define", "the", "coordinate", "mapping", "by", "its", "-", "axis", "-", "scale", ":", "output", "coord", "[", "i", "*", "scale", "]", "<", "-", "input_coord", "[", "i", "]", "-", "shift", ":", "output", "coord", "[", "i", "]", "<", "-", "output_co...
def coord_map(fn): """ Define the coordinate mapping by its - axis - scale: output coord[i * scale] <- input_coord[i] - shift: output coord[i] <- output_coord[i + shift] s.t. the identity mapping, as for pointwise layers like ReLu, is defined by (None, 1, 0) since it is independent of axis and does not transform coords. """ if fn.type_name in ['Convolution', 'Pooling', 'Im2col']: axis, stride, ks, pad = conv_params(fn) return axis, 1 / stride, (pad - (ks - 1) / 2) / stride elif fn.type_name == 'Deconvolution': axis, stride, ks, pad = conv_params(fn) return axis, stride, (ks - 1) / 2 - pad elif fn.type_name in PASS_THROUGH_LAYERS: return None, 1, 0 elif fn.type_name == 'Crop': axis, offset = crop_params(fn) axis -= 1 # -1 for last non-coordinate dim. return axis, 1, - offset else: raise UndefinedMapException
[ "def", "coord_map", "(", "fn", ")", ":", "if", "fn", ".", "type_name", "in", "[", "'Convolution'", ",", "'Pooling'", ",", "'Im2col'", "]", ":", "axis", ",", "stride", ",", "ks", ",", "pad", "=", "conv_params", "(", "fn", ")", "return", "axis", ",", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/python/caffe/coord_map.py#L57-L79
cmu-db/bustub
fe1b9e984bd2967997b52df872c873d80f71cf7d
build_support/cpplint.py
python
NestingState.InnermostClass
(self)
return None
Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise.
Get class info on the top of the stack.
[ "Get", "class", "info", "on", "the", "top", "of", "the", "stack", "." ]
def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None
[ "def", "InnermostClass", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "stack", ")", ",", "0", ",", "-", "1", ")", ":", "classinfo", "=", "self", ".", "stack", "[", "i", "-", "1", "]", "if", "isinstance", "(", ...
https://github.com/cmu-db/bustub/blob/fe1b9e984bd2967997b52df872c873d80f71cf7d/build_support/cpplint.py#L2978-L2988
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/MooseDocs/commands/build.py
python
main
(options)
return 0
Main function for the build command. Inputs: options[argparse options]: Complete options from argparse, see MooseDocs/main.py
Main function for the build command.
[ "Main", "function", "for", "the", "build", "command", "." ]
def main(options): """ Main function for the build command. Inputs: options[argparse options]: Complete options from argparse, see MooseDocs/main.py """ t = time.time() # Infinite nested dict tree = lambda: collections.defaultdict(tree) kwargs = tree() # Setup executioner if options.executioner: kwargs['Executioner']['type'] = options.executioner # Disable extensions if options.stable: pass elif options.fast: options.disable += ['MooseDocs.extensions.appsyntax', 'MooseDocs.extensions.navigation', 'MooseDocs.extensions.sqa', 'MooseDocs.extensions.civet', 'MooseDocs.extensions.gitutils'] else: options.disable += ['MooseDocs.extensions.sqa', 'MooseDocs.extensions.civet', 'MooseDocs.extensions.gitutils'] for name in options.disable: kwargs['Extensions'][name] = dict(active=False) if options.hide_source: kwargs['Extensions']['MooseDocs.extensions.modal']['hide_source'] = True # Apply Translator settings if options.destination: kwargs['Translator']['destination'] = mooseutils.eval_path(options.destination) if options.profile: kwargs['Translator']['profile'] = True # Apply '--args' and override anything already set if options.args is not None: mooseutils.recursive_update(kwargs, options.args) # Create translators for the specified configuration files, provide kwargs to override them config_files = options.config if isinstance(options.config, list) else [options.config] subconfigs = len(config_files) > 1 LOG.info("Loading configuration file{}".format('s' if subconfigs else '')) translators, contents, configurations = common.load_configs(config_files, **kwargs) # Initialize the translator objects for index, translator in enumerate(translators): if subconfigs: LOG.info('Initializing translator object loaded from %s', config_files[index]) translator.init(contents[index]) # init methods can add pages (e.g., civet.py), but don't add pages from another translator contents[index] = [page for page in translator.getPages() if page.translator is translator] # Identify the first translator in the list as the "primary" one for convenience primary = translators[0] pooled = sorted(primary.getPages(), key=(lambda p: p.local)) # Dump page tree from content pool and syntax list from all translators with AppSyntax if options.dump: for page in pooled: print('{}: {}'.format(page.local, page.source)) for index, translator in enumerate(translators): for extension in translator.extensions: if isinstance(extension, MooseDocs.extensions.appsyntax.AppSyntaxExtension): if subconfigs: LOG.info('Building syntax list specified by %s', config_files[index]) extension.preExecute() print(extension.syntax) break return 0 # TODO: See `navigation.postExecute` # The navigation "home" should be a markdown file, when all the apps update to this we # can remove this as well as the use of it by CIVET home = options.home if options.serve and (home is not None) and (not home.endswith('.md')): home = 'http://127.0.0.1:{}'.format(options.port) if home is not None: for ext in primary.extensions: if 'home' in ext: ext.update(home=home) # Set default for --clean: clean when --files is NOT used. if options.clean is None: options.clean = options.files == [] else: options.clean = options.clean.lower() in ['true', 'yes', '1'] if options.clean and os.path.exists(primary.destination): LOG.info("Cleaning destination %s", primary.destination) shutil.rmtree(primary.destination) # Update contents lists if only building certain files if options.files: for index, translator in enumerate(translators): func = lambda p: (p in contents[index] and any([p.local.startswith(f) for f in options.files])) contents[index] = translator.findPages(func) # Execute the read and tokenize methods on all translators for index, translator in enumerate(translators): if subconfigs: LOG.info('Reading content specified by %s', config_files[index]) translator.execute(contents[index], num_threads=options.num_threads, render=False, write=False) # Finally, execute the render and write methods for index, translator in enumerate(translators): if subconfigs: LOG.info('Writing content specified by %s', config_files[index]) translator.execute(contents[index], num_threads=options.num_threads, read=False, tokenize=False) LOG.info('Total Time [%s sec.]', time.time() - t) # Run live server and watch for content changes if options.serve: watcher = MooseDocsWatcher(translators, pooled, configurations, options.num_threads) server = livereload.Server(watcher=watcher) server.serve(root=primary.destination, host=options.host, port=options.port) return 0
[ "def", "main", "(", "options", ")", ":", "t", "=", "time", ".", "time", "(", ")", "# Infinite nested dict", "tree", "=", "lambda", ":", "collections", ".", "defaultdict", "(", "tree", ")", "kwargs", "=", "tree", "(", ")", "# Setup executioner", "if", "op...
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/commands/build.py#L157-L283
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/framework/ops.py
python
Graph._add_op
(self, op)
Adds 'op' to the graph. Args: op: the Operator or Tensor to add. Raises: TypeError: if op is not an Operation or Tensor. ValueError: if the op.name or op._id are already used.
Adds 'op' to the graph.
[ "Adds", "op", "to", "the", "graph", "." ]
def _add_op(self, op): """Adds 'op' to the graph. Args: op: the Operator or Tensor to add. Raises: TypeError: if op is not an Operation or Tensor. ValueError: if the op.name or op._id are already used. """ self._check_not_finalized() if not isinstance(op, (Tensor, Operation)): raise TypeError("op must be a Tensor or Operation: %s" % op) with self._lock: # pylint: disable=protected-access if op._id in self._nodes_by_id: raise ValueError("cannot add an op with id %d as it already " "exists in the graph" % op._id) if op.name in self._nodes_by_name: raise ValueError("cannot add op with name %s as that name " "is already used" % op.name) self._nodes_by_id[op._id] = op self._nodes_by_name[op.name] = op self._version = max(self._version, op._id)
[ "def", "_add_op", "(", "self", ",", "op", ")", ":", "self", ".", "_check_not_finalized", "(", ")", "if", "not", "isinstance", "(", "op", ",", "(", "Tensor", ",", "Operation", ")", ")", ":", "raise", "TypeError", "(", "\"op must be a Tensor or Operation: %s\"...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/ops.py#L2010-L2033
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/config.py
python
DictConfigurator.configure_root
(self, config, incremental=False)
Configure a root logger from a dictionary.
Configure a root logger from a dictionary.
[ "Configure", "a", "root", "logger", "from", "a", "dictionary", "." ]
def configure_root(self, config, incremental=False): """Configure a root logger from a dictionary.""" root = logging.getLogger() self.common_logger_config(root, config, incremental)
[ "def", "configure_root", "(", "self", ",", "config", ",", "incremental", "=", "False", ")", ":", "root", "=", "logging", ".", "getLogger", "(", ")", "self", ".", "common_logger_config", "(", "root", ",", "config", ",", "incremental", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/logging/config.py#L794-L797
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/core/defchararray.py
python
lstrip
(a, chars=None)
return _vec_string(a_arr, a_arr.dtype, 'lstrip', (chars,))
For each element in `a`, return a copy with the leading characters removed. Calls `str.lstrip` element-wise. Parameters ---------- a : array-like, {str, unicode} Input array. chars : {str, unicode}, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix; rather, all combinations of its values are stripped. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.lstrip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') The 'a' variable is unstripped from c[1] because whitespace leading. >>> np.char.lstrip(c, 'a') array(['AaAaA', ' aA ', 'bBABba'], dtype='<U7') >>> np.char.lstrip(c, 'A') # leaves c unchanged array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all() ... # XXX: is this a regression? This used to return True ... # np.char.lstrip(c,'') does not modify c at all. False >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all() True
For each element in `a`, return a copy with the leading characters removed.
[ "For", "each", "element", "in", "a", "return", "a", "copy", "with", "the", "leading", "characters", "removed", "." ]
def lstrip(a, chars=None): """ For each element in `a`, return a copy with the leading characters removed. Calls `str.lstrip` element-wise. Parameters ---------- a : array-like, {str, unicode} Input array. chars : {str, unicode}, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix; rather, all combinations of its values are stripped. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.lstrip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') The 'a' variable is unstripped from c[1] because whitespace leading. >>> np.char.lstrip(c, 'a') array(['AaAaA', ' aA ', 'bBABba'], dtype='<U7') >>> np.char.lstrip(c, 'A') # leaves c unchanged array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all() ... # XXX: is this a regression? This used to return True ... # np.char.lstrip(c,'') does not modify c at all. False >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all() True """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'lstrip', (chars,))
[ "def", "lstrip", "(", "a", ",", "chars", "=", "None", ")", ":", "a_arr", "=", "numpy", ".", "asarray", "(", "a", ")", "return", "_vec_string", "(", "a_arr", ",", "a_arr", ".", "dtype", ",", "'lstrip'", ",", "(", "chars", ",", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/core/defchararray.py#L1045-L1096
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/json/encoder.py
python
py_encode_basestring_ascii
(s)
return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
Return an ASCII-only JSON representation of a Python string
Return an ASCII-only JSON representation of a Python string
[ "Return", "an", "ASCII", "-", "only", "JSON", "representation", "of", "a", "Python", "string" ]
def py_encode_basestring_ascii(s): """Return an ASCII-only JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): s = match.group(0) try: return ESCAPE_DCT[s] except KeyError: n = ord(s) if n < 0x10000: return '\\u{0:04x}'.format(n) #return '\\u%04x' % (n,) else: # surrogate pair n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) s2 = 0xdc00 | (n & 0x3ff) return '\\u{0:04x}\\u{1:04x}'.format(s1, s2) #return '\\u%04x\\u%04x' % (s1, s2) return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
[ "def", "py_encode_basestring_ascii", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "str", ")", "and", "HAS_UTF8", ".", "search", "(", "s", ")", "is", "not", "None", ":", "s", "=", "s", ".", "decode", "(", "'utf-8'", ")", "def", "replace", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/json/encoder.py#L42-L64
bairdzhang/smallhardface
76fa1d87a9602d9b13d7a7fe693fc7aec91cab80
caffe/python/caffe/pycaffe.py
python
_Net_blob_loss_weights
(self)
return self._blob_loss_weights_dict
An OrderedDict (bottom to top, i.e., input to output) of network blob loss weights indexed by name
An OrderedDict (bottom to top, i.e., input to output) of network blob loss weights indexed by name
[ "An", "OrderedDict", "(", "bottom", "to", "top", "i", ".", "e", ".", "input", "to", "output", ")", "of", "network", "blob", "loss", "weights", "indexed", "by", "name" ]
def _Net_blob_loss_weights(self): """ An OrderedDict (bottom to top, i.e., input to output) of network blob loss weights indexed by name """ if not hasattr(self, '_blobs_loss_weights_dict'): self._blob_loss_weights_dict = OrderedDict(zip(self._blob_names, self._blob_loss_weights)) return self._blob_loss_weights_dict
[ "def", "_Net_blob_loss_weights", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_blobs_loss_weights_dict'", ")", ":", "self", ".", "_blob_loss_weights_dict", "=", "OrderedDict", "(", "zip", "(", "self", ".", "_blob_names", ",", "self", ".",...
https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/caffe/python/caffe/pycaffe.py#L36-L44
nileshkulkarni/csm
0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc
csm/nnutils/train_utils.py
python
Trainer.set_input
(self, batch)
Should be implemented by the child class.
Should be implemented by the child class.
[ "Should", "be", "implemented", "by", "the", "child", "class", "." ]
def set_input(self, batch): '''Should be implemented by the child class.''' raise NotImplementedError
[ "def", "set_input", "(", "self", ",", "batch", ")", ":", "raise", "NotImplementedError" ]
https://github.com/nileshkulkarni/csm/blob/0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc/csm/nnutils/train_utils.py#L110-L112
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/Paste/paste/util/killthread.py
python
async_raise
(tid, exctype)
raises the exception, performs cleanup if needed. tid is the value given by thread.get_ident() (an integer). Raise SystemExit to kill a thread.
raises the exception, performs cleanup if needed.
[ "raises", "the", "exception", "performs", "cleanup", "if", "needed", "." ]
def async_raise(tid, exctype): """raises the exception, performs cleanup if needed. tid is the value given by thread.get_ident() (an integer). Raise SystemExit to kill a thread.""" if not isinstance(exctype, (six.class_types, type)): raise TypeError("Only types can be raised (not instances)") if not isinstance(tid, int): raise TypeError("tid must be an integer") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), 0) raise SystemError("PyThreadState_SetAsyncExc failed")
[ "def", "async_raise", "(", "tid", ",", "exctype", ")", ":", "if", "not", "isinstance", "(", "exctype", ",", "(", "six", ".", "class_types", ",", "type", ")", ")", ":", "raise", "TypeError", "(", "\"Only types can be raised (not instances)\"", ")", "if", "not...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/util/killthread.py#L14-L30
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
llvm/bindings/python/llvm/object.py
python
Symbol.address
(self)
return lib.LLVMGetSymbolAddress(self)
The address of this symbol, in long bytes.
The address of this symbol, in long bytes.
[ "The", "address", "of", "this", "symbol", "in", "long", "bytes", "." ]
def address(self): """The address of this symbol, in long bytes.""" if self.expired: raise Exception('Symbol instance has expired.') return lib.LLVMGetSymbolAddress(self)
[ "def", "address", "(", "self", ")", ":", "if", "self", ".", "expired", ":", "raise", "Exception", "(", "'Symbol instance has expired.'", ")", "return", "lib", ".", "LLVMGetSymbolAddress", "(", "self", ")" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/llvm/bindings/python/llvm/object.py#L313-L318
yue/yue
619d62c191b13c51c01be451dc48917c34a5aefc
building/tools/cpplint.py
python
ProcessFile
(filename, vlevel, extra_check_functions=[])
Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Does google-lint on a single file.
[ "Does", "google", "-", "lint", "on", "a", "single", "file", "." ]
def ProcessFile(filename, vlevel, extra_check_functions=[]): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ _SetVerboseLevel(vlevel) _BackupFilters() old_errors = _cpplint_state.error_count if not ProcessConfigOverrides(filename): _RestoreFilters() return lf_lines = [] crlf_lines = [] try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') # Remove trailing '\r'. # The -1 accounts for the extra trailing blank line we get from split() for linenum in range(len(lines) - 1): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') crlf_lines.append(linenum + 1) else: lf_lines.append(linenum + 1) except IOError: sys.stderr.write( "Skipping input '%s': Can't open for reading\n" % filename) _RestoreFilters() return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if filename != '-' and file_extension not in _valid_extensions: sys.stderr.write('Ignoring %s; not a valid file name ' '(%s)\n' % (filename, ', '.join(_valid_extensions))) else: ProcessFileData(filename, file_extension, lines, Error, extra_check_functions) # If end-of-line sequences are a mix of LF and CR-LF, issue # warnings on the lines with CR. # # Don't issue any warnings if all lines are uniformly LF or CR-LF, # since critique can handle these just fine, and the style guide # doesn't dictate a particular end of line sequence. # # We can't depend on os.linesep to determine what the desired # end-of-line sequence should be, since that will return the # server-side end-of-line sequence. if lf_lines and crlf_lines: # Warn on every line with CR. An alternative approach might be to # check whether the file is mostly CRLF or just LF, and warn on the # minority, we bias toward LF here since most tools prefer LF. for linenum in crlf_lines: Error(filename, linenum, 'whitespace/newline', 1, 'Unexpected \\r (^M) found; better to use only \\n') # Suppress printing anything if --quiet was passed unless the error # count has increased after processing this file. if not _cpplint_state.quiet or old_errors != _cpplint_state.error_count: sys.stdout.write('Done processing %s\n' % filename) _RestoreFilters()
[ "def", "ProcessFile", "(", "filename", ",", "vlevel", ",", "extra_check_functions", "=", "[", "]", ")", ":", "_SetVerboseLevel", "(", "vlevel", ")", "_BackupFilters", "(", ")", "old_errors", "=", "_cpplint_state", ".", "error_count", "if", "not", "ProcessConfigO...
https://github.com/yue/yue/blob/619d62c191b13c51c01be451dc48917c34a5aefc/building/tools/cpplint.py#L6015-L6104
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py
python
Dir.get_labspath
(self)
return self._labspath
Get the absolute path of the file.
Get the absolute path of the file.
[ "Get", "the", "absolute", "path", "of", "the", "file", "." ]
def get_labspath(self): """Get the absolute path of the file.""" return self._labspath
[ "def", "get_labspath", "(", "self", ")", ":", "return", "self", ".", "_labspath" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py#L1889-L1891
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/defchararray.py
python
array
(obj, itemsize=None, copy=True, unicode=None, order=None)
return val.view(chararray)
Create a `chararray`. .. note:: This class is provided for numarray backward-compatibility. New code (not concerned with numarray compatibility) should use arrays of type `string_` or `unicode_` and use the free functions in :mod:`numpy.char <numpy.core.defchararray>` for fast vectorized string operations instead. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+, *, %``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (`itemsize`, unicode, `order`, etc.). unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or `unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F', 'A'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is 'A', then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous).
Create a `chararray`.
[ "Create", "a", "chararray", "." ]
def array(obj, itemsize=None, copy=True, unicode=None, order=None): """ Create a `chararray`. .. note:: This class is provided for numarray backward-compatibility. New code (not concerned with numarray compatibility) should use arrays of type `string_` or `unicode_` and use the free functions in :mod:`numpy.char <numpy.core.defchararray>` for fast vectorized string operations instead. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+, *, %``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (`itemsize`, unicode, `order`, etc.). unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or `unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F', 'A'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is 'A', then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous). """ if isinstance(obj, (_bytes, _unicode)): if unicode is None: if isinstance(obj, _unicode): unicode = True else: unicode = False if itemsize is None: itemsize = _len(obj) shape = _len(obj) // itemsize if unicode: if sys.maxunicode == 0xffff: # On a narrow Python build, the buffer for Unicode # strings is UCS2, which doesn't match the buffer for # NumPy Unicode types, which is ALWAYS UCS4. # Therefore, we need to convert the buffer. On Python # 2.6 and later, we can use the utf_32 codec. Earlier # versions don't have that codec, so we convert to a # numerical array that matches the input buffer, and # then use NumPy to convert it to UCS4. All of this # should happen in native endianness. obj = obj.encode('utf_32') else: obj = _unicode(obj) else: # Let the default Unicode -> string encoding (if any) take # precedence. obj = _bytes(obj) return chararray(shape, itemsize=itemsize, unicode=unicode, buffer=obj, order=order) if isinstance(obj, (list, tuple)): obj = numpy.asarray(obj) if isinstance(obj, ndarray) and issubclass(obj.dtype.type, character): # If we just have a vanilla chararray, create a chararray # view around it. if not isinstance(obj, chararray): obj = obj.view(chararray) if itemsize is None: itemsize = obj.itemsize # itemsize is in 8-bit chars, so for Unicode, we need # to divide by the size of a single Unicode character, # which for NumPy is always 4 if issubclass(obj.dtype.type, unicode_): itemsize //= 4 if unicode is None: if issubclass(obj.dtype.type, unicode_): unicode = True else: unicode = False if unicode: dtype = unicode_ else: dtype = string_ if order is not None: obj = numpy.asarray(obj, order=order) if (copy or (itemsize != obj.itemsize) or (not unicode and isinstance(obj, unicode_)) or (unicode and isinstance(obj, string_))): obj = obj.astype((dtype, long(itemsize))) return obj if isinstance(obj, ndarray) and issubclass(obj.dtype.type, object): if itemsize is None: # Since no itemsize was specified, convert the input array to # a list so the ndarray constructor will automatically # determine the itemsize for us. obj = obj.tolist() # Fall through to the default case if unicode: dtype = unicode_ else: dtype = string_ if itemsize is None: val = narray(obj, dtype=dtype, order=order, subok=True) else: val = narray(obj, dtype=(dtype, itemsize), order=order, subok=True) return val.view(chararray)
[ "def", "array", "(", "obj", ",", "itemsize", "=", "None", ",", "copy", "=", "True", ",", "unicode", "=", "None", ",", "order", "=", "None", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "_bytes", ",", "_unicode", ")", ")", ":", "if", "unico...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/defchararray.py#L2618-L2767
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/column/numerical_base.py
python
NumericalBaseColumn.reduce
( self, op: str, skipna: bool = None, min_count: int = 0, **kwargs )
Perform a reduction operation. op : str The operation to perform. skipna : bool Whether or not na values must be
Perform a reduction operation.
[ "Perform", "a", "reduction", "operation", "." ]
def reduce( self, op: str, skipna: bool = None, min_count: int = 0, **kwargs ) -> ScalarLike: """Perform a reduction operation. op : str The operation to perform. skipna : bool Whether or not na values must be """ preprocessed = self._process_for_reduction( skipna=skipna, min_count=min_count ) if isinstance(preprocessed, ColumnBase): return libcudf.reduce.reduce(op, preprocessed, **kwargs) else: return preprocessed
[ "def", "reduce", "(", "self", ",", "op", ":", "str", ",", "skipna", ":", "bool", "=", "None", ",", "min_count", ":", "int", "=", "0", ",", "*", "*", "kwargs", ")", "->", "ScalarLike", ":", "preprocessed", "=", "self", ".", "_process_for_reduction", "...
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column/numerical_base.py#L26-L42
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/framework/docs.py
python
Document.write_markdown_to_file
(self, f)
Writes a Markdown-formatted version of this document to file `f`. Args: f: The output file.
Writes a Markdown-formatted version of this document to file `f`.
[ "Writes", "a", "Markdown", "-", "formatted", "version", "of", "this", "document", "to", "file", "f", "." ]
def write_markdown_to_file(self, f): """Writes a Markdown-formatted version of this document to file `f`. Args: f: The output file. """ raise NotImplementedError("Document.WriteToFile")
[ "def", "write_markdown_to_file", "(", "self", ",", "f", ")", ":", "raise", "NotImplementedError", "(", "\"Document.WriteToFile\"", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/docs.py#L43-L49
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py
python
Context.scaleb
(self, a, b)
return a.scaleb(b, context=self)
Returns the first operand after adding the second value its exp. >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) Decimal('0.0750') >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) Decimal('7.50') >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) Decimal('7.50E+3') >>> ExtendedContext.scaleb(1, 4) Decimal('1E+4') >>> ExtendedContext.scaleb(Decimal(1), 4) Decimal('1E+4') >>> ExtendedContext.scaleb(1, Decimal(4)) Decimal('1E+4')
Returns the first operand after adding the second value its exp.
[ "Returns", "the", "first", "operand", "after", "adding", "the", "second", "value", "its", "exp", "." ]
def scaleb (self, a, b): """Returns the first operand after adding the second value its exp. >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) Decimal('0.0750') >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) Decimal('7.50') >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) Decimal('7.50E+3') >>> ExtendedContext.scaleb(1, 4) Decimal('1E+4') >>> ExtendedContext.scaleb(Decimal(1), 4) Decimal('1E+4') >>> ExtendedContext.scaleb(1, Decimal(4)) Decimal('1E+4') """ a = _convert_other(a, raiseit=True) return a.scaleb(b, context=self)
[ "def", "scaleb", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "scaleb", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py#L5236-L5253
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/distutils/ccompiler.py
python
CCompiler.set_libraries
(self, libnames)
Set the list of libraries to be included in all links driven by this compiler object to 'libnames' (a list of strings). This does not affect any standard system libraries that the linker may include by default.
Set the list of libraries to be included in all links driven by this compiler object to 'libnames' (a list of strings). This does not affect any standard system libraries that the linker may include by default.
[ "Set", "the", "list", "of", "libraries", "to", "be", "included", "in", "all", "links", "driven", "by", "this", "compiler", "object", "to", "libnames", "(", "a", "list", "of", "strings", ")", ".", "This", "does", "not", "affect", "any", "standard", "syste...
def set_libraries(self, libnames): """Set the list of libraries to be included in all links driven by this compiler object to 'libnames' (a list of strings). This does not affect any standard system libraries that the linker may include by default. """ self.libraries = libnames[:]
[ "def", "set_libraries", "(", "self", ",", "libnames", ")", ":", "self", ".", "libraries", "=", "libnames", "[", ":", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/ccompiler.py#L269-L275
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/gensuitemodule.py
python
simplify
(item)
Recursively replace singleton tuples by their constituent item
Recursively replace singleton tuples by their constituent item
[ "Recursively", "replace", "singleton", "tuples", "by", "their", "constituent", "item" ]
def simplify(item): """Recursively replace singleton tuples by their constituent item""" if type(item) is types.ListType: return map(simplify, item) elif type(item) == types.TupleType and len(item) == 2: return simplify(item[1]) else: return item
[ "def", "simplify", "(", "item", ")", ":", "if", "type", "(", "item", ")", "is", "types", ".", "ListType", ":", "return", "map", "(", "simplify", ",", "item", ")", "elif", "type", "(", "item", ")", "==", "types", ".", "TupleType", "and", "len", "(",...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/gensuitemodule.py#L283-L290
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_grad/grad_array_ops.py
python
get_bprop_fill
(self)
return bprop
Generate bprop for Fill
Generate bprop for Fill
[ "Generate", "bprop", "for", "Fill" ]
def get_bprop_fill(self): """Generate bprop for Fill""" def bprop(dtype, dims, x, out, dout): return zeros_like(dims), zeros_like(x) return bprop
[ "def", "get_bprop_fill", "(", "self", ")", ":", "def", "bprop", "(", "dtype", ",", "dims", ",", "x", ",", "out", ",", "dout", ")", ":", "return", "zeros_like", "(", "dims", ")", ",", "zeros_like", "(", "x", ")", "return", "bprop" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_array_ops.py#L47-L53
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/parsers.py
python
_validate_parse_dates_arg
(parse_dates)
return parse_dates
Check whether or not the 'parse_dates' parameter is a non-boolean scalar. Raises a ValueError if that is the case.
Check whether or not the 'parse_dates' parameter is a non-boolean scalar. Raises a ValueError if that is the case.
[ "Check", "whether", "or", "not", "the", "parse_dates", "parameter", "is", "a", "non", "-", "boolean", "scalar", ".", "Raises", "a", "ValueError", "if", "that", "is", "the", "case", "." ]
def _validate_parse_dates_arg(parse_dates): """ Check whether or not the 'parse_dates' parameter is a non-boolean scalar. Raises a ValueError if that is the case. """ msg = ( "Only booleans, lists, and " "dictionaries are accepted " "for the 'parse_dates' parameter" ) if parse_dates is not None: if is_scalar(parse_dates): if not lib.is_bool(parse_dates): raise TypeError(msg) elif not isinstance(parse_dates, (list, dict)): raise TypeError(msg) return parse_dates
[ "def", "_validate_parse_dates_arg", "(", "parse_dates", ")", ":", "msg", "=", "(", "\"Only booleans, lists, and \"", "\"dictionaries are accepted \"", "\"for the 'parse_dates' parameter\"", ")", "if", "parse_dates", "is", "not", "None", ":", "if", "is_scalar", "(", "parse...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/parsers.py#L1321-L1341
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/dummy_thread.py
python
LockType.acquire
(self, waitflag=None)
Dummy implementation of acquire(). For blocking calls, self.locked_status is automatically set to True and returned appropriately based on value of ``waitflag``. If it is non-blocking, then the value is actually checked and not set if it is already acquired. This is all done so that threading.Condition's assert statements aren't triggered and throw a little fit.
Dummy implementation of acquire().
[ "Dummy", "implementation", "of", "acquire", "()", "." ]
def acquire(self, waitflag=None): """Dummy implementation of acquire(). For blocking calls, self.locked_status is automatically set to True and returned appropriately based on value of ``waitflag``. If it is non-blocking, then the value is actually checked and not set if it is already acquired. This is all done so that threading.Condition's assert statements aren't triggered and throw a little fit. """ if waitflag is None or waitflag: self.locked_status = True return True else: if not self.locked_status: self.locked_status = True return True else: return False
[ "def", "acquire", "(", "self", ",", "waitflag", "=", "None", ")", ":", "if", "waitflag", "is", "None", "or", "waitflag", ":", "self", ".", "locked_status", "=", "True", "return", "True", "else", ":", "if", "not", "self", ".", "locked_status", ":", "sel...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/dummy_thread.py#L95-L114
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py
python
ConstBitStream.peek
(self, fmt)
return value
Interpret next bits according to format string and return result. fmt -- Token string describing how to interpret the next bits. The position in the bitstring is not changed. If not enough bits are available then all bits to the end of the bitstring will be used. Raises ReadError if not enough bits are available. Raises ValueError if the format is not understood. See the docstring for 'read' for token examples.
Interpret next bits according to format string and return result.
[ "Interpret", "next", "bits", "according", "to", "format", "string", "and", "return", "result", "." ]
def peek(self, fmt): """Interpret next bits according to format string and return result. fmt -- Token string describing how to interpret the next bits. The position in the bitstring is not changed. If not enough bits are available then all bits to the end of the bitstring will be used. Raises ReadError if not enough bits are available. Raises ValueError if the format is not understood. See the docstring for 'read' for token examples. """ pos_before = self._pos value = self.read(fmt) self._pos = pos_before return value
[ "def", "peek", "(", "self", ",", "fmt", ")", ":", "pos_before", "=", "self", ".", "_pos", "value", "=", "self", ".", "read", "(", "fmt", ")", "self", ".", "_pos", "=", "pos_before", "return", "value" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L3936-L3953
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/email_template.py
python
GetSheriffEmails
(sheriff)
return ','.join(receivers)
Gets all of the email addresses to send mail to for a Sheriff. This includes both the general email address of the sheriff rotation, which is often a mailing list, and the email address of the particular sheriff on duty, if applicable. Args: sheriff: A Sheriff entity. Returns: A comma-separated list of email addresses; this will be an empty string if there are no email addresses.
Gets all of the email addresses to send mail to for a Sheriff.
[ "Gets", "all", "of", "the", "email", "addresses", "to", "send", "mail", "to", "for", "a", "Sheriff", "." ]
def GetSheriffEmails(sheriff): """Gets all of the email addresses to send mail to for a Sheriff. This includes both the general email address of the sheriff rotation, which is often a mailing list, and the email address of the particular sheriff on duty, if applicable. Args: sheriff: A Sheriff entity. Returns: A comma-separated list of email addresses; this will be an empty string if there are no email addresses. """ receivers = [sheriff.email] if sheriff.email else [] sheriff_on_duty = _GetSheriffOnDutyEmail(sheriff) if sheriff_on_duty: receivers.append(sheriff_on_duty) return ','.join(receivers)
[ "def", "GetSheriffEmails", "(", "sheriff", ")", ":", "receivers", "=", "[", "sheriff", ".", "email", "]", "if", "sheriff", ".", "email", "else", "[", "]", "sheriff_on_duty", "=", "_GetSheriffOnDutyEmail", "(", "sheriff", ")", "if", "sheriff_on_duty", ":", "r...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/email_template.py#L185-L203
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
benchmarks/operator_benchmark/benchmark_utils.py
python
random_sample_configs
(**configs)
return configs_attrs_list
This function randomly sample <total_samples> values from the given inputs based on their weights. Here is an example showing what are the expected inputs and outpus from this function: M = [1, 2], N = [4, 5], K = [7, 8], probs = attr_probs( M = [0.7, 0.2], N = [0.5, 0.2], K = [0.6, 0.2], ), total_samples=10, this function will generate [ [{'K': 7}, {'M': 1}, {'N': 4}], [{'K': 7}, {'M': 2}, {'N': 5}], [{'K': 8}, {'M': 2}, {'N': 4}], ... ] Note: The probs is optional. Without them, it implies everything is 1. The probs doesn't have to reflect the actual normalized probability, the implementation will normalize it. TODO (mingzhe09088): (1): a lambda that accepts or rejects a config as a sample. For example: for matmul with M, N, and K, this function could get rid of (M * N * K > 1e8) to filter out very slow benchmarks. (2): Make sure each sample is unique. If the number of samples are larger than the total combinations, just return the cross product. Otherwise, if the number of samples is close to the number of cross-products, it is numerical safer to generate the list that you don't want, and remove them.
This function randomly sample <total_samples> values from the given inputs based on their weights. Here is an example showing what are the expected inputs and outpus from this function: M = [1, 2], N = [4, 5], K = [7, 8], probs = attr_probs( M = [0.7, 0.2], N = [0.5, 0.2], K = [0.6, 0.2], ), total_samples=10, this function will generate [ [{'K': 7}, {'M': 1}, {'N': 4}], [{'K': 7}, {'M': 2}, {'N': 5}], [{'K': 8}, {'M': 2}, {'N': 4}], ... ] Note: The probs is optional. Without them, it implies everything is 1. The probs doesn't have to reflect the actual normalized probability, the implementation will normalize it. TODO (mingzhe09088): (1): a lambda that accepts or rejects a config as a sample. For example: for matmul with M, N, and K, this function could get rid of (M * N * K > 1e8) to filter out very slow benchmarks. (2): Make sure each sample is unique. If the number of samples are larger than the total combinations, just return the cross product. Otherwise, if the number of samples is close to the number of cross-products, it is numerical safer to generate the list that you don't want, and remove them.
[ "This", "function", "randomly", "sample", "<total_samples", ">", "values", "from", "the", "given", "inputs", "based", "on", "their", "weights", ".", "Here", "is", "an", "example", "showing", "what", "are", "the", "expected", "inputs", "and", "outpus", "from", ...
def random_sample_configs(**configs): """ This function randomly sample <total_samples> values from the given inputs based on their weights. Here is an example showing what are the expected inputs and outpus from this function: M = [1, 2], N = [4, 5], K = [7, 8], probs = attr_probs( M = [0.7, 0.2], N = [0.5, 0.2], K = [0.6, 0.2], ), total_samples=10, this function will generate [ [{'K': 7}, {'M': 1}, {'N': 4}], [{'K': 7}, {'M': 2}, {'N': 5}], [{'K': 8}, {'M': 2}, {'N': 4}], ... ] Note: The probs is optional. Without them, it implies everything is 1. The probs doesn't have to reflect the actual normalized probability, the implementation will normalize it. TODO (mingzhe09088): (1): a lambda that accepts or rejects a config as a sample. For example: for matmul with M, N, and K, this function could get rid of (M * N * K > 1e8) to filter out very slow benchmarks. (2): Make sure each sample is unique. If the number of samples are larger than the total combinations, just return the cross product. Otherwise, if the number of samples is close to the number of cross-products, it is numerical safer to generate the list that you don't want, and remove them. """ if "probs" not in configs: raise ValueError("probs is missing. Consider adding probs or" "using other config functions") configs_attrs_list = [] randomsample = RandomSample(configs) for i in range(configs["total_samples"]): tmp_attr_list = randomsample.get_one_set_of_inputs() tmp_attr_list.append({"tags" : '_'.join(configs["tags"])}) configs_attrs_list.append(tmp_attr_list) return configs_attrs_list
[ "def", "random_sample_configs", "(", "*", "*", "configs", ")", ":", "if", "\"probs\"", "not", "in", "configs", ":", "raise", "ValueError", "(", "\"probs is missing. Consider adding probs or\"", "\"using other config functions\"", ")", "configs_attrs_list", "=", "[", "]"...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/benchmarks/operator_benchmark/benchmark_utils.py#L236-L280
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-filter/python/filter/gui/idealbanditems.py
python
IdealBandItems.attach_allidealcurves
(self, plot)
TODO for c in self.idealbandhcurves: c.attach(plot) for c in self.idealbandvcurves: c.attach(plot)
TODO for c in self.idealbandhcurves: c.attach(plot) for c in self.idealbandvcurves: c.attach(plot)
[ "TODO", "for", "c", "in", "self", ".", "idealbandhcurves", ":", "c", ".", "attach", "(", "plot", ")", "for", "c", "in", "self", ".", "idealbandvcurves", ":", "c", ".", "attach", "(", "plot", ")" ]
def attach_allidealcurves(self, plot): ''' TODO for c in self.idealbandhcurves: c.attach(plot) for c in self.idealbandvcurves: c.attach(plot) ''' plot.replot()
[ "def", "attach_allidealcurves", "(", "self", ",", "plot", ")", ":", "plot", ".", "replot", "(", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-filter/python/filter/gui/idealbanditems.py#L205-L212
libornovax/master_thesis_code
6eca474ed3cae673afde010caef338cf7349f839
scripts/plot_multiple_learning_curves.py
python
parse_arguments
()
return args
Parse input options of the script.
Parse input options of the script.
[ "Parse", "input", "options", "of", "the", "script", "." ]
def parse_arguments(): """ Parse input options of the script. """ parser = argparse.ArgumentParser(description='Combine several learning curves into one plot.') parser.add_argument('--paths_csv', nargs='+', type=str, required=True, help='Paths to the CSV files with learning curve points. They must have ' \ '"iter loss_train loss_valid" columns') parser.add_argument('--labels', nargs='+', type=str, required=True, help='Labels of the learning curves. In the order of the CSV files') parser.add_argument('--path_out', type=str, required=True, help='Path to the output file (without extension) - extensions will be ' \ 'added automatically because more files will be generated') parser.add_argument('--title', type=str, default='', help='Title of the plot') parser.add_argument('--ylimit', type=float, default=None, help='Clip the y axis on this value') args = parser.parse_args() for path in args.paths_csv: if not check_path(path): parser.print_help() exit(1) if len(args.paths_csv) != len(args.labels): print('ERROR: Number of CSV files and labels must be the same! (%d != %d)'%(len(args.paths_csv), len(args.labels))) exit(1) return args
[ "def", "parse_arguments", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Combine several learning curves into one plot.'", ")", "parser", ".", "add_argument", "(", "'--paths_csv'", ",", "nargs", "=", "'+'", ",", "type", ...
https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/scripts/plot_multiple_learning_curves.py#L154-L183
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/internal/decoder.py
python
MapDecoder
(field_descriptor, new_default, is_message_map)
return DecodeMap
Returns a decoder for a map field.
Returns a decoder for a map field.
[ "Returns", "a", "decoder", "for", "a", "map", "field", "." ]
def MapDecoder(field_descriptor, new_default, is_message_map): """Returns a decoder for a map field.""" key = field_descriptor tag_bytes = encoder.TagBytes(field_descriptor.number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) local_DecodeVarint = _DecodeVarint # Can't read _concrete_class yet; might not be initialized. message_type = field_descriptor.message_type def DecodeMap(buffer, pos, end, message, field_dict): submsg = message_type._concrete_class() value = field_dict.get(key) if value is None: value = field_dict.setdefault(key, new_default(message)) while 1: # Read length. (size, pos) = local_DecodeVarint(buffer, pos) new_pos = pos + size if new_pos > end: raise _DecodeError('Truncated message.') # Read sub-message. submsg.Clear() if submsg._InternalParse(buffer, pos, new_pos) != new_pos: # The only reason _InternalParse would return early is if it # encountered an end-group tag. raise _DecodeError('Unexpected end-group tag.') if is_message_map: value[submsg.key].CopyFrom(submsg.value) else: value[submsg.key] = submsg.value # Predict that the next tag is another copy of the same repeated field. pos = new_pos + tag_len if buffer[new_pos:pos] != tag_bytes or new_pos == end: # Prediction failed. Return. return new_pos return DecodeMap
[ "def", "MapDecoder", "(", "field_descriptor", ",", "new_default", ",", "is_message_map", ")", ":", "key", "=", "field_descriptor", "tag_bytes", "=", "encoder", ".", "TagBytes", "(", "field_descriptor", ".", "number", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMIT...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/decoder.py#L864-L904
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/scriptutils.py
python
GetPackageModuleName
(fileName)
return fname, newPathReturn
Given a filename, return (module name, new path). eg - given "c:\a\b\c\my.py", return ("b.c.my",None) if "c:\a" is on sys.path. If no package found, will return ("my", "c:\a\b\c")
Given a filename, return (module name, new path). eg - given "c:\a\b\c\my.py", return ("b.c.my",None) if "c:\a" is on sys.path. If no package found, will return ("my", "c:\a\b\c")
[ "Given", "a", "filename", "return", "(", "module", "name", "new", "path", ")", ".", "eg", "-", "given", "c", ":", "\\", "a", "\\", "b", "\\", "c", "\\", "my", ".", "py", "return", "(", "b", ".", "c", ".", "my", "None", ")", "if", "c", ":", ...
def GetPackageModuleName(fileName): """Given a filename, return (module name, new path). eg - given "c:\a\b\c\my.py", return ("b.c.my",None) if "c:\a" is on sys.path. If no package found, will return ("my", "c:\a\b\c") """ path, fname = os.path.split(fileName) path=origPath=win32ui.FullPath(path) fname = os.path.splitext(fname)[0] modBits = [] newPathReturn = None if not IsOnPythonPath(path): # Module not directly on the search path - see if under a package. while len(path)>3: # ie 'C:\' path, modBit = os.path.split(path) modBits.append(modBit) # If on path, _and_ existing package of that name loaded. if IsOnPythonPath(path) and modBit in sys.modules and \ (os.path.exists(os.path.join(path, modBit, '__init__.py')) or \ os.path.exists(os.path.join(path, modBit, '__init__.pyc')) or \ os.path.exists(os.path.join(path, modBit, '__init__.pyo')) \ ): modBits.reverse() return ".".join(modBits) + "." + fname, newPathReturn # Not found - look a level higher else: newPathReturn = origPath return fname, newPathReturn
[ "def", "GetPackageModuleName", "(", "fileName", ")", ":", "path", ",", "fname", "=", "os", ".", "path", ".", "split", "(", "fileName", ")", "path", "=", "origPath", "=", "win32ui", ".", "FullPath", "(", "path", ")", "fname", "=", "os", ".", "path", "...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/scriptutils.py#L87-L114
facebookresearch/minirts
859e747a5e2fab2355bea083daffa6a36820a7f2
scripts/behavior_clone/cmd_heads.py
python
DotAttackHead.forward
(self, ufeat, efeat, globfeat, num_enemy)
return prob
return masked prob that each real enemy is the target return: prob: [batch, pnum_unit, pnum_enemy]
return masked prob that each real enemy is the target
[ "return", "masked", "prob", "that", "each", "real", "enemy", "is", "the", "target" ]
def forward(self, ufeat, efeat, globfeat, num_enemy): """return masked prob that each real enemy is the target return: prob: [batch, pnum_unit, pnum_enemy] """ batch, pnum_unit, _ = ufeat.size() pnum_enemy = efeat.size(1) assert_eq(num_enemy.size(), (batch,)) assert globfeat is None and self.globfeat_dim == 0 infeat = ufeat # infeat [batch, pnum_unit, in_dim] proj = self.net(infeat) proj = proj.unsqueeze(2).repeat(1, 1, pnum_enemy, 1) # proj [batch, pnum_unit, pnum_enemy, efeat_dim] efeat = efeat.unsqueeze(1).repeat(1, pnum_unit, 1, 1) # efeat [batch, pnum_unit, pnum_enemy, efeat_dim logit = (proj * efeat).sum(3) / self.norm # logit [batch, pnum_unit, pnum_enemy] enemy_mask = create_real_unit_mask(num_enemy, pnum_enemy) # enemy_mask [batch, pnum_enemy] enemy_mask = enemy_mask.unsqueeze(1).repeat(1, pnum_unit, 1) # if torch.isinf(logit).any() or torch.isnan(logit).any(): # import pdb # pdb.set_trace() prob = masked_softmax(logit, enemy_mask, 2) # prob [batch, pnum_unit, pnum_enemy] return prob
[ "def", "forward", "(", "self", ",", "ufeat", ",", "efeat", ",", "globfeat", ",", "num_enemy", ")", ":", "batch", ",", "pnum_unit", ",", "_", "=", "ufeat", ".", "size", "(", ")", "pnum_enemy", "=", "efeat", ".", "size", "(", "1", ")", "assert_eq", "...
https://github.com/facebookresearch/minirts/blob/859e747a5e2fab2355bea083daffa6a36820a7f2/scripts/behavior_clone/cmd_heads.py#L281-L309
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/bijectors/weibull.py
python
Weibull.concentration
(self)
return self._concentration
The `k` in `Y = g(X) = 1 - exp((-x / l) ** k)`.
The `k` in `Y = g(X) = 1 - exp((-x / l) ** k)`.
[ "The", "k", "in", "Y", "=", "g", "(", "X", ")", "=", "1", "-", "exp", "((", "-", "x", "/", "l", ")", "**", "k", ")", "." ]
def concentration(self): """The `k` in `Y = g(X) = 1 - exp((-x / l) ** k)`.""" return self._concentration
[ "def", "concentration", "(", "self", ")", ":", "return", "self", ".", "_concentration" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/bijectors/weibull.py#L108-L110
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/gzip.py
python
GzipFile.rewind
(self)
Return the uncompressed stream file position indicator to the beginning of the file
Return the uncompressed stream file position indicator to the beginning of the file
[ "Return", "the", "uncompressed", "stream", "file", "position", "indicator", "to", "the", "beginning", "of", "the", "file" ]
def rewind(self): '''Return the uncompressed stream file position indicator to the beginning of the file''' if self.mode != READ: raise IOError("Can't rewind in write mode") self.fileobj.seek(0) self._new_member = True self.extrabuf = "" self.extrasize = 0 self.extrastart = 0 self.offset = 0
[ "def", "rewind", "(", "self", ")", ":", "if", "self", ".", "mode", "!=", "READ", ":", "raise", "IOError", "(", "\"Can't rewind in write mode\"", ")", "self", ".", "fileobj", ".", "seek", "(", "0", ")", "self", ".", "_new_member", "=", "True", "self", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/gzip.py#L402-L412
googlevr/seurat
7b20ac69265ca7390a6c7f52a4f25b0fe87d0b53
seurat/generation/maya/seurat_rig.py
python
Distance
(point_a, point_b)
return math.sqrt(distance_sqr)
Computes the euclidean distance between two points. The points can have an aribtrary number of dimensions. Args: point_a: A list of numbers representing the first point. point_b: A list of numbers representing the second point. Returns: The euclidean distance as a float.
Computes the euclidean distance between two points.
[ "Computes", "the", "euclidean", "distance", "between", "two", "points", "." ]
def Distance(point_a, point_b): """Computes the euclidean distance between two points. The points can have an aribtrary number of dimensions. Args: point_a: A list of numbers representing the first point. point_b: A list of numbers representing the second point. Returns: The euclidean distance as a float. """ delta = map(operator.sub, point_a, point_b) delta_sqr = map(operator.mul, delta, delta) distance_sqr = 0.0 for element in delta_sqr: distance_sqr += element return math.sqrt(distance_sqr)
[ "def", "Distance", "(", "point_a", ",", "point_b", ")", ":", "delta", "=", "map", "(", "operator", ".", "sub", ",", "point_a", ",", "point_b", ")", "delta_sqr", "=", "map", "(", "operator", ".", "mul", ",", "delta", ",", "delta", ")", "distance_sqr", ...
https://github.com/googlevr/seurat/blob/7b20ac69265ca7390a6c7f52a4f25b0fe87d0b53/seurat/generation/maya/seurat_rig.py#L185-L202
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/extras/codelite.py
python
codelite_generator.project_configurations
(self)
return ret
Helper that returns all the pairs (config,platform)
Helper that returns all the pairs (config,platform)
[ "Helper", "that", "returns", "all", "the", "pairs", "(", "config", "platform", ")" ]
def project_configurations(self): """ Helper that returns all the pairs (config,platform) """ ret = [] for c in self.configurations: for p in self.platforms: ret.append((c, p)) return ret
[ "def", "project_configurations", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "c", "in", "self", ".", "configurations", ":", "for", "p", "in", "self", ".", "platforms", ":", "ret", ".", "append", "(", "(", "c", ",", "p", ")", ")", "return", ...
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/codelite.py#L785-L793
githubharald/CTCWordBeamSearch
43567e5b06dd43bdcbec452f5099171c81f5e737
extras/prototype/Metrics.py
python
Metrics.getCER
(self)
return self.edChars / self.numChars
get character error rate
get character error rate
[ "get", "character", "error", "rate" ]
def getCER(self): "get character error rate" return self.edChars / self.numChars
[ "def", "getCER", "(", "self", ")", ":", "return", "self", ".", "edChars", "/", "self", ".", "numChars" ]
https://github.com/githubharald/CTCWordBeamSearch/blob/43567e5b06dd43bdcbec452f5099171c81f5e737/extras/prototype/Metrics.py#L49-L51
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/symsrc/pefile.py
python
PE.parse_import_directory
(self, rva, size)
return import_descs
Walk and parse the import directory.
Walk and parse the import directory.
[ "Walk", "and", "parse", "the", "import", "directory", "." ]
def parse_import_directory(self, rva, size): """Walk and parse the import directory.""" import_descs = [] while True: try: # If the RVA is invalid all would blow up. Some EXEs seem to be # specially nasty and have an invalid RVA. data = self.get_data(rva) except PEFormatError, e: self.__warnings.append( 'Error parsing the Import directory at RVA: 0x%x' % ( rva ) ) break import_desc = self.__unpack_data__( self.__IMAGE_IMPORT_DESCRIPTOR_format__, data, file_offset = self.get_offset_from_rva(rva) ) # If the structure is all zeores, we reached the end of the list if not import_desc or import_desc.all_zeroes(): break rva += import_desc.sizeof() try: import_data = self.parse_imports( import_desc.OriginalFirstThunk, import_desc.FirstThunk, import_desc.ForwarderChain) except PEFormatError, excp: self.__warnings.append( 'Error parsing the Import directory. ' + 'Invalid Import data at RVA: 0x%x' % ( rva ) ) break #raise excp if not import_data: continue dll = self.get_string_at_rva(import_desc.Name) if dll: import_descs.append( ImportDescData( struct = import_desc, imports = import_data, dll = dll)) return import_descs
[ "def", "parse_import_directory", "(", "self", ",", "rva", ",", "size", ")", ":", "import_descs", "=", "[", "]", "while", "True", ":", "try", ":", "# If the RVA is invalid all would blow up. Some EXEs seem to be", "# specially nasty and have an invalid RVA.", "data", "=", ...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/symsrc/pefile.py#L2744-L2791
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
clang/tools/scan-build-py/libscanbuild/__init__.py
python
duplicate_check
(method)
return predicate
Predicate to detect duplicated entries. Unique hash method can be use to detect duplicates. Entries are represented as dictionaries, which has no default hash method. This implementation uses a set datatype to store the unique hash values. This method returns a method which can detect the duplicate values.
Predicate to detect duplicated entries.
[ "Predicate", "to", "detect", "duplicated", "entries", "." ]
def duplicate_check(method): """ Predicate to detect duplicated entries. Unique hash method can be use to detect duplicates. Entries are represented as dictionaries, which has no default hash method. This implementation uses a set datatype to store the unique hash values. This method returns a method which can detect the duplicate values. """ def predicate(entry): entry_hash = predicate.unique(entry) if entry_hash not in predicate.state: predicate.state.add(entry_hash) return False return True predicate.unique = method predicate.state = set() return predicate
[ "def", "duplicate_check", "(", "method", ")", ":", "def", "predicate", "(", "entry", ")", ":", "entry_hash", "=", "predicate", ".", "unique", "(", "entry", ")", "if", "entry_hash", "not", "in", "predicate", ".", "state", ":", "predicate", ".", "state", "...
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/tools/scan-build-py/libscanbuild/__init__.py#L25-L43
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
LayoutAlgorithm.__init__
(self, *args, **kwargs)
__init__(self) -> LayoutAlgorithm
__init__(self) -> LayoutAlgorithm
[ "__init__", "(", "self", ")", "-", ">", "LayoutAlgorithm" ]
def __init__(self, *args, **kwargs): """__init__(self) -> LayoutAlgorithm""" _windows_.LayoutAlgorithm_swiginit(self,_windows_.new_LayoutAlgorithm(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_windows_", ".", "LayoutAlgorithm_swiginit", "(", "self", ",", "_windows_", ".", "new_LayoutAlgorithm", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L2088-L2090
SeisSol/SeisSol
955fbeb8c5d40d3363a2da0edc611259aebe1653
site_scons/site_tools/PapiTool.py
python
find_lib
(env, name, pathes)
return None
Search for a library in a list of given pathes
Search for a library in a list of given pathes
[ "Search", "for", "a", "library", "in", "a", "list", "of", "given", "pathes" ]
def find_lib(env, name, pathes): """Search for a library in a list of given pathes""" prefixes = SCons.Util.flatten(env.subst_list('$LIBPREFIXES')) suffixes = SCons.Util.flatten(env.subst_list('$LIBSUFFIXES')) for prefix in prefixes: for suffix in suffixes: path = find_file(str(prefix)+name+str(suffix), pathes) if path: return path return None
[ "def", "find_lib", "(", "env", ",", "name", ",", "pathes", ")", ":", "prefixes", "=", "SCons", ".", "Util", ".", "flatten", "(", "env", ".", "subst_list", "(", "'$LIBPREFIXES'", ")", ")", "suffixes", "=", "SCons", ".", "Util", ".", "flatten", "(", "e...
https://github.com/SeisSol/SeisSol/blob/955fbeb8c5d40d3363a2da0edc611259aebe1653/site_scons/site_tools/PapiTool.py#L56-L68
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/math_ops.py
python
Atan.__init__
(self)
Initialize Atan
Initialize Atan
[ "Initialize", "Atan" ]
def __init__(self): """Initialize Atan""" self.init_prim_io_names(inputs=['x'], outputs=['output'])
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "init_prim_io_names", "(", "inputs", "=", "[", "'x'", "]", ",", "outputs", "=", "[", "'output'", "]", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/math_ops.py#L4719-L4721
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pymcuprog/samtarget.py
python
SamD2xTarget.reinitialise
(self)
Re-initialise Required after certain operations which reset the DAP on the target
Re-initialise
[ "Re", "-", "initialise" ]
def reinitialise(self): """ Re-initialise Required after certain operations which reset the DAP on the target """ self.logger.info("Re-init of SAMD2x DAP") self.debugger.dap_connect() self.debugger.dap_reset_ext(True) self.debugger.dap_swd_configure(0) self.debugger.init_swj() self.debugger.dap_target_init()
[ "def", "reinitialise", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Re-init of SAMD2x DAP\"", ")", "self", ".", "debugger", ".", "dap_connect", "(", ")", "self", ".", "debugger", ".", "dap_reset_ext", "(", "True", ")", "self", ".", ...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/samtarget.py#L132-L143
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/service.py
python
GDataService.GetAuthSubToken
(self)
Returns the AuthSub token as a string. If the token is an gdta.auth.AuthSubToken, the Authorization Label ("AuthSub token") is removed. This method examines the current_token to see if it is an AuthSubToken or SecureAuthSubToken. If not, it searches the token_store for a token which matches the current scope. The current scope is determined by the service name string member. Returns: If the current_token is set to an AuthSubToken/SecureAuthSubToken, return the token string. If there is no current_token, a token string for a token which matches the service object's default scope is returned. If there are no tokens valid for the scope, returns None.
Returns the AuthSub token as a string. If the token is an gdta.auth.AuthSubToken, the Authorization Label ("AuthSub token") is removed.
[ "Returns", "the", "AuthSub", "token", "as", "a", "string", ".", "If", "the", "token", "is", "an", "gdta", ".", "auth", ".", "AuthSubToken", "the", "Authorization", "Label", "(", "AuthSub", "token", ")", "is", "removed", "." ]
def GetAuthSubToken(self): """Returns the AuthSub token as a string. If the token is an gdta.auth.AuthSubToken, the Authorization Label ("AuthSub token") is removed. This method examines the current_token to see if it is an AuthSubToken or SecureAuthSubToken. If not, it searches the token_store for a token which matches the current scope. The current scope is determined by the service name string member. Returns: If the current_token is set to an AuthSubToken/SecureAuthSubToken, return the token string. If there is no current_token, a token string for a token which matches the service object's default scope is returned. If there are no tokens valid for the scope, returns None. """ if isinstance(self.current_token, gdata.auth.AuthSubToken): return self.current_token.get_token_string() current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.AuthSubToken): return token.get_token_string() else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() return None
[ "def", "GetAuthSubToken", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "current_token", ",", "gdata", ".", "auth", ".", "AuthSubToken", ")", ":", "return", "self", ".", "current_token", ".", "get_token_string", "(", ")", "current_scopes", "="...
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/service.py#L609-L638
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/p4util/text.py
python
Table.save
(self, file)
Function to save string of the Table object to *file*.
Function to save string of the Table object to *file*.
[ "Function", "to", "save", "string", "of", "the", "Table", "object", "to", "*", "file", "*", "." ]
def save(self, file): """Function to save string of the Table object to *file*.""" import pickle pickle_str = pickle.dumps(self) fileobj = open(file, "w") fileobj.write(str(self)) fileobj.close()
[ "def", "save", "(", "self", ",", "file", ")", ":", "import", "pickle", "pickle_str", "=", "pickle", ".", "dumps", "(", "self", ")", "fileobj", "=", "open", "(", "file", ",", "\"w\"", ")", "fileobj", ".", "write", "(", "str", "(", "self", ")", ")", ...
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/p4util/text.py#L87-L93
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/pyclbr.py
python
_create_tree
(fullmodule, path, fname, source, tree, inpackage)
return tree
Return the tree for a particular module. fullmodule (full module name), inpackage+module, becomes o.module. path is passed to recursive calls of _readmodule. fname becomes o.file. source is tokenized. Imports cause recursive calls to _readmodule. tree is {} or {'__path__': <submodule search locations>}. inpackage, None or string, is passed to recursive calls of _readmodule. The effect of recursive calls is mutation of global _modules.
Return the tree for a particular module.
[ "Return", "the", "tree", "for", "a", "particular", "module", "." ]
def _create_tree(fullmodule, path, fname, source, tree, inpackage): """Return the tree for a particular module. fullmodule (full module name), inpackage+module, becomes o.module. path is passed to recursive calls of _readmodule. fname becomes o.file. source is tokenized. Imports cause recursive calls to _readmodule. tree is {} or {'__path__': <submodule search locations>}. inpackage, None or string, is passed to recursive calls of _readmodule. The effect of recursive calls is mutation of global _modules. """ f = io.StringIO(source) stack = [] # Initialize stack of (class, indent) pairs. g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, _end, _line in g: if tokentype == DEDENT: lineno, thisindent = start # Close previous nested classes and defs. while stack and stack[-1][1] >= thisindent: del stack[-1] elif token == 'def': lineno, thisindent = start # Close previous nested classes and defs. while stack and stack[-1][1] >= thisindent: del stack[-1] tokentype, func_name, start = next(g)[0:3] if tokentype != NAME: continue # Skip def with syntax error. cur_func = None if stack: cur_obj = stack[-1][0] cur_func = _nest_function(cur_obj, func_name, lineno) else: # It is just a function. cur_func = Function(fullmodule, func_name, fname, lineno) tree[func_name] = cur_func stack.append((cur_func, thisindent)) elif token == 'class': lineno, thisindent = start # Close previous nested classes and defs. while stack and stack[-1][1] >= thisindent: del stack[-1] tokentype, class_name, start = next(g)[0:3] if tokentype != NAME: continue # Skip class with syntax error. # Parse what follows the class name. tokentype, token, start = next(g)[0:3] inherit = None if token == '(': names = [] # Initialize list of superclasses. level = 1 super = [] # Tokens making up current superclass. while True: tokentype, token, start = next(g)[0:3] if token in (')', ',') and level == 1: n = "".join(super) if n in tree: # We know this super class. n = tree[n] else: c = n.split('.') if len(c) > 1: # Super class form is module.class: # look in module for class. m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) super = [] if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass # Only use NAME and OP (== dot) tokens for type name. elif tokentype in (NAME, OP) and level == 1: super.append(token) # Expressions in the base list are not supported. inherit = names if stack: cur_obj = stack[-1][0] cur_class = _nest_class( cur_obj, class_name, lineno, inherit) else: cur_class = Class(fullmodule, class_name, inherit, fname, lineno) tree[class_name] = cur_class stack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, _mod2 in modules: try: # Recursively read the imported module. if inpackage is None: _readmodule(mod, path) else: try: _readmodule(mod, path, inpackage) except ImportError: _readmodule(mod, []) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module. d = _readmodule(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # Add any classes that were defined in the imported module # to our name space if they were mentioned in the list. for n, n2 in names: if n in d: tree[n2 or n] = d[n] elif n == '*': # Don't add names that start with _. for n in d: if n[0] != '_': tree[n] = d[n] except StopIteration: pass f.close() return tree
[ "def", "_create_tree", "(", "fullmodule", ",", "path", ",", "fname", ",", "source", ",", "tree", ",", "inpackage", ")", ":", "f", "=", "io", ".", "StringIO", "(", "source", ")", "stack", "=", "[", "]", "# Initialize stack of (class, indent) pairs.", "g", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pyclbr.py#L182-L322
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/lamb_next_right.py
python
_lamb_next_right_tbe
()
return
LambNextRight TBE register
LambNextRight TBE register
[ "LambNextRight", "TBE", "register" ]
def _lamb_next_right_tbe(): """LambNextRight TBE register""" return
[ "def", "_lamb_next_right_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/lamb_next_right.py#L42-L44
apache/parquet-cpp
642da055adf009652689b20e68a198cffb857651
build-support/cpplint.py
python
CheckCStyleCast
(filename, clean_lines, linenum, cast_type, pattern, error)
return True
Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise.
Checks for a C-style cast by looking for the pattern.
[ "Checks", "for", "a", "C", "-", "style", "cast", "by", "looking", "for", "the", "pattern", "." ]
def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ line = clean_lines.elided[linenum] match = Search(pattern, line) if not match: return False # Exclude lines with keywords that tend to look like casts context = line[0:match.start(1) - 1] if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): return False # Try expanding current context to see if we one level of # parentheses inside a macro. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 5), -1): context = clean_lines.elided[i] + context if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): return False # operator++(int) and operator--(int) if context.endswith(' operator++') or context.endswith(' operator--'): return False # A single unnamed argument for a function tends to look like old # style cast. If we see those, don't issue warnings for deprecated # casts, instead issue warnings for unnamed arguments where # appropriate. # # These are things that we want warnings for, since the style guide # explicitly require all parameters to be named: # Function(int); # Function(int) { # ConstMember(int) const; # ConstMember(int) const { # ExceptionMember(int) throw (...); # ExceptionMember(int) throw (...) { # PureVirtual(int) = 0; # [](int) -> bool { # # These are functions of some sort, where the compiler would be fine # if they had named parameters, but people often omit those # identifiers to reduce clutter: # (FunctionPointer)(int); # (FunctionPointer)(int) = value; # Function((function_pointer_arg)(int)) # Function((function_pointer_arg)(int), int param) # <TemplateArgument(int)>; # <(FunctionPointerTemplateArgument)(int)>; remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)', remainder): # Looks like an unnamed parameter. # Don't warn on any kind of template arguments. if Match(r'^\s*>', remainder): return False # Don't warn on assignments to function pointers, but keep warnings for # unnamed parameters to pure virtual functions. Note that this pattern # will also pass on assignments of "0" to function pointers, but the # preferred values for those would be "nullptr" or "NULL". matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder) if matched_zero and matched_zero.group(1) != '0': return False # Don't warn on function pointer declarations. For this we need # to check what came before the "(type)" string. if Match(r'.*\)\s*$', line[0:match.start(0)]): return False # Don't warn if the parameter is named with block comments, e.g.: # Function(int /*unused_param*/); raw_line = clean_lines.raw_lines[linenum] if '/*' in raw_line: return False # Passed all filters, issue warning here. error(filename, linenum, 'readability/function', 3, 'All parameters should be named in a function') return True # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True
[ "def", "CheckCStyleCast", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "cast_type", ",", "pattern", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Search", "(", "pattern", ",", "line", ...
https://github.com/apache/parquet-cpp/blob/642da055adf009652689b20e68a198cffb857651/build-support/cpplint.py#L5337-L5438
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ebmlib/fileutil.py
python
GetFileSize
(path)
Get the size of the file at a given path @param path: Path to file @return: long
Get the size of the file at a given path @param path: Path to file @return: long
[ "Get", "the", "size", "of", "the", "file", "at", "a", "given", "path", "@param", "path", ":", "Path", "to", "file", "@return", ":", "long" ]
def GetFileSize(path): """Get the size of the file at a given path @param path: Path to file @return: long """ try: return os.stat(path)[stat.ST_SIZE] except: return 0
[ "def", "GetFileSize", "(", "path", ")", ":", "try", ":", "return", "os", ".", "stat", "(", "path", ")", "[", "stat", ".", "ST_SIZE", "]", "except", ":", "return", "0" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/fileutil.py#L153-L162
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
xpathParserContext.xpathFreeParserContext
(self)
Free up an xmlXPathParserContext
Free up an xmlXPathParserContext
[ "Free", "up", "an", "xmlXPathParserContext" ]
def xpathFreeParserContext(self): """Free up an xmlXPathParserContext """ libxml2mod.xmlXPathFreeParserContext(self._o)
[ "def", "xpathFreeParserContext", "(", "self", ")", ":", "libxml2mod", ".", "xmlXPathFreeParserContext", "(", "self", ".", "_o", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L7521-L7523
pristineio/webrtc-mirror
7a5bcdffaab90a05bc1146b2b1ea71c004e54d71
webrtc/rtc_tools/barcode_tools/barcode_decoder.py
python
_GenerateStatsFile
(stats_file_name, input_directory='.')
Generate statistics file. The function generates a statistics file. The contents of the file are in the format <frame_name> <barcode>, where frame name is the name of every frame (effectively the frame number) and barcode is the decoded barcode. The frames and the helper .txt files are removed after they have been used.
Generate statistics file.
[ "Generate", "statistics", "file", "." ]
def _GenerateStatsFile(stats_file_name, input_directory='.'): """Generate statistics file. The function generates a statistics file. The contents of the file are in the format <frame_name> <barcode>, where frame name is the name of every frame (effectively the frame number) and barcode is the decoded barcode. The frames and the helper .txt files are removed after they have been used. """ file_prefix = os.path.join(input_directory, 'frame_') stats_file = open(stats_file_name, 'w') print 'Generating stats file: %s' % stats_file_name for i in range(1, _CountFramesIn(input_directory=input_directory) + 1): frame_number = helper_functions.ZeroPad(i) barcode_file_name = file_prefix + frame_number + '.txt' png_frame = file_prefix + frame_number + '.png' entry_frame_number = helper_functions.ZeroPad(i-1) entry = 'frame_' + entry_frame_number + ' ' if os.path.isfile(barcode_file_name): barcode = _ReadBarcodeFromTextFile(barcode_file_name) os.remove(barcode_file_name) if _CheckBarcode(barcode): entry += (helper_functions.ZeroPad(int(barcode[0:11])) + '\n') else: entry += 'Barcode error\n' # Barcode is wrongly detected. else: # Barcode file doesn't exist. entry += 'Barcode error\n' stats_file.write(entry) os.remove(png_frame) stats_file.close()
[ "def", "_GenerateStatsFile", "(", "stats_file_name", ",", "input_directory", "=", "'.'", ")", ":", "file_prefix", "=", "os", ".", "path", ".", "join", "(", "input_directory", ",", "'frame_'", ")", "stats_file", "=", "open", "(", "stats_file_name", ",", "'w'", ...
https://github.com/pristineio/webrtc-mirror/blob/7a5bcdffaab90a05bc1146b2b1ea71c004e54d71/webrtc/rtc_tools/barcode_tools/barcode_decoder.py#L119-L152
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/msgmerge.py
python
_update_or_init_po_files
(target, source, env)
return 0
Action function for `POUpdate` builder
Action function for `POUpdate` builder
[ "Action", "function", "for", "POUpdate", "builder" ]
def _update_or_init_po_files(target, source, env): """ Action function for `POUpdate` builder """ import SCons.Action from SCons.Tool.GettextCommon import _init_po_files for tgt in target: if tgt.rexists(): action = SCons.Action.Action('$MSGMERGECOM', '$MSGMERGECOMSTR') else: action = _init_po_files status = action([tgt], source, env) if status : return status return 0
[ "def", "_update_or_init_po_files", "(", "target", ",", "source", ",", "env", ")", ":", "import", "SCons", ".", "Action", "from", "SCons", ".", "Tool", ".", "GettextCommon", "import", "_init_po_files", "for", "tgt", "in", "target", ":", "if", "tgt", ".", "r...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/msgmerge.py#L30-L41
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/ansic/cparse.py
python
p_parameter_type_list_opt_2
(t)
parameter_type_list_opt : parameter_type_list
parameter_type_list_opt : parameter_type_list
[ "parameter_type_list_opt", ":", "parameter_type_list" ]
def p_parameter_type_list_opt_2(t): 'parameter_type_list_opt : parameter_type_list' pass
[ "def", "p_parameter_type_list_opt_2", "(", "t", ")", ":", "pass" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/ansic/cparse.py#L447-L449
nmslib/nmslib
5acedb651c277af8d99fa75def9f8b2590bd9512
query_server/python_client/protocol/QueryService.py
python
Client.rangeQuery
(self, r, queryObj, retExternId, retObj)
return self.recv_rangeQuery()
Parameters: - r - queryObj - retExternId - retObj
Parameters: - r - queryObj - retExternId - retObj
[ "Parameters", ":", "-", "r", "-", "queryObj", "-", "retExternId", "-", "retObj" ]
def rangeQuery(self, r, queryObj, retExternId, retObj): """ Parameters: - r - queryObj - retExternId - retObj """ self.send_rangeQuery(r, queryObj, retExternId, retObj) return self.recv_rangeQuery()
[ "def", "rangeQuery", "(", "self", ",", "r", ",", "queryObj", ",", "retExternId", ",", "retObj", ")", ":", "self", ".", "send_rangeQuery", "(", "r", ",", "queryObj", ",", "retExternId", ",", "retObj", ")", "return", "self", ".", "recv_rangeQuery", "(", ")...
https://github.com/nmslib/nmslib/blob/5acedb651c277af8d99fa75def9f8b2590bd9512/query_server/python_client/protocol/QueryService.py#L146-L155
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy/multiarray.py
python
ldexp
(x1, x2, out=None, **kwargs)
return _mx_nd_np.ldexp(x1, x2, out)
Returns x1 * 2**x2, element-wise. The mantissas `x1` and twos exponents `x2` are used to construct floating point numbers ``x1 * 2**x2``. Parameters ---------- x1 : ndarray or scalar Array of multipliers. x2 : ndarray or scalar, int Array of twos exponents. out : ndarray, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not, a freshly-allocated array is returned. Returns ------- y : ndarray or scalar The result of ``x1 * 2**x2``. This is a scalar if both `x1` and `x2` are scalars. Notes ----- Complex dtypes are not supported, they will raise a TypeError. Different from numpy, we allow x2 to be float besides int. `ldexp` is useful as the inverse of `frexp`, if used by itself it is more clear to simply use the expression ``x1 * 2**x2``. Examples -------- >>> np.ldexp(5, np.arange(4)) array([ 5., 10., 20., 40.])
Returns x1 * 2**x2, element-wise. The mantissas `x1` and twos exponents `x2` are used to construct floating point numbers ``x1 * 2**x2``.
[ "Returns", "x1", "*", "2", "**", "x2", "element", "-", "wise", ".", "The", "mantissas", "x1", "and", "twos", "exponents", "x2", "are", "used", "to", "construct", "floating", "point", "numbers", "x1", "*", "2", "**", "x2", "." ]
def ldexp(x1, x2, out=None, **kwargs): """ Returns x1 * 2**x2, element-wise. The mantissas `x1` and twos exponents `x2` are used to construct floating point numbers ``x1 * 2**x2``. Parameters ---------- x1 : ndarray or scalar Array of multipliers. x2 : ndarray or scalar, int Array of twos exponents. out : ndarray, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not, a freshly-allocated array is returned. Returns ------- y : ndarray or scalar The result of ``x1 * 2**x2``. This is a scalar if both `x1` and `x2` are scalars. Notes ----- Complex dtypes are not supported, they will raise a TypeError. Different from numpy, we allow x2 to be float besides int. `ldexp` is useful as the inverse of `frexp`, if used by itself it is more clear to simply use the expression ``x1 * 2**x2``. Examples -------- >>> np.ldexp(5, np.arange(4)) array([ 5., 10., 20., 40.]) """ return _mx_nd_np.ldexp(x1, x2, out)
[ "def", "ldexp", "(", "x1", ",", "x2", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_mx_nd_np", ".", "ldexp", "(", "x1", ",", "x2", ",", "out", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L9785-L9819
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/robotparser.py
python
RobotFileParser.set_url
(self, url)
Sets the URL referring to a robots.txt file.
Sets the URL referring to a robots.txt file.
[ "Sets", "the", "URL", "referring", "to", "a", "robots", ".", "txt", "file", "." ]
def set_url(self, url): """Sets the URL referring to a robots.txt file.""" self.url = url self.host, self.path = urlparse.urlparse(url)[1:3]
[ "def", "set_url", "(", "self", ",", "url", ")", ":", "self", ".", "url", "=", "url", "self", ".", "host", ",", "self", ".", "path", "=", "urlparse", ".", "urlparse", "(", "url", ")", "[", "1", ":", "3", "]" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/robotparser.py#L49-L52
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
driver/python/pysequoiadb/lob.py
python
lob.get_size
(self)
return size
get the size of lob. Return Values: the size of current lob Exceptions: pysequoiadb.error.SDBBaseError
get the size of lob.
[ "get", "the", "size", "of", "lob", "." ]
def get_size(self): """get the size of lob. Return Values: the size of current lob Exceptions: pysequoiadb.error.SDBBaseError """ rc, size = sdb.lob_get_size(self._handle) raise_if_error(rc, "Failed to get size of lob") return size
[ "def", "get_size", "(", "self", ")", ":", "rc", ",", "size", "=", "sdb", ".", "lob_get_size", "(", "self", ".", "_handle", ")", "raise_if_error", "(", "rc", ",", "\"Failed to get size of lob\"", ")", "return", "size" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/driver/python/pysequoiadb/lob.py#L54-L64
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/jinja2/meta.py
python
find_undeclared_variables
(ast)
return codegen.undeclared_identifiers
Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') >>> meta.find_undeclared_variables(ast) == set(['bar']) True .. admonition:: Implementation Internally the code generator is used for finding undeclared variables. This is good to know because the code generator might raise a :exc:`TemplateAssertionError` during compilation and as a matter of fact this function can currently raise that exception as well.
Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned.
[ "Returns", "a", "set", "of", "all", "variables", "in", "the", "AST", "that", "will", "be", "looked", "up", "from", "the", "context", "at", "runtime", ".", "Because", "at", "compile", "time", "it", "s", "not", "known", "which", "variables", "will", "be", ...
def find_undeclared_variables(ast): """Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') >>> meta.find_undeclared_variables(ast) == set(['bar']) True .. admonition:: Implementation Internally the code generator is used for finding undeclared variables. This is good to know because the code generator might raise a :exc:`TemplateAssertionError` during compilation and as a matter of fact this function can currently raise that exception as well. """ codegen = TrackingCodeGenerator(ast.environment) codegen.visit(ast) return codegen.undeclared_identifiers
[ "def", "find_undeclared_variables", "(", "ast", ")", ":", "codegen", "=", "TrackingCodeGenerator", "(", "ast", ".", "environment", ")", "codegen", ".", "visit", "(", "ast", ")", "return", "codegen", ".", "undeclared_identifiers" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/meta.py#L36-L57
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/external/bazel_tools/third_party/py/concurrent/futures/_base.py
python
Future.cancelled
(self)
Return True if the future has cancelled.
Return True if the future has cancelled.
[ "Return", "True", "if", "the", "future", "has", "cancelled", "." ]
def cancelled(self): """Return True if the future has cancelled.""" with self._condition: return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]
[ "def", "cancelled", "(", "self", ")", ":", "with", "self", ".", "_condition", ":", "return", "self", ".", "_state", "in", "[", "CANCELLED", ",", "CANCELLED_AND_NOTIFIED", "]" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/third_party/py/concurrent/futures/_base.py#L340-L343
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/io/ros.py
python
from_Pose
(ros_pose)
return (from_Quaternion(ros_pose.orientation),from_Point(ros_pose.position))
From ROS Pose to Klamp't se3 element
From ROS Pose to Klamp't se3 element
[ "From", "ROS", "Pose", "to", "Klamp", "t", "se3", "element" ]
def from_Pose(ros_pose): """From ROS Pose to Klamp't se3 element""" return (from_Quaternion(ros_pose.orientation),from_Point(ros_pose.position))
[ "def", "from_Pose", "(", "ros_pose", ")", ":", "return", "(", "from_Quaternion", "(", "ros_pose", ".", "orientation", ")", ",", "from_Point", "(", "ros_pose", ".", "position", ")", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/io/ros.py#L61-L63
keyboardio/Kaleidoscope
d59604e98b2439d108647f15be52984a6837d360
bin/cpplint.py
python
_DropCommonSuffixes
(filename)
return os.path.splitext(filename)[0]
Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed.
Drops common suffixes like _test.cc or -inl.h from filename.
[ "Drops", "common", "suffixes", "like", "_test", ".", "cc", "or", "-", "inl", ".", "h", "from", "filename", "." ]
def _DropCommonSuffixes(filename): """Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed. """ for suffix in itertools.chain( ('%s.%s' % (test_suffix.lstrip('_'), ext) for test_suffix, ext in itertools.product(_test_suffixes, GetNonHeaderExtensions())), ('%s.%s' % (suffix, ext) for suffix, ext in itertools.product(['inl', 'imp', 'internal'], GetHeaderExtensions()))): if (filename.endswith(suffix) and len(filename) > len(suffix) and filename[-len(suffix) - 1] in ('-', '_')): return filename[:-len(suffix) - 1] return os.path.splitext(filename)[0]
[ "def", "_DropCommonSuffixes", "(", "filename", ")", ":", "for", "suffix", "in", "itertools", ".", "chain", "(", "(", "'%s.%s'", "%", "(", "test_suffix", ".", "lstrip", "(", "'_'", ")", ",", "ext", ")", "for", "test_suffix", ",", "ext", "in", "itertools",...
https://github.com/keyboardio/Kaleidoscope/blob/d59604e98b2439d108647f15be52984a6837d360/bin/cpplint.py#L4672-L4699
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/npy_pkg_config.py
python
read_config
(pkgname, dirs=None)
Return library info for a package from its configuration file. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of directories - usually including the NumPy base directory - where to look for npy-pkg-config files. Returns ------- pkginfo : class instance The `LibraryInfo` instance containing the build information. Raises ------ PkgNotFound If the package is not found. See Also -------- misc_util.get_info, misc_util.get_pkg_info Examples -------- >>> npymath_info = np.distutils.npy_pkg_config.read_config('npymath') >>> type(npymath_info) <class 'numpy.distutils.npy_pkg_config.LibraryInfo'> >>> print npymath_info Name: npymath Description: Portable, core math library implementing C99 standard Requires: Version: 0.1 #random
Return library info for a package from its configuration file.
[ "Return", "library", "info", "for", "a", "package", "from", "its", "configuration", "file", "." ]
def read_config(pkgname, dirs=None): """ Return library info for a package from its configuration file. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of directories - usually including the NumPy base directory - where to look for npy-pkg-config files. Returns ------- pkginfo : class instance The `LibraryInfo` instance containing the build information. Raises ------ PkgNotFound If the package is not found. See Also -------- misc_util.get_info, misc_util.get_pkg_info Examples -------- >>> npymath_info = np.distutils.npy_pkg_config.read_config('npymath') >>> type(npymath_info) <class 'numpy.distutils.npy_pkg_config.LibraryInfo'> >>> print npymath_info Name: npymath Description: Portable, core math library implementing C99 standard Requires: Version: 0.1 #random """ try: return _CACHE[pkgname] except KeyError: v = _read_config_imp(pkg_to_filename(pkgname), dirs) _CACHE[pkgname] = v return v
[ "def", "read_config", "(", "pkgname", ",", "dirs", "=", "None", ")", ":", "try", ":", "return", "_CACHE", "[", "pkgname", "]", "except", "KeyError", ":", "v", "=", "_read_config_imp", "(", "pkg_to_filename", "(", "pkgname", ")", ",", "dirs", ")", "_CACHE...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/npy_pkg_config.py#L351-L395
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
FileDialog.SetMessage
(*args, **kwargs)
return _windows_.FileDialog_SetMessage(*args, **kwargs)
SetMessage(self, String message) Sets the message that will be displayed on the dialog.
SetMessage(self, String message)
[ "SetMessage", "(", "self", "String", "message", ")" ]
def SetMessage(*args, **kwargs): """ SetMessage(self, String message) Sets the message that will be displayed on the dialog. """ return _windows_.FileDialog_SetMessage(*args, **kwargs)
[ "def", "SetMessage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "FileDialog_SetMessage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L3142-L3148
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/model_fitting/model_fitting_view.py
python
ModelFittingView.current_result_table_index
(self)
return self.model_fitting_data_selector.current_result_table_index
Returns the index of the currently displayed result table.
Returns the index of the currently displayed result table.
[ "Returns", "the", "index", "of", "the", "currently", "displayed", "result", "table", "." ]
def current_result_table_index(self) -> str: """Returns the index of the currently displayed result table.""" return self.model_fitting_data_selector.current_result_table_index
[ "def", "current_result_table_index", "(", "self", ")", "->", "str", ":", "return", "self", ".", "model_fitting_data_selector", ".", "current_result_table_index" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/model_fitting/model_fitting_view.py#L74-L76
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/ops.py
python
Graph._add_op
(self, op)
Adds 'op' to the graph. Args: op: the Operator or Tensor to add. Raises: TypeError: if op is not an Operation or Tensor. ValueError: if the op.name or op._id are already used.
Adds 'op' to the graph.
[ "Adds", "op", "to", "the", "graph", "." ]
def _add_op(self, op): """Adds 'op' to the graph. Args: op: the Operator or Tensor to add. Raises: TypeError: if op is not an Operation or Tensor. ValueError: if the op.name or op._id are already used. """ self._check_not_finalized() if not isinstance(op, (Tensor, Operation)): raise TypeError("op must be a Tensor or Operation: %s" % op) with self._lock: # pylint: disable=protected-access if op._id in self._nodes_by_id: raise ValueError("cannot add an op with id %d as it already " "exists in the graph" % op._id) if op.name in self._nodes_by_name: raise ValueError("cannot add op with name %s as that name " "is already used" % op.name) self._nodes_by_id[op._id] = op self._nodes_by_name[op.name] = op self._version = max(self._version, op._id)
[ "def", "_add_op", "(", "self", ",", "op", ")", ":", "self", ".", "_check_not_finalized", "(", ")", "if", "not", "isinstance", "(", "op", ",", "(", "Tensor", ",", "Operation", ")", ")", ":", "raise", "TypeError", "(", "\"op must be a Tensor or Operation: %s\"...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/ops.py#L2292-L2315
pristineio/webrtc-mirror
7a5bcdffaab90a05bc1146b2b1ea71c004e54d71
tools_webrtc/mb/mb.py
python
MetaBuildWrapper.ToSrcRelPath
(self, path)
return self.RelPath(path, self.src_dir)
Returns a relative path from the top of the repo.
Returns a relative path from the top of the repo.
[ "Returns", "a", "relative", "path", "from", "the", "top", "of", "the", "repo", "." ]
def ToSrcRelPath(self, path): """Returns a relative path from the top of the repo.""" if path.startswith('//'): return path[2:].replace('/', self.sep) return self.RelPath(path, self.src_dir)
[ "def", "ToSrcRelPath", "(", "self", ",", "path", ")", ":", "if", "path", ".", "startswith", "(", "'//'", ")", ":", "return", "path", "[", "2", ":", "]", ".", "replace", "(", "'/'", ",", "self", ".", "sep", ")", "return", "self", ".", "RelPath", "...
https://github.com/pristineio/webrtc-mirror/blob/7a5bcdffaab90a05bc1146b2b1ea71c004e54d71/tools_webrtc/mb/mb.py#L1147-L1151
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/poplib.py
python
POP3.pass_
(self, pswd)
return self._shortcmd('PASS %s' % pswd)
Send password, return response (response includes message count, mailbox size). NB: mailbox is locked by server from here to 'quit()'
Send password, return response
[ "Send", "password", "return", "response" ]
def pass_(self, pswd): """Send password, return response (response includes message count, mailbox size). NB: mailbox is locked by server from here to 'quit()' """ return self._shortcmd('PASS %s' % pswd)
[ "def", "pass_", "(", "self", ",", "pswd", ")", ":", "return", "self", ".", "_shortcmd", "(", "'PASS %s'", "%", "pswd", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/poplib.py#L211-L218
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/layered_cache.py
python
SetExternal
(key, value, days_to_keep=None)
Sets the value in the datastore for the externally namespaced key. Needed for things like /add_point that update internal/external data at the same time. Args: key: The key name, which will be namespaced as externally_visible. value: The value to set. days_to_keep: Number of days to keep entity in datastore, default is None. Entity will not expire when this value is 0 or None.
Sets the value in the datastore for the externally namespaced key.
[ "Sets", "the", "value", "in", "the", "datastore", "for", "the", "externally", "namespaced", "key", "." ]
def SetExternal(key, value, days_to_keep=None): """Sets the value in the datastore for the externally namespaced key. Needed for things like /add_point that update internal/external data at the same time. Args: key: The key name, which will be namespaced as externally_visible. value: The value to set. days_to_keep: Number of days to keep entity in datastore, default is None. Entity will not expire when this value is 0 or None. """ Set(key, value, days_to_keep, datastore_hooks.EXTERNAL)
[ "def", "SetExternal", "(", "key", ",", "value", ",", "days_to_keep", "=", "None", ")", ":", "Set", "(", "key", ",", "value", ",", "days_to_keep", ",", "datastore_hooks", ".", "EXTERNAL", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/layered_cache.py#L150-L162
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/debug/lib/debug_data.py
python
DebugDumpDir._get_merge_node_names
(self, device_name)
return self._merge_node_names[device_name]
Lazily get a list of Merge nodes on a given device.
Lazily get a list of Merge nodes on a given device.
[ "Lazily", "get", "a", "list", "of", "Merge", "nodes", "on", "a", "given", "device", "." ]
def _get_merge_node_names(self, device_name): """Lazily get a list of Merge nodes on a given device.""" if device_name not in self._device_names: raise ValueError("Invalid device name: %s" % device_name) if not hasattr(self, "_merge_node_names"): self._merge_node_names = {} if device_name not in self._merge_node_names: debug_graph = self._debug_graphs[device_name] self._merge_node_names[device_name] = [ node for node in debug_graph.node_op_types if debug_graph.node_op_types[node] == "Merge"] return self._merge_node_names[device_name]
[ "def", "_get_merge_node_names", "(", "self", ",", "device_name", ")", ":", "if", "device_name", "not", "in", "self", ".", "_device_names", ":", "raise", "ValueError", "(", "\"Invalid device name: %s\"", "%", "device_name", ")", "if", "not", "hasattr", "(", "self...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/lib/debug_data.py#L1137-L1149
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/tpu/training_loop.py
python
while_loop
(condition: Callable[..., Any], body: Callable[..., Any], inputs: Optional[List[Any]] = None, infeed_queue: Optional[tpu_feed.InfeedQueue] = None, name: Any = None)
return control_flow_ops.while_loop( condition_wrapper, body_wrapper, inputs, name="", parallel_iterations=1)
Builds a training loop for TPUs. The set of loop-carried tensors corresponds to `inputs`. Both `condition` and `body` take the current value of the loop-carried tensors. 'body' additionally takes a tuple of infeed from infeed_queue if infeed_queue is not None. `condition` must return a single boolean value that determines whether iteration continues. `body` must return an updated list of values for the loop-carried tensors. Args: condition: a Python function that builds the loop condition. body: a Python function that builds the loop body. inputs: a list of initial values passed into the training loop, or None (equivalent to an empty list). infeed_queue: if not None, the infeed queue from which to append a tuple of arguments as inputs to condition. name: (Deprecated) Does nothing. Returns: The final values of the loop-carried tensors. Raises: TypeError: if body or condition has the wrong signature.
Builds a training loop for TPUs.
[ "Builds", "a", "training", "loop", "for", "TPUs", "." ]
def while_loop(condition: Callable[..., Any], body: Callable[..., Any], inputs: Optional[List[Any]] = None, infeed_queue: Optional[tpu_feed.InfeedQueue] = None, name: Any = None) -> Any: """Builds a training loop for TPUs. The set of loop-carried tensors corresponds to `inputs`. Both `condition` and `body` take the current value of the loop-carried tensors. 'body' additionally takes a tuple of infeed from infeed_queue if infeed_queue is not None. `condition` must return a single boolean value that determines whether iteration continues. `body` must return an updated list of values for the loop-carried tensors. Args: condition: a Python function that builds the loop condition. body: a Python function that builds the loop body. inputs: a list of initial values passed into the training loop, or None (equivalent to an empty list). infeed_queue: if not None, the infeed queue from which to append a tuple of arguments as inputs to condition. name: (Deprecated) Does nothing. Returns: The final values of the loop-carried tensors. Raises: TypeError: if body or condition has the wrong signature. """ del name # Converts inputs to Tensors. inputs = [] if inputs is None else [ops.convert_to_tensor(x) for x in inputs] input_types = [x.dtype for x in inputs] input_arity = len(inputs) body_arg_error = xla.check_function_argument_count( body, input_arity, infeed_queue) if body_arg_error is not None: if infeed_queue is None: raise TypeError( f"Supplied loop body function cannot be called with the specified " f"inputs. You specified {input_arity} inputs: {[i.name for i in inputs]}, but the loop body needs {body_arg_error}" ) else: raise TypeError( f"Supplied loop body function cannot be called with the specified " f"inputs. You specified {input_arity} inputs: {[i.name for i in inputs]} and {infeed_queue.number_of_tuple_elements} additional inputs from " f"infeed, but the computation needs {body_arg_error}") condition_arg_error = xla.check_function_argument_count( condition, input_arity, None) if condition_arg_error is not None: if infeed_queue is None: raise TypeError( f"Supplied loop condition function cannot be called with the " f"specified inputs. You specified {input_arity} inputs: {[i.name for i in inputs]}, but the loop " f"condition needs {condition_arg_error}") else: raise TypeError( f"Supplied loop condition function cannot be called with the " f"specified inputs. You specified {input_arity} inputs: {[i.name for i in inputs]}, but the loop " f"condition needs {condition_arg_error}. Note that infeed is not passed to the loop condition." ) def condition_wrapper(*inputs): # Discards the dummy output added for arity-0 loops. if input_arity == 0: inputs = [] return condition(*inputs) def body_wrapper(*inputs): """Wrapper around `body` that handles infeed queues and control deps.""" inputs = list(inputs) # Discards the dummy output added for arity-0 loops. if input_arity == 0: inputs = [] # Runs `body` with the dequeue_ops appended. if infeed_queue: number_of_shards = tpu_function.get_tpu_context().number_of_shards if number_of_shards is None: raise ValueError("Can't build training loop with infeed when there is " "no tpu_shard_context. Are you building a loop or " "graph directly rather than from inside tpu.rewrite, " "tpu.batch_parallel, tpu.shard, or tpu.replicate?") infeed_queue.set_number_of_shards(number_of_shards) dequeue_ops = [d for d in infeed_queue.generate_dequeue_op()] else: dequeue_ops = [] outputs = body(*(inputs + dequeue_ops)) # If the computation only returned one value, make it a tuple. if not isinstance(outputs, (list, tuple)): outputs = (outputs,) outputs = [ o if isinstance(o, ops.Operation) else ops.convert_to_tensor(o) for o in outputs ] # Separates the returned Operations and Tensors. output_operations = [o for o in outputs if isinstance(o, ops.Operation)] output_tensors = [o for o in outputs if not isinstance(o, ops.Operation)] if outputs != output_tensors + output_operations: raise ValueError( "TPU training loop body must return zero or more Tensor values " "followed by zero or more Operations.") output_types = [op.dtype for op in output_tensors] if input_types != output_types: raise TypeError( "Mismatch between input types and output types for training loop " "body: {} vs {}".format(input_types, output_types)) # Add the dequeue operations to output_operations to ensure they are run # by the loop, even if the programmer's loop body does not use them. output_operations += dequeue_ops # Add a dummy output, if needed. if not output_tensors: output_tensors = array_ops.constant(0) if output_operations: # TODO(phawkins): in principle this is too restrictive since it serializes # the training loop steps. In practice it does not matter since this loop # will be compiled by XLA. output_tensors = control_flow_ops.tuple(output_tensors, control_inputs=output_operations) if tensor_tracer.TensorTracer.is_enabled(): num_replicas = tpu_function.get_tpu_context().number_of_shards if num_replicas is None: num_replicas = 1 tt = tensor_tracer.TensorTracer() output_tensors = tt.trace_tpu(ops.get_default_graph(), output_tensors, None, num_replicas) return output_tensors # If the body has arity 0, add a dummy loop-carried value to which we can add # control dependencies from any side-effecting operations. if input_arity == 0: inputs = [array_ops.constant(0)] return control_flow_ops.while_loop( condition_wrapper, body_wrapper, inputs, name="", parallel_iterations=1)
[ "def", "while_loop", "(", "condition", ":", "Callable", "[", "...", ",", "Any", "]", ",", "body", ":", "Callable", "[", "...", ",", "Any", "]", ",", "inputs", ":", "Optional", "[", "List", "[", "Any", "]", "]", "=", "None", ",", "infeed_queue", ":"...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/training_loop.py#L30-L178
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
bindings/python/cntk/ops/functions.py
python
Function.arguments
(self)
return super(Function, self).arguments(python_operand_order)
List of all input variables of the Function that are not of type Parameter or Constant. Note that due to the different matrix storage format in C++(column major) and Python(row major), the order of arguments for some ops(Times, TransposeTimes, and Gemm) in C++ and Python are not the same. In previous CNTK versions, the default for this api was to return arguments in C++ order. Now the default for this api is set to python order. This way it will return arguments in the same order as they are fed into ops. If you wish to still get arguments in C++ order, you can simply override the global option. Example: >>> import cntk as C >>> a = C.input_variable((3,4), name='a') >>> b = C.input_variable((4,5), name='b') >>> c = C.times(a, b) >>> c.arguments # python order (Input('a', [#], [3 x 4]), Input('b', [#], [4 x 5])) >>> from cntk.default_options import set_global_option >>> set_global_option('python_operand_order', False) >>> c.arguments # C++ order (Input('b', [#], [4 x 5]), Input('a', [#], [3 x 4]))
List of all input variables of the Function that are not of type Parameter or Constant. Note that due to the different matrix storage format in C++(column major) and Python(row major), the order of arguments for some ops(Times, TransposeTimes, and Gemm) in C++ and Python are not the same. In previous CNTK versions, the default for this api was to return arguments in C++ order. Now the default for this api is set to python order. This way it will return arguments in the same order as they are fed into ops. If you wish to still get arguments in C++ order, you can simply override the global option. Example: >>> import cntk as C >>> a = C.input_variable((3,4), name='a') >>> b = C.input_variable((4,5), name='b') >>> c = C.times(a, b) >>> c.arguments # python order (Input('a', [#], [3 x 4]), Input('b', [#], [4 x 5]))
[ "List", "of", "all", "input", "variables", "of", "the", "Function", "that", "are", "not", "of", "type", "Parameter", "or", "Constant", ".", "Note", "that", "due", "to", "the", "different", "matrix", "storage", "format", "in", "C", "++", "(", "column", "m...
def arguments(self): ''' List of all input variables of the Function that are not of type Parameter or Constant. Note that due to the different matrix storage format in C++(column major) and Python(row major), the order of arguments for some ops(Times, TransposeTimes, and Gemm) in C++ and Python are not the same. In previous CNTK versions, the default for this api was to return arguments in C++ order. Now the default for this api is set to python order. This way it will return arguments in the same order as they are fed into ops. If you wish to still get arguments in C++ order, you can simply override the global option. Example: >>> import cntk as C >>> a = C.input_variable((3,4), name='a') >>> b = C.input_variable((4,5), name='b') >>> c = C.times(a, b) >>> c.arguments # python order (Input('a', [#], [3 x 4]), Input('b', [#], [4 x 5])) >>> from cntk.default_options import set_global_option >>> set_global_option('python_operand_order', False) >>> c.arguments # C++ order (Input('b', [#], [4 x 5]), Input('a', [#], [3 x 4])) ''' from ..default_options import get_global_option python_operand_order = get_global_option('python_operand_order', True) return super(Function, self).arguments(python_operand_order)
[ "def", "arguments", "(", "self", ")", ":", "from", ".", ".", "default_options", "import", "get_global_option", "python_operand_order", "=", "get_global_option", "(", "'python_operand_order'", ",", "True", ")", "return", "super", "(", "Function", ",", "self", ")", ...
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/ops/functions.py#L535-L561
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
veles/external/pydot.py
python
Graph.get_type
(self)
return self.obj_dict['type']
Get the graph's type, 'graph' or 'digraph'.
Get the graph's type, 'graph' or 'digraph'.
[ "Get", "the", "graph", "s", "type", "graph", "or", "digraph", "." ]
def get_type(self): """Get the graph's type, 'graph' or 'digraph'.""" return self.obj_dict['type']
[ "def", "get_type", "(", "self", ")", ":", "return", "self", ".", "obj_dict", "[", "'type'", "]" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/pydot.py#L1180-L1183
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/metric.py
python
EvalMetric.get_global_name_value
(self)
Returns zipped name and value pairs for global results. Returns ------- list of tuples A (name, value) tuple list.
Returns zipped name and value pairs for global results.
[ "Returns", "zipped", "name", "and", "value", "pairs", "for", "global", "results", "." ]
def get_global_name_value(self): """Returns zipped name and value pairs for global results. Returns ------- list of tuples A (name, value) tuple list. """ if self._has_global_stats: name, value = self.get_global() if not isinstance(name, list): name = [name] if not isinstance(value, list): value = [value] return list(zip(name, value)) else: return self.get_name_value()
[ "def", "get_global_name_value", "(", "self", ")", ":", "if", "self", ".", "_has_global_stats", ":", "name", ",", "value", "=", "self", ".", "get_global", "(", ")", "if", "not", "isinstance", "(", "name", ",", "list", ")", ":", "name", "=", "[", "name",...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/metric.py#L209-L225
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/learn/python/learn/monitors.py
python
ValidationMonitor.best_step
(self)
return self._best_value_step
Returns the step at which the best early stopping metric was found.
Returns the step at which the best early stopping metric was found.
[ "Returns", "the", "step", "at", "which", "the", "best", "early", "stopping", "metric", "was", "found", "." ]
def best_step(self): """Returns the step at which the best early stopping metric was found.""" return self._best_value_step
[ "def", "best_step", "(", "self", ")", ":", "return", "self", ".", "_best_value_step" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/monitors.py#L629-L631
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/traitlets/py3/traitlets/traitlets.py
python
Enum._choices_str
(self, as_rst=False)
return choices
Returns a description of the trait choices (not none).
Returns a description of the trait choices (not none).
[ "Returns", "a", "description", "of", "the", "trait", "choices", "(", "not", "none", ")", "." ]
def _choices_str(self, as_rst=False): """ Returns a description of the trait choices (not none).""" choices = self.values if as_rst: choices = '|'.join('``%r``' % x for x in choices) else: choices = repr(list(choices)) return choices
[ "def", "_choices_str", "(", "self", ",", "as_rst", "=", "False", ")", ":", "choices", "=", "self", ".", "values", "if", "as_rst", ":", "choices", "=", "'|'", ".", "join", "(", "'``%r``'", "%", "x", "for", "x", "in", "choices", ")", "else", ":", "ch...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py3/traitlets/traitlets.py#L2303-L2310
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/win_tool.py
python
WinTool.ExecMidlWrapper
(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, *flags)
return popen.returncode
Filter noisy filenames output from MIDL compile step that isn't quietable via command line flags.
Filter noisy filenames output from MIDL compile step that isn't quietable via command line flags.
[ "Filter", "noisy", "filenames", "output", "from", "MIDL", "compile", "step", "that", "isn", "t", "quietable", "via", "command", "line", "flags", "." ]
def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, *flags): """Filter noisy filenames output from MIDL compile step that isn't quietable via command line flags. """ args = ['midl', '/nologo'] + list(flags) + [ '/out', outdir, '/tlb', tlb, '/h', h, '/dlldata', dlldata, '/iid', iid, '/proxy', proxy, idl] env = self._GetEnv(arch) popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = popen.communicate() # Filter junk out of stdout, and write filtered versions. Output we want # to filter is pairs of lines that look like this: # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl # objidl.idl lines = out.splitlines() prefixes = ('Processing ', '64 bit Processing ') processing = set(os.path.basename(x) for x in lines if x.startswith(prefixes)) for line in lines: if not line.startswith(prefixes) and line not in processing: print line return popen.returncode
[ "def", "ExecMidlWrapper", "(", "self", ",", "arch", ",", "outdir", ",", "tlb", ",", "h", ",", "dlldata", ",", "iid", ",", "proxy", ",", "idl", ",", "*", "flags", ")", ":", "args", "=", "[", "'midl'", ",", "'/nologo'", "]", "+", "list", "(", "flag...
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/win_tool.py#L229-L257
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/perf/profile_creators/profile_extender.py
python
ProfileExtender.profile_path
(self)
return getattr(self.finder_options, 'output_profile_path', self.finder_options.browser_options.output_profile_path)
The path of the profile that the browser will use while it's running.
The path of the profile that the browser will use while it's running.
[ "The", "path", "of", "the", "profile", "that", "the", "browser", "will", "use", "while", "it", "s", "running", "." ]
def profile_path(self): """The path of the profile that the browser will use while it's running.""" # TODO(eakuefner): Remove this after crrev.com/1874473006 rolls in. return getattr(self.finder_options, 'output_profile_path', self.finder_options.browser_options.output_profile_path)
[ "def", "profile_path", "(", "self", ")", ":", "# TODO(eakuefner): Remove this after crrev.com/1874473006 rolls in.", "return", "getattr", "(", "self", ".", "finder_options", ",", "'output_profile_path'", ",", "self", ".", "finder_options", ".", "browser_options", ".", "ou...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/perf/profile_creators/profile_extender.py#L62-L66