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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | bert-gpu/modeling.py | python | get_activation | (activation_string) | Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`.
Args:
activation_string: String name of the activation function.
Returns:
A Python function corresponding to the activation function. If
`activation_string` is None, empty, or "linear", this will return None.
If `activation_string` is not a string, it will return `activation_string`.
Raises:
ValueError: The `activation_string` does not correspond to a known
activation. | Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`. | [
"Maps",
"a",
"string",
"to",
"a",
"Python",
"function",
"e",
".",
"g",
".",
"relu",
"=",
">",
"tf",
".",
"nn",
".",
"relu",
"."
] | def get_activation(activation_string):
"""Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`.
Args:
activation_string: String name of the activation function.
Returns:
A Python function corresponding to the activation function. If
`activation_string` is None, empty, or "linear", this will return None.
If `activation_string` is not a string, it will return `activation_string`.
Raises:
ValueError: The `activation_string` does not correspond to a known
activation.
"""
# We assume that anything that"s not a string is already an activation
# function, so we just return it.
if not isinstance(activation_string, six.string_types):
return activation_string
if not activation_string:
return None
act = activation_string.lower()
if act == "linear":
return None
elif act == "relu":
return tf.nn.relu
elif act == "gelu":
return gelu
elif act == "tanh":
return tf.tanh
else:
raise ValueError("Unsupported activation: %s" % act) | [
"def",
"get_activation",
"(",
"activation_string",
")",
":",
"# We assume that anything that\"s not a string is already an activation",
"# function, so we just return it.",
"if",
"not",
"isinstance",
"(",
"activation_string",
",",
"six",
".",
"string_types",
")",
":",
"return",
"activation_string",
"if",
"not",
"activation_string",
":",
"return",
"None",
"act",
"=",
"activation_string",
".",
"lower",
"(",
")",
"if",
"act",
"==",
"\"linear\"",
":",
"return",
"None",
"elif",
"act",
"==",
"\"relu\"",
":",
"return",
"tf",
".",
"nn",
".",
"relu",
"elif",
"act",
"==",
"\"gelu\"",
":",
"return",
"gelu",
"elif",
"act",
"==",
"\"tanh\"",
":",
"return",
"tf",
".",
"tanh",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unsupported activation: %s\"",
"%",
"act",
")"
] | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/modeling.py#L288-L322 | ||
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | demo/HuggingFace/run.py | python | main | () | return action.execute(known_args) | Parses network folders and responsible for passing --help flags to subcommands if --network is provided.
Returns:
None | Parses network folders and responsible for passing --help flags to subcommands if --network is provided. | [
"Parses",
"network",
"folders",
"and",
"responsible",
"for",
"passing",
"--",
"help",
"flags",
"to",
"subcommands",
"if",
"--",
"network",
"is",
"provided",
"."
] | def main() -> None:
"""
Parses network folders and responsible for passing --help flags to subcommands if --network is provided.
Returns:
None
"""
# Get all available network scripts
networks = register_network_folders(os.getcwd())
# Add network folder for entry point
description = "Runs TensorRT networks that are based-off of HuggingFace variants."
parser = get_default_parser(networks, description, add_default_help=False)
# Get the general network wrapper help
known_args, _ = parser.parse_known_args()
# Delegate parser to action specifics
action = get_action(known_args.action, networks, parser)
known_args, _ = parser.parse_known_args()
return action.execute(known_args) | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"# Get all available network scripts",
"networks",
"=",
"register_network_folders",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"# Add network folder for entry point",
"description",
"=",
"\"Runs TensorRT networks that are based-off of HuggingFace variants.\"",
"parser",
"=",
"get_default_parser",
"(",
"networks",
",",
"description",
",",
"add_default_help",
"=",
"False",
")",
"# Get the general network wrapper help",
"known_args",
",",
"_",
"=",
"parser",
".",
"parse_known_args",
"(",
")",
"# Delegate parser to action specifics",
"action",
"=",
"get_action",
"(",
"known_args",
".",
"action",
",",
"networks",
",",
"parser",
")",
"known_args",
",",
"_",
"=",
"parser",
".",
"parse_known_args",
"(",
")",
"return",
"action",
".",
"execute",
"(",
"known_args",
")"
] | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/demo/HuggingFace/run.py#L231-L251 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | MouseEvent.Aux1Down | (*args, **kwargs) | return _core_.MouseEvent_Aux1Down(*args, **kwargs) | Aux1Down(self) -> bool
Returns true if the AUX1 mouse button state changed to down. | Aux1Down(self) -> bool | [
"Aux1Down",
"(",
"self",
")",
"-",
">",
"bool"
] | def Aux1Down(*args, **kwargs):
"""
Aux1Down(self) -> bool
Returns true if the AUX1 mouse button state changed to down.
"""
return _core_.MouseEvent_Aux1Down(*args, **kwargs) | [
"def",
"Aux1Down",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MouseEvent_Aux1Down",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L5649-L5655 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/utils.py | python | iter_token_lines | (tokenlist) | Iterator that yields tokenlists for each line. | Iterator that yields tokenlists for each line. | [
"Iterator",
"that",
"yields",
"tokenlists",
"for",
"each",
"line",
"."
] | def iter_token_lines(tokenlist):
"""
Iterator that yields tokenlists for each line.
"""
line = []
for token, c in explode_tokens(tokenlist):
line.append((token, c))
if c == '\n':
yield line
line = []
yield line | [
"def",
"iter_token_lines",
"(",
"tokenlist",
")",
":",
"line",
"=",
"[",
"]",
"for",
"token",
",",
"c",
"in",
"explode_tokens",
"(",
"tokenlist",
")",
":",
"line",
".",
"append",
"(",
"(",
"token",
",",
"c",
")",
")",
"if",
"c",
"==",
"'\\n'",
":",
"yield",
"line",
"line",
"=",
"[",
"]",
"yield",
"line"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/utils.py#L47-L59 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/dateutil/rrule.py | python | rrulebase.xafter | (self, dt, count=None, inc=False) | Generator which yields up to `count` recurrences after the given
datetime instance, equivalent to `after`.
:param dt:
The datetime at which to start generating recurrences.
:param count:
The maximum number of recurrences to generate. If `None` (default),
dates are generated until the recurrence rule is exhausted.
:param inc:
If `dt` is an instance of the rule and `inc` is `True`, it is
included in the output.
:yields: Yields a sequence of `datetime` objects. | Generator which yields up to `count` recurrences after the given
datetime instance, equivalent to `after`. | [
"Generator",
"which",
"yields",
"up",
"to",
"count",
"recurrences",
"after",
"the",
"given",
"datetime",
"instance",
"equivalent",
"to",
"after",
"."
] | def xafter(self, dt, count=None, inc=False):
"""
Generator which yields up to `count` recurrences after the given
datetime instance, equivalent to `after`.
:param dt:
The datetime at which to start generating recurrences.
:param count:
The maximum number of recurrences to generate. If `None` (default),
dates are generated until the recurrence rule is exhausted.
:param inc:
If `dt` is an instance of the rule and `inc` is `True`, it is
included in the output.
:yields: Yields a sequence of `datetime` objects.
"""
if self._cache_complete:
gen = self._cache
else:
gen = self
# Select the comparison function
if inc:
comp = lambda dc, dtc: dc >= dtc
else:
comp = lambda dc, dtc: dc > dtc
# Generate dates
n = 0
for d in gen:
if comp(d, dt):
if count is not None:
n += 1
if n > count:
break
yield d | [
"def",
"xafter",
"(",
"self",
",",
"dt",
",",
"count",
"=",
"None",
",",
"inc",
"=",
"False",
")",
":",
"if",
"self",
".",
"_cache_complete",
":",
"gen",
"=",
"self",
".",
"_cache",
"else",
":",
"gen",
"=",
"self",
"# Select the comparison function",
"if",
"inc",
":",
"comp",
"=",
"lambda",
"dc",
",",
"dtc",
":",
"dc",
">=",
"dtc",
"else",
":",
"comp",
"=",
"lambda",
"dc",
",",
"dtc",
":",
"dc",
">",
"dtc",
"# Generate dates",
"n",
"=",
"0",
"for",
"d",
"in",
"gen",
":",
"if",
"comp",
"(",
"d",
",",
"dt",
")",
":",
"if",
"count",
"is",
"not",
"None",
":",
"n",
"+=",
"1",
"if",
"n",
">",
"count",
":",
"break",
"yield",
"d"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/dateutil/rrule.py#L228-L267 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/training/queue_runner_impl.py | python | QueueRunner.exceptions_raised | (self) | return self._exceptions_raised | Exceptions raised but not handled by the `QueueRunner` threads.
Exceptions raised in queue runner threads are handled in one of two ways
depending on whether or not a `Coordinator` was passed to
`create_threads()`:
* With a `Coordinator`, exceptions are reported to the coordinator and
forgotten by the `QueueRunner`.
* Without a `Coordinator`, exceptions are captured by the `QueueRunner` and
made available in this `exceptions_raised` property.
Returns:
A list of Python `Exception` objects. The list is empty if no exception
was captured. (No exceptions are captured when using a Coordinator.) | Exceptions raised but not handled by the `QueueRunner` threads. | [
"Exceptions",
"raised",
"but",
"not",
"handled",
"by",
"the",
"QueueRunner",
"threads",
"."
] | def exceptions_raised(self):
"""Exceptions raised but not handled by the `QueueRunner` threads.
Exceptions raised in queue runner threads are handled in one of two ways
depending on whether or not a `Coordinator` was passed to
`create_threads()`:
* With a `Coordinator`, exceptions are reported to the coordinator and
forgotten by the `QueueRunner`.
* Without a `Coordinator`, exceptions are captured by the `QueueRunner` and
made available in this `exceptions_raised` property.
Returns:
A list of Python `Exception` objects. The list is empty if no exception
was captured. (No exceptions are captured when using a Coordinator.)
"""
return self._exceptions_raised | [
"def",
"exceptions_raised",
"(",
"self",
")",
":",
"return",
"self",
".",
"_exceptions_raised"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/queue_runner_impl.py#L196-L212 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/labeled_tensor/python/ops/core.py | python | _find_consistent_ordering | (a, b) | return ordering | Find the left-most consistent ordering between two lists of unique items.
A consistent ordering combines all elements in both a and b while keeping all
elements in their original order in both inputs. The left-most consistent
ordering orders elements from `a` not found in `b` before elements in `b` not
found in `a`.
For example, given ['x', 'z'] and ['y', 'z'], both ['x', 'y', 'z'] and ['y',
'x', 'z'] are consistent orderings because each of the inputs appears in
each consistent ordering in the same order, and ['x', 'y', 'z'] is the
left-most, because 'x' appears only in `a` and 'y' appears only in `b`. In
contrast, there is no consistent ordering between ['x', 'y'] and ['y', 'x'].
Args:
a: list with unique elements.
b: list with unique elements.
Returns:
List containing all elements in either a or b, or None, if no consistent
ordering exists. | Find the left-most consistent ordering between two lists of unique items. | [
"Find",
"the",
"left",
"-",
"most",
"consistent",
"ordering",
"between",
"two",
"lists",
"of",
"unique",
"items",
"."
] | def _find_consistent_ordering(a, b):
"""Find the left-most consistent ordering between two lists of unique items.
A consistent ordering combines all elements in both a and b while keeping all
elements in their original order in both inputs. The left-most consistent
ordering orders elements from `a` not found in `b` before elements in `b` not
found in `a`.
For example, given ['x', 'z'] and ['y', 'z'], both ['x', 'y', 'z'] and ['y',
'x', 'z'] are consistent orderings because each of the inputs appears in
each consistent ordering in the same order, and ['x', 'y', 'z'] is the
left-most, because 'x' appears only in `a` and 'y' appears only in `b`. In
contrast, there is no consistent ordering between ['x', 'y'] and ['y', 'x'].
Args:
a: list with unique elements.
b: list with unique elements.
Returns:
List containing all elements in either a or b, or None, if no consistent
ordering exists.
"""
a_set = set(a)
b_set = set(b)
i = 0
j = 0
ordering = []
while i < len(a) and j < len(b):
if a[i] not in b_set:
ordering.append(a[i])
i += 1
elif b[j] not in a_set:
ordering.append(b[j])
j += 1
elif a[i] == b[j]:
ordering.append(a[i])
i += 1
j += 1
else:
return None
ordering.extend(a[i:])
ordering.extend(b[j:])
return ordering | [
"def",
"_find_consistent_ordering",
"(",
"a",
",",
"b",
")",
":",
"a_set",
"=",
"set",
"(",
"a",
")",
"b_set",
"=",
"set",
"(",
"b",
")",
"i",
"=",
"0",
"j",
"=",
"0",
"ordering",
"=",
"[",
"]",
"while",
"i",
"<",
"len",
"(",
"a",
")",
"and",
"j",
"<",
"len",
"(",
"b",
")",
":",
"if",
"a",
"[",
"i",
"]",
"not",
"in",
"b_set",
":",
"ordering",
".",
"append",
"(",
"a",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"elif",
"b",
"[",
"j",
"]",
"not",
"in",
"a_set",
":",
"ordering",
".",
"append",
"(",
"b",
"[",
"j",
"]",
")",
"j",
"+=",
"1",
"elif",
"a",
"[",
"i",
"]",
"==",
"b",
"[",
"j",
"]",
":",
"ordering",
".",
"append",
"(",
"a",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"j",
"+=",
"1",
"else",
":",
"return",
"None",
"ordering",
".",
"extend",
"(",
"a",
"[",
"i",
":",
"]",
")",
"ordering",
".",
"extend",
"(",
"b",
"[",
"j",
":",
"]",
")",
"return",
"ordering"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/labeled_tensor/python/ops/core.py#L916-L960 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/multiprocessing/connection.py | python | Listener.accept | (self) | return c | Accept a connection on the bound socket or named pipe of `self`.
Returns a `Connection` object. | Accept a connection on the bound socket or named pipe of `self`. | [
"Accept",
"a",
"connection",
"on",
"the",
"bound",
"socket",
"or",
"named",
"pipe",
"of",
"self",
"."
] | def accept(self):
'''
Accept a connection on the bound socket or named pipe of `self`.
Returns a `Connection` object.
'''
c = self._listener.accept()
if self._authkey:
deliver_challenge(c, self._authkey)
answer_challenge(c, self._authkey)
return c | [
"def",
"accept",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"_listener",
".",
"accept",
"(",
")",
"if",
"self",
".",
"_authkey",
":",
"deliver_challenge",
"(",
"c",
",",
"self",
".",
"_authkey",
")",
"answer_challenge",
"(",
"c",
",",
"self",
".",
"_authkey",
")",
"return",
"c"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/multiprocessing/connection.py#L139-L149 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/imaplib.py | python | IMAP4.login | (self, user, password) | return typ, dat | Identify client using plaintext password.
(typ, [data]) = <instance>.login(user, password)
NB: 'password' will be quoted. | Identify client using plaintext password. | [
"Identify",
"client",
"using",
"plaintext",
"password",
"."
] | def login(self, user, password):
"""Identify client using plaintext password.
(typ, [data]) = <instance>.login(user, password)
NB: 'password' will be quoted.
"""
typ, dat = self._simple_command('LOGIN', user, self._quote(password))
if typ != 'OK':
raise self.error(dat[-1])
self.state = 'AUTH'
return typ, dat | [
"def",
"login",
"(",
"self",
",",
"user",
",",
"password",
")",
":",
"typ",
",",
"dat",
"=",
"self",
".",
"_simple_command",
"(",
"'LOGIN'",
",",
"user",
",",
"self",
".",
"_quote",
"(",
"password",
")",
")",
"if",
"typ",
"!=",
"'OK'",
":",
"raise",
"self",
".",
"error",
"(",
"dat",
"[",
"-",
"1",
"]",
")",
"self",
".",
"state",
"=",
"'AUTH'",
"return",
"typ",
",",
"dat"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/imaplib.py#L603-L614 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/ma/core.py | python | filled | (a, fill_value=None) | Return input as an array with masked data replaced by a fill value.
If `a` is not a `MaskedArray`, `a` itself is returned.
If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to
``a.fill_value``.
Parameters
----------
a : MaskedArray or array_like
An input object.
fill_value : scalar, optional
Filling value. Default is None.
Returns
-------
a : ndarray
The filled array.
See Also
--------
compressed
Examples
--------
>>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
... [1, 0, 0],
... [0, 0, 0]])
>>> x.filled()
array([[999999, 1, 2],
[999999, 4, 5],
[ 6, 7, 8]]) | Return input as an array with masked data replaced by a fill value. | [
"Return",
"input",
"as",
"an",
"array",
"with",
"masked",
"data",
"replaced",
"by",
"a",
"fill",
"value",
"."
] | def filled(a, fill_value=None):
"""
Return input as an array with masked data replaced by a fill value.
If `a` is not a `MaskedArray`, `a` itself is returned.
If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to
``a.fill_value``.
Parameters
----------
a : MaskedArray or array_like
An input object.
fill_value : scalar, optional
Filling value. Default is None.
Returns
-------
a : ndarray
The filled array.
See Also
--------
compressed
Examples
--------
>>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
... [1, 0, 0],
... [0, 0, 0]])
>>> x.filled()
array([[999999, 1, 2],
[999999, 4, 5],
[ 6, 7, 8]])
"""
if hasattr(a, 'filled'):
return a.filled(fill_value)
elif isinstance(a, ndarray):
# Should we check for contiguity ? and a.flags['CONTIGUOUS']:
return a
elif isinstance(a, dict):
return np.array(a, 'O')
else:
return np.array(a) | [
"def",
"filled",
"(",
"a",
",",
"fill_value",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"a",
",",
"'filled'",
")",
":",
"return",
"a",
".",
"filled",
"(",
"fill_value",
")",
"elif",
"isinstance",
"(",
"a",
",",
"ndarray",
")",
":",
"# Should we check for contiguity ? and a.flags['CONTIGUOUS']:",
"return",
"a",
"elif",
"isinstance",
"(",
"a",
",",
"dict",
")",
":",
"return",
"np",
".",
"array",
"(",
"a",
",",
"'O'",
")",
"else",
":",
"return",
"np",
".",
"array",
"(",
"a",
")"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/core.py#L532-L575 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/protocols.py | python | DatagramProtocol.error_received | (self, exc) | Called when a send or receive operation raises an OSError.
(Other than BlockingIOError or InterruptedError.) | Called when a send or receive operation raises an OSError. | [
"Called",
"when",
"a",
"send",
"or",
"receive",
"operation",
"raises",
"an",
"OSError",
"."
] | def error_received(self, exc):
"""Called when a send or receive operation raises an OSError.
(Other than BlockingIOError or InterruptedError.)
""" | [
"def",
"error_received",
"(",
"self",
",",
"exc",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/protocols.py#L166-L170 | ||
garbear/kodi-steamlink | 3f8e5970b01607cdb3c2688fbaa78e08f2d9c561 | tools/EventClients/lib/python/xbmcclient.py | python | XBMCClient.send_action | (self, actionmessage="", actiontype=ACTION_EXECBUILTIN) | Keyword arguments:
actionmessage -- the ActionString
actiontype -- The ActionType the ActionString should be sent to. | Keyword arguments:
actionmessage -- the ActionString
actiontype -- The ActionType the ActionString should be sent to. | [
"Keyword",
"arguments",
":",
"actionmessage",
"--",
"the",
"ActionString",
"actiontype",
"--",
"The",
"ActionType",
"the",
"ActionString",
"should",
"be",
"sent",
"to",
"."
] | def send_action(self, actionmessage="", actiontype=ACTION_EXECBUILTIN):
"""
Keyword arguments:
actionmessage -- the ActionString
actiontype -- The ActionType the ActionString should be sent to.
"""
packet = PacketACTION(actionmessage, actiontype)
packet.send(self.sock, self.addr, self.uid) | [
"def",
"send_action",
"(",
"self",
",",
"actionmessage",
"=",
"\"\"",
",",
"actiontype",
"=",
"ACTION_EXECBUILTIN",
")",
":",
"packet",
"=",
"PacketACTION",
"(",
"actionmessage",
",",
"actiontype",
")",
"packet",
".",
"send",
"(",
"self",
".",
"sock",
",",
"self",
".",
"addr",
",",
"self",
".",
"uid",
")"
] | https://github.com/garbear/kodi-steamlink/blob/3f8e5970b01607cdb3c2688fbaa78e08f2d9c561/tools/EventClients/lib/python/xbmcclient.py#L624-L631 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/solvers/python/ops/util.py | python | identity_operator | (matrix) | return linear_operator(
shape=shape,
dtype=matrix.dtype,
apply=lambda v: v,
apply_adjoint=lambda v: v) | Creates a linear operator from a rank-2 identity tensor. | Creates a linear operator from a rank-2 identity tensor. | [
"Creates",
"a",
"linear",
"operator",
"from",
"a",
"rank",
"-",
"2",
"identity",
"tensor",
"."
] | def identity_operator(matrix):
"""Creates a linear operator from a rank-2 identity tensor."""
linear_operator = collections.namedtuple(
"LinearOperator", ["shape", "dtype", "apply", "apply_adjoint"])
shape = matrix.get_shape()
if shape.is_fully_defined():
shape = shape.as_list()
else:
shape = array_ops.shape(matrix)
return linear_operator(
shape=shape,
dtype=matrix.dtype,
apply=lambda v: v,
apply_adjoint=lambda v: v) | [
"def",
"identity_operator",
"(",
"matrix",
")",
":",
"linear_operator",
"=",
"collections",
".",
"namedtuple",
"(",
"\"LinearOperator\"",
",",
"[",
"\"shape\"",
",",
"\"dtype\"",
",",
"\"apply\"",
",",
"\"apply_adjoint\"",
"]",
")",
"shape",
"=",
"matrix",
".",
"get_shape",
"(",
")",
"if",
"shape",
".",
"is_fully_defined",
"(",
")",
":",
"shape",
"=",
"shape",
".",
"as_list",
"(",
")",
"else",
":",
"shape",
"=",
"array_ops",
".",
"shape",
"(",
"matrix",
")",
"return",
"linear_operator",
"(",
"shape",
"=",
"shape",
",",
"dtype",
"=",
"matrix",
".",
"dtype",
",",
"apply",
"=",
"lambda",
"v",
":",
"v",
",",
"apply_adjoint",
"=",
"lambda",
"v",
":",
"v",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/solvers/python/ops/util.py#L48-L62 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/device_worker.py | python | DeviceWorker._gen_worker_desc | (self, trainer_desc) | Generator worker desc.
Args:
trainer_desc(TrainerDesc): a TrainerDesc object | Generator worker desc. | [
"Generator",
"worker",
"desc",
"."
] | def _gen_worker_desc(self, trainer_desc):
"""
Generator worker desc.
Args:
trainer_desc(TrainerDesc): a TrainerDesc object
"""
raise NotImplementedError(
"DeviceWorker does not implement gen_worker_desc, "
"please use Hogwild or DownpourSGD, etc.") | [
"def",
"_gen_worker_desc",
"(",
"self",
",",
"trainer_desc",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"DeviceWorker does not implement gen_worker_desc, \"",
"\"please use Hogwild or DownpourSGD, etc.\"",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/device_worker.py#L63-L72 | ||
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/programs/scripts/metadata/Music/discid/disc.py | python | Disc._get_first_track_num | (self) | return _LIB.discid_get_first_track_num(self._handle) | Gets the first track number | Gets the first track number | [
"Gets",
"the",
"first",
"track",
"number"
] | def _get_first_track_num(self):
"""Gets the first track number
"""
assert self._success
return _LIB.discid_get_first_track_num(self._handle) | [
"def",
"_get_first_track_num",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_success",
"return",
"_LIB",
".",
"discid_get_first_track_num",
"(",
"self",
".",
"_handle",
")"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/metadata/Music/discid/disc.py#L227-L231 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/nvvm.py | python | _replace_llvm_memset_usage | (m) | return '({})'.format(out) | Replace `llvm.memset` usage for llvm7+.
Used as functor for `re.sub. | Replace `llvm.memset` usage for llvm7+. | [
"Replace",
"llvm",
".",
"memset",
"usage",
"for",
"llvm7",
"+",
"."
] | def _replace_llvm_memset_usage(m):
"""Replace `llvm.memset` usage for llvm7+.
Used as functor for `re.sub.
"""
params = list(m.group(1).split(','))
align = re.search(r'align (\d+)', params[0]).group(1)
params.insert(-1, 'i32 {}'.format(align))
out = ', '.join(params)
return '({})'.format(out) | [
"def",
"_replace_llvm_memset_usage",
"(",
"m",
")",
":",
"params",
"=",
"list",
"(",
"m",
".",
"group",
"(",
"1",
")",
".",
"split",
"(",
"','",
")",
")",
"align",
"=",
"re",
".",
"search",
"(",
"r'align (\\d+)'",
",",
"params",
"[",
"0",
"]",
")",
".",
"group",
"(",
"1",
")",
"params",
".",
"insert",
"(",
"-",
"1",
",",
"'i32 {}'",
".",
"format",
"(",
"align",
")",
")",
"out",
"=",
"', '",
".",
"join",
"(",
"params",
")",
"return",
"'({})'",
".",
"format",
"(",
"out",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/nvvm.py#L652-L661 | |
gemrb/gemrb | 730206eed8d1dd358ca5e69a62f9e099aa22ffc6 | gemrb/GUIScripts/GUIOPTControls.py | python | OptCheckbox | (winhelp, ctlhelp, help_ta, window, button_id, label_id, label_strref, variable, handler=None, value=1) | return button | Standard checkbox for option windows | Standard checkbox for option windows | [
"Standard",
"checkbox",
"for",
"option",
"windows"
] | def OptCheckbox (winhelp, ctlhelp, help_ta, window, button_id, label_id, label_strref, variable, handler=None, value=1):
"""Standard checkbox for option windows"""
button = window.GetControl (button_id)
button.SetFlags (IE_GUI_BUTTON_CHECKBOX, OP_OR)
if variable:
button.SetVarAssoc (variable, value)
if GameCheck.IsIWD2():
button.SetSprites("GBTNOPT4", 0, 0, 1, 2, 3)
elif GameCheck.IsIWD1() or GameCheck.IsBG1():
button.SetSprites ("GMPPARBC", 3, 1, 2, 3, 5)
if handler:
button.SetEvent (IE_GUI_BUTTON_ON_PRESS, handler)
else:
def callback():
help_ta.SetText(ctlhelp)
button.SetEvent (IE_GUI_MOUSE_ENTER_BUTTON, callback)
OptBuddyLabel (window, label_id, label_strref, help_ta, ctlhelp, winhelp)
return button | [
"def",
"OptCheckbox",
"(",
"winhelp",
",",
"ctlhelp",
",",
"help_ta",
",",
"window",
",",
"button_id",
",",
"label_id",
",",
"label_strref",
",",
"variable",
",",
"handler",
"=",
"None",
",",
"value",
"=",
"1",
")",
":",
"button",
"=",
"window",
".",
"GetControl",
"(",
"button_id",
")",
"button",
".",
"SetFlags",
"(",
"IE_GUI_BUTTON_CHECKBOX",
",",
"OP_OR",
")",
"if",
"variable",
":",
"button",
".",
"SetVarAssoc",
"(",
"variable",
",",
"value",
")",
"if",
"GameCheck",
".",
"IsIWD2",
"(",
")",
":",
"button",
".",
"SetSprites",
"(",
"\"GBTNOPT4\"",
",",
"0",
",",
"0",
",",
"1",
",",
"2",
",",
"3",
")",
"elif",
"GameCheck",
".",
"IsIWD1",
"(",
")",
"or",
"GameCheck",
".",
"IsBG1",
"(",
")",
":",
"button",
".",
"SetSprites",
"(",
"\"GMPPARBC\"",
",",
"3",
",",
"1",
",",
"2",
",",
"3",
",",
"5",
")",
"if",
"handler",
":",
"button",
".",
"SetEvent",
"(",
"IE_GUI_BUTTON_ON_PRESS",
",",
"handler",
")",
"else",
":",
"def",
"callback",
"(",
")",
":",
"help_ta",
".",
"SetText",
"(",
"ctlhelp",
")",
"button",
".",
"SetEvent",
"(",
"IE_GUI_MOUSE_ENTER_BUTTON",
",",
"callback",
")",
"OptBuddyLabel",
"(",
"window",
",",
"label_id",
",",
"label_strref",
",",
"help_ta",
",",
"ctlhelp",
",",
"winhelp",
")",
"return",
"button"
] | https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/GUIOPTControls.py#L76-L99 | |
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/util/tty/color.py | python | cescape | (string) | return str(string).replace('@', '@@') | Replace all @ with @@ in the string provided. | Replace all | [
"Replace",
"all"
] | def cescape(string):
"""Replace all @ with @@ in the string provided."""
return str(string).replace('@', '@@') | [
"def",
"cescape",
"(",
"string",
")",
":",
"return",
"str",
"(",
"string",
")",
".",
"replace",
"(",
"'@'",
",",
"'@@'",
")"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/util/tty/color.py#L189-L191 | |
fifengine/fifengine | 4b62c42e85bec19893cef8e63e6855927cff2c47 | engine/python/fife/extensions/pychan/widgets/widget.py | python | Widget.getNamedChildren | (self, include_unnamed = False) | return children | Create a dictionary of child widgets with the keys being
their name. This will contain only Widgets which have
a name different from "__unnamed__" (which is the default).
@param include_unnamed: Defaults to false. If this is true unnamed widgets are added, too.
The values are lists of widgets, so not only unique names
are handled correctly.
Usage::
children = widget.getNamedChildren()
for widget in children.get("info",[])
print widget.name , " == info" | Create a dictionary of child widgets with the keys being
their name. This will contain only Widgets which have
a name different from "__unnamed__" (which is the default).
@param include_unnamed: Defaults to false. If this is true unnamed widgets are added, too.
The values are lists of widgets, so not only unique names
are handled correctly. | [
"Create",
"a",
"dictionary",
"of",
"child",
"widgets",
"with",
"the",
"keys",
"being",
"their",
"name",
".",
"This",
"will",
"contain",
"only",
"Widgets",
"which",
"have",
"a",
"name",
"different",
"from",
"__unnamed__",
"(",
"which",
"is",
"the",
"default",
")",
".",
"@param",
"include_unnamed",
":",
"Defaults",
"to",
"false",
".",
"If",
"this",
"is",
"true",
"unnamed",
"widgets",
"are",
"added",
"too",
".",
"The",
"values",
"are",
"lists",
"of",
"widgets",
"so",
"not",
"only",
"unique",
"names",
"are",
"handled",
"correctly",
"."
] | def getNamedChildren(self, include_unnamed = False):
"""
Create a dictionary of child widgets with the keys being
their name. This will contain only Widgets which have
a name different from "__unnamed__" (which is the default).
@param include_unnamed: Defaults to false. If this is true unnamed widgets are added, too.
The values are lists of widgets, so not only unique names
are handled correctly.
Usage::
children = widget.getNamedChildren()
for widget in children.get("info",[])
print widget.name , " == info"
"""
children = {}
if include_unnamed:
def _childCollector(widget):
children.setdefault(widget._name,[]).append(widget)
else:
def _childCollector(widget):
if widget.has_name:
children.setdefault(widget._name,[]).append(widget)
self.deepApply(_childCollector)
return children | [
"def",
"getNamedChildren",
"(",
"self",
",",
"include_unnamed",
"=",
"False",
")",
":",
"children",
"=",
"{",
"}",
"if",
"include_unnamed",
":",
"def",
"_childCollector",
"(",
"widget",
")",
":",
"children",
".",
"setdefault",
"(",
"widget",
".",
"_name",
",",
"[",
"]",
")",
".",
"append",
"(",
"widget",
")",
"else",
":",
"def",
"_childCollector",
"(",
"widget",
")",
":",
"if",
"widget",
".",
"has_name",
":",
"children",
".",
"setdefault",
"(",
"widget",
".",
"_name",
",",
"[",
"]",
")",
".",
"append",
"(",
"widget",
")",
"self",
".",
"deepApply",
"(",
"_childCollector",
")",
"return",
"children"
] | https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/pychan/widgets/widget.py#L562-L587 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/Input/BlockTree.py | python | BlockTree._includeParents | (self, block) | Recursively set all parent blocks to be included
Input:
block[BlockInfo]: Include the parent of this block | Recursively set all parent blocks to be included
Input:
block[BlockInfo]: Include the parent of this block | [
"Recursively",
"set",
"all",
"parent",
"blocks",
"to",
"be",
"included",
"Input",
":",
"block",
"[",
"BlockInfo",
"]",
":",
"Include",
"the",
"parent",
"of",
"this",
"block"
] | def _includeParents(self, block):
"""
Recursively set all parent blocks to be included
Input:
block[BlockInfo]: Include the parent of this block
"""
item = self._path_item_map.get(block.path)
if item:
parent = item.parent()
if parent:
parent_block = self._item_block_map.get(parent.__str__())
if parent.checkState(0) == Qt.Unchecked:
parent.setCheckState(0, Qt.Checked)
parent_block.included = True
self.changed.emit(parent_block)
self._includeParents(parent_block) | [
"def",
"_includeParents",
"(",
"self",
",",
"block",
")",
":",
"item",
"=",
"self",
".",
"_path_item_map",
".",
"get",
"(",
"block",
".",
"path",
")",
"if",
"item",
":",
"parent",
"=",
"item",
".",
"parent",
"(",
")",
"if",
"parent",
":",
"parent_block",
"=",
"self",
".",
"_item_block_map",
".",
"get",
"(",
"parent",
".",
"__str__",
"(",
")",
")",
"if",
"parent",
".",
"checkState",
"(",
"0",
")",
"==",
"Qt",
".",
"Unchecked",
":",
"parent",
".",
"setCheckState",
"(",
"0",
",",
"Qt",
".",
"Checked",
")",
"parent_block",
".",
"included",
"=",
"True",
"self",
".",
"changed",
".",
"emit",
"(",
"parent_block",
")",
"self",
".",
"_includeParents",
"(",
"parent_block",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/BlockTree.py#L306-L321 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | benchmark/opperf/nd_operations/nn_optimizer_operators.py | python | run_optimizer_operators_benchmarks | (ctx=mx.cpu(), dtype='float32', profiler='native', int64_tensor='off', warmup=25, runs=100) | return merge_map_list(multi_sgd_mom_res + multi_sgd_mom_res + multi_sgd_res + multi_mp_sgd_res + preloaded_multi_mp_sgd_res +\
preloaded_multi_sgd_mom_res + preloaded_multi_mp_sgd_res + preloaded_multi_mp_sgd_mom_res +\
multi_mp_sgd_mom_res + preloaded_multi_sgd_res + [mx_optimizer_op_results]) | Runs benchmarks with the given context, precision (dtype), and input data size (int64_tensor) for all the neural network
optimizer update operators in MXNet.
Parameters
----------
ctx: mx.ctx
Context to run benchmarks
dtype: str, default 'float32'
Precision to use for benchmarks
profiler: str, default 'native'
Type of Profiler to use (native/python)
int64_tensor: str, default 'off'
Input tensor size to use for tests (if on, dimensions >= 2**32)
warmup: int, default 25
Number of times to run for warmup
runs: int, default 100
Number of runs to capture benchmark results
Returns
-------
Dictionary of results. Key -> Name of the operator, Value -> Benchmark results. | Runs benchmarks with the given context, precision (dtype), and input data size (int64_tensor) for all the neural network
optimizer update operators in MXNet. | [
"Runs",
"benchmarks",
"with",
"the",
"given",
"context",
"precision",
"(",
"dtype",
")",
"and",
"input",
"data",
"size",
"(",
"int64_tensor",
")",
"for",
"all",
"the",
"neural",
"network",
"optimizer",
"update",
"operators",
"in",
"MXNet",
"."
] | def run_optimizer_operators_benchmarks(ctx=mx.cpu(), dtype='float32', profiler='native', int64_tensor='off', warmup=25, runs=100):
"""Runs benchmarks with the given context, precision (dtype), and input data size (int64_tensor) for all the neural network
optimizer update operators in MXNet.
Parameters
----------
ctx: mx.ctx
Context to run benchmarks
dtype: str, default 'float32'
Precision to use for benchmarks
profiler: str, default 'native'
Type of Profiler to use (native/python)
int64_tensor: str, default 'off'
Input tensor size to use for tests (if on, dimensions >= 2**32)
warmup: int, default 25
Number of times to run for warmup
runs: int, default 100
Number of runs to capture benchmark results
Returns
-------
Dictionary of results. Key -> Name of the operator, Value -> Benchmark results.
"""
standard_shape = (5, 5)
int64_tensor_shape = (2**16, 2**16)
if int64_tensor == 'on':
arg_shape = int64_tensor_shape
else:
arg_shape = standard_shape
# Run independent tests for ops that need specific input data
multi_mp_sgd_mom_res = run_performance_test([getattr(MX_OP_MODULE, "multi_mp_sgd_mom_update")],
inputs=[{"args0": nd.random_normal(shape=arg_shape),
"args1": nd.random_normal(shape=arg_shape), "args2": nd.random_normal(shape=arg_shape),
"args3": nd.random_normal(shape=arg_shape), "lrs": 0.1, "wds": 0.2,
"out": nd.random_normal(shape=arg_shape)}],run_backward=False)
multi_sgd_mom_res = run_performance_test([getattr(MX_OP_MODULE, "multi_sgd_mom_update")],
inputs=[{"args0": nd.random_normal(shape=arg_shape),
"args1": nd.random_normal(shape=arg_shape),"args2": nd.random_normal(shape=arg_shape),
"lrs": 0.1, "wds": 0.2, "out": nd.random_normal(shape=arg_shape)}], run_backward=False)
multi_sgd_res = run_performance_test([getattr(MX_OP_MODULE, "multi_sgd_update")],
inputs=[{"args0": nd.random_normal(shape=arg_shape),
"args1": nd.random_normal(shape=arg_shape), "lrs": 0.1, "wds": 0.2,
"out": nd.random_normal(shape=arg_shape)}], run_backward=False)
multi_mp_sgd_res = run_performance_test([getattr(MX_OP_MODULE, "multi_mp_sgd_update")],
inputs=[{"args0": nd.random_normal(shape=arg_shape),
"args1": nd.random_normal(shape=arg_shape),"args2": nd.random_normal(shape=arg_shape),
"lrs": 0.1, "wds": 0.2, "out": nd.random_normal(shape=arg_shape)}], run_backward=False)
preloaded_multi_mp_sgd_res = run_performance_test(
[getattr(MX_OP_MODULE, "preloaded_multi_mp_sgd_update")],
inputs=[{"args0": nd.random_normal(shape=arg_shape),
"args1": nd.random_normal(shape=arg_shape), "args2": nd.random_normal(shape=arg_shape),
"args3": nd.random_normal(shape=(1)), "args4": nd.random_normal(shape=(1)),
"out": nd.random_normal(shape=arg_shape)}], run_backward=False)
preloaded_multi_sgd_mom_res = run_performance_test(
[getattr(MX_OP_MODULE, "preloaded_multi_sgd_mom_update")],
inputs=[{"args0": nd.random_normal(shape=arg_shape),
"args1": nd.random_normal(shape=arg_shape), "args2": nd.random_normal(shape=arg_shape),
"args3": nd.random_normal(shape=(1)), "args4": nd.random_normal(shape=(1)),
"out": nd.random_normal(shape=arg_shape)}], run_backward=False)
preloaded_multi_sgd_res = run_performance_test(
[getattr(MX_OP_MODULE, "preloaded_multi_sgd_update")],
inputs=[{"args0": nd.random_normal(shape=arg_shape), "args1": nd.random_normal(shape=arg_shape),
"args4": nd.random_normal(shape=(1)), "args5": nd.random_normal(shape=(1)),
"out": nd.random_normal(shape=arg_shape)}], run_backward=False)
preloaded_multi_mp_sgd_mom_res = run_performance_test(
[getattr(MX_OP_MODULE, "preloaded_multi_mp_sgd_mom_update")],
inputs=[{"args0": nd.random_normal(shape=arg_shape), "args1": nd.random_normal(shape=arg_shape),
"args2": nd.random_normal(shape=arg_shape), "args3": nd.random_normal(shape=arg_shape),
"args4": nd.random_normal(shape=(1)), "args5": nd.random_normal(shape=(1)),
"out": nd.random_normal(shape=arg_shape)}], run_backward=False)
# Fetch remaining optimizer operators
mx_optimizer_ops = get_all_optimizer_operators()
# Run benchmarks
mx_optimizer_op_results = run_op_benchmarks(mx_optimizer_ops, dtype, ctx, profiler, int64_tensor, warmup, runs)
return merge_map_list(multi_sgd_mom_res + multi_sgd_mom_res + multi_sgd_res + multi_mp_sgd_res + preloaded_multi_mp_sgd_res +\
preloaded_multi_sgd_mom_res + preloaded_multi_mp_sgd_res + preloaded_multi_mp_sgd_mom_res +\
multi_mp_sgd_mom_res + preloaded_multi_sgd_res + [mx_optimizer_op_results]) | [
"def",
"run_optimizer_operators_benchmarks",
"(",
"ctx",
"=",
"mx",
".",
"cpu",
"(",
")",
",",
"dtype",
"=",
"'float32'",
",",
"profiler",
"=",
"'native'",
",",
"int64_tensor",
"=",
"'off'",
",",
"warmup",
"=",
"25",
",",
"runs",
"=",
"100",
")",
":",
"standard_shape",
"=",
"(",
"5",
",",
"5",
")",
"int64_tensor_shape",
"=",
"(",
"2",
"**",
"16",
",",
"2",
"**",
"16",
")",
"if",
"int64_tensor",
"==",
"'on'",
":",
"arg_shape",
"=",
"int64_tensor_shape",
"else",
":",
"arg_shape",
"=",
"standard_shape",
"# Run independent tests for ops that need specific input data",
"multi_mp_sgd_mom_res",
"=",
"run_performance_test",
"(",
"[",
"getattr",
"(",
"MX_OP_MODULE",
",",
"\"multi_mp_sgd_mom_update\"",
")",
"]",
",",
"inputs",
"=",
"[",
"{",
"\"args0\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args1\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args2\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args3\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"lrs\"",
":",
"0.1",
",",
"\"wds\"",
":",
"0.2",
",",
"\"out\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
"}",
"]",
",",
"run_backward",
"=",
"False",
")",
"multi_sgd_mom_res",
"=",
"run_performance_test",
"(",
"[",
"getattr",
"(",
"MX_OP_MODULE",
",",
"\"multi_sgd_mom_update\"",
")",
"]",
",",
"inputs",
"=",
"[",
"{",
"\"args0\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args1\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args2\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"lrs\"",
":",
"0.1",
",",
"\"wds\"",
":",
"0.2",
",",
"\"out\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
"}",
"]",
",",
"run_backward",
"=",
"False",
")",
"multi_sgd_res",
"=",
"run_performance_test",
"(",
"[",
"getattr",
"(",
"MX_OP_MODULE",
",",
"\"multi_sgd_update\"",
")",
"]",
",",
"inputs",
"=",
"[",
"{",
"\"args0\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args1\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"lrs\"",
":",
"0.1",
",",
"\"wds\"",
":",
"0.2",
",",
"\"out\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
"}",
"]",
",",
"run_backward",
"=",
"False",
")",
"multi_mp_sgd_res",
"=",
"run_performance_test",
"(",
"[",
"getattr",
"(",
"MX_OP_MODULE",
",",
"\"multi_mp_sgd_update\"",
")",
"]",
",",
"inputs",
"=",
"[",
"{",
"\"args0\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args1\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args2\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"lrs\"",
":",
"0.1",
",",
"\"wds\"",
":",
"0.2",
",",
"\"out\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
"}",
"]",
",",
"run_backward",
"=",
"False",
")",
"preloaded_multi_mp_sgd_res",
"=",
"run_performance_test",
"(",
"[",
"getattr",
"(",
"MX_OP_MODULE",
",",
"\"preloaded_multi_mp_sgd_update\"",
")",
"]",
",",
"inputs",
"=",
"[",
"{",
"\"args0\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args1\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args2\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args3\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"(",
"1",
")",
")",
",",
"\"args4\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"(",
"1",
")",
")",
",",
"\"out\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
"}",
"]",
",",
"run_backward",
"=",
"False",
")",
"preloaded_multi_sgd_mom_res",
"=",
"run_performance_test",
"(",
"[",
"getattr",
"(",
"MX_OP_MODULE",
",",
"\"preloaded_multi_sgd_mom_update\"",
")",
"]",
",",
"inputs",
"=",
"[",
"{",
"\"args0\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args1\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args2\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args3\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"(",
"1",
")",
")",
",",
"\"args4\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"(",
"1",
")",
")",
",",
"\"out\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
"}",
"]",
",",
"run_backward",
"=",
"False",
")",
"preloaded_multi_sgd_res",
"=",
"run_performance_test",
"(",
"[",
"getattr",
"(",
"MX_OP_MODULE",
",",
"\"preloaded_multi_sgd_update\"",
")",
"]",
",",
"inputs",
"=",
"[",
"{",
"\"args0\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args1\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args4\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"(",
"1",
")",
")",
",",
"\"args5\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"(",
"1",
")",
")",
",",
"\"out\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
"}",
"]",
",",
"run_backward",
"=",
"False",
")",
"preloaded_multi_mp_sgd_mom_res",
"=",
"run_performance_test",
"(",
"[",
"getattr",
"(",
"MX_OP_MODULE",
",",
"\"preloaded_multi_mp_sgd_mom_update\"",
")",
"]",
",",
"inputs",
"=",
"[",
"{",
"\"args0\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args1\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args2\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args3\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
",",
"\"args4\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"(",
"1",
")",
")",
",",
"\"args5\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"(",
"1",
")",
")",
",",
"\"out\"",
":",
"nd",
".",
"random_normal",
"(",
"shape",
"=",
"arg_shape",
")",
"}",
"]",
",",
"run_backward",
"=",
"False",
")",
"# Fetch remaining optimizer operators",
"mx_optimizer_ops",
"=",
"get_all_optimizer_operators",
"(",
")",
"# Run benchmarks",
"mx_optimizer_op_results",
"=",
"run_op_benchmarks",
"(",
"mx_optimizer_ops",
",",
"dtype",
",",
"ctx",
",",
"profiler",
",",
"int64_tensor",
",",
"warmup",
",",
"runs",
")",
"return",
"merge_map_list",
"(",
"multi_sgd_mom_res",
"+",
"multi_sgd_mom_res",
"+",
"multi_sgd_res",
"+",
"multi_mp_sgd_res",
"+",
"preloaded_multi_mp_sgd_res",
"+",
"preloaded_multi_sgd_mom_res",
"+",
"preloaded_multi_mp_sgd_res",
"+",
"preloaded_multi_mp_sgd_mom_res",
"+",
"multi_mp_sgd_mom_res",
"+",
"preloaded_multi_sgd_res",
"+",
"[",
"mx_optimizer_op_results",
"]",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/benchmark/opperf/nd_operations/nn_optimizer_operators.py#L57-L145 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/string.py | python | count | (s, *args) | return s.count(*args) | count(s, sub[, start[,end]]) -> int
Return the number of occurrences of substring sub in string
s[start:end]. Optional arguments start and end are
interpreted as in slice notation. | count(s, sub[, start[,end]]) -> int | [
"count",
"(",
"s",
"sub",
"[",
"start",
"[",
"end",
"]]",
")",
"-",
">",
"int"
] | def count(s, *args):
"""count(s, sub[, start[,end]]) -> int
Return the number of occurrences of substring sub in string
s[start:end]. Optional arguments start and end are
interpreted as in slice notation.
"""
return s.count(*args) | [
"def",
"count",
"(",
"s",
",",
"*",
"args",
")",
":",
"return",
"s",
".",
"count",
"(",
"*",
"args",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/string.py#L342-L350 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/random/_pickle.py | python | __generator_ctor | (bit_generator_name='MT19937') | return Generator(bit_generator()) | Pickling helper function that returns a Generator object
Parameters
----------
bit_generator_name: str
String containing the core BitGenerator
Returns
-------
rg: Generator
Generator using the named core BitGenerator | Pickling helper function that returns a Generator object | [
"Pickling",
"helper",
"function",
"that",
"returns",
"a",
"Generator",
"object"
] | def __generator_ctor(bit_generator_name='MT19937'):
"""
Pickling helper function that returns a Generator object
Parameters
----------
bit_generator_name: str
String containing the core BitGenerator
Returns
-------
rg: Generator
Generator using the named core BitGenerator
"""
if bit_generator_name in BitGenerators:
bit_generator = BitGenerators[bit_generator_name]
else:
raise ValueError(str(bit_generator_name) + ' is not a known '
'BitGenerator module.')
return Generator(bit_generator()) | [
"def",
"__generator_ctor",
"(",
"bit_generator_name",
"=",
"'MT19937'",
")",
":",
"if",
"bit_generator_name",
"in",
"BitGenerators",
":",
"bit_generator",
"=",
"BitGenerators",
"[",
"bit_generator_name",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"bit_generator_name",
")",
"+",
"' is not a known '",
"'BitGenerator module.'",
")",
"return",
"Generator",
"(",
"bit_generator",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/random/_pickle.py#L16-L36 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/fileinput.py | python | fileno | () | return _state.fileno() | Return the file number of the current file. When no file is currently
opened, returns -1. | Return the file number of the current file. When no file is currently
opened, returns -1. | [
"Return",
"the",
"file",
"number",
"of",
"the",
"current",
"file",
".",
"When",
"no",
"file",
"is",
"currently",
"opened",
"returns",
"-",
"1",
"."
] | def fileno():
"""
Return the file number of the current file. When no file is currently
opened, returns -1.
"""
if not _state:
raise RuntimeError, "no active input()"
return _state.fileno() | [
"def",
"fileno",
"(",
")",
":",
"if",
"not",
"_state",
":",
"raise",
"RuntimeError",
",",
"\"no active input()\"",
"return",
"_state",
".",
"fileno",
"(",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/fileinput.py#L157-L164 | |
cyberbotics/webots | af7fa7d68dcf7b4550f1f2e132092b41e83698fc | projects/humans/c3d/controllers/c3d_viewer/c3d.py | python | Param.float_array | (self) | return self._as_array('f') | Get the param as an array of 32-bit floats. | Get the param as an array of 32-bit floats. | [
"Get",
"the",
"param",
"as",
"an",
"array",
"of",
"32",
"-",
"bit",
"floats",
"."
] | def float_array(self):
'''Get the param as an array of 32-bit floats.'''
return self._as_array('f') | [
"def",
"float_array",
"(",
"self",
")",
":",
"return",
"self",
".",
"_as_array",
"(",
"'f'",
")"
] | https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/projects/humans/c3d/controllers/c3d_viewer/c3d.py#L363-L365 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/containers.py | python | Window._copy_body | (
self,
ui_content: UIContent,
new_screen: Screen,
write_position: WritePosition,
move_x: int,
width: int,
vertical_scroll: int = 0,
horizontal_scroll: int = 0,
wrap_lines: bool = False,
highlight_lines: bool = False,
vertical_scroll_2: int = 0,
always_hide_cursor: bool = False,
has_focus: bool = False,
align: WindowAlign = WindowAlign.LEFT,
get_line_prefix: Optional[Callable[[int, int], AnyFormattedText]] = None,
) | return visible_line_to_row_col, rowcol_to_yx | Copy the UIContent into the output screen.
Return (visible_line_to_row_col, rowcol_to_yx) tuple.
:param get_line_prefix: None or a callable that takes a line number
(int) and a wrap_count (int) and returns formatted text. | Copy the UIContent into the output screen.
Return (visible_line_to_row_col, rowcol_to_yx) tuple. | [
"Copy",
"the",
"UIContent",
"into",
"the",
"output",
"screen",
".",
"Return",
"(",
"visible_line_to_row_col",
"rowcol_to_yx",
")",
"tuple",
"."
] | def _copy_body(
self,
ui_content: UIContent,
new_screen: Screen,
write_position: WritePosition,
move_x: int,
width: int,
vertical_scroll: int = 0,
horizontal_scroll: int = 0,
wrap_lines: bool = False,
highlight_lines: bool = False,
vertical_scroll_2: int = 0,
always_hide_cursor: bool = False,
has_focus: bool = False,
align: WindowAlign = WindowAlign.LEFT,
get_line_prefix: Optional[Callable[[int, int], AnyFormattedText]] = None,
) -> Tuple[Dict[int, Tuple[int, int]], Dict[Tuple[int, int], Tuple[int, int]]]:
"""
Copy the UIContent into the output screen.
Return (visible_line_to_row_col, rowcol_to_yx) tuple.
:param get_line_prefix: None or a callable that takes a line number
(int) and a wrap_count (int) and returns formatted text.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
line_count = ui_content.line_count
new_buffer = new_screen.data_buffer
empty_char = _CHAR_CACHE["", ""]
# Map visible line number to (row, col) of input.
# 'col' will always be zero if line wrapping is off.
visible_line_to_row_col: Dict[int, Tuple[int, int]] = {}
# Maps (row, col) from the input to (y, x) screen coordinates.
rowcol_to_yx: Dict[Tuple[int, int], Tuple[int, int]] = {}
def copy_line(
line: StyleAndTextTuples,
lineno: int,
x: int,
y: int,
is_input: bool = False,
) -> Tuple[int, int]:
"""
Copy over a single line to the output screen. This can wrap over
multiple lines in the output. It will call the prefix (prompt)
function before every line.
"""
if is_input:
current_rowcol_to_yx = rowcol_to_yx
else:
current_rowcol_to_yx = {} # Throwaway dictionary.
# Draw line prefix.
if is_input and get_line_prefix:
prompt = to_formatted_text(get_line_prefix(lineno, 0))
x, y = copy_line(prompt, lineno, x, y, is_input=False)
# Scroll horizontally.
skipped = 0 # Characters skipped because of horizontal scrolling.
if horizontal_scroll and is_input:
h_scroll = horizontal_scroll
line = explode_text_fragments(line)
while h_scroll > 0 and line:
h_scroll -= get_cwidth(line[0][1])
skipped += 1
del line[:1] # Remove first character.
x -= h_scroll # When scrolling over double width character,
# this can end up being negative.
# Align this line. (Note that this doesn't work well when we use
# get_line_prefix and that function returns variable width prefixes.)
if align == WindowAlign.CENTER:
line_width = fragment_list_width(line)
if line_width < width:
x += (width - line_width) // 2
elif align == WindowAlign.RIGHT:
line_width = fragment_list_width(line)
if line_width < width:
x += width - line_width
col = 0
wrap_count = 0
for style, text, *_ in line:
new_buffer_row = new_buffer[y + ypos]
# Remember raw VT escape sequences. (E.g. FinalTerm's
# escape sequences.)
if "[ZeroWidthEscape]" in style:
new_screen.zero_width_escapes[y + ypos][x + xpos] += text
continue
for c in text:
char = _CHAR_CACHE[c, style]
char_width = char.width
# Wrap when the line width is exceeded.
if wrap_lines and x + char_width > width:
visible_line_to_row_col[y + 1] = (
lineno,
visible_line_to_row_col[y][1] + x,
)
y += 1
wrap_count += 1
x = 0
# Insert line prefix (continuation prompt).
if is_input and get_line_prefix:
prompt = to_formatted_text(
get_line_prefix(lineno, wrap_count)
)
x, y = copy_line(prompt, lineno, x, y, is_input=False)
new_buffer_row = new_buffer[y + ypos]
if y >= write_position.height:
return x, y # Break out of all for loops.
# Set character in screen and shift 'x'.
if x >= 0 and y >= 0 and x < width:
new_buffer_row[x + xpos] = char
# When we print a multi width character, make sure
# to erase the neighbours positions in the screen.
# (The empty string if different from everything,
# so next redraw this cell will repaint anyway.)
if char_width > 1:
for i in range(1, char_width):
new_buffer_row[x + xpos + i] = empty_char
# If this is a zero width characters, then it's
# probably part of a decomposed unicode character.
# See: https://en.wikipedia.org/wiki/Unicode_equivalence
# Merge it in the previous cell.
elif char_width == 0:
# Handle all character widths. If the previous
# character is a multiwidth character, then
# merge it two positions back.
for pw in [2, 1]: # Previous character width.
if (
x - pw >= 0
and new_buffer_row[x + xpos - pw].width == pw
):
prev_char = new_buffer_row[x + xpos - pw]
char2 = _CHAR_CACHE[
prev_char.char + c, prev_char.style
]
new_buffer_row[x + xpos - pw] = char2
# Keep track of write position for each character.
current_rowcol_to_yx[lineno, col + skipped] = (
y + ypos,
x + xpos,
)
col += 1
x += char_width
return x, y
# Copy content.
def copy() -> int:
y = -vertical_scroll_2
lineno = vertical_scroll
while y < write_position.height and lineno < line_count:
# Take the next line and copy it in the real screen.
line = ui_content.get_line(lineno)
visible_line_to_row_col[y] = (lineno, horizontal_scroll)
# Copy margin and actual line.
x = 0
x, y = copy_line(line, lineno, x, y, is_input=True)
lineno += 1
y += 1
return y
copy()
def cursor_pos_to_screen_pos(row: int, col: int) -> Point:
"Translate row/col from UIContent to real Screen coordinates."
try:
y, x = rowcol_to_yx[row, col]
except KeyError:
# Normally this should never happen. (It is a bug, if it happens.)
# But to be sure, return (0, 0)
return Point(x=0, y=0)
# raise ValueError(
# 'Invalid position. row=%r col=%r, vertical_scroll=%r, '
# 'horizontal_scroll=%r, height=%r' %
# (row, col, vertical_scroll, horizontal_scroll, write_position.height))
else:
return Point(x=x, y=y)
# Set cursor and menu positions.
if ui_content.cursor_position:
screen_cursor_position = cursor_pos_to_screen_pos(
ui_content.cursor_position.y, ui_content.cursor_position.x
)
if has_focus:
new_screen.set_cursor_position(self, screen_cursor_position)
if always_hide_cursor:
new_screen.show_cursor = False
else:
new_screen.show_cursor = ui_content.show_cursor
self._highlight_digraph(new_screen)
if highlight_lines:
self._highlight_cursorlines(
new_screen,
screen_cursor_position,
xpos,
ypos,
width,
write_position.height,
)
# Draw input characters from the input processor queue.
if has_focus and ui_content.cursor_position:
self._show_key_processor_key_buffer(new_screen)
# Set menu position.
if ui_content.menu_position:
new_screen.set_menu_position(
self,
cursor_pos_to_screen_pos(
ui_content.menu_position.y, ui_content.menu_position.x
),
)
# Update output screen height.
new_screen.height = max(new_screen.height, ypos + write_position.height)
return visible_line_to_row_col, rowcol_to_yx | [
"def",
"_copy_body",
"(",
"self",
",",
"ui_content",
":",
"UIContent",
",",
"new_screen",
":",
"Screen",
",",
"write_position",
":",
"WritePosition",
",",
"move_x",
":",
"int",
",",
"width",
":",
"int",
",",
"vertical_scroll",
":",
"int",
"=",
"0",
",",
"horizontal_scroll",
":",
"int",
"=",
"0",
",",
"wrap_lines",
":",
"bool",
"=",
"False",
",",
"highlight_lines",
":",
"bool",
"=",
"False",
",",
"vertical_scroll_2",
":",
"int",
"=",
"0",
",",
"always_hide_cursor",
":",
"bool",
"=",
"False",
",",
"has_focus",
":",
"bool",
"=",
"False",
",",
"align",
":",
"WindowAlign",
"=",
"WindowAlign",
".",
"LEFT",
",",
"get_line_prefix",
":",
"Optional",
"[",
"Callable",
"[",
"[",
"int",
",",
"int",
"]",
",",
"AnyFormattedText",
"]",
"]",
"=",
"None",
",",
")",
"->",
"Tuple",
"[",
"Dict",
"[",
"int",
",",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
",",
"Dict",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
",",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"]",
":",
"xpos",
"=",
"write_position",
".",
"xpos",
"+",
"move_x",
"ypos",
"=",
"write_position",
".",
"ypos",
"line_count",
"=",
"ui_content",
".",
"line_count",
"new_buffer",
"=",
"new_screen",
".",
"data_buffer",
"empty_char",
"=",
"_CHAR_CACHE",
"[",
"\"\"",
",",
"\"\"",
"]",
"# Map visible line number to (row, col) of input.",
"# 'col' will always be zero if line wrapping is off.",
"visible_line_to_row_col",
":",
"Dict",
"[",
"int",
",",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"=",
"{",
"}",
"# Maps (row, col) from the input to (y, x) screen coordinates.",
"rowcol_to_yx",
":",
"Dict",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
",",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"=",
"{",
"}",
"def",
"copy_line",
"(",
"line",
":",
"StyleAndTextTuples",
",",
"lineno",
":",
"int",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"is_input",
":",
"bool",
"=",
"False",
",",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"\"\"\"\n Copy over a single line to the output screen. This can wrap over\n multiple lines in the output. It will call the prefix (prompt)\n function before every line.\n \"\"\"",
"if",
"is_input",
":",
"current_rowcol_to_yx",
"=",
"rowcol_to_yx",
"else",
":",
"current_rowcol_to_yx",
"=",
"{",
"}",
"# Throwaway dictionary.",
"# Draw line prefix.",
"if",
"is_input",
"and",
"get_line_prefix",
":",
"prompt",
"=",
"to_formatted_text",
"(",
"get_line_prefix",
"(",
"lineno",
",",
"0",
")",
")",
"x",
",",
"y",
"=",
"copy_line",
"(",
"prompt",
",",
"lineno",
",",
"x",
",",
"y",
",",
"is_input",
"=",
"False",
")",
"# Scroll horizontally.",
"skipped",
"=",
"0",
"# Characters skipped because of horizontal scrolling.",
"if",
"horizontal_scroll",
"and",
"is_input",
":",
"h_scroll",
"=",
"horizontal_scroll",
"line",
"=",
"explode_text_fragments",
"(",
"line",
")",
"while",
"h_scroll",
">",
"0",
"and",
"line",
":",
"h_scroll",
"-=",
"get_cwidth",
"(",
"line",
"[",
"0",
"]",
"[",
"1",
"]",
")",
"skipped",
"+=",
"1",
"del",
"line",
"[",
":",
"1",
"]",
"# Remove first character.",
"x",
"-=",
"h_scroll",
"# When scrolling over double width character,",
"# this can end up being negative.",
"# Align this line. (Note that this doesn't work well when we use",
"# get_line_prefix and that function returns variable width prefixes.)",
"if",
"align",
"==",
"WindowAlign",
".",
"CENTER",
":",
"line_width",
"=",
"fragment_list_width",
"(",
"line",
")",
"if",
"line_width",
"<",
"width",
":",
"x",
"+=",
"(",
"width",
"-",
"line_width",
")",
"//",
"2",
"elif",
"align",
"==",
"WindowAlign",
".",
"RIGHT",
":",
"line_width",
"=",
"fragment_list_width",
"(",
"line",
")",
"if",
"line_width",
"<",
"width",
":",
"x",
"+=",
"width",
"-",
"line_width",
"col",
"=",
"0",
"wrap_count",
"=",
"0",
"for",
"style",
",",
"text",
",",
"",
"*",
"_",
"in",
"line",
":",
"new_buffer_row",
"=",
"new_buffer",
"[",
"y",
"+",
"ypos",
"]",
"# Remember raw VT escape sequences. (E.g. FinalTerm's",
"# escape sequences.)",
"if",
"\"[ZeroWidthEscape]\"",
"in",
"style",
":",
"new_screen",
".",
"zero_width_escapes",
"[",
"y",
"+",
"ypos",
"]",
"[",
"x",
"+",
"xpos",
"]",
"+=",
"text",
"continue",
"for",
"c",
"in",
"text",
":",
"char",
"=",
"_CHAR_CACHE",
"[",
"c",
",",
"style",
"]",
"char_width",
"=",
"char",
".",
"width",
"# Wrap when the line width is exceeded.",
"if",
"wrap_lines",
"and",
"x",
"+",
"char_width",
">",
"width",
":",
"visible_line_to_row_col",
"[",
"y",
"+",
"1",
"]",
"=",
"(",
"lineno",
",",
"visible_line_to_row_col",
"[",
"y",
"]",
"[",
"1",
"]",
"+",
"x",
",",
")",
"y",
"+=",
"1",
"wrap_count",
"+=",
"1",
"x",
"=",
"0",
"# Insert line prefix (continuation prompt).",
"if",
"is_input",
"and",
"get_line_prefix",
":",
"prompt",
"=",
"to_formatted_text",
"(",
"get_line_prefix",
"(",
"lineno",
",",
"wrap_count",
")",
")",
"x",
",",
"y",
"=",
"copy_line",
"(",
"prompt",
",",
"lineno",
",",
"x",
",",
"y",
",",
"is_input",
"=",
"False",
")",
"new_buffer_row",
"=",
"new_buffer",
"[",
"y",
"+",
"ypos",
"]",
"if",
"y",
">=",
"write_position",
".",
"height",
":",
"return",
"x",
",",
"y",
"# Break out of all for loops.",
"# Set character in screen and shift 'x'.",
"if",
"x",
">=",
"0",
"and",
"y",
">=",
"0",
"and",
"x",
"<",
"width",
":",
"new_buffer_row",
"[",
"x",
"+",
"xpos",
"]",
"=",
"char",
"# When we print a multi width character, make sure",
"# to erase the neighbours positions in the screen.",
"# (The empty string if different from everything,",
"# so next redraw this cell will repaint anyway.)",
"if",
"char_width",
">",
"1",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"char_width",
")",
":",
"new_buffer_row",
"[",
"x",
"+",
"xpos",
"+",
"i",
"]",
"=",
"empty_char",
"# If this is a zero width characters, then it's",
"# probably part of a decomposed unicode character.",
"# See: https://en.wikipedia.org/wiki/Unicode_equivalence",
"# Merge it in the previous cell.",
"elif",
"char_width",
"==",
"0",
":",
"# Handle all character widths. If the previous",
"# character is a multiwidth character, then",
"# merge it two positions back.",
"for",
"pw",
"in",
"[",
"2",
",",
"1",
"]",
":",
"# Previous character width.",
"if",
"(",
"x",
"-",
"pw",
">=",
"0",
"and",
"new_buffer_row",
"[",
"x",
"+",
"xpos",
"-",
"pw",
"]",
".",
"width",
"==",
"pw",
")",
":",
"prev_char",
"=",
"new_buffer_row",
"[",
"x",
"+",
"xpos",
"-",
"pw",
"]",
"char2",
"=",
"_CHAR_CACHE",
"[",
"prev_char",
".",
"char",
"+",
"c",
",",
"prev_char",
".",
"style",
"]",
"new_buffer_row",
"[",
"x",
"+",
"xpos",
"-",
"pw",
"]",
"=",
"char2",
"# Keep track of write position for each character.",
"current_rowcol_to_yx",
"[",
"lineno",
",",
"col",
"+",
"skipped",
"]",
"=",
"(",
"y",
"+",
"ypos",
",",
"x",
"+",
"xpos",
",",
")",
"col",
"+=",
"1",
"x",
"+=",
"char_width",
"return",
"x",
",",
"y",
"# Copy content.",
"def",
"copy",
"(",
")",
"->",
"int",
":",
"y",
"=",
"-",
"vertical_scroll_2",
"lineno",
"=",
"vertical_scroll",
"while",
"y",
"<",
"write_position",
".",
"height",
"and",
"lineno",
"<",
"line_count",
":",
"# Take the next line and copy it in the real screen.",
"line",
"=",
"ui_content",
".",
"get_line",
"(",
"lineno",
")",
"visible_line_to_row_col",
"[",
"y",
"]",
"=",
"(",
"lineno",
",",
"horizontal_scroll",
")",
"# Copy margin and actual line.",
"x",
"=",
"0",
"x",
",",
"y",
"=",
"copy_line",
"(",
"line",
",",
"lineno",
",",
"x",
",",
"y",
",",
"is_input",
"=",
"True",
")",
"lineno",
"+=",
"1",
"y",
"+=",
"1",
"return",
"y",
"copy",
"(",
")",
"def",
"cursor_pos_to_screen_pos",
"(",
"row",
":",
"int",
",",
"col",
":",
"int",
")",
"->",
"Point",
":",
"\"Translate row/col from UIContent to real Screen coordinates.\"",
"try",
":",
"y",
",",
"x",
"=",
"rowcol_to_yx",
"[",
"row",
",",
"col",
"]",
"except",
"KeyError",
":",
"# Normally this should never happen. (It is a bug, if it happens.)",
"# But to be sure, return (0, 0)",
"return",
"Point",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"0",
")",
"# raise ValueError(",
"# 'Invalid position. row=%r col=%r, vertical_scroll=%r, '",
"# 'horizontal_scroll=%r, height=%r' %",
"# (row, col, vertical_scroll, horizontal_scroll, write_position.height))",
"else",
":",
"return",
"Point",
"(",
"x",
"=",
"x",
",",
"y",
"=",
"y",
")",
"# Set cursor and menu positions.",
"if",
"ui_content",
".",
"cursor_position",
":",
"screen_cursor_position",
"=",
"cursor_pos_to_screen_pos",
"(",
"ui_content",
".",
"cursor_position",
".",
"y",
",",
"ui_content",
".",
"cursor_position",
".",
"x",
")",
"if",
"has_focus",
":",
"new_screen",
".",
"set_cursor_position",
"(",
"self",
",",
"screen_cursor_position",
")",
"if",
"always_hide_cursor",
":",
"new_screen",
".",
"show_cursor",
"=",
"False",
"else",
":",
"new_screen",
".",
"show_cursor",
"=",
"ui_content",
".",
"show_cursor",
"self",
".",
"_highlight_digraph",
"(",
"new_screen",
")",
"if",
"highlight_lines",
":",
"self",
".",
"_highlight_cursorlines",
"(",
"new_screen",
",",
"screen_cursor_position",
",",
"xpos",
",",
"ypos",
",",
"width",
",",
"write_position",
".",
"height",
",",
")",
"# Draw input characters from the input processor queue.",
"if",
"has_focus",
"and",
"ui_content",
".",
"cursor_position",
":",
"self",
".",
"_show_key_processor_key_buffer",
"(",
"new_screen",
")",
"# Set menu position.",
"if",
"ui_content",
".",
"menu_position",
":",
"new_screen",
".",
"set_menu_position",
"(",
"self",
",",
"cursor_pos_to_screen_pos",
"(",
"ui_content",
".",
"menu_position",
".",
"y",
",",
"ui_content",
".",
"menu_position",
".",
"x",
")",
",",
")",
"# Update output screen height.",
"new_screen",
".",
"height",
"=",
"max",
"(",
"new_screen",
".",
"height",
",",
"ypos",
"+",
"write_position",
".",
"height",
")",
"return",
"visible_line_to_row_col",
",",
"rowcol_to_yx"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/containers.py#L1941-L2181 | |
cornell-zhang/heterocl | 6d9e4b4acc2ee2707b2d25b27298c0335bccedfd | python/heterocl/tvm/make.py | python | stmt_list | (stmt) | return [stmt] | Make list of stmt from blocks.
Parameters
----------
stmt : A block statement
Returns
-------
stmt_list : list of Stmt
The unpacked list of statements | Make list of stmt from blocks. | [
"Make",
"list",
"of",
"stmt",
"from",
"blocks",
"."
] | def stmt_list(stmt):
"""Make list of stmt from blocks.
Parameters
----------
stmt : A block statement
Returns
-------
stmt_list : list of Stmt
The unpacked list of statements
"""
if isinstance(stmt, _stmt.Block):
return stmt_list(stmt.first) + stmt_list(stmt.rest)
elif isinstance(stmt, _stmt.ProducerConsumer):
return stmt_list(stmt.body)
return [stmt] | [
"def",
"stmt_list",
"(",
"stmt",
")",
":",
"if",
"isinstance",
"(",
"stmt",
",",
"_stmt",
".",
"Block",
")",
":",
"return",
"stmt_list",
"(",
"stmt",
".",
"first",
")",
"+",
"stmt_list",
"(",
"stmt",
".",
"rest",
")",
"elif",
"isinstance",
"(",
"stmt",
",",
"_stmt",
".",
"ProducerConsumer",
")",
":",
"return",
"stmt_list",
"(",
"stmt",
".",
"body",
")",
"return",
"[",
"stmt",
"]"
] | https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/make.py#L111-L127 | |
google/skia | 82d65d0487bd72f5f7332d002429ec2dc61d2463 | infra/bots/recipe_modules/build/api.py | python | BuildApi.copy_build_products | (self, out_dir, dst) | Copy selected build products to dst. | Copy selected build products to dst. | [
"Copy",
"selected",
"build",
"products",
"to",
"dst",
"."
] | def copy_build_products(self, out_dir, dst):
"""Copy selected build products to dst."""
self.copy_fn(self.m, out_dir, dst) | [
"def",
"copy_build_products",
"(",
"self",
",",
"out_dir",
",",
"dst",
")",
":",
"self",
".",
"copy_fn",
"(",
"self",
".",
"m",
",",
"out_dir",
",",
"dst",
")"
] | https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/infra/bots/recipe_modules/build/api.py#L55-L57 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/parserdata.py | python | ConditionBlock.condition_source | (statement, index) | Convert a condition to its source representation.
The index argument defines the index of this condition inside a
ConditionBlock. If it is greater than 0, an "else" will be prepended
to the result, if necessary. | Convert a condition to its source representation. | [
"Convert",
"a",
"condition",
"to",
"its",
"source",
"representation",
"."
] | def condition_source(statement, index):
"""Convert a condition to its source representation.
The index argument defines the index of this condition inside a
ConditionBlock. If it is greater than 0, an "else" will be prepended
to the result, if necessary.
"""
prefix = ''
if isinstance(statement, (EqCondition, IfdefCondition)) and index > 0:
prefix = 'else '
if isinstance(statement, IfdefCondition):
s = statement.exp.s
if statement.expected:
return '%sifdef %s' % (prefix, s)
return '%sifndef %s' % (prefix, s)
if isinstance(statement, EqCondition):
args = [
statement.exp1.to_source(escape_comments=True),
statement.exp2.to_source(escape_comments=True)]
use_quotes = False
single_quote_present = False
double_quote_present = False
for i, arg in enumerate(args):
if len(arg) > 0 and (arg[0].isspace() or arg[-1].isspace()):
use_quotes = True
if "'" in arg:
single_quote_present = True
if '"' in arg:
double_quote_present = True
# Quote everything if needed.
if single_quote_present and double_quote_present:
raise Exception('Cannot format condition with multiple quotes.')
if use_quotes:
for i, arg in enumerate(args):
# Double to single quotes.
if single_quote_present:
args[i] = '"' + arg + '"'
else:
args[i] = "'" + arg + "'"
body = None
if use_quotes:
body = ' '.join(args)
else:
body = '(%s)' % ','.join(args)
if statement.expected:
return '%sifeq %s' % (prefix, body)
return '%sifneq %s' % (prefix, body)
if isinstance(statement, ElseCondition):
return 'else'
raise Exception('Unhandled Condition statement: %s' %
statement.__class__) | [
"def",
"condition_source",
"(",
"statement",
",",
"index",
")",
":",
"prefix",
"=",
"''",
"if",
"isinstance",
"(",
"statement",
",",
"(",
"EqCondition",
",",
"IfdefCondition",
")",
")",
"and",
"index",
">",
"0",
":",
"prefix",
"=",
"'else '",
"if",
"isinstance",
"(",
"statement",
",",
"IfdefCondition",
")",
":",
"s",
"=",
"statement",
".",
"exp",
".",
"s",
"if",
"statement",
".",
"expected",
":",
"return",
"'%sifdef %s'",
"%",
"(",
"prefix",
",",
"s",
")",
"return",
"'%sifndef %s'",
"%",
"(",
"prefix",
",",
"s",
")",
"if",
"isinstance",
"(",
"statement",
",",
"EqCondition",
")",
":",
"args",
"=",
"[",
"statement",
".",
"exp1",
".",
"to_source",
"(",
"escape_comments",
"=",
"True",
")",
",",
"statement",
".",
"exp2",
".",
"to_source",
"(",
"escape_comments",
"=",
"True",
")",
"]",
"use_quotes",
"=",
"False",
"single_quote_present",
"=",
"False",
"double_quote_present",
"=",
"False",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"len",
"(",
"arg",
")",
">",
"0",
"and",
"(",
"arg",
"[",
"0",
"]",
".",
"isspace",
"(",
")",
"or",
"arg",
"[",
"-",
"1",
"]",
".",
"isspace",
"(",
")",
")",
":",
"use_quotes",
"=",
"True",
"if",
"\"'\"",
"in",
"arg",
":",
"single_quote_present",
"=",
"True",
"if",
"'\"'",
"in",
"arg",
":",
"double_quote_present",
"=",
"True",
"# Quote everything if needed.",
"if",
"single_quote_present",
"and",
"double_quote_present",
":",
"raise",
"Exception",
"(",
"'Cannot format condition with multiple quotes.'",
")",
"if",
"use_quotes",
":",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"# Double to single quotes.",
"if",
"single_quote_present",
":",
"args",
"[",
"i",
"]",
"=",
"'\"'",
"+",
"arg",
"+",
"'\"'",
"else",
":",
"args",
"[",
"i",
"]",
"=",
"\"'\"",
"+",
"arg",
"+",
"\"'\"",
"body",
"=",
"None",
"if",
"use_quotes",
":",
"body",
"=",
"' '",
".",
"join",
"(",
"args",
")",
"else",
":",
"body",
"=",
"'(%s)'",
"%",
"','",
".",
"join",
"(",
"args",
")",
"if",
"statement",
".",
"expected",
":",
"return",
"'%sifeq %s'",
"%",
"(",
"prefix",
",",
"body",
")",
"return",
"'%sifneq %s'",
"%",
"(",
"prefix",
",",
"body",
")",
"if",
"isinstance",
"(",
"statement",
",",
"ElseCondition",
")",
":",
"return",
"'else'",
"raise",
"Exception",
"(",
"'Unhandled Condition statement: %s'",
"%",
"statement",
".",
"__class__",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/parserdata.py#L697-L761 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags2man.py | python | ProgramInfo.ParseCFlags | (self, start_line=0) | Parse C style flags. | Parse C style flags. | [
"Parse",
"C",
"style",
"flags",
"."
] | def ParseCFlags(self, start_line=0):
"""Parse C style flags."""
modname = None # name of current module
modlist = []
flag = None
for line_num in range(start_line, len(self.output)): # collect flags
line = self.output[line_num].rstrip()
if not line: # blank lines terminate flags
if flag: # save last flag
modlist.append(flag)
flag = None
continue
mobj = self.module_c_re.match(line)
if mobj: # start of a new module
modname = mobj.group(1)
logging.debug('Module: %s' % line)
if flag:
modlist.append(flag)
self.module_list.append(modname)
self.modules.setdefault(modname, [])
modlist = self.modules[modname]
flag = None
continue
mobj = self.flag_c_re.match(line)
if mobj: # start of a new flag
if flag: # save last flag
modlist.append(flag)
logging.debug('Flag: %s' % line)
flag = Flag(mobj.group(1), mobj.group(2))
continue
# append to flag help. type and default are part of the main text
if flag:
flag.help += ' ' + line.strip()
else:
logging.info('Extra: %s' % line)
if flag:
modlist.append(flag) | [
"def",
"ParseCFlags",
"(",
"self",
",",
"start_line",
"=",
"0",
")",
":",
"modname",
"=",
"None",
"# name of current module",
"modlist",
"=",
"[",
"]",
"flag",
"=",
"None",
"for",
"line_num",
"in",
"range",
"(",
"start_line",
",",
"len",
"(",
"self",
".",
"output",
")",
")",
":",
"# collect flags",
"line",
"=",
"self",
".",
"output",
"[",
"line_num",
"]",
".",
"rstrip",
"(",
")",
"if",
"not",
"line",
":",
"# blank lines terminate flags",
"if",
"flag",
":",
"# save last flag",
"modlist",
".",
"append",
"(",
"flag",
")",
"flag",
"=",
"None",
"continue",
"mobj",
"=",
"self",
".",
"module_c_re",
".",
"match",
"(",
"line",
")",
"if",
"mobj",
":",
"# start of a new module",
"modname",
"=",
"mobj",
".",
"group",
"(",
"1",
")",
"logging",
".",
"debug",
"(",
"'Module: %s'",
"%",
"line",
")",
"if",
"flag",
":",
"modlist",
".",
"append",
"(",
"flag",
")",
"self",
".",
"module_list",
".",
"append",
"(",
"modname",
")",
"self",
".",
"modules",
".",
"setdefault",
"(",
"modname",
",",
"[",
"]",
")",
"modlist",
"=",
"self",
".",
"modules",
"[",
"modname",
"]",
"flag",
"=",
"None",
"continue",
"mobj",
"=",
"self",
".",
"flag_c_re",
".",
"match",
"(",
"line",
")",
"if",
"mobj",
":",
"# start of a new flag",
"if",
"flag",
":",
"# save last flag",
"modlist",
".",
"append",
"(",
"flag",
")",
"logging",
".",
"debug",
"(",
"'Flag: %s'",
"%",
"line",
")",
"flag",
"=",
"Flag",
"(",
"mobj",
".",
"group",
"(",
"1",
")",
",",
"mobj",
".",
"group",
"(",
"2",
")",
")",
"continue",
"# append to flag help. type and default are part of the main text",
"if",
"flag",
":",
"flag",
".",
"help",
"+=",
"' '",
"+",
"line",
".",
"strip",
"(",
")",
"else",
":",
"logging",
".",
"info",
"(",
"'Extra: %s'",
"%",
"line",
")",
"if",
"flag",
":",
"modlist",
".",
"append",
"(",
"flag",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags2man.py#L323-L362 | ||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/directnotify/Notifier.py | python | Notifier.debug | (self, debugString) | return 1 | Issue the debug message if debug flag is on | Issue the debug message if debug flag is on | [
"Issue",
"the",
"debug",
"message",
"if",
"debug",
"flag",
"is",
"on"
] | def debug(self, debugString):
"""
Issue the debug message if debug flag is on
"""
if self.__debug:
message = str(debugString)
if Notifier.showTime.getValue():
string = (self.getTime() + self.__name + '(debug): ' + message)
else:
string = (':' + self.__name + '(debug): ' + message)
self.__log(string)
self.__print(string)
return 1 | [
"def",
"debug",
"(",
"self",
",",
"debugString",
")",
":",
"if",
"self",
".",
"__debug",
":",
"message",
"=",
"str",
"(",
"debugString",
")",
"if",
"Notifier",
".",
"showTime",
".",
"getValue",
"(",
")",
":",
"string",
"=",
"(",
"self",
".",
"getTime",
"(",
")",
"+",
"self",
".",
"__name",
"+",
"'(debug): '",
"+",
"message",
")",
"else",
":",
"string",
"=",
"(",
"':'",
"+",
"self",
".",
"__name",
"+",
"'(debug): '",
"+",
"message",
")",
"self",
".",
"__log",
"(",
"string",
")",
"self",
".",
"__print",
"(",
"string",
")",
"return",
"1"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/directnotify/Notifier.py#L160-L172 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | AlphaPixelData.__nonzero__ | (*args, **kwargs) | return _gdi_.AlphaPixelData___nonzero__(*args, **kwargs) | __nonzero__(self) -> bool | __nonzero__(self) -> bool | [
"__nonzero__",
"(",
"self",
")",
"-",
">",
"bool"
] | def __nonzero__(*args, **kwargs):
"""__nonzero__(self) -> bool"""
return _gdi_.AlphaPixelData___nonzero__(*args, **kwargs) | [
"def",
"__nonzero__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"AlphaPixelData___nonzero__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L1150-L1152 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/summary/text_summary.py | python | text_summary | (name, tensor, collections=None) | return t_summary | Summarizes textual data.
Text data summarized via this plugin will be visible in the Text Dashboard
in TensorBoard. The standard TensorBoard Text Dashboard will render markdown
in the strings, and will automatically organize 1d and 2d tensors into tables.
If a tensor with more than 2 dimensions is provided, a 2d subarray will be
displayed along with a warning message. (Note that this behavior is not
intrinsic to the text summary api, but rather to the default TensorBoard text
plugin.)
Args:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
tensor: a string-type Tensor to summarize.
collections: Optional list of ops.GraphKeys. The collections to add the
summary to. Defaults to [_ops.GraphKeys.SUMMARIES]
Returns:
A TensorSummary op that is configured so that TensorBoard will recognize
that it contains textual data. The TensorSummary is a scalar `Tensor` of
type `string` which contains `Summary` protobufs.
Raises:
ValueError: If tensor has the wrong type. | Summarizes textual data. | [
"Summarizes",
"textual",
"data",
"."
] | def text_summary(name, tensor, collections=None):
"""Summarizes textual data.
Text data summarized via this plugin will be visible in the Text Dashboard
in TensorBoard. The standard TensorBoard Text Dashboard will render markdown
in the strings, and will automatically organize 1d and 2d tensors into tables.
If a tensor with more than 2 dimensions is provided, a 2d subarray will be
displayed along with a warning message. (Note that this behavior is not
intrinsic to the text summary api, but rather to the default TensorBoard text
plugin.)
Args:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
tensor: a string-type Tensor to summarize.
collections: Optional list of ops.GraphKeys. The collections to add the
summary to. Defaults to [_ops.GraphKeys.SUMMARIES]
Returns:
A TensorSummary op that is configured so that TensorBoard will recognize
that it contains textual data. The TensorSummary is a scalar `Tensor` of
type `string` which contains `Summary` protobufs.
Raises:
ValueError: If tensor has the wrong type.
"""
if tensor.dtype != dtypes.string:
raise ValueError("Expected tensor %s to have dtype string, got %s" %
(tensor.name, tensor.dtype))
summary_metadata = summary_pb2.SummaryMetadata(
plugin_data=summary_pb2.SummaryMetadata.PluginData(
plugin_name=PLUGIN_NAME))
t_summary = tensor_summary(
name=name,
tensor=tensor,
summary_metadata=summary_metadata,
collections=collections)
return t_summary | [
"def",
"text_summary",
"(",
"name",
",",
"tensor",
",",
"collections",
"=",
"None",
")",
":",
"if",
"tensor",
".",
"dtype",
"!=",
"dtypes",
".",
"string",
":",
"raise",
"ValueError",
"(",
"\"Expected tensor %s to have dtype string, got %s\"",
"%",
"(",
"tensor",
".",
"name",
",",
"tensor",
".",
"dtype",
")",
")",
"summary_metadata",
"=",
"summary_pb2",
".",
"SummaryMetadata",
"(",
"plugin_data",
"=",
"summary_pb2",
".",
"SummaryMetadata",
".",
"PluginData",
"(",
"plugin_name",
"=",
"PLUGIN_NAME",
")",
")",
"t_summary",
"=",
"tensor_summary",
"(",
"name",
"=",
"name",
",",
"tensor",
"=",
"tensor",
",",
"summary_metadata",
"=",
"summary_metadata",
",",
"collections",
"=",
"collections",
")",
"return",
"t_summary"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/summary/text_summary.py#L36-L74 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/etree/ElementTree.py | python | XMLParser.close | (self) | Finish feeding data to parser and return element structure. | Finish feeding data to parser and return element structure. | [
"Finish",
"feeding",
"data",
"to",
"parser",
"and",
"return",
"element",
"structure",
"."
] | def close(self):
"""Finish feeding data to parser and return element structure."""
try:
self.parser.Parse("", 1) # end of data
except self._error as v:
self._raiseerror(v)
try:
close_handler = self.target.close
except AttributeError:
pass
else:
return close_handler()
finally:
# get rid of circular references
del self.parser, self._parser
del self.target, self._target | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"parser",
".",
"Parse",
"(",
"\"\"",
",",
"1",
")",
"# end of data",
"except",
"self",
".",
"_error",
"as",
"v",
":",
"self",
".",
"_raiseerror",
"(",
"v",
")",
"try",
":",
"close_handler",
"=",
"self",
".",
"target",
".",
"close",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"return",
"close_handler",
"(",
")",
"finally",
":",
"# get rid of circular references",
"del",
"self",
".",
"parser",
",",
"self",
".",
"_parser",
"del",
"self",
".",
"target",
",",
"self",
".",
"_target"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/etree/ElementTree.py#L1634-L1649 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/site_compare/commands/maskmaker.py | python | ValidateMaskmaker | (command) | Validate the arguments to maskmaker. Raises ParseError if failed. | Validate the arguments to maskmaker. Raises ParseError if failed. | [
"Validate",
"the",
"arguments",
"to",
"maskmaker",
".",
"Raises",
"ParseError",
"if",
"failed",
"."
] | def ValidateMaskmaker(command):
"""Validate the arguments to maskmaker. Raises ParseError if failed."""
executables = [".exe", ".com", ".bat"]
if command["--browserpath"]:
if os.path.splitext(command["--browserpath"])[1].lower() not in executables:
raise command_line.ParseError("Browser filename must be an executable") | [
"def",
"ValidateMaskmaker",
"(",
"command",
")",
":",
"executables",
"=",
"[",
"\".exe\"",
",",
"\".com\"",
",",
"\".bat\"",
"]",
"if",
"command",
"[",
"\"--browserpath\"",
"]",
":",
"if",
"os",
".",
"path",
".",
"splitext",
"(",
"command",
"[",
"\"--browserpath\"",
"]",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"not",
"in",
"executables",
":",
"raise",
"command_line",
".",
"ParseError",
"(",
"\"Browser filename must be an executable\"",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/site_compare/commands/maskmaker.py#L88-L93 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/distutils/dir_util.py | python | copy_tree | (src, dst, preserve_mode=1, preserve_times=1,
preserve_symlinks=0, update=0, verbose=1, dry_run=0) | return outputs | Copy an entire directory tree 'src' to a new location 'dst'.
Both 'src' and 'dst' must be directory names. If 'src' is not a
directory, raise DistutilsFileError. If 'dst' does not exist, it is
created with 'mkpath()'. The end result of the copy is that every
file in 'src' is copied to 'dst', and directories under 'src' are
recursively copied to 'dst'. Return the list of files that were
copied or might have been copied, using their output name. The
return value is unaffected by 'update' or 'dry_run': it is simply
the list of all files under 'src', with the names changed to be
under 'dst'.
'preserve_mode' and 'preserve_times' are the same as for
'copy_file'; note that they only apply to regular files, not to
directories. If 'preserve_symlinks' is true, symlinks will be
copied as symlinks (on platforms that support them!); otherwise
(the default), the destination of the symlink will be copied.
'update' and 'verbose' are the same as for 'copy_file'. | Copy an entire directory tree 'src' to a new location 'dst'. | [
"Copy",
"an",
"entire",
"directory",
"tree",
"src",
"to",
"a",
"new",
"location",
"dst",
"."
] | def copy_tree(src, dst, preserve_mode=1, preserve_times=1,
preserve_symlinks=0, update=0, verbose=1, dry_run=0):
"""Copy an entire directory tree 'src' to a new location 'dst'.
Both 'src' and 'dst' must be directory names. If 'src' is not a
directory, raise DistutilsFileError. If 'dst' does not exist, it is
created with 'mkpath()'. The end result of the copy is that every
file in 'src' is copied to 'dst', and directories under 'src' are
recursively copied to 'dst'. Return the list of files that were
copied or might have been copied, using their output name. The
return value is unaffected by 'update' or 'dry_run': it is simply
the list of all files under 'src', with the names changed to be
under 'dst'.
'preserve_mode' and 'preserve_times' are the same as for
'copy_file'; note that they only apply to regular files, not to
directories. If 'preserve_symlinks' is true, symlinks will be
copied as symlinks (on platforms that support them!); otherwise
(the default), the destination of the symlink will be copied.
'update' and 'verbose' are the same as for 'copy_file'.
"""
from distutils.file_util import copy_file
if not dry_run and not os.path.isdir(src):
raise DistutilsFileError(
"cannot copy tree '%s': not a directory" % src)
try:
names = os.listdir(src)
except OSError as e:
if dry_run:
names = []
else:
raise DistutilsFileError(
"error listing files in '%s': %s" % (src, e.strerror))
if not dry_run:
mkpath(dst, verbose=verbose)
outputs = []
for n in names:
src_name = os.path.join(src, n)
dst_name = os.path.join(dst, n)
if n.startswith('.nfs'):
# skip NFS rename files
continue
if preserve_symlinks and os.path.islink(src_name):
link_dest = os.readlink(src_name)
if verbose >= 1:
log.info("linking %s -> %s", dst_name, link_dest)
if not dry_run:
os.symlink(link_dest, dst_name)
outputs.append(dst_name)
elif os.path.isdir(src_name):
outputs.extend(
copy_tree(src_name, dst_name, preserve_mode,
preserve_times, preserve_symlinks, update,
verbose=verbose, dry_run=dry_run))
else:
copy_file(src_name, dst_name, preserve_mode,
preserve_times, update, verbose=verbose,
dry_run=dry_run)
outputs.append(dst_name)
return outputs | [
"def",
"copy_tree",
"(",
"src",
",",
"dst",
",",
"preserve_mode",
"=",
"1",
",",
"preserve_times",
"=",
"1",
",",
"preserve_symlinks",
"=",
"0",
",",
"update",
"=",
"0",
",",
"verbose",
"=",
"1",
",",
"dry_run",
"=",
"0",
")",
":",
"from",
"distutils",
".",
"file_util",
"import",
"copy_file",
"if",
"not",
"dry_run",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"src",
")",
":",
"raise",
"DistutilsFileError",
"(",
"\"cannot copy tree '%s': not a directory\"",
"%",
"src",
")",
"try",
":",
"names",
"=",
"os",
".",
"listdir",
"(",
"src",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"dry_run",
":",
"names",
"=",
"[",
"]",
"else",
":",
"raise",
"DistutilsFileError",
"(",
"\"error listing files in '%s': %s\"",
"%",
"(",
"src",
",",
"e",
".",
"strerror",
")",
")",
"if",
"not",
"dry_run",
":",
"mkpath",
"(",
"dst",
",",
"verbose",
"=",
"verbose",
")",
"outputs",
"=",
"[",
"]",
"for",
"n",
"in",
"names",
":",
"src_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"src",
",",
"n",
")",
"dst_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"n",
")",
"if",
"n",
".",
"startswith",
"(",
"'.nfs'",
")",
":",
"# skip NFS rename files",
"continue",
"if",
"preserve_symlinks",
"and",
"os",
".",
"path",
".",
"islink",
"(",
"src_name",
")",
":",
"link_dest",
"=",
"os",
".",
"readlink",
"(",
"src_name",
")",
"if",
"verbose",
">=",
"1",
":",
"log",
".",
"info",
"(",
"\"linking %s -> %s\"",
",",
"dst_name",
",",
"link_dest",
")",
"if",
"not",
"dry_run",
":",
"os",
".",
"symlink",
"(",
"link_dest",
",",
"dst_name",
")",
"outputs",
".",
"append",
"(",
"dst_name",
")",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"src_name",
")",
":",
"outputs",
".",
"extend",
"(",
"copy_tree",
"(",
"src_name",
",",
"dst_name",
",",
"preserve_mode",
",",
"preserve_times",
",",
"preserve_symlinks",
",",
"update",
",",
"verbose",
"=",
"verbose",
",",
"dry_run",
"=",
"dry_run",
")",
")",
"else",
":",
"copy_file",
"(",
"src_name",
",",
"dst_name",
",",
"preserve_mode",
",",
"preserve_times",
",",
"update",
",",
"verbose",
"=",
"verbose",
",",
"dry_run",
"=",
"dry_run",
")",
"outputs",
".",
"append",
"(",
"dst_name",
")",
"return",
"outputs"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/dir_util.py#L99-L166 | |
google/swiftshader | 8ccc63f045d5975fb67f9dfd3d2b8235b0526990 | third_party/SPIRV-Tools/utils/check_copyright.py | python | insert_copyright | (author, glob, comment_prefix) | Finds all glob-matching files under the current directory and inserts the
copyright message, and license notice. An MIT license or Khronos free
use license (modified MIT) is replaced with an Apache 2 license.
The copyright message goes into the first non-whitespace, non-shebang line
in a file. The license notice follows it. Both are prefixed on each line
by comment_prefix and a space. | Finds all glob-matching files under the current directory and inserts the
copyright message, and license notice. An MIT license or Khronos free
use license (modified MIT) is replaced with an Apache 2 license. | [
"Finds",
"all",
"glob",
"-",
"matching",
"files",
"under",
"the",
"current",
"directory",
"and",
"inserts",
"the",
"copyright",
"message",
"and",
"license",
"notice",
".",
"An",
"MIT",
"license",
"or",
"Khronos",
"free",
"use",
"license",
"(",
"modified",
"MIT",
")",
"is",
"replaced",
"with",
"an",
"Apache",
"2",
"license",
"."
] | def insert_copyright(author, glob, comment_prefix):
"""Finds all glob-matching files under the current directory and inserts the
copyright message, and license notice. An MIT license or Khronos free
use license (modified MIT) is replaced with an Apache 2 license.
The copyright message goes into the first non-whitespace, non-shebang line
in a file. The license notice follows it. Both are prefixed on each line
by comment_prefix and a space.
"""
copyright = comment('Copyright (c) {} {}'.format(CURRENT_YEAR, author),
comment_prefix) + '\n\n'
licensed = comment(LICENSED, comment_prefix) + '\n\n'
for file in filtered_descendants(glob):
# Parsing states are:
# 0 Initial: Have not seen a copyright declaration.
# 1 Seen a copyright line and no other interesting lines
# 2 In the middle of an MIT or Khronos free use license
# 9 Exited any of the above
state = 0
update_file = False
for line in fileinput.input(file, inplace=1):
emit = True
if state == 0:
if COPYRIGHT_RE.search(line):
state = 1
elif skip(line):
pass
else:
# Didn't see a copyright. Inject copyright and license.
sys.stdout.write(copyright)
sys.stdout.write(licensed)
# Assume there isn't a previous license notice.
state = 1
elif state == 1:
if MIT_BEGIN_RE.search(line):
state = 2
emit = False
elif APACHE2_BEGIN_RE.search(line):
# Assume an Apache license is preceded by a copyright
# notice. So just emit it like the rest of the file.
state = 9
elif state == 2:
# Replace the MIT license with Apache 2
emit = False
if MIT_END_RE.search(line):
state = 9
sys.stdout.write(licensed)
if emit:
sys.stdout.write(line) | [
"def",
"insert_copyright",
"(",
"author",
",",
"glob",
",",
"comment_prefix",
")",
":",
"copyright",
"=",
"comment",
"(",
"'Copyright (c) {} {}'",
".",
"format",
"(",
"CURRENT_YEAR",
",",
"author",
")",
",",
"comment_prefix",
")",
"+",
"'\\n\\n'",
"licensed",
"=",
"comment",
"(",
"LICENSED",
",",
"comment_prefix",
")",
"+",
"'\\n\\n'",
"for",
"file",
"in",
"filtered_descendants",
"(",
"glob",
")",
":",
"# Parsing states are:",
"# 0 Initial: Have not seen a copyright declaration.",
"# 1 Seen a copyright line and no other interesting lines",
"# 2 In the middle of an MIT or Khronos free use license",
"# 9 Exited any of the above",
"state",
"=",
"0",
"update_file",
"=",
"False",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"file",
",",
"inplace",
"=",
"1",
")",
":",
"emit",
"=",
"True",
"if",
"state",
"==",
"0",
":",
"if",
"COPYRIGHT_RE",
".",
"search",
"(",
"line",
")",
":",
"state",
"=",
"1",
"elif",
"skip",
"(",
"line",
")",
":",
"pass",
"else",
":",
"# Didn't see a copyright. Inject copyright and license.",
"sys",
".",
"stdout",
".",
"write",
"(",
"copyright",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"licensed",
")",
"# Assume there isn't a previous license notice.",
"state",
"=",
"1",
"elif",
"state",
"==",
"1",
":",
"if",
"MIT_BEGIN_RE",
".",
"search",
"(",
"line",
")",
":",
"state",
"=",
"2",
"emit",
"=",
"False",
"elif",
"APACHE2_BEGIN_RE",
".",
"search",
"(",
"line",
")",
":",
"# Assume an Apache license is preceded by a copyright",
"# notice. So just emit it like the rest of the file.",
"state",
"=",
"9",
"elif",
"state",
"==",
"2",
":",
"# Replace the MIT license with Apache 2",
"emit",
"=",
"False",
"if",
"MIT_END_RE",
".",
"search",
"(",
"line",
")",
":",
"state",
"=",
"9",
"sys",
".",
"stdout",
".",
"write",
"(",
"licensed",
")",
"if",
"emit",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"line",
")"
] | https://github.com/google/swiftshader/blob/8ccc63f045d5975fb67f9dfd3d2b8235b0526990/third_party/SPIRV-Tools/utils/check_copyright.py#L112-L161 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/eager/core.py | python | active_trace | () | return _active_trace | Returns the current global active trace of execution and memory usage. | Returns the current global active trace of execution and memory usage. | [
"Returns",
"the",
"current",
"global",
"active",
"trace",
"of",
"execution",
"and",
"memory",
"usage",
"."
] | def active_trace():
"""Returns the current global active trace of execution and memory usage."""
return _active_trace | [
"def",
"active_trace",
"(",
")",
":",
"return",
"_active_trace"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/eager/core.py#L73-L75 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | build/util/lib/common/util.py | python | Kill | (pid) | Terminate the given pid. | Terminate the given pid. | [
"Terminate",
"the",
"given",
"pid",
"."
] | def Kill(pid):
"""Terminate the given pid."""
if IsWindows():
subprocess.call(['taskkill.exe', '/T', '/F', '/PID', str(pid)])
else:
os.kill(pid, signal.SIGTERM) | [
"def",
"Kill",
"(",
"pid",
")",
":",
"if",
"IsWindows",
"(",
")",
":",
"subprocess",
".",
"call",
"(",
"[",
"'taskkill.exe'",
",",
"'/T'",
",",
"'/F'",
",",
"'/PID'",
",",
"str",
"(",
"pid",
")",
"]",
")",
"else",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGTERM",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/util/lib/common/util.py#L106-L111 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | xmlDoc.schemaNewDocParserCtxt | (self) | return __tmp | Create an XML Schemas parse context for that document. NB.
The document may be modified during the parsing process. | Create an XML Schemas parse context for that document. NB.
The document may be modified during the parsing process. | [
"Create",
"an",
"XML",
"Schemas",
"parse",
"context",
"for",
"that",
"document",
".",
"NB",
".",
"The",
"document",
"may",
"be",
"modified",
"during",
"the",
"parsing",
"process",
"."
] | def schemaNewDocParserCtxt(self):
"""Create an XML Schemas parse context for that document. NB.
The document may be modified during the parsing process. """
ret = libxml2mod.xmlSchemaNewDocParserCtxt(self._o)
if ret is None:raise parserError('xmlSchemaNewDocParserCtxt() failed')
__tmp = SchemaParserCtxt(_obj=ret)
return __tmp | [
"def",
"schemaNewDocParserCtxt",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlSchemaNewDocParserCtxt",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"parserError",
"(",
"'xmlSchemaNewDocParserCtxt() failed'",
")",
"__tmp",
"=",
"SchemaParserCtxt",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L4854-L4860 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | MenuItem.GetBackgroundColour | (*args, **kwargs) | return _core_.MenuItem_GetBackgroundColour(*args, **kwargs) | GetBackgroundColour(self) -> Colour | GetBackgroundColour(self) -> Colour | [
"GetBackgroundColour",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetBackgroundColour(*args, **kwargs):
"""GetBackgroundColour(self) -> Colour"""
return _core_.MenuItem_GetBackgroundColour(*args, **kwargs) | [
"def",
"GetBackgroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MenuItem_GetBackgroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L12577-L12579 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py2/prompt_toolkit/document.py | python | Document.leading_whitespace_in_current_line | (self) | return current_line[:length] | The leading whitespace in the left margin of the current line. | The leading whitespace in the left margin of the current line. | [
"The",
"leading",
"whitespace",
"in",
"the",
"left",
"margin",
"of",
"the",
"current",
"line",
"."
] | def leading_whitespace_in_current_line(self):
""" The leading whitespace in the left margin of the current line. """
current_line = self.current_line
length = len(current_line) - len(current_line.lstrip())
return current_line[:length] | [
"def",
"leading_whitespace_in_current_line",
"(",
"self",
")",
":",
"current_line",
"=",
"self",
".",
"current_line",
"length",
"=",
"len",
"(",
"current_line",
")",
"-",
"len",
"(",
"current_line",
".",
"lstrip",
"(",
")",
")",
"return",
"current_line",
"[",
":",
"length",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/document.py#L225-L229 | |
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_data.py | python | Data.get_py_described | (self) | A convenience method for decoding an AMQP described value.
:returns: The decoded AMQP descriptor. | A convenience method for decoding an AMQP described value. | [
"A",
"convenience",
"method",
"for",
"decoding",
"an",
"AMQP",
"described",
"value",
"."
] | def get_py_described(self) -> Described:
"""
A convenience method for decoding an AMQP described value.
:returns: The decoded AMQP descriptor.
"""
if self.enter():
try:
self.next()
descriptor = self.get_object()
self.next()
value = self.get_object()
finally:
self.exit()
return Described(descriptor, value) | [
"def",
"get_py_described",
"(",
"self",
")",
"->",
"Described",
":",
"if",
"self",
".",
"enter",
"(",
")",
":",
"try",
":",
"self",
".",
"next",
"(",
")",
"descriptor",
"=",
"self",
".",
"get_object",
"(",
")",
"self",
".",
"next",
"(",
")",
"value",
"=",
"self",
".",
"get_object",
"(",
")",
"finally",
":",
"self",
".",
"exit",
"(",
")",
"return",
"Described",
"(",
"descriptor",
",",
"value",
")"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_data.py#L1480-L1494 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/cloud/common/google_instance_helper.py | python | GoogleInstanceHelper.CreateTemplate | (self, tag, bucket, task_dir) | return self._ExecuteApiRequest(request)[0] | Creates an instance template for instances identified by tag.
Args:
tag: (string) Tag associated to a task.
bucket: (string) Root bucket where the deployment is located.
task_dir: (string) Subdirectory of |bucket| where task data is read and
written.
Returns:
boolean: True if successful. | Creates an instance template for instances identified by tag. | [
"Creates",
"an",
"instance",
"template",
"for",
"instances",
"identified",
"by",
"tag",
"."
] | def CreateTemplate(self, tag, bucket, task_dir):
"""Creates an instance template for instances identified by tag.
Args:
tag: (string) Tag associated to a task.
bucket: (string) Root bucket where the deployment is located.
task_dir: (string) Subdirectory of |bucket| where task data is read and
written.
Returns:
boolean: True if successful.
"""
image_url = self._COMPUTE_API_ROOT + \
'ubuntu-os-cloud/global/images/ubuntu-1404-trusty-v20160406'
request_body = {
'name': self._GetTemplateName(tag),
'properties': {
'machineType': 'n1-standard-1',
'networkInterfaces': [{
'network': self._project_api_url + '/global/networks/default',
'accessConfigs': [{
'name': 'external-IP',
'type': 'ONE_TO_ONE_NAT'
}]}],
'disks': [{
'type': 'PERSISTENT',
'boot': True,
'autoDelete': True,
'mode': 'READ_WRITE',
'initializeParams': {'sourceImage': image_url}}],
'canIpForward': False,
'scheduling': {
'automaticRestart': True,
'onHostMaintenance': 'MIGRATE',
'preemptible': False},
'serviceAccounts': [{
'scopes': [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/cloud-taskqueue'],
'email': 'default'}],
'metadata': { 'items': [
{'key': 'cloud-storage-path',
'value': bucket},
{'key': 'task-dir',
'value': task_dir},
{'key': 'startup-script-url',
'value': 'gs://%s/deployment/startup-script.sh' % bucket},
{'key': 'taskqueue-tag', 'value': tag}]}}}
request = self._compute_api.instanceTemplates().insert(
project=self._project, body=request_body)
return self._ExecuteApiRequest(request)[0] | [
"def",
"CreateTemplate",
"(",
"self",
",",
"tag",
",",
"bucket",
",",
"task_dir",
")",
":",
"image_url",
"=",
"self",
".",
"_COMPUTE_API_ROOT",
"+",
"'ubuntu-os-cloud/global/images/ubuntu-1404-trusty-v20160406'",
"request_body",
"=",
"{",
"'name'",
":",
"self",
".",
"_GetTemplateName",
"(",
"tag",
")",
",",
"'properties'",
":",
"{",
"'machineType'",
":",
"'n1-standard-1'",
",",
"'networkInterfaces'",
":",
"[",
"{",
"'network'",
":",
"self",
".",
"_project_api_url",
"+",
"'/global/networks/default'",
",",
"'accessConfigs'",
":",
"[",
"{",
"'name'",
":",
"'external-IP'",
",",
"'type'",
":",
"'ONE_TO_ONE_NAT'",
"}",
"]",
"}",
"]",
",",
"'disks'",
":",
"[",
"{",
"'type'",
":",
"'PERSISTENT'",
",",
"'boot'",
":",
"True",
",",
"'autoDelete'",
":",
"True",
",",
"'mode'",
":",
"'READ_WRITE'",
",",
"'initializeParams'",
":",
"{",
"'sourceImage'",
":",
"image_url",
"}",
"}",
"]",
",",
"'canIpForward'",
":",
"False",
",",
"'scheduling'",
":",
"{",
"'automaticRestart'",
":",
"True",
",",
"'onHostMaintenance'",
":",
"'MIGRATE'",
",",
"'preemptible'",
":",
"False",
"}",
",",
"'serviceAccounts'",
":",
"[",
"{",
"'scopes'",
":",
"[",
"'https://www.googleapis.com/auth/cloud-platform'",
",",
"'https://www.googleapis.com/auth/cloud-taskqueue'",
"]",
",",
"'email'",
":",
"'default'",
"}",
"]",
",",
"'metadata'",
":",
"{",
"'items'",
":",
"[",
"{",
"'key'",
":",
"'cloud-storage-path'",
",",
"'value'",
":",
"bucket",
"}",
",",
"{",
"'key'",
":",
"'task-dir'",
",",
"'value'",
":",
"task_dir",
"}",
",",
"{",
"'key'",
":",
"'startup-script-url'",
",",
"'value'",
":",
"'gs://%s/deployment/startup-script.sh'",
"%",
"bucket",
"}",
",",
"{",
"'key'",
":",
"'taskqueue-tag'",
",",
"'value'",
":",
"tag",
"}",
"]",
"}",
"}",
"}",
"request",
"=",
"self",
".",
"_compute_api",
".",
"instanceTemplates",
"(",
")",
".",
"insert",
"(",
"project",
"=",
"self",
".",
"_project",
",",
"body",
"=",
"request_body",
")",
"return",
"self",
".",
"_ExecuteApiRequest",
"(",
"request",
")",
"[",
"0",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/cloud/common/google_instance_helper.py#L62-L112 | |
berndpfrommer/tagslam | 406562abfb27ec0f409d7bd27dd6c45dabd9965d | src/rpp.py | python | project_points | (wph_cam) | return (wph_cam/wph_cam[:,2])[:,0:3] | project homogeneous world points in camera coord to image points | project homogeneous world points in camera coord to image points | [
"project",
"homogeneous",
"world",
"points",
"in",
"camera",
"coord",
"to",
"image",
"points"
] | def project_points(wph_cam):
""" project homogeneous world points in camera coord to image points """
return (wph_cam/wph_cam[:,2])[:,0:3] | [
"def",
"project_points",
"(",
"wph_cam",
")",
":",
"return",
"(",
"wph_cam",
"/",
"wph_cam",
"[",
":",
",",
"2",
"]",
")",
"[",
":",
",",
"0",
":",
"3",
"]"
] | https://github.com/berndpfrommer/tagslam/blob/406562abfb27ec0f409d7bd27dd6c45dabd9965d/src/rpp.py#L58-L60 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/tools/grokdump.py | python | InspectionShell.do_dp | (self, address) | return self.do_display_page(address) | see display_page | see display_page | [
"see",
"display_page"
] | def do_dp(self, address):
""" see display_page """
return self.do_display_page(address) | [
"def",
"do_dp",
"(",
"self",
",",
"address",
")",
":",
"return",
"self",
".",
"do_display_page",
"(",
"address",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/tools/grokdump.py#L3610-L3612 | |
lightvector/KataGo | 20d34784703c5b4000643d3ccc43bb37d418f3b5 | python/sgfmill/sgf_properties.py | python | serialise_point | (point, context) | return serialise_go_point(point, context.size) | Serialise a Point or Stone value.
point -- pair (row, col)
See serialise_go_point() above for details. | Serialise a Point or Stone value. | [
"Serialise",
"a",
"Point",
"or",
"Stone",
"value",
"."
] | def serialise_point(point, context):
"""Serialise a Point or Stone value.
point -- pair (row, col)
See serialise_go_point() above for details.
"""
if point is None:
raise ValueError
return serialise_go_point(point, context.size) | [
"def",
"serialise_point",
"(",
"point",
",",
"context",
")",
":",
"if",
"point",
"is",
"None",
":",
"raise",
"ValueError",
"return",
"serialise_go_point",
"(",
"point",
",",
"context",
".",
"size",
")"
] | https://github.com/lightvector/KataGo/blob/20d34784703c5b4000643d3ccc43bb37d418f3b5/python/sgfmill/sgf_properties.py#L274-L284 | |
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/qcdb/vecutil.py | python | dot | (v, u) | return sum(u[i] * v[i] for i in range(len(v))) | Compute dot product of vectors *v* and *u*. | Compute dot product of vectors *v* and *u*. | [
"Compute",
"dot",
"product",
"of",
"vectors",
"*",
"v",
"*",
"and",
"*",
"u",
"*",
"."
] | def dot(v, u):
"""Compute dot product of vectors *v* and *u*."""
return sum(u[i] * v[i] for i in range(len(v))) | [
"def",
"dot",
"(",
"v",
",",
"u",
")",
":",
"return",
"sum",
"(",
"u",
"[",
"i",
"]",
"*",
"v",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"v",
")",
")",
")"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/vecutil.py#L59-L61 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/algorithms/sfm/OpenSfM/opensfm/dataset.py | python | DataSet._load_mask_list | (self) | Load mask list from mask_list.txt or list masks/ folder. | Load mask list from mask_list.txt or list masks/ folder. | [
"Load",
"mask",
"list",
"from",
"mask_list",
".",
"txt",
"or",
"list",
"masks",
"/",
"folder",
"."
] | def _load_mask_list(self):
"""Load mask list from mask_list.txt or list masks/ folder."""
mask_list_file = os.path.join(self.data_path, 'mask_list.txt')
if os.path.isfile(mask_list_file):
with io.open_rt(mask_list_file) as fin:
lines = fin.read().splitlines()
self._set_mask_list(lines)
else:
self._set_mask_path(os.path.join(self.data_path, 'masks')) | [
"def",
"_load_mask_list",
"(",
"self",
")",
":",
"mask_list_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_path",
",",
"'mask_list.txt'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"mask_list_file",
")",
":",
"with",
"io",
".",
"open_rt",
"(",
"mask_list_file",
")",
"as",
"fin",
":",
"lines",
"=",
"fin",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"self",
".",
"_set_mask_list",
"(",
"lines",
")",
"else",
":",
"self",
".",
"_set_mask_path",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_path",
",",
"'masks'",
")",
")"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/dataset.py#L96-L104 | ||
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/sping/PDF/pidPDF.py | python | PDFCanvas.drawString | (self, s, x, y, font=None, color=None, angle=0, **kwargs) | As it says, but many options to process. It translates
user space rather than text space, in case underlining is
needed on rotated text. It cheats and does literals
for efficiency, avoiding changing the python graphics state. | As it says, but many options to process. It translates
user space rather than text space, in case underlining is
needed on rotated text. It cheats and does literals
for efficiency, avoiding changing the python graphics state. | [
"As",
"it",
"says",
"but",
"many",
"options",
"to",
"process",
".",
"It",
"translates",
"user",
"space",
"rather",
"than",
"text",
"space",
"in",
"case",
"underlining",
"is",
"needed",
"on",
"rotated",
"text",
".",
"It",
"cheats",
"and",
"does",
"literals",
"for",
"efficiency",
"avoiding",
"changing",
"the",
"python",
"graphics",
"state",
"."
] | def drawString(self, s, x, y, font=None, color=None, angle=0, **kwargs):
"""As it says, but many options to process. It translates
user space rather than text space, in case underlining is
needed on rotated text. It cheats and does literals
for efficiency, avoiding changing the python graphics state."""
self.pdf.addLiteral('%begin drawString')
col = color or self.defaultLineColor
if col != transparent:
if '\n' in s or '\r' in s:
# normalize line ends
s = s.replace('\r\n', '\n')
s = s.replace('\n\r', '\n')
lines = s.split('\n')
else:
lines = [s]
fnt = font or self.defaultFont
self._updateFont(fnt)
text = self.pdf._escape(s)
# start of Chris's hacking
# inserting basic commands here to see if can get working
textobj = self.pdf.beginText()
if col != self.defaultFillColor:
textobj.setFillColorRGB(col.red, col.green, col.blue)
if angle != 0:
co = cos(angle * pi / 180.0)
si = sin(angle * pi / 180.0)
textobj.setTextTransform(co, -si, si, co, x, y) # top down coords so reverse angle
else:
textobj.setTextOrigin(x, y)
for line in lines:
# keep underlining separate - it is slow and unusual anyway
if fnt.underline:
# breaks on angled text - FIXME
ycursor = textobj.getY() # returns offset from last set origin
dy = 0.5 * self.fontDescent(fnt)
width = self.stringWidth(line, fnt)
linewidth = fnt.size * 0.1
self.pdf.saveState()
self.pdf.setLineWidth(linewidth)
self.pdf.translate(x, y) # need to translate first before rotate
if angle != 0:
self.pdf.rotate(-angle)
self.pdf.translate(0, ycursor - y) # move down to start of current text line
self.pdf.line(0, dy, width, dy)
self.pdf.restoreState()
lasty = ycursor
textobj.textLine(line) # adds text to textobj, advances getY's cursor
# finally actually send text object to the page
self.pdf.drawText(textobj) # draw all the text afterwards? Doesn't seem right
self.pdf.addLiteral('%end drawString') | [
"def",
"drawString",
"(",
"self",
",",
"s",
",",
"x",
",",
"y",
",",
"font",
"=",
"None",
",",
"color",
"=",
"None",
",",
"angle",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"pdf",
".",
"addLiteral",
"(",
"'%begin drawString'",
")",
"col",
"=",
"color",
"or",
"self",
".",
"defaultLineColor",
"if",
"col",
"!=",
"transparent",
":",
"if",
"'\\n'",
"in",
"s",
"or",
"'\\r'",
"in",
"s",
":",
"# normalize line ends",
"s",
"=",
"s",
".",
"replace",
"(",
"'\\r\\n'",
",",
"'\\n'",
")",
"s",
"=",
"s",
".",
"replace",
"(",
"'\\n\\r'",
",",
"'\\n'",
")",
"lines",
"=",
"s",
".",
"split",
"(",
"'\\n'",
")",
"else",
":",
"lines",
"=",
"[",
"s",
"]",
"fnt",
"=",
"font",
"or",
"self",
".",
"defaultFont",
"self",
".",
"_updateFont",
"(",
"fnt",
")",
"text",
"=",
"self",
".",
"pdf",
".",
"_escape",
"(",
"s",
")",
"# start of Chris's hacking",
"# inserting basic commands here to see if can get working",
"textobj",
"=",
"self",
".",
"pdf",
".",
"beginText",
"(",
")",
"if",
"col",
"!=",
"self",
".",
"defaultFillColor",
":",
"textobj",
".",
"setFillColorRGB",
"(",
"col",
".",
"red",
",",
"col",
".",
"green",
",",
"col",
".",
"blue",
")",
"if",
"angle",
"!=",
"0",
":",
"co",
"=",
"cos",
"(",
"angle",
"*",
"pi",
"/",
"180.0",
")",
"si",
"=",
"sin",
"(",
"angle",
"*",
"pi",
"/",
"180.0",
")",
"textobj",
".",
"setTextTransform",
"(",
"co",
",",
"-",
"si",
",",
"si",
",",
"co",
",",
"x",
",",
"y",
")",
"# top down coords so reverse angle",
"else",
":",
"textobj",
".",
"setTextOrigin",
"(",
"x",
",",
"y",
")",
"for",
"line",
"in",
"lines",
":",
"# keep underlining separate - it is slow and unusual anyway",
"if",
"fnt",
".",
"underline",
":",
"# breaks on angled text - FIXME",
"ycursor",
"=",
"textobj",
".",
"getY",
"(",
")",
"# returns offset from last set origin",
"dy",
"=",
"0.5",
"*",
"self",
".",
"fontDescent",
"(",
"fnt",
")",
"width",
"=",
"self",
".",
"stringWidth",
"(",
"line",
",",
"fnt",
")",
"linewidth",
"=",
"fnt",
".",
"size",
"*",
"0.1",
"self",
".",
"pdf",
".",
"saveState",
"(",
")",
"self",
".",
"pdf",
".",
"setLineWidth",
"(",
"linewidth",
")",
"self",
".",
"pdf",
".",
"translate",
"(",
"x",
",",
"y",
")",
"# need to translate first before rotate",
"if",
"angle",
"!=",
"0",
":",
"self",
".",
"pdf",
".",
"rotate",
"(",
"-",
"angle",
")",
"self",
".",
"pdf",
".",
"translate",
"(",
"0",
",",
"ycursor",
"-",
"y",
")",
"# move down to start of current text line",
"self",
".",
"pdf",
".",
"line",
"(",
"0",
",",
"dy",
",",
"width",
",",
"dy",
")",
"self",
".",
"pdf",
".",
"restoreState",
"(",
")",
"lasty",
"=",
"ycursor",
"textobj",
".",
"textLine",
"(",
"line",
")",
"# adds text to textobj, advances getY's cursor",
"# finally actually send text object to the page",
"self",
".",
"pdf",
".",
"drawText",
"(",
"textobj",
")",
"# draw all the text afterwards? Doesn't seem right",
"self",
".",
"pdf",
".",
"addLiteral",
"(",
"'%end drawString'",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/PDF/pidPDF.py#L329-L383 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatnotebook.py | python | FlatNotebook.SetRightClickMenu | (self, menu) | Sets the popup menu associated to a right click on a tab.
:param `menu`: an instance of :class:`Menu`. | Sets the popup menu associated to a right click on a tab. | [
"Sets",
"the",
"popup",
"menu",
"associated",
"to",
"a",
"right",
"click",
"on",
"a",
"tab",
"."
] | def SetRightClickMenu(self, menu):
"""
Sets the popup menu associated to a right click on a tab.
:param `menu`: an instance of :class:`Menu`.
"""
self._pages._pRightClickMenu = menu | [
"def",
"SetRightClickMenu",
"(",
"self",
",",
"menu",
")",
":",
"self",
".",
"_pages",
".",
"_pRightClickMenu",
"=",
"menu"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatnotebook.py#L4850-L4857 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ptyprocess/ptyprocess/ptyprocess.py | python | PtyProcess.close | (self, force=True) | This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SIGKILL is sent if the child ignores SIGHUP
and SIGINT). | This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SIGKILL is sent if the child ignores SIGHUP
and SIGINT). | [
"This",
"closes",
"the",
"connection",
"with",
"the",
"child",
"application",
".",
"Note",
"that",
"calling",
"close",
"()",
"more",
"than",
"once",
"is",
"valid",
".",
"This",
"emulates",
"standard",
"Python",
"behavior",
"with",
"files",
".",
"Set",
"force",
"to",
"True",
"if",
"you",
"want",
"to",
"make",
"sure",
"that",
"the",
"child",
"is",
"terminated",
"(",
"SIGKILL",
"is",
"sent",
"if",
"the",
"child",
"ignores",
"SIGHUP",
"and",
"SIGINT",
")",
"."
] | def close(self, force=True):
'''This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SIGKILL is sent if the child ignores SIGHUP
and SIGINT). '''
if not self.closed:
self.flush()
self.fileobj.close() # Closes the file descriptor
# Give kernel time to update process status.
time.sleep(self.delayafterclose)
if self.isalive():
if not self.terminate(force):
raise PtyProcessError('Could not terminate the child.')
self.fd = -1
self.closed = True | [
"def",
"close",
"(",
"self",
",",
"force",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"closed",
":",
"self",
".",
"flush",
"(",
")",
"self",
".",
"fileobj",
".",
"close",
"(",
")",
"# Closes the file descriptor",
"# Give kernel time to update process status.",
"time",
".",
"sleep",
"(",
"self",
".",
"delayafterclose",
")",
"if",
"self",
".",
"isalive",
"(",
")",
":",
"if",
"not",
"self",
".",
"terminate",
"(",
"force",
")",
":",
"raise",
"PtyProcessError",
"(",
"'Could not terminate the child.'",
")",
"self",
".",
"fd",
"=",
"-",
"1",
"self",
".",
"closed",
"=",
"True"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ptyprocess/ptyprocess/ptyprocess.py#L393-L408 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/coverage/coverage/misc.py | python | file_be_gone | (path) | Remove a file, and don't get annoyed if it doesn't exist. | Remove a file, and don't get annoyed if it doesn't exist. | [
"Remove",
"a",
"file",
"and",
"don",
"t",
"get",
"annoyed",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | def file_be_gone(path):
"""Remove a file, and don't get annoyed if it doesn't exist."""
try:
os.remove(path)
except OSError as e:
if e.errno != errno.ENOENT:
raise | [
"def",
"file_be_gone",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/misc.py#L145-L151 | ||
Yelp/MOE | 5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c | moe/views/exceptions.py | python | failed_colander_validation | (exception, request) | return response | Catch ``colander.Invalid`` and give an informative 500 response.
:param exception: exception to be handled
:type exception: colander.Invalid
:param request: the pyramid request that lead to the exception being raised.
:type request: pyramid.request.Request
:return: the pyramid response to be rendered
:rtype: pyramid.response.Response | Catch ``colander.Invalid`` and give an informative 500 response. | [
"Catch",
"colander",
".",
"Invalid",
"and",
"give",
"an",
"informative",
"500",
"response",
"."
] | def failed_colander_validation(exception, request):
"""Catch ``colander.Invalid`` and give an informative 500 response.
:param exception: exception to be handled
:type exception: colander.Invalid
:param request: the pyramid request that lead to the exception being raised.
:type request: pyramid.request.Request
:return: the pyramid response to be rendered
:rtype: pyramid.response.Response
"""
status_int = 500
body = '{0:d}: {1:s}\nFailed validation:\n{2:s}'.format(status_int, request.referrer, pprint.pformat(exception.asdict()))
response = Response(body=body, status_int=status_int)
return response | [
"def",
"failed_colander_validation",
"(",
"exception",
",",
"request",
")",
":",
"status_int",
"=",
"500",
"body",
"=",
"'{0:d}: {1:s}\\nFailed validation:\\n{2:s}'",
".",
"format",
"(",
"status_int",
",",
"request",
".",
"referrer",
",",
"pprint",
".",
"pformat",
"(",
"exception",
".",
"asdict",
"(",
")",
")",
")",
"response",
"=",
"Response",
"(",
"body",
"=",
"body",
",",
"status_int",
"=",
"status_int",
")",
"return",
"response"
] | https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/views/exceptions.py#L60-L74 | |
cksystemsgroup/scalloc | 049857919b5fa1d539c9e4206e353daca2e87394 | tools/cpplint.py | python | _BlockInfo.CheckEnd | (self, filename, clean_lines, linenum, error) | Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Run checks that applies to text after the closing brace. | [
"Run",
"checks",
"that",
"applies",
"to",
"text",
"after",
"the",
"closing",
"brace",
"."
] | def CheckEnd(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
pass | [
"def",
"CheckEnd",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"pass"
] | https://github.com/cksystemsgroup/scalloc/blob/049857919b5fa1d539c9e4206e353daca2e87394/tools/cpplint.py#L1666-L1677 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/storage.py | python | TypedStorage._new_shared | (cls, size) | return cls(wrap_storage=untyped_storage) | Creates a new storage in shared memory with the same data type | Creates a new storage in shared memory with the same data type | [
"Creates",
"a",
"new",
"storage",
"in",
"shared",
"memory",
"with",
"the",
"same",
"data",
"type"
] | def _new_shared(cls, size):
"""Creates a new storage in shared memory with the same data type"""
module = eval(cls.__module__)
untyped_storage = module.UntypedStorage._new_shared(size * cls().element_size())
return cls(wrap_storage=untyped_storage) | [
"def",
"_new_shared",
"(",
"cls",
",",
"size",
")",
":",
"module",
"=",
"eval",
"(",
"cls",
".",
"__module__",
")",
"untyped_storage",
"=",
"module",
".",
"UntypedStorage",
".",
"_new_shared",
"(",
"size",
"*",
"cls",
"(",
")",
".",
"element_size",
"(",
")",
")",
"return",
"cls",
"(",
"wrap_storage",
"=",
"untyped_storage",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/storage.py#L484-L488 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py | python | TurtleScreenBase._blankimage | () | return img | return a blank image object | return a blank image object | [
"return",
"a",
"blank",
"image",
"object"
] | def _blankimage():
"""return a blank image object
"""
img = TK.PhotoImage(width=1, height=1)
img.blank()
return img | [
"def",
"_blankimage",
"(",
")",
":",
"img",
"=",
"TK",
".",
"PhotoImage",
"(",
"width",
"=",
"1",
",",
"height",
"=",
"1",
")",
"img",
".",
"blank",
"(",
")",
"return",
"img"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py#L491-L496 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/rfc822.py | python | Message.getheader | (self, name, default=None) | return self.dict.get(name.lower(), default) | Get the header value for a name.
This is the normal interface: it returns a stripped version of the
header value for a given header name, or None if it doesn't exist.
This uses the dictionary version which finds the *last* such header. | Get the header value for a name. | [
"Get",
"the",
"header",
"value",
"for",
"a",
"name",
"."
] | def getheader(self, name, default=None):
"""Get the header value for a name.
This is the normal interface: it returns a stripped version of the
header value for a given header name, or None if it doesn't exist.
This uses the dictionary version which finds the *last* such header.
"""
return self.dict.get(name.lower(), default) | [
"def",
"getheader",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"dict",
".",
"get",
"(",
"name",
".",
"lower",
"(",
")",
",",
"default",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/rfc822.py#L285-L292 | |
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/Crypto/PublicKey/qNEW.py | python | qNEWobj.publickey | (self) | return construct((self.p, self.q, self.g, self.y)) | Return a new key object containing only the public information. | Return a new key object containing only the public information. | [
"Return",
"a",
"new",
"key",
"object",
"containing",
"only",
"the",
"public",
"information",
"."
] | def publickey(self):
"""Return a new key object containing only the public information."""
return construct((self.p, self.q, self.g, self.y)) | [
"def",
"publickey",
"(",
"self",
")",
":",
"return",
"construct",
"(",
"(",
"self",
".",
"p",
",",
"self",
".",
"q",
",",
"self",
".",
"g",
",",
"self",
".",
"y",
")",
")"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/Crypto/PublicKey/qNEW.py#L165-L167 | |
citra-emu/citra | cdbd72e79c9f91fd8261fd3bc2fa25b883a17fbe | dist/scripting/citra.py | python | Citra.read_memory | (self, read_address, read_size) | return result | >>> c.read_memory(0x100000, 4)
b'\\x07\\x00\\x00\\xeb' | >>> c.read_memory(0x100000, 4)
b'\\x07\\x00\\x00\\xeb' | [
">>>",
"c",
".",
"read_memory",
"(",
"0x100000",
"4",
")",
"b",
"\\\\",
"x07",
"\\\\",
"x00",
"\\\\",
"x00",
"\\\\",
"xeb"
] | def read_memory(self, read_address, read_size):
"""
>>> c.read_memory(0x100000, 4)
b'\\x07\\x00\\x00\\xeb'
"""
result = bytes()
while read_size > 0:
temp_read_size = min(read_size, MAX_REQUEST_DATA_SIZE)
request_data = struct.pack("II", read_address, temp_read_size)
request, request_id = self._generate_header(RequestType.ReadMemory, len(request_data))
request += request_data
self.socket.sendto(request, (self.address, CITRA_PORT))
raw_reply = self.socket.recv(MAX_PACKET_SIZE)
reply_data = self._read_and_validate_header(raw_reply, request_id, RequestType.ReadMemory)
if reply_data:
result += reply_data
read_size -= len(reply_data)
read_address += len(reply_data)
else:
return None
return result | [
"def",
"read_memory",
"(",
"self",
",",
"read_address",
",",
"read_size",
")",
":",
"result",
"=",
"bytes",
"(",
")",
"while",
"read_size",
">",
"0",
":",
"temp_read_size",
"=",
"min",
"(",
"read_size",
",",
"MAX_REQUEST_DATA_SIZE",
")",
"request_data",
"=",
"struct",
".",
"pack",
"(",
"\"II\"",
",",
"read_address",
",",
"temp_read_size",
")",
"request",
",",
"request_id",
"=",
"self",
".",
"_generate_header",
"(",
"RequestType",
".",
"ReadMemory",
",",
"len",
"(",
"request_data",
")",
")",
"request",
"+=",
"request_data",
"self",
".",
"socket",
".",
"sendto",
"(",
"request",
",",
"(",
"self",
".",
"address",
",",
"CITRA_PORT",
")",
")",
"raw_reply",
"=",
"self",
".",
"socket",
".",
"recv",
"(",
"MAX_PACKET_SIZE",
")",
"reply_data",
"=",
"self",
".",
"_read_and_validate_header",
"(",
"raw_reply",
",",
"request_id",
",",
"RequestType",
".",
"ReadMemory",
")",
"if",
"reply_data",
":",
"result",
"+=",
"reply_data",
"read_size",
"-=",
"len",
"(",
"reply_data",
")",
"read_address",
"+=",
"len",
"(",
"reply_data",
")",
"else",
":",
"return",
"None",
"return",
"result"
] | https://github.com/citra-emu/citra/blob/cdbd72e79c9f91fd8261fd3bc2fa25b883a17fbe/dist/scripting/citra.py#L37-L60 | |
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/qcdb/align.py | python | B787 | (cgeom,
rgeom,
cuniq,
runiq,
do_plot=False,
verbose=1,
atoms_map=False,
run_resorting=False,
mols_align=False,
run_to_completion=False,
uno_cutoff=1.e-3,
run_mirror=False) | return qcel.molutil.B787(cgeom,
rgeom,
cuniq,
runiq,
do_plot=do_plot,
verbose=verbose,
atoms_map=atoms_map,
run_resorting=run_resorting,
mols_align=mols_align,
run_to_completion=run_to_completion,
uno_cutoff=uno_cutoff,
run_mirror=run_mirror) | Use Kabsch algorithm to find best alignment of geometry `cgeom` onto
`rgeom` while sampling atom mappings restricted by `runiq` and `cuniq`.
Parameters
----------
rgeom : ndarray of float
(nat, 3) array of reference/target/unchanged geometry. Assumed [a0]
for RMSD purposes.
cgeom : ndarray of float
(nat, 3) array of concern/changeable geometry. Assumed [a0] for RMSD
purposes. Must have same nat, units, and atom content as rgeom.
runiq : ndarray of str
(nat,) array indicating which rows (atoms) in `rgeom` are shuffleable
without changing the molecule. Generally hashes of element symbol and
mass are used, but could be as simple as ['C', 'H', 'H', 'D', 'H'] for
monodeuterated methane.
cuniq : ndarray of str
(nat,) array indicating which rows (atoms) in `cgeom` are shuffleable.
See `runiq` for more details. Strings and count in `cuniq` must match
`runiq`. That is, `sorted(cuniq) == sorted(runiq)`.
do_plot : bool, optional
Pops up a mpl plot showing before, after, and ref geometries.
verbose : int, optional
Quantity of printing. 0 to silence.
atoms_map : bool, optional
Whether atom1 of rgeom already corresponds to atom1 of cgeom and so on.
If `True`, no resorting will be run, parameters `runiq` and `cuniq`
may be passed as `None`, and much time will be saved.
run_resorting : bool, optional
Run the resorting machinery even if unnecessary because `atoms_map=True`.
mols_align : bool or float, optional
Whether ref_mol and concern_mol have identical geometries by eye
(barring orientation or atom mapping) and expected final RMSD = 0.
If `True`, procedure is truncated when RMSD condition met, saving time.
If float, convcrit at which search for minimium truncates.
run_to_completion : bool, optional
Run reorderings to completion (past RMSD = 0) even if unnecessary because
`mols_align=True`. Used to test worst-case timings.
uno_cutoff : float, optional
TODO
run_mirror : bool, optional
Run alternate geometries potentially allowing best match to `rgeom`
from mirror image of `cgeom`. Only run if system confirmed to
be nonsuperimposable upon mirror reflection.
Returns
-------
float, tuple
First item is RMSD [A] between `rgeom` and the optimally aligned
geometry computed.
Second item is a AlignmentMill namedtuple with fields
(shift, rotation, atommap, mirror) that prescribe the transformation
from `cgeom` and the optimally aligned geometry. | Use Kabsch algorithm to find best alignment of geometry `cgeom` onto
`rgeom` while sampling atom mappings restricted by `runiq` and `cuniq`. | [
"Use",
"Kabsch",
"algorithm",
"to",
"find",
"best",
"alignment",
"of",
"geometry",
"cgeom",
"onto",
"rgeom",
"while",
"sampling",
"atom",
"mappings",
"restricted",
"by",
"runiq",
"and",
"cuniq",
"."
] | def B787(cgeom,
rgeom,
cuniq,
runiq,
do_plot=False,
verbose=1,
atoms_map=False,
run_resorting=False,
mols_align=False,
run_to_completion=False,
uno_cutoff=1.e-3,
run_mirror=False):
"""Use Kabsch algorithm to find best alignment of geometry `cgeom` onto
`rgeom` while sampling atom mappings restricted by `runiq` and `cuniq`.
Parameters
----------
rgeom : ndarray of float
(nat, 3) array of reference/target/unchanged geometry. Assumed [a0]
for RMSD purposes.
cgeom : ndarray of float
(nat, 3) array of concern/changeable geometry. Assumed [a0] for RMSD
purposes. Must have same nat, units, and atom content as rgeom.
runiq : ndarray of str
(nat,) array indicating which rows (atoms) in `rgeom` are shuffleable
without changing the molecule. Generally hashes of element symbol and
mass are used, but could be as simple as ['C', 'H', 'H', 'D', 'H'] for
monodeuterated methane.
cuniq : ndarray of str
(nat,) array indicating which rows (atoms) in `cgeom` are shuffleable.
See `runiq` for more details. Strings and count in `cuniq` must match
`runiq`. That is, `sorted(cuniq) == sorted(runiq)`.
do_plot : bool, optional
Pops up a mpl plot showing before, after, and ref geometries.
verbose : int, optional
Quantity of printing. 0 to silence.
atoms_map : bool, optional
Whether atom1 of rgeom already corresponds to atom1 of cgeom and so on.
If `True`, no resorting will be run, parameters `runiq` and `cuniq`
may be passed as `None`, and much time will be saved.
run_resorting : bool, optional
Run the resorting machinery even if unnecessary because `atoms_map=True`.
mols_align : bool or float, optional
Whether ref_mol and concern_mol have identical geometries by eye
(barring orientation or atom mapping) and expected final RMSD = 0.
If `True`, procedure is truncated when RMSD condition met, saving time.
If float, convcrit at which search for minimium truncates.
run_to_completion : bool, optional
Run reorderings to completion (past RMSD = 0) even if unnecessary because
`mols_align=True`. Used to test worst-case timings.
uno_cutoff : float, optional
TODO
run_mirror : bool, optional
Run alternate geometries potentially allowing best match to `rgeom`
from mirror image of `cgeom`. Only run if system confirmed to
be nonsuperimposable upon mirror reflection.
Returns
-------
float, tuple
First item is RMSD [A] between `rgeom` and the optimally aligned
geometry computed.
Second item is a AlignmentMill namedtuple with fields
(shift, rotation, atommap, mirror) that prescribe the transformation
from `cgeom` and the optimally aligned geometry.
"""
warnings.warn(
"Using `qcdb.align.B787` instead of `qcelemental.molutil.B787` is deprecated, and in 1.5 it will stop working\n",
category=FutureWarning,
stacklevel=2)
return qcel.molutil.B787(cgeom,
rgeom,
cuniq,
runiq,
do_plot=do_plot,
verbose=verbose,
atoms_map=atoms_map,
run_resorting=run_resorting,
mols_align=mols_align,
run_to_completion=run_to_completion,
uno_cutoff=uno_cutoff,
run_mirror=run_mirror) | [
"def",
"B787",
"(",
"cgeom",
",",
"rgeom",
",",
"cuniq",
",",
"runiq",
",",
"do_plot",
"=",
"False",
",",
"verbose",
"=",
"1",
",",
"atoms_map",
"=",
"False",
",",
"run_resorting",
"=",
"False",
",",
"mols_align",
"=",
"False",
",",
"run_to_completion",
"=",
"False",
",",
"uno_cutoff",
"=",
"1.e-3",
",",
"run_mirror",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Using `qcdb.align.B787` instead of `qcelemental.molutil.B787` is deprecated, and in 1.5 it will stop working\\n\"",
",",
"category",
"=",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"qcel",
".",
"molutil",
".",
"B787",
"(",
"cgeom",
",",
"rgeom",
",",
"cuniq",
",",
"runiq",
",",
"do_plot",
"=",
"do_plot",
",",
"verbose",
"=",
"verbose",
",",
"atoms_map",
"=",
"atoms_map",
",",
"run_resorting",
"=",
"run_resorting",
",",
"mols_align",
"=",
"mols_align",
",",
"run_to_completion",
"=",
"run_to_completion",
",",
"uno_cutoff",
"=",
"uno_cutoff",
",",
"run_mirror",
"=",
"run_mirror",
")"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/align.py#L34-L117 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/inspector_protocol/jinja2/visitor.py | python | NodeVisitor.get_visitor | (self, node) | return getattr(self, method, None) | Return the visitor function for this node or `None` if no visitor
exists for this node. In that case the generic visit function is
used instead. | Return the visitor function for this node or `None` if no visitor
exists for this node. In that case the generic visit function is
used instead. | [
"Return",
"the",
"visitor",
"function",
"for",
"this",
"node",
"or",
"None",
"if",
"no",
"visitor",
"exists",
"for",
"this",
"node",
".",
"In",
"that",
"case",
"the",
"generic",
"visit",
"function",
"is",
"used",
"instead",
"."
] | def get_visitor(self, node):
"""Return the visitor function for this node or `None` if no visitor
exists for this node. In that case the generic visit function is
used instead.
"""
method = 'visit_' + node.__class__.__name__
return getattr(self, method, None) | [
"def",
"get_visitor",
"(",
"self",
",",
"node",
")",
":",
"method",
"=",
"'visit_'",
"+",
"node",
".",
"__class__",
".",
"__name__",
"return",
"getattr",
"(",
"self",
",",
"method",
",",
"None",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/visitor.py#L26-L32 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/set.py | python | Set.difference | (self, other) | return obj | Return a new set which I{self} - I{other}, i.e. the items
in I{self} which are not also in I{other}.
@param other: the other set
@type other: Set object
@rtype: the same type as I{self} | Return a new set which I{self} - I{other}, i.e. the items
in I{self} which are not also in I{other}. | [
"Return",
"a",
"new",
"set",
"which",
"I",
"{",
"self",
"}",
"-",
"I",
"{",
"other",
"}",
"i",
".",
"e",
".",
"the",
"items",
"in",
"I",
"{",
"self",
"}",
"which",
"are",
"not",
"also",
"in",
"I",
"{",
"other",
"}",
"."
] | def difference(self, other):
"""Return a new set which I{self} - I{other}, i.e. the items
in I{self} which are not also in I{other}.
@param other: the other set
@type other: Set object
@rtype: the same type as I{self}
"""
obj = self._clone()
obj.difference_update(other)
return obj | [
"def",
"difference",
"(",
"self",
",",
"other",
")",
":",
"obj",
"=",
"self",
".",
"_clone",
"(",
")",
"obj",
".",
"difference_update",
"(",
"other",
")",
"return",
"obj"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/set.py#L154-L165 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/_lib/decorator.py | python | FunctionMaker.create | (cls, obj, body, evaldict, defaults=None,
doc=None, module=None, addsource=True, **attrs) | return self.make('def %(name)s(%(signature)s):\n' + ibody,
evaldict, addsource, **attrs) | Create a function from the strings name, signature and body.
evaldict is the evaluation dictionary. If addsource is true an
attribute __source__ is added to the result. The attributes attrs
are added, if any. | Create a function from the strings name, signature and body.
evaldict is the evaluation dictionary. If addsource is true an
attribute __source__ is added to the result. The attributes attrs
are added, if any. | [
"Create",
"a",
"function",
"from",
"the",
"strings",
"name",
"signature",
"and",
"body",
".",
"evaldict",
"is",
"the",
"evaluation",
"dictionary",
".",
"If",
"addsource",
"is",
"true",
"an",
"attribute",
"__source__",
"is",
"added",
"to",
"the",
"result",
".",
"The",
"attributes",
"attrs",
"are",
"added",
"if",
"any",
"."
] | def create(cls, obj, body, evaldict, defaults=None,
doc=None, module=None, addsource=True, **attrs):
"""
Create a function from the strings name, signature and body.
evaldict is the evaluation dictionary. If addsource is true an
attribute __source__ is added to the result. The attributes attrs
are added, if any.
"""
if isinstance(obj, str): # "name(signature)"
name, rest = obj.strip().split('(', 1)
signature = rest[:-1] # strip a right parens
func = None
else: # a function
name = None
signature = None
func = obj
self = cls(func, name, signature, defaults, doc, module)
ibody = '\n'.join(' ' + line for line in body.splitlines())
return self.make('def %(name)s(%(signature)s):\n' + ibody,
evaldict, addsource, **attrs) | [
"def",
"create",
"(",
"cls",
",",
"obj",
",",
"body",
",",
"evaldict",
",",
"defaults",
"=",
"None",
",",
"doc",
"=",
"None",
",",
"module",
"=",
"None",
",",
"addsource",
"=",
"True",
",",
"*",
"*",
"attrs",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"# \"name(signature)\"",
"name",
",",
"rest",
"=",
"obj",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'('",
",",
"1",
")",
"signature",
"=",
"rest",
"[",
":",
"-",
"1",
"]",
"# strip a right parens",
"func",
"=",
"None",
"else",
":",
"# a function",
"name",
"=",
"None",
"signature",
"=",
"None",
"func",
"=",
"obj",
"self",
"=",
"cls",
"(",
"func",
",",
"name",
",",
"signature",
",",
"defaults",
",",
"doc",
",",
"module",
")",
"ibody",
"=",
"'\\n'",
".",
"join",
"(",
"' '",
"+",
"line",
"for",
"line",
"in",
"body",
".",
"splitlines",
"(",
")",
")",
"return",
"self",
".",
"make",
"(",
"'def %(name)s(%(signature)s):\\n'",
"+",
"ibody",
",",
"evaldict",
",",
"addsource",
",",
"*",
"*",
"attrs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/_lib/decorator.py#L203-L222 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/_parseaddr.py | python | AddrlistClass.getdelimited | (self, beginchar, endchars, allowcomments=True) | return EMPTYSTRING.join(slist) | Parse a header fragment delimited by special characters.
`beginchar' is the start character for the fragment.
If self is not looking at an instance of `beginchar' then
getdelimited returns the empty string.
`endchars' is a sequence of allowable end-delimiting characters.
Parsing stops when one of these is encountered.
If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed
within the parsed fragment. | Parse a header fragment delimited by special characters. | [
"Parse",
"a",
"header",
"fragment",
"delimited",
"by",
"special",
"characters",
"."
] | def getdelimited(self, beginchar, endchars, allowcomments=True):
"""Parse a header fragment delimited by special characters.
`beginchar' is the start character for the fragment.
If self is not looking at an instance of `beginchar' then
getdelimited returns the empty string.
`endchars' is a sequence of allowable end-delimiting characters.
Parsing stops when one of these is encountered.
If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed
within the parsed fragment.
"""
if self.field[self.pos] != beginchar:
return ''
slist = ['']
quote = False
self.pos += 1
while self.pos < len(self.field):
if quote:
slist.append(self.field[self.pos])
quote = False
elif self.field[self.pos] in endchars:
self.pos += 1
break
elif allowcomments and self.field[self.pos] == '(':
slist.append(self.getcomment())
continue # have already advanced pos from getcomment
elif self.field[self.pos] == '\\':
quote = True
else:
slist.append(self.field[self.pos])
self.pos += 1
return EMPTYSTRING.join(slist) | [
"def",
"getdelimited",
"(",
"self",
",",
"beginchar",
",",
"endchars",
",",
"allowcomments",
"=",
"True",
")",
":",
"if",
"self",
".",
"field",
"[",
"self",
".",
"pos",
"]",
"!=",
"beginchar",
":",
"return",
"''",
"slist",
"=",
"[",
"''",
"]",
"quote",
"=",
"False",
"self",
".",
"pos",
"+=",
"1",
"while",
"self",
".",
"pos",
"<",
"len",
"(",
"self",
".",
"field",
")",
":",
"if",
"quote",
":",
"slist",
".",
"append",
"(",
"self",
".",
"field",
"[",
"self",
".",
"pos",
"]",
")",
"quote",
"=",
"False",
"elif",
"self",
".",
"field",
"[",
"self",
".",
"pos",
"]",
"in",
"endchars",
":",
"self",
".",
"pos",
"+=",
"1",
"break",
"elif",
"allowcomments",
"and",
"self",
".",
"field",
"[",
"self",
".",
"pos",
"]",
"==",
"'('",
":",
"slist",
".",
"append",
"(",
"self",
".",
"getcomment",
"(",
")",
")",
"continue",
"# have already advanced pos from getcomment",
"elif",
"self",
".",
"field",
"[",
"self",
".",
"pos",
"]",
"==",
"'\\\\'",
":",
"quote",
"=",
"True",
"else",
":",
"slist",
".",
"append",
"(",
"self",
".",
"field",
"[",
"self",
".",
"pos",
"]",
")",
"self",
".",
"pos",
"+=",
"1",
"return",
"EMPTYSTRING",
".",
"join",
"(",
"slist",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/_parseaddr.py#L412-L447 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/websocket-client/websocket.py | python | WebSocketApp.send | (self, data, opcode=ABNF.OPCODE_TEXT) | send message.
data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode.
opcode: operation code of data. default is OPCODE_TEXT. | send message.
data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode.
opcode: operation code of data. default is OPCODE_TEXT. | [
"send",
"message",
".",
"data",
":",
"message",
"to",
"send",
".",
"If",
"you",
"set",
"opcode",
"to",
"OPCODE_TEXT",
"data",
"must",
"be",
"utf",
"-",
"8",
"string",
"or",
"unicode",
".",
"opcode",
":",
"operation",
"code",
"of",
"data",
".",
"default",
"is",
"OPCODE_TEXT",
"."
] | def send(self, data, opcode=ABNF.OPCODE_TEXT):
"""
send message.
data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode.
opcode: operation code of data. default is OPCODE_TEXT.
"""
if self.sock.send(data, opcode) == 0:
raise WebSocketConnectionClosedException() | [
"def",
"send",
"(",
"self",
",",
"data",
",",
"opcode",
"=",
"ABNF",
".",
"OPCODE_TEXT",
")",
":",
"if",
"self",
".",
"sock",
".",
"send",
"(",
"data",
",",
"opcode",
")",
"==",
"0",
":",
"raise",
"WebSocketConnectionClosedException",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/websocket-client/websocket.py#L806-L813 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBDebugger.GetScriptingLanguage | (self, script_language_name) | return _lldb.SBDebugger_GetScriptingLanguage(self, script_language_name) | GetScriptingLanguage(SBDebugger self, char const * script_language_name) -> lldb::ScriptLanguage | GetScriptingLanguage(SBDebugger self, char const * script_language_name) -> lldb::ScriptLanguage | [
"GetScriptingLanguage",
"(",
"SBDebugger",
"self",
"char",
"const",
"*",
"script_language_name",
")",
"-",
">",
"lldb",
"::",
"ScriptLanguage"
] | def GetScriptingLanguage(self, script_language_name):
"""GetScriptingLanguage(SBDebugger self, char const * script_language_name) -> lldb::ScriptLanguage"""
return _lldb.SBDebugger_GetScriptingLanguage(self, script_language_name) | [
"def",
"GetScriptingLanguage",
"(",
"self",
",",
"script_language_name",
")",
":",
"return",
"_lldb",
".",
"SBDebugger_GetScriptingLanguage",
"(",
"self",
",",
"script_language_name",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L4096-L4098 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py | python | GraphRewriter.eightbitize_concat_node | (self, original_node) | Replaces a Concat node with the eight bit equivalent sub-graph.
Converts a node like this:
Shape(f) Input0(f) Input1(f)
| | |
+--------v v v----------+
Concat
|
v
(f)
Into a quantized equivalent:
Shape(f) Input0(f) ReshapeDims Input1(f)
| +------v v--------------+------------------v v------+
| | Reshape Reshape |
| | | | |
| | | ReductionDims | |
| | +------+ | +--------+ |
| | | +---c---------+-----------c-----+ | |
| | +v v v v-------+---------v v v v+ |
| | Min Max Min Max |
| | +----+ | | +-----+ |
| v v v--------+ +----------v v v
| Quantize Quantize
| +------------------+ +----------------------+
+-------------------------------+ | |
v v v
QuantizedConcat
| | |
v v v
Dequantize
|
v
(f)
Args:
original_node: Float node to be converted.
Returns:
Subgraph representing the quantized version of the original node. | Replaces a Concat node with the eight bit equivalent sub-graph. | [
"Replaces",
"a",
"Concat",
"node",
"with",
"the",
"eight",
"bit",
"equivalent",
"sub",
"-",
"graph",
"."
] | def eightbitize_concat_node(self, original_node):
"""Replaces a Concat node with the eight bit equivalent sub-graph.
Converts a node like this:
Shape(f) Input0(f) Input1(f)
| | |
+--------v v v----------+
Concat
|
v
(f)
Into a quantized equivalent:
Shape(f) Input0(f) ReshapeDims Input1(f)
| +------v v--------------+------------------v v------+
| | Reshape Reshape |
| | | | |
| | | ReductionDims | |
| | +------+ | +--------+ |
| | | +---c---------+-----------c-----+ | |
| | +v v v v-------+---------v v v v+ |
| | Min Max Min Max |
| | +----+ | | +-----+ |
| v v v--------+ +----------v v v
| Quantize Quantize
| +------------------+ +----------------------+
+-------------------------------+ | |
v v v
QuantizedConcat
| | |
v v v
Dequantize
|
v
(f)
Args:
original_node: Float node to be converted.
Returns:
Subgraph representing the quantized version of the original node.
"""
namespace_prefix = original_node.name + "_eightbit"
quantized_concat_name = namespace_prefix + "_quantized_concat"
reshape_dims_name, reduction_dims_name = self.add_common_quantization_nodes(
namespace_prefix)
shape_input_name = original_node.input[0]
original_inputs = original_node.input[1:]
input_names = []
min_names = []
max_names = []
for original_input_name in original_inputs:
quantize_input_name, min_input_name, max_input_name = (
self.eightbitize_input_to_node(namespace_prefix, original_input_name,
reshape_dims_name,
reduction_dims_name))
input_names.append(quantize_input_name)
min_names.append(min_input_name)
max_names.append(max_input_name)
all_input_names = [shape_input_name]
all_input_names.extend(input_names)
all_input_names.extend(min_names)
all_input_names.extend(max_names)
quantized_concat_node = create_node(
"QuantizedConcat", quantized_concat_name, all_input_names)
set_attr_int(quantized_concat_node, "N", len(original_inputs))
set_attr_dtype(quantized_concat_node, "T", tf.quint8)
self.add_output_graph_node(quantized_concat_node)
self.add_dequantize_result_node(quantized_concat_name, original_node.name) | [
"def",
"eightbitize_concat_node",
"(",
"self",
",",
"original_node",
")",
":",
"namespace_prefix",
"=",
"original_node",
".",
"name",
"+",
"\"_eightbit\"",
"quantized_concat_name",
"=",
"namespace_prefix",
"+",
"\"_quantized_concat\"",
"reshape_dims_name",
",",
"reduction_dims_name",
"=",
"self",
".",
"add_common_quantization_nodes",
"(",
"namespace_prefix",
")",
"shape_input_name",
"=",
"original_node",
".",
"input",
"[",
"0",
"]",
"original_inputs",
"=",
"original_node",
".",
"input",
"[",
"1",
":",
"]",
"input_names",
"=",
"[",
"]",
"min_names",
"=",
"[",
"]",
"max_names",
"=",
"[",
"]",
"for",
"original_input_name",
"in",
"original_inputs",
":",
"quantize_input_name",
",",
"min_input_name",
",",
"max_input_name",
"=",
"(",
"self",
".",
"eightbitize_input_to_node",
"(",
"namespace_prefix",
",",
"original_input_name",
",",
"reshape_dims_name",
",",
"reduction_dims_name",
")",
")",
"input_names",
".",
"append",
"(",
"quantize_input_name",
")",
"min_names",
".",
"append",
"(",
"min_input_name",
")",
"max_names",
".",
"append",
"(",
"max_input_name",
")",
"all_input_names",
"=",
"[",
"shape_input_name",
"]",
"all_input_names",
".",
"extend",
"(",
"input_names",
")",
"all_input_names",
".",
"extend",
"(",
"min_names",
")",
"all_input_names",
".",
"extend",
"(",
"max_names",
")",
"quantized_concat_node",
"=",
"create_node",
"(",
"\"QuantizedConcat\"",
",",
"quantized_concat_name",
",",
"all_input_names",
")",
"set_attr_int",
"(",
"quantized_concat_node",
",",
"\"N\"",
",",
"len",
"(",
"original_inputs",
")",
")",
"set_attr_dtype",
"(",
"quantized_concat_node",
",",
"\"T\"",
",",
"tf",
".",
"quint8",
")",
"self",
".",
"add_output_graph_node",
"(",
"quantized_concat_node",
")",
"self",
".",
"add_dequantize_result_node",
"(",
"quantized_concat_name",
",",
"original_node",
".",
"name",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py#L683-L753 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tarfile.py | python | TarInfo._posix_split_name | (self, name, encoding, errors) | return prefix, name | Split a name longer than 100 chars into a prefix
and a name part. | Split a name longer than 100 chars into a prefix
and a name part. | [
"Split",
"a",
"name",
"longer",
"than",
"100",
"chars",
"into",
"a",
"prefix",
"and",
"a",
"name",
"part",
"."
] | def _posix_split_name(self, name, encoding, errors):
"""Split a name longer than 100 chars into a prefix
and a name part.
"""
components = name.split("/")
for i in range(1, len(components)):
prefix = "/".join(components[:i])
name = "/".join(components[i:])
if len(prefix.encode(encoding, errors)) <= LENGTH_PREFIX and \
len(name.encode(encoding, errors)) <= LENGTH_NAME:
break
else:
raise ValueError("name is too long")
return prefix, name | [
"def",
"_posix_split_name",
"(",
"self",
",",
"name",
",",
"encoding",
",",
"errors",
")",
":",
"components",
"=",
"name",
".",
"split",
"(",
"\"/\"",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"components",
")",
")",
":",
"prefix",
"=",
"\"/\"",
".",
"join",
"(",
"components",
"[",
":",
"i",
"]",
")",
"name",
"=",
"\"/\"",
".",
"join",
"(",
"components",
"[",
"i",
":",
"]",
")",
"if",
"len",
"(",
"prefix",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
")",
"<=",
"LENGTH_PREFIX",
"and",
"len",
"(",
"name",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
")",
"<=",
"LENGTH_NAME",
":",
"break",
"else",
":",
"raise",
"ValueError",
"(",
"\"name is too long\"",
")",
"return",
"prefix",
",",
"name"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tarfile.py#L904-L918 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/uuid.py | python | _ip_getnode | () | return None | Get the hardware address on Unix by running ip. | Get the hardware address on Unix by running ip. | [
"Get",
"the",
"hardware",
"address",
"on",
"Unix",
"by",
"running",
"ip",
"."
] | def _ip_getnode():
"""Get the hardware address on Unix by running ip."""
# This works on Linux with iproute2.
mac = _find_mac_near_keyword('ip', 'link', [b'link/ether'], lambda i: i+1)
if mac:
return mac
return None | [
"def",
"_ip_getnode",
"(",
")",
":",
"# This works on Linux with iproute2.",
"mac",
"=",
"_find_mac_near_keyword",
"(",
"'ip'",
",",
"'link'",
",",
"[",
"b'link/ether'",
"]",
",",
"lambda",
"i",
":",
"i",
"+",
"1",
")",
"if",
"mac",
":",
"return",
"mac",
"return",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/uuid.py#L515-L521 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/pathlib.py | python | Path.symlink_to | (self, target, target_is_directory=False) | Make this path a symlink pointing to the given path.
Note the order of arguments (self, target) is the reverse of os.symlink's. | Make this path a symlink pointing to the given path.
Note the order of arguments (self, target) is the reverse of os.symlink's. | [
"Make",
"this",
"path",
"a",
"symlink",
"pointing",
"to",
"the",
"given",
"path",
".",
"Note",
"the",
"order",
"of",
"arguments",
"(",
"self",
"target",
")",
"is",
"the",
"reverse",
"of",
"os",
".",
"symlink",
"s",
"."
] | def symlink_to(self, target, target_is_directory=False):
"""
Make this path a symlink pointing to the given path.
Note the order of arguments (self, target) is the reverse of os.symlink's.
"""
if self._closed:
self._raise_closed()
self._accessor.symlink(target, self, target_is_directory) | [
"def",
"symlink_to",
"(",
"self",
",",
"target",
",",
"target_is_directory",
"=",
"False",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_raise_closed",
"(",
")",
"self",
".",
"_accessor",
".",
"symlink",
"(",
"target",
",",
"self",
",",
"target_is_directory",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pathlib.py#L1345-L1352 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | PageSetupDialogData.GetMinMarginTopLeft | (*args, **kwargs) | return _windows_.PageSetupDialogData_GetMinMarginTopLeft(*args, **kwargs) | GetMinMarginTopLeft(self) -> Point | GetMinMarginTopLeft(self) -> Point | [
"GetMinMarginTopLeft",
"(",
"self",
")",
"-",
">",
"Point"
] | def GetMinMarginTopLeft(*args, **kwargs):
"""GetMinMarginTopLeft(self) -> Point"""
return _windows_.PageSetupDialogData_GetMinMarginTopLeft(*args, **kwargs) | [
"def",
"GetMinMarginTopLeft",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PageSetupDialogData_GetMinMarginTopLeft",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L4930-L4932 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/msvc.py | python | SystemInfo.NetFxSdkDir | (self) | return sdkdir or '' | Microsoft .NET Framework SDK directory. | Microsoft .NET Framework SDK directory. | [
"Microsoft",
".",
"NET",
"Framework",
"SDK",
"directory",
"."
] | def NetFxSdkDir(self):
"""
Microsoft .NET Framework SDK directory.
"""
for ver in self.NetFxSdkVersion:
loc = os.path.join(self.ri.netfx_sdk, ver)
sdkdir = self.ri.lookup(loc, 'kitsinstallationfolder')
if sdkdir:
break
return sdkdir or '' | [
"def",
"NetFxSdkDir",
"(",
"self",
")",
":",
"for",
"ver",
"in",
"self",
".",
"NetFxSdkVersion",
":",
"loc",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"ri",
".",
"netfx_sdk",
",",
"ver",
")",
"sdkdir",
"=",
"self",
".",
"ri",
".",
"lookup",
"(",
"loc",
",",
"'kitsinstallationfolder'",
")",
"if",
"sdkdir",
":",
"break",
"return",
"sdkdir",
"or",
"''"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/msvc.py#L724-L733 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/LargeScaleStructures/data_stitching.py | python | Stitcher.size | (self) | return len(self._data_sets) | Return the number of data sets | Return the number of data sets | [
"Return",
"the",
"number",
"of",
"data",
"sets"
] | def size(self):
"""
Return the number of data sets
"""
return len(self._data_sets) | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"_data_sets",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/LargeScaleStructures/data_stitching.py#L470-L474 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/html2.py | python | WebView.GetSelectedText | (*args, **kwargs) | return _html2.WebView_GetSelectedText(*args, **kwargs) | GetSelectedText(self) -> String | GetSelectedText(self) -> String | [
"GetSelectedText",
"(",
"self",
")",
"-",
">",
"String"
] | def GetSelectedText(*args, **kwargs):
"""GetSelectedText(self) -> String"""
return _html2.WebView_GetSelectedText(*args, **kwargs) | [
"def",
"GetSelectedText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html2",
".",
"WebView_GetSelectedText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html2.py#L278-L280 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/mfg/games/linear_quadratic.py | python | MFGLinearQuadraticState._legal_actions | (self, player) | Returns a list of legal actions for player and MFG nodes. | Returns a list of legal actions for player and MFG nodes. | [
"Returns",
"a",
"list",
"of",
"legal",
"actions",
"for",
"player",
"and",
"MFG",
"nodes",
"."
] | def _legal_actions(self, player):
"""Returns a list of legal actions for player and MFG nodes."""
if player == pyspiel.PlayerId.MEAN_FIELD:
return []
if (player == pyspiel.PlayerId.DEFAULT_PLAYER_ID and
player == self.current_player()):
return list(range(self.n_actions))
raise ValueError(f"Unexpected player {player}. "
"Expected a mean field or current player 0.") | [
"def",
"_legal_actions",
"(",
"self",
",",
"player",
")",
":",
"if",
"player",
"==",
"pyspiel",
".",
"PlayerId",
".",
"MEAN_FIELD",
":",
"return",
"[",
"]",
"if",
"(",
"player",
"==",
"pyspiel",
".",
"PlayerId",
".",
"DEFAULT_PLAYER_ID",
"and",
"player",
"==",
"self",
".",
"current_player",
"(",
")",
")",
":",
"return",
"list",
"(",
"range",
"(",
"self",
".",
"n_actions",
")",
")",
"raise",
"ValueError",
"(",
"f\"Unexpected player {player}. \"",
"\"Expected a mean field or current player 0.\"",
")"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/mfg/games/linear_quadratic.py#L180-L188 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/ValidationKit/common/utils.py | python | ProcessInfo.loadAll | (self) | Load all the info. | Load all the info. | [
"Load",
"all",
"the",
"info",
"."
] | def loadAll(self):
"""Load all the info."""
sOs = getHostOs();
if sOs == 'linux':
sProc = '/proc/%s/' % (self.iPid,);
if self.sImage is None: self.sImage = noxcptReadLink(sProc + 'exe', None);
if self.sCwd is None: self.sCwd = noxcptReadLink(sProc + 'cwd', None);
if self.asArgs is None: self.asArgs = noxcptReadFile(sProc + 'cmdline', '').split('\x00');
#elif sOs == 'solaris': - doesn't work for root processes, suid proces, and other stuff.
# sProc = '/proc/%s/' % (self.iPid,);
# if self.sImage is None: self.sImage = noxcptReadLink(sProc + 'path/a.out', None);
# if self.sCwd is None: self.sCwd = noxcptReadLink(sProc + 'path/cwd', None);
else:
pass;
if self.sName is None and self.sImage is not None:
self.sName = self.sImage; | [
"def",
"loadAll",
"(",
"self",
")",
":",
"sOs",
"=",
"getHostOs",
"(",
")",
"if",
"sOs",
"==",
"'linux'",
":",
"sProc",
"=",
"'/proc/%s/'",
"%",
"(",
"self",
".",
"iPid",
",",
")",
"if",
"self",
".",
"sImage",
"is",
"None",
":",
"self",
".",
"sImage",
"=",
"noxcptReadLink",
"(",
"sProc",
"+",
"'exe'",
",",
"None",
")",
"if",
"self",
".",
"sCwd",
"is",
"None",
":",
"self",
".",
"sCwd",
"=",
"noxcptReadLink",
"(",
"sProc",
"+",
"'cwd'",
",",
"None",
")",
"if",
"self",
".",
"asArgs",
"is",
"None",
":",
"self",
".",
"asArgs",
"=",
"noxcptReadFile",
"(",
"sProc",
"+",
"'cmdline'",
",",
"''",
")",
".",
"split",
"(",
"'\\x00'",
")",
"#elif sOs == 'solaris': - doesn't work for root processes, suid proces, and other stuff.",
"# sProc = '/proc/%s/' % (self.iPid,);",
"# if self.sImage is None: self.sImage = noxcptReadLink(sProc + 'path/a.out', None);",
"# if self.sCwd is None: self.sCwd = noxcptReadLink(sProc + 'path/cwd', None);",
"else",
":",
"pass",
"if",
"self",
".",
"sName",
"is",
"None",
"and",
"self",
".",
"sImage",
"is",
"not",
"None",
":",
"self",
".",
"sName",
"=",
"self",
".",
"sImage"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/ValidationKit/common/utils.py#L950-L965 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/contrib/dag/__init__.py | python | DAG.reverse_edges | (self, graph=None) | Reversed dependencies in current graph. | Reversed dependencies in current graph. | [
"Reversed",
"dependencies",
"in",
"current",
"graph",
"."
] | def reverse_edges(self, graph=None):
""" Reversed dependencies in current graph. """
new_graph = self.reverse_clone()
self.graph = new_graph.graph | [
"def",
"reverse_edges",
"(",
"self",
",",
"graph",
"=",
"None",
")",
":",
"new_graph",
"=",
"self",
".",
"reverse_clone",
"(",
")",
"self",
".",
"graph",
"=",
"new_graph",
".",
"graph"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/contrib/dag/__init__.py#L304-L308 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/math_ops.py | python | _OverrideBinaryOperatorHelper | (func, op_name, clazz_object=ops.Tensor) | Register operators with different tensor and scalar versions.
If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices,
sp_values, sp_shape, dense)` and outputs `(new_sp_values)`.
Args:
func: the operator
op_name: name of the operator being overridden
clazz_object: class to override for. Either `Tensor` or `SparseTensor`. | Register operators with different tensor and scalar versions. | [
"Register",
"operators",
"with",
"different",
"tensor",
"and",
"scalar",
"versions",
"."
] | def _OverrideBinaryOperatorHelper(func, op_name, clazz_object=ops.Tensor):
"""Register operators with different tensor and scalar versions.
If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices,
sp_values, sp_shape, dense)` and outputs `(new_sp_values)`.
Args:
func: the operator
op_name: name of the operator being overridden
clazz_object: class to override for. Either `Tensor` or `SparseTensor`.
"""
def binary_op_wrapper(x, y):
with ops.name_scope(None, op_name, [x, y]) as name:
if not isinstance(y, sparse_tensor.SparseTensor):
try:
y = ops.convert_to_tensor(y, dtype=x.dtype.base_dtype, name="y")
except TypeError:
# If the RHS is not a tensor, it might be a tensor aware object
# that can implement the operator with knowledge of itself
# and the tensor.
if hasattr(type(y), "__r%s__" % op_name):
return NotImplemented
else:
raise
return func(x, y, name=name)
def binary_op_wrapper_sparse(sp_x, y):
with ops.name_scope(None, op_name, [sp_x, y]) as name:
y = ops.convert_to_tensor(y, dtype=sp_x.dtype.base_dtype, name="y")
return sparse_tensor.SparseTensor(sp_x.indices,
func(
sp_x.indices,
sp_x.values,
sp_x.dense_shape,
y,
name=name), sp_x.dense_shape)
def r_binary_op_wrapper(y, x):
with ops.name_scope(None, op_name, [x, y]) as name:
x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name="x")
return func(x, y, name=name)
# Propagate func.__doc__ to the wrappers
try:
doc = func.__doc__
except AttributeError:
doc = None
binary_op_wrapper.__doc__ = doc
r_binary_op_wrapper.__doc__ = doc
binary_op_wrapper_sparse.__doc__ = doc
if clazz_object is ops.Tensor:
clazz_object._override_operator("__%s__" % op_name, binary_op_wrapper)
del binary_op_wrapper
clazz_object._override_operator("__r%s__" % op_name, r_binary_op_wrapper)
del r_binary_op_wrapper
else:
clazz_object._override_operator("__%s__" % op_name,
binary_op_wrapper_sparse)
del binary_op_wrapper_sparse | [
"def",
"_OverrideBinaryOperatorHelper",
"(",
"func",
",",
"op_name",
",",
"clazz_object",
"=",
"ops",
".",
"Tensor",
")",
":",
"def",
"binary_op_wrapper",
"(",
"x",
",",
"y",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"None",
",",
"op_name",
",",
"[",
"x",
",",
"y",
"]",
")",
"as",
"name",
":",
"if",
"not",
"isinstance",
"(",
"y",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
":",
"try",
":",
"y",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"y",
",",
"dtype",
"=",
"x",
".",
"dtype",
".",
"base_dtype",
",",
"name",
"=",
"\"y\"",
")",
"except",
"TypeError",
":",
"# If the RHS is not a tensor, it might be a tensor aware object",
"# that can implement the operator with knowledge of itself",
"# and the tensor.",
"if",
"hasattr",
"(",
"type",
"(",
"y",
")",
",",
"\"__r%s__\"",
"%",
"op_name",
")",
":",
"return",
"NotImplemented",
"else",
":",
"raise",
"return",
"func",
"(",
"x",
",",
"y",
",",
"name",
"=",
"name",
")",
"def",
"binary_op_wrapper_sparse",
"(",
"sp_x",
",",
"y",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"None",
",",
"op_name",
",",
"[",
"sp_x",
",",
"y",
"]",
")",
"as",
"name",
":",
"y",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"y",
",",
"dtype",
"=",
"sp_x",
".",
"dtype",
".",
"base_dtype",
",",
"name",
"=",
"\"y\"",
")",
"return",
"sparse_tensor",
".",
"SparseTensor",
"(",
"sp_x",
".",
"indices",
",",
"func",
"(",
"sp_x",
".",
"indices",
",",
"sp_x",
".",
"values",
",",
"sp_x",
".",
"dense_shape",
",",
"y",
",",
"name",
"=",
"name",
")",
",",
"sp_x",
".",
"dense_shape",
")",
"def",
"r_binary_op_wrapper",
"(",
"y",
",",
"x",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"None",
",",
"op_name",
",",
"[",
"x",
",",
"y",
"]",
")",
"as",
"name",
":",
"x",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"x",
",",
"dtype",
"=",
"y",
".",
"dtype",
".",
"base_dtype",
",",
"name",
"=",
"\"x\"",
")",
"return",
"func",
"(",
"x",
",",
"y",
",",
"name",
"=",
"name",
")",
"# Propagate func.__doc__ to the wrappers",
"try",
":",
"doc",
"=",
"func",
".",
"__doc__",
"except",
"AttributeError",
":",
"doc",
"=",
"None",
"binary_op_wrapper",
".",
"__doc__",
"=",
"doc",
"r_binary_op_wrapper",
".",
"__doc__",
"=",
"doc",
"binary_op_wrapper_sparse",
".",
"__doc__",
"=",
"doc",
"if",
"clazz_object",
"is",
"ops",
".",
"Tensor",
":",
"clazz_object",
".",
"_override_operator",
"(",
"\"__%s__\"",
"%",
"op_name",
",",
"binary_op_wrapper",
")",
"del",
"binary_op_wrapper",
"clazz_object",
".",
"_override_operator",
"(",
"\"__r%s__\"",
"%",
"op_name",
",",
"r_binary_op_wrapper",
")",
"del",
"r_binary_op_wrapper",
"else",
":",
"clazz_object",
".",
"_override_operator",
"(",
"\"__%s__\"",
"%",
"op_name",
",",
"binary_op_wrapper_sparse",
")",
"del",
"binary_op_wrapper_sparse"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/math_ops.py#L840-L900 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/threading.py | python | Thread.is_alive | (self) | return not self._is_stopped | Return whether the thread is alive.
This method returns True just before the run() method starts until just
after the run() method terminates. See also the module function
enumerate(). | Return whether the thread is alive. | [
"Return",
"whether",
"the",
"thread",
"is",
"alive",
"."
] | def is_alive(self):
"""Return whether the thread is alive.
This method returns True just before the run() method starts until just
after the run() method terminates. See also the module function
enumerate().
"""
assert self._initialized, "Thread.__init__() not called"
if self._is_stopped or not self._started.is_set():
return False
self._wait_for_tstate_lock(False)
return not self._is_stopped | [
"def",
"is_alive",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_initialized",
",",
"\"Thread.__init__() not called\"",
"if",
"self",
".",
"_is_stopped",
"or",
"not",
"self",
".",
"_started",
".",
"is_set",
"(",
")",
":",
"return",
"False",
"self",
".",
"_wait_for_tstate_lock",
"(",
"False",
")",
"return",
"not",
"self",
".",
"_is_stopped"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/threading.py#L1126-L1138 | |
NetSys/bess | ae52fc5804290fc3116daf2aef52226fafcedf5d | bessctl/measurement_utils.py | python | PortStats.jitter | (self, percentile=None) | return self.jitter[percentile] | Returns the dictionary of all jitter value if `percentile` is none.
Otherwise returns the `percentile`th percentile jitter. | Returns the dictionary of all jitter value if `percentile` is none.
Otherwise returns the `percentile`th percentile jitter. | [
"Returns",
"the",
"dictionary",
"of",
"all",
"jitter",
"value",
"if",
"percentile",
"is",
"none",
".",
"Otherwise",
"returns",
"the",
"percentile",
"th",
"percentile",
"jitter",
"."
] | def jitter(self, percentile=None):
"""
Returns the dictionary of all jitter value if `percentile` is none.
Otherwise returns the `percentile`th percentile jitter.
"""
if self.jitter is None or percentile is None:
return self.jitter
return self.jitter[percentile] | [
"def",
"jitter",
"(",
"self",
",",
"percentile",
"=",
"None",
")",
":",
"if",
"self",
".",
"jitter",
"is",
"None",
"or",
"percentile",
"is",
"None",
":",
"return",
"self",
".",
"jitter",
"return",
"self",
".",
"jitter",
"[",
"percentile",
"]"
] | https://github.com/NetSys/bess/blob/ae52fc5804290fc3116daf2aef52226fafcedf5d/bessctl/measurement_utils.py#L95-L102 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | PageSetupDialogData.GetDefaultMinMargins | (*args, **kwargs) | return _windows_.PageSetupDialogData_GetDefaultMinMargins(*args, **kwargs) | GetDefaultMinMargins(self) -> bool | GetDefaultMinMargins(self) -> bool | [
"GetDefaultMinMargins",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetDefaultMinMargins(*args, **kwargs):
"""GetDefaultMinMargins(self) -> bool"""
return _windows_.PageSetupDialogData_GetDefaultMinMargins(*args, **kwargs) | [
"def",
"GetDefaultMinMargins",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PageSetupDialogData_GetDefaultMinMargins",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L4886-L4888 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | dom/bindings/Codegen.py | python | getWrapTemplateForType | (type, descriptorProvider, result, successCode,
returnsNewObject, exceptionCode, typedArraysAreStructs) | Reflect a C++ value stored in "result", of IDL type "type" into JS. The
"successCode" is the code to run once we have successfully done the
conversion and must guarantee that execution of the conversion template
stops once the successCode has executed (e.g. by doing a 'return', or by
doing a 'break' if the entire conversion template is inside a block that
the 'break' will exit).
If typedArraysAreStructs is true, then if the type is a typed array,
"result" is one of the dom::TypedArray subclasses, not a JSObject*.
The resulting string should be used with string.Template. It
needs the following keys when substituting:
jsvalHandle: something that can be passed to methods taking a
JS::MutableHandle<JS::Value>. This can be a
JS::MutableHandle<JS::Value> or a JS::Rooted<JS::Value>*.
jsvalRef: something that can have .address() called on it to get a
JS::Value* and .set() called on it to set it to a JS::Value.
This can be a JS::MutableHandle<JS::Value> or a
JS::Rooted<JS::Value>.
obj: a JS::Handle<JSObject*>.
Returns (templateString, infallibility of conversion template) | Reflect a C++ value stored in "result", of IDL type "type" into JS. The
"successCode" is the code to run once we have successfully done the
conversion and must guarantee that execution of the conversion template
stops once the successCode has executed (e.g. by doing a 'return', or by
doing a 'break' if the entire conversion template is inside a block that
the 'break' will exit). | [
"Reflect",
"a",
"C",
"++",
"value",
"stored",
"in",
"result",
"of",
"IDL",
"type",
"type",
"into",
"JS",
".",
"The",
"successCode",
"is",
"the",
"code",
"to",
"run",
"once",
"we",
"have",
"successfully",
"done",
"the",
"conversion",
"and",
"must",
"guarantee",
"that",
"execution",
"of",
"the",
"conversion",
"template",
"stops",
"once",
"the",
"successCode",
"has",
"executed",
"(",
"e",
".",
"g",
".",
"by",
"doing",
"a",
"return",
"or",
"by",
"doing",
"a",
"break",
"if",
"the",
"entire",
"conversion",
"template",
"is",
"inside",
"a",
"block",
"that",
"the",
"break",
"will",
"exit",
")",
"."
] | def getWrapTemplateForType(type, descriptorProvider, result, successCode,
returnsNewObject, exceptionCode, typedArraysAreStructs):
"""
Reflect a C++ value stored in "result", of IDL type "type" into JS. The
"successCode" is the code to run once we have successfully done the
conversion and must guarantee that execution of the conversion template
stops once the successCode has executed (e.g. by doing a 'return', or by
doing a 'break' if the entire conversion template is inside a block that
the 'break' will exit).
If typedArraysAreStructs is true, then if the type is a typed array,
"result" is one of the dom::TypedArray subclasses, not a JSObject*.
The resulting string should be used with string.Template. It
needs the following keys when substituting:
jsvalHandle: something that can be passed to methods taking a
JS::MutableHandle<JS::Value>. This can be a
JS::MutableHandle<JS::Value> or a JS::Rooted<JS::Value>*.
jsvalRef: something that can have .address() called on it to get a
JS::Value* and .set() called on it to set it to a JS::Value.
This can be a JS::MutableHandle<JS::Value> or a
JS::Rooted<JS::Value>.
obj: a JS::Handle<JSObject*>.
Returns (templateString, infallibility of conversion template)
"""
if successCode is None:
successCode = "return true;\n"
def setUndefined():
return _setValue("", setter="setUndefined")
def setNull():
return _setValue("", setter="setNull")
def setInt32(value):
return _setValue(value, setter="setInt32")
def setString(value):
return _setValue(value, setter="setString")
def setObject(value, wrapAsType=None):
return _setValue(value, wrapAsType=wrapAsType, setter="setObject")
def setObjectOrNull(value, wrapAsType=None):
return _setValue(value, wrapAsType=wrapAsType, setter="setObjectOrNull")
def setUint32(value):
return _setValue(value, setter="setNumber")
def setDouble(value):
return _setValue("JS_NumberValue(%s)" % value)
def setBoolean(value):
return _setValue(value, setter="setBoolean")
def _setValue(value, wrapAsType=None, setter="set"):
"""
Returns the code to set the jsval to value.
If wrapAsType is not None, then will wrap the resulting value using the
function that getMaybeWrapValueFuncForType(wrapAsType) returns.
Otherwise, no wrapping will be done.
"""
if wrapAsType is None:
tail = successCode
else:
tail = fill(
"""
if (!${maybeWrap}(cx, $${jsvalHandle})) {
$*{exceptionCode}
}
$*{successCode}
""",
maybeWrap=getMaybeWrapValueFuncForType(wrapAsType),
exceptionCode=exceptionCode,
successCode=successCode)
return ("${jsvalRef}.%s(%s);\n" % (setter, value)) + tail
def wrapAndSetPtr(wrapCall, failureCode=None):
"""
Returns the code to set the jsval by calling "wrapCall". "failureCode"
is the code to run if calling "wrapCall" fails
"""
if failureCode is None:
failureCode = exceptionCode
return fill(
"""
if (!${wrapCall}) {
$*{failureCode}
}
$*{successCode}
""",
wrapCall=wrapCall,
failureCode=failureCode,
successCode=successCode)
if type is None or type.isVoid():
return (setUndefined(), True)
if type.isArray():
raise TypeError("Can't handle array return values yet")
if (type.isSequence() or type.isMozMap()) and type.nullable():
# These are both wrapped in Nullable<>
recTemplate, recInfall = getWrapTemplateForType(type.inner, descriptorProvider,
"%s.Value()" % result, successCode,
returnsNewObject, exceptionCode,
typedArraysAreStructs)
code = fill(
"""
if (${result}.IsNull()) {
$*{setNull}
}
$*{recTemplate}
""",
result=result,
setNull=setNull(),
recTemplate=recTemplate)
return code, recInfall
if type.isSequence():
# Now do non-nullable sequences. Our success code is just to break to
# where we set the element in the array. Note that we bump the
# sequenceWrapLevel around this call so that nested sequence conversions
# will use different iteration variables.
global sequenceWrapLevel
index = "sequenceIdx%d" % sequenceWrapLevel
sequenceWrapLevel += 1
innerTemplate = wrapForType(
type.inner, descriptorProvider,
{
'result': "%s[%s]" % (result, index),
'successCode': "break;\n",
'jsvalRef': "tmp",
'jsvalHandle': "&tmp",
'returnsNewObject': returnsNewObject,
'exceptionCode': exceptionCode,
'obj': "returnArray",
'typedArraysAreStructs': typedArraysAreStructs
})
sequenceWrapLevel -= 1
code = fill(
"""
uint32_t length = ${result}.Length();
JS::Rooted<JSObject*> returnArray(cx, JS_NewArrayObject(cx, length));
if (!returnArray) {
$*{exceptionCode}
}
// Scope for 'tmp'
{
JS::Rooted<JS::Value> tmp(cx);
for (uint32_t ${index} = 0; ${index} < length; ++${index}) {
// Control block to let us common up the JS_DefineElement calls when there
// are different ways to succeed at wrapping the object.
do {
$*{innerTemplate}
} while (0);
if (!JS_DefineElement(cx, returnArray, ${index}, tmp,
JSPROP_ENUMERATE)) {
$*{exceptionCode}
}
}
}
$*{set}
""",
result=result,
exceptionCode=exceptionCode,
index=index,
innerTemplate=innerTemplate,
set=setObject("*returnArray"))
return (code, False)
if type.isMozMap():
# Now do non-nullable MozMap. Our success code is just to break to
# where we define the property on the object. Note that we bump the
# mozMapWrapLevel around this call so that nested MozMap conversions
# will use different temp value names.
global mozMapWrapLevel
valueName = "mozMapValue%d" % mozMapWrapLevel
mozMapWrapLevel += 1
innerTemplate = wrapForType(
type.inner, descriptorProvider,
{
'result': valueName,
'successCode': "break;\n",
'jsvalRef': "tmp",
'jsvalHandle': "&tmp",
'returnsNewObject': returnsNewObject,
'exceptionCode': exceptionCode,
'obj': "returnObj",
'typedArraysAreStructs': typedArraysAreStructs
})
mozMapWrapLevel -= 1
code = fill(
"""
nsTArray<nsString> keys;
${result}.GetKeys(keys);
JS::Rooted<JSObject*> returnObj(cx, JS_NewObject(cx, nullptr, JS::NullPtr(), JS::NullPtr()));
if (!returnObj) {
$*{exceptionCode}
}
// Scope for 'tmp'
{
JS::Rooted<JS::Value> tmp(cx);
for (size_t idx = 0; idx < keys.Length(); ++idx) {
auto& ${valueName} = ${result}.Get(keys[idx]);
// Control block to let us common up the JS_DefineUCProperty calls when there
// are different ways to succeed at wrapping the value.
do {
$*{innerTemplate}
} while (0);
if (!JS_DefineUCProperty(cx, returnObj, keys[idx].get(),
keys[idx].Length(), tmp,
JSPROP_ENUMERATE)) {
$*{exceptionCode}
}
}
}
$*{set}
""",
result=result,
exceptionCode=exceptionCode,
valueName=valueName,
innerTemplate=innerTemplate,
set=setObject("*returnObj"))
return (code, False)
if type.isGeckoInterface() and not type.isCallbackInterface():
descriptor = descriptorProvider.getDescriptor(type.unroll().inner.identifier.name)
if type.nullable():
wrappingCode = ("if (!%s) {\n" % (result) +
indent(setNull()) +
"}\n")
else:
wrappingCode = ""
if not descriptor.interface.isExternal() and not descriptor.skipGen:
if descriptor.wrapperCache:
assert descriptor.nativeOwnership != 'owned'
wrapMethod = "WrapNewBindingObject"
else:
if not returnsNewObject:
raise MethodNotNewObjectError(descriptor.interface.identifier.name)
if descriptor.nativeOwnership == 'owned':
wrapMethod = "WrapNewBindingNonWrapperCachedOwnedObject"
else:
wrapMethod = "WrapNewBindingNonWrapperCachedObject"
wrap = "%s(cx, ${obj}, %s, ${jsvalHandle})" % (wrapMethod, result)
if not descriptor.hasXPConnectImpls:
# Can only fail to wrap as a new-binding object
# if they already threw an exception.
#XXX Assertion disabled for now, see bug 991271.
failed = ("MOZ_ASSERT(true || JS_IsExceptionPending(cx));\n" +
exceptionCode)
else:
if descriptor.notflattened:
raise TypeError("%s has XPConnect impls but not flattened; "
"fallback won't work correctly" %
descriptor.interface.identifier.name)
# Try old-style wrapping for bindings which might be XPConnect impls.
failed = wrapAndSetPtr("HandleNewBindingWrappingFailure(cx, ${obj}, %s, ${jsvalHandle})" % result)
else:
if descriptor.notflattened:
getIID = "&NS_GET_IID(%s), " % descriptor.nativeType
else:
getIID = ""
wrap = "WrapObject(cx, %s, %s${jsvalHandle})" % (result, getIID)
failed = None
wrappingCode += wrapAndSetPtr(wrap, failed)
return (wrappingCode, False)
if type.isDOMString() or type.isScalarValueString():
if type.nullable():
return (wrapAndSetPtr("xpc::StringToJsval(cx, %s, ${jsvalHandle})" % result), False)
else:
return (wrapAndSetPtr("xpc::NonVoidStringToJsval(cx, %s, ${jsvalHandle})" % result), False)
if type.isByteString():
if type.nullable():
return (wrapAndSetPtr("ByteStringToJsval(cx, %s, ${jsvalHandle})" % result), False)
else:
return (wrapAndSetPtr("NonVoidByteStringToJsval(cx, %s, ${jsvalHandle})" % result), False)
if type.isEnum():
if type.nullable():
resultLoc = "%s.Value()" % result
else:
resultLoc = result
conversion = fill(
"""
{
// Scope for resultStr
MOZ_ASSERT(uint32_t(${result}) < ArrayLength(${strings}));
JSString* resultStr = JS_NewStringCopyN(cx, ${strings}[uint32_t(${result})].value, ${strings}[uint32_t(${result})].length);
if (!resultStr) {
$*{exceptionCode}
}
$*{setResultStr}
}
""",
result=resultLoc,
strings=(type.unroll().inner.identifier.name + "Values::" +
ENUM_ENTRY_VARIABLE_NAME),
exceptionCode=exceptionCode,
setResultStr=setString("resultStr"))
if type.nullable():
conversion = CGIfElseWrapper(
"%s.IsNull()" % result,
CGGeneric(setNull()),
CGGeneric(conversion)).define()
return conversion, False
if type.isCallback() or type.isCallbackInterface():
wrapCode = setObject(
"*GetCallbackFromCallbackObject(%(result)s)",
wrapAsType=type)
if type.nullable():
wrapCode = (
"if (%(result)s) {\n" +
indent(wrapCode) +
"} else {\n" +
indent(setNull()) +
"}\n")
wrapCode = wrapCode % {"result": result}
return wrapCode, False
if type.isAny():
# See comments in WrapNewBindingObject explaining why we need
# to wrap here.
# NB: _setValue(..., type-that-is-any) calls JS_WrapValue(), so is fallible
head = "JS::ExposeValueToActiveJS(%s);\n" % result
return (head + _setValue(result, wrapAsType=type), False)
if (type.isObject() or (type.isSpiderMonkeyInterface() and
not typedArraysAreStructs)):
# See comments in WrapNewBindingObject explaining why we need
# to wrap here.
if type.nullable():
toValue = "%s"
setter = setObjectOrNull
head = """if (%s) {
JS::ExposeObjectToActiveJS(%s);
}
""" % (result, result)
else:
toValue = "*%s"
setter = setObject
head = "JS::ExposeObjectToActiveJS(%s);\n" % result
# NB: setObject{,OrNull}(..., some-object-type) calls JS_WrapValue(), so is fallible
return (head + setter(toValue % result, wrapAsType=type), False)
if not (type.isUnion() or type.isPrimitive() or type.isDictionary() or
type.isDate() or
(type.isSpiderMonkeyInterface() and typedArraysAreStructs)):
raise TypeError("Need to learn to wrap %s" % type)
if type.nullable():
recTemplate, recInfal = getWrapTemplateForType(type.inner, descriptorProvider,
"%s.Value()" % result, successCode,
returnsNewObject, exceptionCode,
typedArraysAreStructs)
return ("if (%s.IsNull()) {\n" % result +
indent(setNull()) +
"}\n" +
recTemplate, recInfal)
if type.isSpiderMonkeyInterface():
assert typedArraysAreStructs
# See comments in WrapNewBindingObject explaining why we need
# to wrap here.
# NB: setObject(..., some-object-type) calls JS_WrapValue(), so is fallible
return (setObject("*%s.Obj()" % result,
wrapAsType=type), False)
if type.isUnion():
return (wrapAndSetPtr("%s.ToJSVal(cx, ${obj}, ${jsvalHandle})" % result),
False)
if type.isDictionary():
return (wrapAndSetPtr("%s.ToObjectInternal(cx, ${jsvalHandle})" % result),
False)
if type.isDate():
return (wrapAndSetPtr("%s.ToDateObject(cx, ${jsvalHandle})" % result),
False)
tag = type.tag()
if tag in [IDLType.Tags.int8, IDLType.Tags.uint8, IDLType.Tags.int16,
IDLType.Tags.uint16, IDLType.Tags.int32]:
return (setInt32("int32_t(%s)" % result), True)
elif tag in [IDLType.Tags.int64, IDLType.Tags.uint64,
IDLType.Tags.unrestricted_float, IDLType.Tags.float,
IDLType.Tags.unrestricted_double, IDLType.Tags.double]:
# XXXbz will cast to double do the "even significand" thing that webidl
# calls for for 64-bit ints? Do we care?
return (setDouble("double(%s)" % result), True)
elif tag == IDLType.Tags.uint32:
return (setUint32(result), True)
elif tag == IDLType.Tags.bool:
return (setBoolean(result), True)
else:
raise TypeError("Need to learn to wrap primitive: %s" % type) | [
"def",
"getWrapTemplateForType",
"(",
"type",
",",
"descriptorProvider",
",",
"result",
",",
"successCode",
",",
"returnsNewObject",
",",
"exceptionCode",
",",
"typedArraysAreStructs",
")",
":",
"if",
"successCode",
"is",
"None",
":",
"successCode",
"=",
"\"return true;\\n\"",
"def",
"setUndefined",
"(",
")",
":",
"return",
"_setValue",
"(",
"\"\"",
",",
"setter",
"=",
"\"setUndefined\"",
")",
"def",
"setNull",
"(",
")",
":",
"return",
"_setValue",
"(",
"\"\"",
",",
"setter",
"=",
"\"setNull\"",
")",
"def",
"setInt32",
"(",
"value",
")",
":",
"return",
"_setValue",
"(",
"value",
",",
"setter",
"=",
"\"setInt32\"",
")",
"def",
"setString",
"(",
"value",
")",
":",
"return",
"_setValue",
"(",
"value",
",",
"setter",
"=",
"\"setString\"",
")",
"def",
"setObject",
"(",
"value",
",",
"wrapAsType",
"=",
"None",
")",
":",
"return",
"_setValue",
"(",
"value",
",",
"wrapAsType",
"=",
"wrapAsType",
",",
"setter",
"=",
"\"setObject\"",
")",
"def",
"setObjectOrNull",
"(",
"value",
",",
"wrapAsType",
"=",
"None",
")",
":",
"return",
"_setValue",
"(",
"value",
",",
"wrapAsType",
"=",
"wrapAsType",
",",
"setter",
"=",
"\"setObjectOrNull\"",
")",
"def",
"setUint32",
"(",
"value",
")",
":",
"return",
"_setValue",
"(",
"value",
",",
"setter",
"=",
"\"setNumber\"",
")",
"def",
"setDouble",
"(",
"value",
")",
":",
"return",
"_setValue",
"(",
"\"JS_NumberValue(%s)\"",
"%",
"value",
")",
"def",
"setBoolean",
"(",
"value",
")",
":",
"return",
"_setValue",
"(",
"value",
",",
"setter",
"=",
"\"setBoolean\"",
")",
"def",
"_setValue",
"(",
"value",
",",
"wrapAsType",
"=",
"None",
",",
"setter",
"=",
"\"set\"",
")",
":",
"\"\"\"\n Returns the code to set the jsval to value.\n\n If wrapAsType is not None, then will wrap the resulting value using the\n function that getMaybeWrapValueFuncForType(wrapAsType) returns.\n Otherwise, no wrapping will be done.\n \"\"\"",
"if",
"wrapAsType",
"is",
"None",
":",
"tail",
"=",
"successCode",
"else",
":",
"tail",
"=",
"fill",
"(",
"\"\"\"\n if (!${maybeWrap}(cx, $${jsvalHandle})) {\n $*{exceptionCode}\n }\n $*{successCode}\n \"\"\"",
",",
"maybeWrap",
"=",
"getMaybeWrapValueFuncForType",
"(",
"wrapAsType",
")",
",",
"exceptionCode",
"=",
"exceptionCode",
",",
"successCode",
"=",
"successCode",
")",
"return",
"(",
"\"${jsvalRef}.%s(%s);\\n\"",
"%",
"(",
"setter",
",",
"value",
")",
")",
"+",
"tail",
"def",
"wrapAndSetPtr",
"(",
"wrapCall",
",",
"failureCode",
"=",
"None",
")",
":",
"\"\"\"\n Returns the code to set the jsval by calling \"wrapCall\". \"failureCode\"\n is the code to run if calling \"wrapCall\" fails\n \"\"\"",
"if",
"failureCode",
"is",
"None",
":",
"failureCode",
"=",
"exceptionCode",
"return",
"fill",
"(",
"\"\"\"\n if (!${wrapCall}) {\n $*{failureCode}\n }\n $*{successCode}\n \"\"\"",
",",
"wrapCall",
"=",
"wrapCall",
",",
"failureCode",
"=",
"failureCode",
",",
"successCode",
"=",
"successCode",
")",
"if",
"type",
"is",
"None",
"or",
"type",
".",
"isVoid",
"(",
")",
":",
"return",
"(",
"setUndefined",
"(",
")",
",",
"True",
")",
"if",
"type",
".",
"isArray",
"(",
")",
":",
"raise",
"TypeError",
"(",
"\"Can't handle array return values yet\"",
")",
"if",
"(",
"type",
".",
"isSequence",
"(",
")",
"or",
"type",
".",
"isMozMap",
"(",
")",
")",
"and",
"type",
".",
"nullable",
"(",
")",
":",
"# These are both wrapped in Nullable<>",
"recTemplate",
",",
"recInfall",
"=",
"getWrapTemplateForType",
"(",
"type",
".",
"inner",
",",
"descriptorProvider",
",",
"\"%s.Value()\"",
"%",
"result",
",",
"successCode",
",",
"returnsNewObject",
",",
"exceptionCode",
",",
"typedArraysAreStructs",
")",
"code",
"=",
"fill",
"(",
"\"\"\"\n\n if (${result}.IsNull()) {\n $*{setNull}\n }\n $*{recTemplate}\n \"\"\"",
",",
"result",
"=",
"result",
",",
"setNull",
"=",
"setNull",
"(",
")",
",",
"recTemplate",
"=",
"recTemplate",
")",
"return",
"code",
",",
"recInfall",
"if",
"type",
".",
"isSequence",
"(",
")",
":",
"# Now do non-nullable sequences. Our success code is just to break to",
"# where we set the element in the array. Note that we bump the",
"# sequenceWrapLevel around this call so that nested sequence conversions",
"# will use different iteration variables.",
"global",
"sequenceWrapLevel",
"index",
"=",
"\"sequenceIdx%d\"",
"%",
"sequenceWrapLevel",
"sequenceWrapLevel",
"+=",
"1",
"innerTemplate",
"=",
"wrapForType",
"(",
"type",
".",
"inner",
",",
"descriptorProvider",
",",
"{",
"'result'",
":",
"\"%s[%s]\"",
"%",
"(",
"result",
",",
"index",
")",
",",
"'successCode'",
":",
"\"break;\\n\"",
",",
"'jsvalRef'",
":",
"\"tmp\"",
",",
"'jsvalHandle'",
":",
"\"&tmp\"",
",",
"'returnsNewObject'",
":",
"returnsNewObject",
",",
"'exceptionCode'",
":",
"exceptionCode",
",",
"'obj'",
":",
"\"returnArray\"",
",",
"'typedArraysAreStructs'",
":",
"typedArraysAreStructs",
"}",
")",
"sequenceWrapLevel",
"-=",
"1",
"code",
"=",
"fill",
"(",
"\"\"\"\n\n uint32_t length = ${result}.Length();\n JS::Rooted<JSObject*> returnArray(cx, JS_NewArrayObject(cx, length));\n if (!returnArray) {\n $*{exceptionCode}\n }\n // Scope for 'tmp'\n {\n JS::Rooted<JS::Value> tmp(cx);\n for (uint32_t ${index} = 0; ${index} < length; ++${index}) {\n // Control block to let us common up the JS_DefineElement calls when there\n // are different ways to succeed at wrapping the object.\n do {\n $*{innerTemplate}\n } while (0);\n if (!JS_DefineElement(cx, returnArray, ${index}, tmp,\n JSPROP_ENUMERATE)) {\n $*{exceptionCode}\n }\n }\n }\n $*{set}\n \"\"\"",
",",
"result",
"=",
"result",
",",
"exceptionCode",
"=",
"exceptionCode",
",",
"index",
"=",
"index",
",",
"innerTemplate",
"=",
"innerTemplate",
",",
"set",
"=",
"setObject",
"(",
"\"*returnArray\"",
")",
")",
"return",
"(",
"code",
",",
"False",
")",
"if",
"type",
".",
"isMozMap",
"(",
")",
":",
"# Now do non-nullable MozMap. Our success code is just to break to",
"# where we define the property on the object. Note that we bump the",
"# mozMapWrapLevel around this call so that nested MozMap conversions",
"# will use different temp value names.",
"global",
"mozMapWrapLevel",
"valueName",
"=",
"\"mozMapValue%d\"",
"%",
"mozMapWrapLevel",
"mozMapWrapLevel",
"+=",
"1",
"innerTemplate",
"=",
"wrapForType",
"(",
"type",
".",
"inner",
",",
"descriptorProvider",
",",
"{",
"'result'",
":",
"valueName",
",",
"'successCode'",
":",
"\"break;\\n\"",
",",
"'jsvalRef'",
":",
"\"tmp\"",
",",
"'jsvalHandle'",
":",
"\"&tmp\"",
",",
"'returnsNewObject'",
":",
"returnsNewObject",
",",
"'exceptionCode'",
":",
"exceptionCode",
",",
"'obj'",
":",
"\"returnObj\"",
",",
"'typedArraysAreStructs'",
":",
"typedArraysAreStructs",
"}",
")",
"mozMapWrapLevel",
"-=",
"1",
"code",
"=",
"fill",
"(",
"\"\"\"\n\n nsTArray<nsString> keys;\n ${result}.GetKeys(keys);\n JS::Rooted<JSObject*> returnObj(cx, JS_NewObject(cx, nullptr, JS::NullPtr(), JS::NullPtr()));\n if (!returnObj) {\n $*{exceptionCode}\n }\n // Scope for 'tmp'\n {\n JS::Rooted<JS::Value> tmp(cx);\n for (size_t idx = 0; idx < keys.Length(); ++idx) {\n auto& ${valueName} = ${result}.Get(keys[idx]);\n // Control block to let us common up the JS_DefineUCProperty calls when there\n // are different ways to succeed at wrapping the value.\n do {\n $*{innerTemplate}\n } while (0);\n if (!JS_DefineUCProperty(cx, returnObj, keys[idx].get(),\n keys[idx].Length(), tmp,\n JSPROP_ENUMERATE)) {\n $*{exceptionCode}\n }\n }\n }\n $*{set}\n \"\"\"",
",",
"result",
"=",
"result",
",",
"exceptionCode",
"=",
"exceptionCode",
",",
"valueName",
"=",
"valueName",
",",
"innerTemplate",
"=",
"innerTemplate",
",",
"set",
"=",
"setObject",
"(",
"\"*returnObj\"",
")",
")",
"return",
"(",
"code",
",",
"False",
")",
"if",
"type",
".",
"isGeckoInterface",
"(",
")",
"and",
"not",
"type",
".",
"isCallbackInterface",
"(",
")",
":",
"descriptor",
"=",
"descriptorProvider",
".",
"getDescriptor",
"(",
"type",
".",
"unroll",
"(",
")",
".",
"inner",
".",
"identifier",
".",
"name",
")",
"if",
"type",
".",
"nullable",
"(",
")",
":",
"wrappingCode",
"=",
"(",
"\"if (!%s) {\\n\"",
"%",
"(",
"result",
")",
"+",
"indent",
"(",
"setNull",
"(",
")",
")",
"+",
"\"}\\n\"",
")",
"else",
":",
"wrappingCode",
"=",
"\"\"",
"if",
"not",
"descriptor",
".",
"interface",
".",
"isExternal",
"(",
")",
"and",
"not",
"descriptor",
".",
"skipGen",
":",
"if",
"descriptor",
".",
"wrapperCache",
":",
"assert",
"descriptor",
".",
"nativeOwnership",
"!=",
"'owned'",
"wrapMethod",
"=",
"\"WrapNewBindingObject\"",
"else",
":",
"if",
"not",
"returnsNewObject",
":",
"raise",
"MethodNotNewObjectError",
"(",
"descriptor",
".",
"interface",
".",
"identifier",
".",
"name",
")",
"if",
"descriptor",
".",
"nativeOwnership",
"==",
"'owned'",
":",
"wrapMethod",
"=",
"\"WrapNewBindingNonWrapperCachedOwnedObject\"",
"else",
":",
"wrapMethod",
"=",
"\"WrapNewBindingNonWrapperCachedObject\"",
"wrap",
"=",
"\"%s(cx, ${obj}, %s, ${jsvalHandle})\"",
"%",
"(",
"wrapMethod",
",",
"result",
")",
"if",
"not",
"descriptor",
".",
"hasXPConnectImpls",
":",
"# Can only fail to wrap as a new-binding object",
"# if they already threw an exception.",
"#XXX Assertion disabled for now, see bug 991271.",
"failed",
"=",
"(",
"\"MOZ_ASSERT(true || JS_IsExceptionPending(cx));\\n\"",
"+",
"exceptionCode",
")",
"else",
":",
"if",
"descriptor",
".",
"notflattened",
":",
"raise",
"TypeError",
"(",
"\"%s has XPConnect impls but not flattened; \"",
"\"fallback won't work correctly\"",
"%",
"descriptor",
".",
"interface",
".",
"identifier",
".",
"name",
")",
"# Try old-style wrapping for bindings which might be XPConnect impls.",
"failed",
"=",
"wrapAndSetPtr",
"(",
"\"HandleNewBindingWrappingFailure(cx, ${obj}, %s, ${jsvalHandle})\"",
"%",
"result",
")",
"else",
":",
"if",
"descriptor",
".",
"notflattened",
":",
"getIID",
"=",
"\"&NS_GET_IID(%s), \"",
"%",
"descriptor",
".",
"nativeType",
"else",
":",
"getIID",
"=",
"\"\"",
"wrap",
"=",
"\"WrapObject(cx, %s, %s${jsvalHandle})\"",
"%",
"(",
"result",
",",
"getIID",
")",
"failed",
"=",
"None",
"wrappingCode",
"+=",
"wrapAndSetPtr",
"(",
"wrap",
",",
"failed",
")",
"return",
"(",
"wrappingCode",
",",
"False",
")",
"if",
"type",
".",
"isDOMString",
"(",
")",
"or",
"type",
".",
"isScalarValueString",
"(",
")",
":",
"if",
"type",
".",
"nullable",
"(",
")",
":",
"return",
"(",
"wrapAndSetPtr",
"(",
"\"xpc::StringToJsval(cx, %s, ${jsvalHandle})\"",
"%",
"result",
")",
",",
"False",
")",
"else",
":",
"return",
"(",
"wrapAndSetPtr",
"(",
"\"xpc::NonVoidStringToJsval(cx, %s, ${jsvalHandle})\"",
"%",
"result",
")",
",",
"False",
")",
"if",
"type",
".",
"isByteString",
"(",
")",
":",
"if",
"type",
".",
"nullable",
"(",
")",
":",
"return",
"(",
"wrapAndSetPtr",
"(",
"\"ByteStringToJsval(cx, %s, ${jsvalHandle})\"",
"%",
"result",
")",
",",
"False",
")",
"else",
":",
"return",
"(",
"wrapAndSetPtr",
"(",
"\"NonVoidByteStringToJsval(cx, %s, ${jsvalHandle})\"",
"%",
"result",
")",
",",
"False",
")",
"if",
"type",
".",
"isEnum",
"(",
")",
":",
"if",
"type",
".",
"nullable",
"(",
")",
":",
"resultLoc",
"=",
"\"%s.Value()\"",
"%",
"result",
"else",
":",
"resultLoc",
"=",
"result",
"conversion",
"=",
"fill",
"(",
"\"\"\"\n {\n // Scope for resultStr\n MOZ_ASSERT(uint32_t(${result}) < ArrayLength(${strings}));\n JSString* resultStr = JS_NewStringCopyN(cx, ${strings}[uint32_t(${result})].value, ${strings}[uint32_t(${result})].length);\n if (!resultStr) {\n $*{exceptionCode}\n }\n $*{setResultStr}\n }\n \"\"\"",
",",
"result",
"=",
"resultLoc",
",",
"strings",
"=",
"(",
"type",
".",
"unroll",
"(",
")",
".",
"inner",
".",
"identifier",
".",
"name",
"+",
"\"Values::\"",
"+",
"ENUM_ENTRY_VARIABLE_NAME",
")",
",",
"exceptionCode",
"=",
"exceptionCode",
",",
"setResultStr",
"=",
"setString",
"(",
"\"resultStr\"",
")",
")",
"if",
"type",
".",
"nullable",
"(",
")",
":",
"conversion",
"=",
"CGIfElseWrapper",
"(",
"\"%s.IsNull()\"",
"%",
"result",
",",
"CGGeneric",
"(",
"setNull",
"(",
")",
")",
",",
"CGGeneric",
"(",
"conversion",
")",
")",
".",
"define",
"(",
")",
"return",
"conversion",
",",
"False",
"if",
"type",
".",
"isCallback",
"(",
")",
"or",
"type",
".",
"isCallbackInterface",
"(",
")",
":",
"wrapCode",
"=",
"setObject",
"(",
"\"*GetCallbackFromCallbackObject(%(result)s)\"",
",",
"wrapAsType",
"=",
"type",
")",
"if",
"type",
".",
"nullable",
"(",
")",
":",
"wrapCode",
"=",
"(",
"\"if (%(result)s) {\\n\"",
"+",
"indent",
"(",
"wrapCode",
")",
"+",
"\"} else {\\n\"",
"+",
"indent",
"(",
"setNull",
"(",
")",
")",
"+",
"\"}\\n\"",
")",
"wrapCode",
"=",
"wrapCode",
"%",
"{",
"\"result\"",
":",
"result",
"}",
"return",
"wrapCode",
",",
"False",
"if",
"type",
".",
"isAny",
"(",
")",
":",
"# See comments in WrapNewBindingObject explaining why we need",
"# to wrap here.",
"# NB: _setValue(..., type-that-is-any) calls JS_WrapValue(), so is fallible",
"head",
"=",
"\"JS::ExposeValueToActiveJS(%s);\\n\"",
"%",
"result",
"return",
"(",
"head",
"+",
"_setValue",
"(",
"result",
",",
"wrapAsType",
"=",
"type",
")",
",",
"False",
")",
"if",
"(",
"type",
".",
"isObject",
"(",
")",
"or",
"(",
"type",
".",
"isSpiderMonkeyInterface",
"(",
")",
"and",
"not",
"typedArraysAreStructs",
")",
")",
":",
"# See comments in WrapNewBindingObject explaining why we need",
"# to wrap here.",
"if",
"type",
".",
"nullable",
"(",
")",
":",
"toValue",
"=",
"\"%s\"",
"setter",
"=",
"setObjectOrNull",
"head",
"=",
"\"\"\"if (%s) {\n JS::ExposeObjectToActiveJS(%s);\n }\n \"\"\"",
"%",
"(",
"result",
",",
"result",
")",
"else",
":",
"toValue",
"=",
"\"*%s\"",
"setter",
"=",
"setObject",
"head",
"=",
"\"JS::ExposeObjectToActiveJS(%s);\\n\"",
"%",
"result",
"# NB: setObject{,OrNull}(..., some-object-type) calls JS_WrapValue(), so is fallible",
"return",
"(",
"head",
"+",
"setter",
"(",
"toValue",
"%",
"result",
",",
"wrapAsType",
"=",
"type",
")",
",",
"False",
")",
"if",
"not",
"(",
"type",
".",
"isUnion",
"(",
")",
"or",
"type",
".",
"isPrimitive",
"(",
")",
"or",
"type",
".",
"isDictionary",
"(",
")",
"or",
"type",
".",
"isDate",
"(",
")",
"or",
"(",
"type",
".",
"isSpiderMonkeyInterface",
"(",
")",
"and",
"typedArraysAreStructs",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Need to learn to wrap %s\"",
"%",
"type",
")",
"if",
"type",
".",
"nullable",
"(",
")",
":",
"recTemplate",
",",
"recInfal",
"=",
"getWrapTemplateForType",
"(",
"type",
".",
"inner",
",",
"descriptorProvider",
",",
"\"%s.Value()\"",
"%",
"result",
",",
"successCode",
",",
"returnsNewObject",
",",
"exceptionCode",
",",
"typedArraysAreStructs",
")",
"return",
"(",
"\"if (%s.IsNull()) {\\n\"",
"%",
"result",
"+",
"indent",
"(",
"setNull",
"(",
")",
")",
"+",
"\"}\\n\"",
"+",
"recTemplate",
",",
"recInfal",
")",
"if",
"type",
".",
"isSpiderMonkeyInterface",
"(",
")",
":",
"assert",
"typedArraysAreStructs",
"# See comments in WrapNewBindingObject explaining why we need",
"# to wrap here.",
"# NB: setObject(..., some-object-type) calls JS_WrapValue(), so is fallible",
"return",
"(",
"setObject",
"(",
"\"*%s.Obj()\"",
"%",
"result",
",",
"wrapAsType",
"=",
"type",
")",
",",
"False",
")",
"if",
"type",
".",
"isUnion",
"(",
")",
":",
"return",
"(",
"wrapAndSetPtr",
"(",
"\"%s.ToJSVal(cx, ${obj}, ${jsvalHandle})\"",
"%",
"result",
")",
",",
"False",
")",
"if",
"type",
".",
"isDictionary",
"(",
")",
":",
"return",
"(",
"wrapAndSetPtr",
"(",
"\"%s.ToObjectInternal(cx, ${jsvalHandle})\"",
"%",
"result",
")",
",",
"False",
")",
"if",
"type",
".",
"isDate",
"(",
")",
":",
"return",
"(",
"wrapAndSetPtr",
"(",
"\"%s.ToDateObject(cx, ${jsvalHandle})\"",
"%",
"result",
")",
",",
"False",
")",
"tag",
"=",
"type",
".",
"tag",
"(",
")",
"if",
"tag",
"in",
"[",
"IDLType",
".",
"Tags",
".",
"int8",
",",
"IDLType",
".",
"Tags",
".",
"uint8",
",",
"IDLType",
".",
"Tags",
".",
"int16",
",",
"IDLType",
".",
"Tags",
".",
"uint16",
",",
"IDLType",
".",
"Tags",
".",
"int32",
"]",
":",
"return",
"(",
"setInt32",
"(",
"\"int32_t(%s)\"",
"%",
"result",
")",
",",
"True",
")",
"elif",
"tag",
"in",
"[",
"IDLType",
".",
"Tags",
".",
"int64",
",",
"IDLType",
".",
"Tags",
".",
"uint64",
",",
"IDLType",
".",
"Tags",
".",
"unrestricted_float",
",",
"IDLType",
".",
"Tags",
".",
"float",
",",
"IDLType",
".",
"Tags",
".",
"unrestricted_double",
",",
"IDLType",
".",
"Tags",
".",
"double",
"]",
":",
"# XXXbz will cast to double do the \"even significand\" thing that webidl",
"# calls for for 64-bit ints? Do we care?",
"return",
"(",
"setDouble",
"(",
"\"double(%s)\"",
"%",
"result",
")",
",",
"True",
")",
"elif",
"tag",
"==",
"IDLType",
".",
"Tags",
".",
"uint32",
":",
"return",
"(",
"setUint32",
"(",
"result",
")",
",",
"True",
")",
"elif",
"tag",
"==",
"IDLType",
".",
"Tags",
".",
"bool",
":",
"return",
"(",
"setBoolean",
"(",
"result",
")",
",",
"True",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Need to learn to wrap primitive: %s\"",
"%",
"type",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/Codegen.py#L5395-L5810 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | snapx/snapx/classes/graph.py | python | Graph._edge_iter | (self) | return _TNEANetEdgeIter(self._graph.Edges(), directed=False) | Returns a SNAP edge iterator. | Returns a SNAP edge iterator. | [
"Returns",
"a",
"SNAP",
"edge",
"iterator",
"."
] | def _edge_iter(self):
"""Returns a SNAP edge iterator."""
return _TNEANetEdgeIter(self._graph.Edges(), directed=False) | [
"def",
"_edge_iter",
"(",
"self",
")",
":",
"return",
"_TNEANetEdgeIter",
"(",
"self",
".",
"_graph",
".",
"Edges",
"(",
")",
",",
"directed",
"=",
"False",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/snapx/snapx/classes/graph.py#L1360-L1362 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py | python | convert_matmul_selfatt_qk | (node, **kwargs) | return nodes | Map MXNet's _contrib_interleaved_matmul_selfatt_qk operator | Map MXNet's _contrib_interleaved_matmul_selfatt_qk operator | [
"Map",
"MXNet",
"s",
"_contrib_interleaved_matmul_selfatt_qk",
"operator"
] | def convert_matmul_selfatt_qk(node, **kwargs):
"""Map MXNet's _contrib_interleaved_matmul_selfatt_qk operator
"""
from onnx.helper import make_node
from onnx import TensorProto
name, input_nodes, attrs = get_inputs(node, kwargs)
heads = int(attrs.get('heads'))
# a, b, c, d, e are seq_len, batch_size, num_heads, 3, head_dim respectively
create_tensor([0], name+"_0", kwargs["initializer"])
create_tensor([1], name+"_1", kwargs["initializer"])
create_tensor([1], name+"_1_f", kwargs["initializer"], dtype='float32')
create_tensor([2], name+"_2", kwargs["initializer"])
create_tensor([3], name+"_3", kwargs["initializer"])
create_tensor([heads], name+"_c", kwargs["initializer"])
create_tensor([3], name+"_d", kwargs["initializer"])
nodes = [
make_node('Shape', [input_nodes[0]], [name+"_data_shape"]),
make_node('Slice', [name+'_data_shape', name+'_0', name+'_1'], [name+"_a"]),
make_node('Slice', [name+'_data_shape', name+'_1', name+'_2'], [name+"_b"]),
make_node('Slice', [name+'_data_shape', name+'_2', name+'_3'], [name+"_cde"]),
make_node('Div', [name+'_cde', name+'_c'], [name+'_de']),
make_node('Div', [name+'_de', name+'_d'], [name+'_e']),
make_node('Cast', [name+'_e'], [name+'_e_f'], to=int(TensorProto.FLOAT)),
make_node('Sqrt', [name+'_e_f'], [name+'_sqrt_e']),
make_node('Div', [name+'_1_f', name+'_sqrt_e'], [name+'_1_over_sqrt_e']),
make_node('Mul', [name+'_b', name+'_c'], [name+'_bc']),
make_node("Concat", [name+'_a', name+'_b', name+'_c', name+'_d', name+'_e'], \
[name+'_shape0'], axis=0),
make_node("Concat", [name+'_0', name+'_0', name+'_0', name+'_0', name+'_0'], \
[name+'_slice_start0'], axis=0),
make_node("Concat", [name+'_a', name+'_b', name+'_c', name+'_1', name+'_e'], \
[name+'_slice_end0'], axis=0),
make_node("Concat", [name+'_a', name+'_b', name+'_c', name+'_e'], \
[name+'_shape1'], axis=0),
make_node("Concat", [name+'_bc', name+'_a', name+'_e'], \
[name+'_shape2'], axis=0),
make_node("Concat", [name+'_0', name+'_0', name+'_0', name+'_1', name+'_0'], \
[name+'_slice_start1'], axis=0),
make_node("Concat", [name+'_a', name+'_b', name+'_c', name+'_2', name+'_e'], \
[name+'_slice_end1'], axis=0),
make_node('Reshape', [input_nodes[0], name+'_shape0'], [name+'_reshape0_out']),
make_node('Slice', [name+'_reshape0_out', name+'_slice_start0', name+'_slice_end0'], \
[name+'_slice0_out']),
make_node('Reshape', [name+'_slice0_out', name+'_shape1'], [name+'_reshape1_out']),
make_node('Transpose', [name+'_reshape1_out'], [name+'_transpose0_out'], \
perm=(1, 2, 0, 3)),
make_node('Reshape', [name+'_transpose0_out', name+'_shape2'], [name+'_reshape2_out']),
make_node('Mul', [name+'_reshape2_out', name+'_1_over_sqrt_e'], [name+'_mul0_out']),
make_node('Slice', [name+'_reshape0_out', name+'_slice_start1', name+'_slice_end1'], \
[name+'_slice1_out']),
make_node('Reshape', [name+'_slice1_out', name+'_shape1'], [name+'_reshape3_out']),
make_node('Transpose', [name+'_reshape3_out'], [name+'_transpose1_out'], \
perm=(1, 2, 0, 3)),
make_node('Reshape', [name+'_transpose1_out', name+'_shape2'], [name+'_reshape4_out']),
make_node('Transpose', [name+'_reshape4_out'], [name+'_transpose2_out'], \
perm=(0, 2, 1)),
make_node('MatMul', [name+'_mul0_out', name+'_transpose2_out'], [name], name=name)
]
return nodes | [
"def",
"convert_matmul_selfatt_qk",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"onnx",
".",
"helper",
"import",
"make_node",
"from",
"onnx",
"import",
"TensorProto",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"heads",
"=",
"int",
"(",
"attrs",
".",
"get",
"(",
"'heads'",
")",
")",
"# a, b, c, d, e are seq_len, batch_size, num_heads, 3, head_dim respectively",
"create_tensor",
"(",
"[",
"0",
"]",
",",
"name",
"+",
"\"_0\"",
",",
"kwargs",
"[",
"\"initializer\"",
"]",
")",
"create_tensor",
"(",
"[",
"1",
"]",
",",
"name",
"+",
"\"_1\"",
",",
"kwargs",
"[",
"\"initializer\"",
"]",
")",
"create_tensor",
"(",
"[",
"1",
"]",
",",
"name",
"+",
"\"_1_f\"",
",",
"kwargs",
"[",
"\"initializer\"",
"]",
",",
"dtype",
"=",
"'float32'",
")",
"create_tensor",
"(",
"[",
"2",
"]",
",",
"name",
"+",
"\"_2\"",
",",
"kwargs",
"[",
"\"initializer\"",
"]",
")",
"create_tensor",
"(",
"[",
"3",
"]",
",",
"name",
"+",
"\"_3\"",
",",
"kwargs",
"[",
"\"initializer\"",
"]",
")",
"create_tensor",
"(",
"[",
"heads",
"]",
",",
"name",
"+",
"\"_c\"",
",",
"kwargs",
"[",
"\"initializer\"",
"]",
")",
"create_tensor",
"(",
"[",
"3",
"]",
",",
"name",
"+",
"\"_d\"",
",",
"kwargs",
"[",
"\"initializer\"",
"]",
")",
"nodes",
"=",
"[",
"make_node",
"(",
"'Shape'",
",",
"[",
"input_nodes",
"[",
"0",
"]",
"]",
",",
"[",
"name",
"+",
"\"_data_shape\"",
"]",
")",
",",
"make_node",
"(",
"'Slice'",
",",
"[",
"name",
"+",
"'_data_shape'",
",",
"name",
"+",
"'_0'",
",",
"name",
"+",
"'_1'",
"]",
",",
"[",
"name",
"+",
"\"_a\"",
"]",
")",
",",
"make_node",
"(",
"'Slice'",
",",
"[",
"name",
"+",
"'_data_shape'",
",",
"name",
"+",
"'_1'",
",",
"name",
"+",
"'_2'",
"]",
",",
"[",
"name",
"+",
"\"_b\"",
"]",
")",
",",
"make_node",
"(",
"'Slice'",
",",
"[",
"name",
"+",
"'_data_shape'",
",",
"name",
"+",
"'_2'",
",",
"name",
"+",
"'_3'",
"]",
",",
"[",
"name",
"+",
"\"_cde\"",
"]",
")",
",",
"make_node",
"(",
"'Div'",
",",
"[",
"name",
"+",
"'_cde'",
",",
"name",
"+",
"'_c'",
"]",
",",
"[",
"name",
"+",
"'_de'",
"]",
")",
",",
"make_node",
"(",
"'Div'",
",",
"[",
"name",
"+",
"'_de'",
",",
"name",
"+",
"'_d'",
"]",
",",
"[",
"name",
"+",
"'_e'",
"]",
")",
",",
"make_node",
"(",
"'Cast'",
",",
"[",
"name",
"+",
"'_e'",
"]",
",",
"[",
"name",
"+",
"'_e_f'",
"]",
",",
"to",
"=",
"int",
"(",
"TensorProto",
".",
"FLOAT",
")",
")",
",",
"make_node",
"(",
"'Sqrt'",
",",
"[",
"name",
"+",
"'_e_f'",
"]",
",",
"[",
"name",
"+",
"'_sqrt_e'",
"]",
")",
",",
"make_node",
"(",
"'Div'",
",",
"[",
"name",
"+",
"'_1_f'",
",",
"name",
"+",
"'_sqrt_e'",
"]",
",",
"[",
"name",
"+",
"'_1_over_sqrt_e'",
"]",
")",
",",
"make_node",
"(",
"'Mul'",
",",
"[",
"name",
"+",
"'_b'",
",",
"name",
"+",
"'_c'",
"]",
",",
"[",
"name",
"+",
"'_bc'",
"]",
")",
",",
"make_node",
"(",
"\"Concat\"",
",",
"[",
"name",
"+",
"'_a'",
",",
"name",
"+",
"'_b'",
",",
"name",
"+",
"'_c'",
",",
"name",
"+",
"'_d'",
",",
"name",
"+",
"'_e'",
"]",
",",
"[",
"name",
"+",
"'_shape0'",
"]",
",",
"axis",
"=",
"0",
")",
",",
"make_node",
"(",
"\"Concat\"",
",",
"[",
"name",
"+",
"'_0'",
",",
"name",
"+",
"'_0'",
",",
"name",
"+",
"'_0'",
",",
"name",
"+",
"'_0'",
",",
"name",
"+",
"'_0'",
"]",
",",
"[",
"name",
"+",
"'_slice_start0'",
"]",
",",
"axis",
"=",
"0",
")",
",",
"make_node",
"(",
"\"Concat\"",
",",
"[",
"name",
"+",
"'_a'",
",",
"name",
"+",
"'_b'",
",",
"name",
"+",
"'_c'",
",",
"name",
"+",
"'_1'",
",",
"name",
"+",
"'_e'",
"]",
",",
"[",
"name",
"+",
"'_slice_end0'",
"]",
",",
"axis",
"=",
"0",
")",
",",
"make_node",
"(",
"\"Concat\"",
",",
"[",
"name",
"+",
"'_a'",
",",
"name",
"+",
"'_b'",
",",
"name",
"+",
"'_c'",
",",
"name",
"+",
"'_e'",
"]",
",",
"[",
"name",
"+",
"'_shape1'",
"]",
",",
"axis",
"=",
"0",
")",
",",
"make_node",
"(",
"\"Concat\"",
",",
"[",
"name",
"+",
"'_bc'",
",",
"name",
"+",
"'_a'",
",",
"name",
"+",
"'_e'",
"]",
",",
"[",
"name",
"+",
"'_shape2'",
"]",
",",
"axis",
"=",
"0",
")",
",",
"make_node",
"(",
"\"Concat\"",
",",
"[",
"name",
"+",
"'_0'",
",",
"name",
"+",
"'_0'",
",",
"name",
"+",
"'_0'",
",",
"name",
"+",
"'_1'",
",",
"name",
"+",
"'_0'",
"]",
",",
"[",
"name",
"+",
"'_slice_start1'",
"]",
",",
"axis",
"=",
"0",
")",
",",
"make_node",
"(",
"\"Concat\"",
",",
"[",
"name",
"+",
"'_a'",
",",
"name",
"+",
"'_b'",
",",
"name",
"+",
"'_c'",
",",
"name",
"+",
"'_2'",
",",
"name",
"+",
"'_e'",
"]",
",",
"[",
"name",
"+",
"'_slice_end1'",
"]",
",",
"axis",
"=",
"0",
")",
",",
"make_node",
"(",
"'Reshape'",
",",
"[",
"input_nodes",
"[",
"0",
"]",
",",
"name",
"+",
"'_shape0'",
"]",
",",
"[",
"name",
"+",
"'_reshape0_out'",
"]",
")",
",",
"make_node",
"(",
"'Slice'",
",",
"[",
"name",
"+",
"'_reshape0_out'",
",",
"name",
"+",
"'_slice_start0'",
",",
"name",
"+",
"'_slice_end0'",
"]",
",",
"[",
"name",
"+",
"'_slice0_out'",
"]",
")",
",",
"make_node",
"(",
"'Reshape'",
",",
"[",
"name",
"+",
"'_slice0_out'",
",",
"name",
"+",
"'_shape1'",
"]",
",",
"[",
"name",
"+",
"'_reshape1_out'",
"]",
")",
",",
"make_node",
"(",
"'Transpose'",
",",
"[",
"name",
"+",
"'_reshape1_out'",
"]",
",",
"[",
"name",
"+",
"'_transpose0_out'",
"]",
",",
"perm",
"=",
"(",
"1",
",",
"2",
",",
"0",
",",
"3",
")",
")",
",",
"make_node",
"(",
"'Reshape'",
",",
"[",
"name",
"+",
"'_transpose0_out'",
",",
"name",
"+",
"'_shape2'",
"]",
",",
"[",
"name",
"+",
"'_reshape2_out'",
"]",
")",
",",
"make_node",
"(",
"'Mul'",
",",
"[",
"name",
"+",
"'_reshape2_out'",
",",
"name",
"+",
"'_1_over_sqrt_e'",
"]",
",",
"[",
"name",
"+",
"'_mul0_out'",
"]",
")",
",",
"make_node",
"(",
"'Slice'",
",",
"[",
"name",
"+",
"'_reshape0_out'",
",",
"name",
"+",
"'_slice_start1'",
",",
"name",
"+",
"'_slice_end1'",
"]",
",",
"[",
"name",
"+",
"'_slice1_out'",
"]",
")",
",",
"make_node",
"(",
"'Reshape'",
",",
"[",
"name",
"+",
"'_slice1_out'",
",",
"name",
"+",
"'_shape1'",
"]",
",",
"[",
"name",
"+",
"'_reshape3_out'",
"]",
")",
",",
"make_node",
"(",
"'Transpose'",
",",
"[",
"name",
"+",
"'_reshape3_out'",
"]",
",",
"[",
"name",
"+",
"'_transpose1_out'",
"]",
",",
"perm",
"=",
"(",
"1",
",",
"2",
",",
"0",
",",
"3",
")",
")",
",",
"make_node",
"(",
"'Reshape'",
",",
"[",
"name",
"+",
"'_transpose1_out'",
",",
"name",
"+",
"'_shape2'",
"]",
",",
"[",
"name",
"+",
"'_reshape4_out'",
"]",
")",
",",
"make_node",
"(",
"'Transpose'",
",",
"[",
"name",
"+",
"'_reshape4_out'",
"]",
",",
"[",
"name",
"+",
"'_transpose2_out'",
"]",
",",
"perm",
"=",
"(",
"0",
",",
"2",
",",
"1",
")",
")",
",",
"make_node",
"(",
"'MatMul'",
",",
"[",
"name",
"+",
"'_mul0_out'",
",",
"name",
"+",
"'_transpose2_out'",
"]",
",",
"[",
"name",
"]",
",",
"name",
"=",
"name",
")",
"]",
"return",
"nodes"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py#L2940-L3003 | |
chromiumembedded/cef | 80caf947f3fe2210e5344713c5281d8af9bdc295 | tools/combine_libs.py | python | CombineLibraries | (output, remove_re, inputs) | Combines all the libraries and objects in inputs, while removing any
object files that match remove_re. | Combines all the libraries and objects in inputs, while removing any
object files that match remove_re. | [
"Combines",
"all",
"the",
"libraries",
"and",
"objects",
"in",
"inputs",
"while",
"removing",
"any",
"object",
"files",
"that",
"match",
"remove_re",
"."
] | def CombineLibraries(output, remove_re, inputs):
'''Combines all the libraries and objects in inputs, while removing any
object files that match remove_re.
'''
removals = []
if remove_re:
removals = CollectRemovals(remove_re, inputs)
if len(removals) > 0:
print('Removals: ', removals)
args = ['lib.exe', '/out:%s' % output]
args += ['/remove:%s' % obj for obj in removals]
args += inputs
Shell(*args) | [
"def",
"CombineLibraries",
"(",
"output",
",",
"remove_re",
",",
"inputs",
")",
":",
"removals",
"=",
"[",
"]",
"if",
"remove_re",
":",
"removals",
"=",
"CollectRemovals",
"(",
"remove_re",
",",
"inputs",
")",
"if",
"len",
"(",
"removals",
")",
">",
"0",
":",
"print",
"(",
"'Removals: '",
",",
"removals",
")",
"args",
"=",
"[",
"'lib.exe'",
",",
"'/out:%s'",
"%",
"output",
"]",
"args",
"+=",
"[",
"'/remove:%s'",
"%",
"obj",
"for",
"obj",
"in",
"removals",
"]",
"args",
"+=",
"inputs",
"Shell",
"(",
"*",
"args",
")"
] | https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/combine_libs.py#L47-L61 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/_exceptions.py | python | SAXParseException.getLineNumber | (self) | return self._linenum | The line number of the end of the text where the exception occurred. | The line number of the end of the text where the exception occurred. | [
"The",
"line",
"number",
"of",
"the",
"end",
"of",
"the",
"text",
"where",
"the",
"exception",
"occurred",
"."
] | def getLineNumber(self):
"The line number of the end of the text where the exception occurred."
return self._linenum | [
"def",
"getLineNumber",
"(",
"self",
")",
":",
"return",
"self",
".",
"_linenum"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/_exceptions.py#L77-L79 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/decorators.py | python | jit_module | (**kwargs) | Automatically ``jit``-wraps functions defined in a Python module
Note that ``jit_module`` should only be called at the end of the module to
be jitted. In addition, only functions which are defined in the module
``jit_module`` is called from are considered for automatic jit-wrapping.
See the Numba documentation for more information about what can/cannot be
jitted.
:param kwargs: Keyword arguments to pass to ``jit`` such as ``nopython``
or ``error_model``. | Automatically ``jit``-wraps functions defined in a Python module | [
"Automatically",
"jit",
"-",
"wraps",
"functions",
"defined",
"in",
"a",
"Python",
"module"
] | def jit_module(**kwargs):
""" Automatically ``jit``-wraps functions defined in a Python module
Note that ``jit_module`` should only be called at the end of the module to
be jitted. In addition, only functions which are defined in the module
``jit_module`` is called from are considered for automatic jit-wrapping.
See the Numba documentation for more information about what can/cannot be
jitted.
:param kwargs: Keyword arguments to pass to ``jit`` such as ``nopython``
or ``error_model``.
"""
# Get the module jit_module is being called from
frame = inspect.stack()[1]
module = inspect.getmodule(frame[0])
# Replace functions in module with jit-wrapped versions
for name, obj in module.__dict__.items():
if inspect.isfunction(obj) and inspect.getmodule(obj) == module:
_logger.debug("Auto decorating function {} from module {} with jit "
"and options: {}".format(obj, module.__name__, kwargs))
module.__dict__[name] = jit(obj, **kwargs) | [
"def",
"jit_module",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Get the module jit_module is being called from",
"frame",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"1",
"]",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
"frame",
"[",
"0",
"]",
")",
"# Replace functions in module with jit-wrapped versions",
"for",
"name",
",",
"obj",
"in",
"module",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
"and",
"inspect",
".",
"getmodule",
"(",
"obj",
")",
"==",
"module",
":",
"_logger",
".",
"debug",
"(",
"\"Auto decorating function {} from module {} with jit \"",
"\"and options: {}\"",
".",
"format",
"(",
"obj",
",",
"module",
".",
"__name__",
",",
"kwargs",
")",
")",
"module",
".",
"__dict__",
"[",
"name",
"]",
"=",
"jit",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/decorators.py#L265-L286 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Tux/NavigationIndicatorGui.py | python | onMenu | (action) | Set navigation style on selection. | Set navigation style on selection. | [
"Set",
"navigation",
"style",
"on",
"selection",
"."
] | def onMenu(action):
"""Set navigation style on selection."""
s = False
if action and action.data() != "Undefined":
s = True
setCompact(action)
menu.setDefaultAction(action)
indicator.setIcon(action.icon())
indicator.setToolTip(action.toolTip())
pView.SetString("NavigationStyle", action.data())
else:
pass
if s:
a0.setVisible(False)
else:
a0.setVisible(True)
a0.setEnabled(True)
setCompact(a0)
menu.setDefaultAction(a0)
indicator.setIcon(a0.icon())
indicator.setToolTip(a0.toolTip()) | [
"def",
"onMenu",
"(",
"action",
")",
":",
"s",
"=",
"False",
"if",
"action",
"and",
"action",
".",
"data",
"(",
")",
"!=",
"\"Undefined\"",
":",
"s",
"=",
"True",
"setCompact",
"(",
"action",
")",
"menu",
".",
"setDefaultAction",
"(",
"action",
")",
"indicator",
".",
"setIcon",
"(",
"action",
".",
"icon",
"(",
")",
")",
"indicator",
".",
"setToolTip",
"(",
"action",
".",
"toolTip",
"(",
")",
")",
"pView",
".",
"SetString",
"(",
"\"NavigationStyle\"",
",",
"action",
".",
"data",
"(",
")",
")",
"else",
":",
"pass",
"if",
"s",
":",
"a0",
".",
"setVisible",
"(",
"False",
")",
"else",
":",
"a0",
".",
"setVisible",
"(",
"True",
")",
"a0",
".",
"setEnabled",
"(",
"True",
")",
"setCompact",
"(",
"a0",
")",
"menu",
".",
"setDefaultAction",
"(",
"a0",
")",
"indicator",
".",
"setIcon",
"(",
"a0",
".",
"icon",
"(",
")",
")",
"indicator",
".",
"setToolTip",
"(",
"a0",
".",
"toolTip",
"(",
")",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Tux/NavigationIndicatorGui.py#L517-L540 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/tracemalloc.py | python | take_snapshot | () | return Snapshot(traces, traceback_limit) | Take a snapshot of traces of memory blocks allocated by Python. | Take a snapshot of traces of memory blocks allocated by Python. | [
"Take",
"a",
"snapshot",
"of",
"traces",
"of",
"memory",
"blocks",
"allocated",
"by",
"Python",
"."
] | def take_snapshot():
"""
Take a snapshot of traces of memory blocks allocated by Python.
"""
if not is_tracing():
raise RuntimeError("the tracemalloc module must be tracing memory "
"allocations to take a snapshot")
traces = _get_traces()
traceback_limit = get_traceback_limit()
return Snapshot(traces, traceback_limit) | [
"def",
"take_snapshot",
"(",
")",
":",
"if",
"not",
"is_tracing",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"the tracemalloc module must be tracing memory \"",
"\"allocations to take a snapshot\"",
")",
"traces",
"=",
"_get_traces",
"(",
")",
"traceback_limit",
"=",
"get_traceback_limit",
"(",
")",
"return",
"Snapshot",
"(",
"traces",
",",
"traceback_limit",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/tracemalloc.py#L551-L560 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.HomeWrapExtend | (*args, **kwargs) | return _stc.StyledTextCtrl_HomeWrapExtend(*args, **kwargs) | HomeWrapExtend(self) | HomeWrapExtend(self) | [
"HomeWrapExtend",
"(",
"self",
")"
] | def HomeWrapExtend(*args, **kwargs):
"""HomeWrapExtend(self)"""
return _stc.StyledTextCtrl_HomeWrapExtend(*args, **kwargs) | [
"def",
"HomeWrapExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_HomeWrapExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L4755-L4757 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/special/_precompute/gammainc_data.py | python | gammaincc | (a, x, dps=50, maxterms=10**8) | Compute gammaincc exactly like mpmath does but allow for more
terms in hypercomb. See
mpmath/functions/expintegrals.py#L187
in the mpmath github repository. | Compute gammaincc exactly like mpmath does but allow for more
terms in hypercomb. See | [
"Compute",
"gammaincc",
"exactly",
"like",
"mpmath",
"does",
"but",
"allow",
"for",
"more",
"terms",
"in",
"hypercomb",
".",
"See"
] | def gammaincc(a, x, dps=50, maxterms=10**8):
"""Compute gammaincc exactly like mpmath does but allow for more
terms in hypercomb. See
mpmath/functions/expintegrals.py#L187
in the mpmath github repository.
"""
with mp.workdps(dps):
z, a = a, x
if mp.isint(z):
try:
# mpmath has a fast integer path
return mpf2float(mp.gammainc(z, a=a, regularized=True))
except mp.libmp.NoConvergence:
pass
nega = mp.fneg(a, exact=True)
G = [z]
# Use 2F0 series when possible; fall back to lower gamma representation
try:
def h(z):
r = z-1
return [([mp.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)]
return mpf2float(mp.hypercomb(h, [z], force_series=True))
except mp.libmp.NoConvergence:
def h(z):
T1 = [], [1, z-1], [z], G, [], [], 0
T2 = [-mp.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a
return T1, T2
return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms)) | [
"def",
"gammaincc",
"(",
"a",
",",
"x",
",",
"dps",
"=",
"50",
",",
"maxterms",
"=",
"10",
"**",
"8",
")",
":",
"with",
"mp",
".",
"workdps",
"(",
"dps",
")",
":",
"z",
",",
"a",
"=",
"a",
",",
"x",
"if",
"mp",
".",
"isint",
"(",
"z",
")",
":",
"try",
":",
"# mpmath has a fast integer path",
"return",
"mpf2float",
"(",
"mp",
".",
"gammainc",
"(",
"z",
",",
"a",
"=",
"a",
",",
"regularized",
"=",
"True",
")",
")",
"except",
"mp",
".",
"libmp",
".",
"NoConvergence",
":",
"pass",
"nega",
"=",
"mp",
".",
"fneg",
"(",
"a",
",",
"exact",
"=",
"True",
")",
"G",
"=",
"[",
"z",
"]",
"# Use 2F0 series when possible; fall back to lower gamma representation",
"try",
":",
"def",
"h",
"(",
"z",
")",
":",
"r",
"=",
"z",
"-",
"1",
"return",
"[",
"(",
"[",
"mp",
".",
"exp",
"(",
"nega",
")",
",",
"a",
"]",
",",
"[",
"1",
",",
"r",
"]",
",",
"[",
"]",
",",
"G",
",",
"[",
"1",
",",
"-",
"r",
"]",
",",
"[",
"]",
",",
"1",
"/",
"nega",
")",
"]",
"return",
"mpf2float",
"(",
"mp",
".",
"hypercomb",
"(",
"h",
",",
"[",
"z",
"]",
",",
"force_series",
"=",
"True",
")",
")",
"except",
"mp",
".",
"libmp",
".",
"NoConvergence",
":",
"def",
"h",
"(",
"z",
")",
":",
"T1",
"=",
"[",
"]",
",",
"[",
"1",
",",
"z",
"-",
"1",
"]",
",",
"[",
"z",
"]",
",",
"G",
",",
"[",
"]",
",",
"[",
"]",
",",
"0",
"T2",
"=",
"[",
"-",
"mp",
".",
"exp",
"(",
"nega",
")",
",",
"a",
",",
"z",
"]",
",",
"[",
"1",
",",
"z",
",",
"-",
"1",
"]",
",",
"[",
"]",
",",
"G",
",",
"[",
"1",
"]",
",",
"[",
"1",
"+",
"z",
"]",
",",
"a",
"return",
"T1",
",",
"T2",
"return",
"mpf2float",
"(",
"mp",
".",
"hypercomb",
"(",
"h",
",",
"[",
"z",
"]",
",",
"maxterms",
"=",
"maxterms",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/special/_precompute/gammainc_data.py#L57-L88 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | PrintDialog.GetPrintData | (*args, **kwargs) | return _windows_.PrintDialog_GetPrintData(*args, **kwargs) | GetPrintData(self) -> PrintData | GetPrintData(self) -> PrintData | [
"GetPrintData",
"(",
"self",
")",
"-",
">",
"PrintData"
] | def GetPrintData(*args, **kwargs):
"""GetPrintData(self) -> PrintData"""
return _windows_.PrintDialog_GetPrintData(*args, **kwargs) | [
"def",
"GetPrintData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PrintDialog_GetPrintData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L5189-L5191 | |
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/generators/ChannelHeader.py | python | ChannelHeader.getObj | (self) | return self.__obj | Return the object to the visitor. | Return the object to the visitor. | [
"Return",
"the",
"object",
"to",
"the",
"visitor",
"."
] | def getObj(self):
"""
Return the object to the visitor.
"""
return self.__obj | [
"def",
"getObj",
"(",
"self",
")",
":",
"return",
"self",
".",
"__obj"
] | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/ChannelHeader.py#L101-L105 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/template.py | python | Template.__init__ | (self, name, func, create_scope_now=False, unique_name=None) | Creates a template for the given function.
Args:
name: A name for the scope created by this template. The
name will be made unique by appending `_N` to the it (see how
`tf.variable_scope` treats the `default_name` for details).
func: The function to apply each time.
create_scope_now: Whether to create the scope at Template construction
time, rather than first call. Defaults to false. Creating the scope at
construction time may be more convenient if the template is to passed
through much lower level code, and you want to be sure of the scope
name without knowing exactly where it will be first called. If set to
True, the scope will be created in the constructor, and all subsequent
times in __call__, leading to a trailing numeral being added to the
names of all created Tensors. If set to False, the scope will be created
at the first call location.
unique_name: When used, it overrides name_ and is not made unique. If a
template of the same scope/unique_name already exists and reuse is
false, an error is raised. Defaults to None.
Raises:
ValueError: if the name is None. | Creates a template for the given function. | [
"Creates",
"a",
"template",
"for",
"the",
"given",
"function",
"."
] | def __init__(self, name, func, create_scope_now=False, unique_name=None):
"""Creates a template for the given function.
Args:
name: A name for the scope created by this template. The
name will be made unique by appending `_N` to the it (see how
`tf.variable_scope` treats the `default_name` for details).
func: The function to apply each time.
create_scope_now: Whether to create the scope at Template construction
time, rather than first call. Defaults to false. Creating the scope at
construction time may be more convenient if the template is to passed
through much lower level code, and you want to be sure of the scope
name without knowing exactly where it will be first called. If set to
True, the scope will be created in the constructor, and all subsequent
times in __call__, leading to a trailing numeral being added to the
names of all created Tensors. If set to False, the scope will be created
at the first call location.
unique_name: When used, it overrides name_ and is not made unique. If a
template of the same scope/unique_name already exists and reuse is
false, an error is raised. Defaults to None.
Raises:
ValueError: if the name is None.
"""
self._func = func
self._stacktrace = traceback.format_stack()[:-2]
self._name = name
self._unique_name = unique_name
if name is None:
raise ValueError("name cannot be None.")
if create_scope_now:
with variable_scope.variable_scope(
self._unique_name, self._name) as vs:
self._var_scope = vs
else:
self._var_scope = None
# This variable keeps track of whether the template has been called yet,
# which is not the same as whether the scope has been created.
self._variables_created = False | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"func",
",",
"create_scope_now",
"=",
"False",
",",
"unique_name",
"=",
"None",
")",
":",
"self",
".",
"_func",
"=",
"func",
"self",
".",
"_stacktrace",
"=",
"traceback",
".",
"format_stack",
"(",
")",
"[",
":",
"-",
"2",
"]",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_unique_name",
"=",
"unique_name",
"if",
"name",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"name cannot be None.\"",
")",
"if",
"create_scope_now",
":",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"self",
".",
"_unique_name",
",",
"self",
".",
"_name",
")",
"as",
"vs",
":",
"self",
".",
"_var_scope",
"=",
"vs",
"else",
":",
"self",
".",
"_var_scope",
"=",
"None",
"# This variable keeps track of whether the template has been called yet,",
"# which is not the same as whether the scope has been created.",
"self",
".",
"_variables_created",
"=",
"False"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/template.py#L162-L200 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/lookup_ops.py | python | KeyValueTensorInitializer.__init__ | (self, keys, values, key_dtype=None, value_dtype=None, name=None) | Constructs a table initializer object based on keys and values tensors.
Args:
keys: The tensor for the keys.
values: The tensor for the values.
key_dtype: The `keys` data type. Used when `keys` is a python array.
value_dtype: The `values` data type. Used when `values` is a python array.
name: A name for the operation (optional). | Constructs a table initializer object based on keys and values tensors. | [
"Constructs",
"a",
"table",
"initializer",
"object",
"based",
"on",
"keys",
"and",
"values",
"tensors",
"."
] | def __init__(self, keys, values, key_dtype=None, value_dtype=None, name=None):
"""Constructs a table initializer object based on keys and values tensors.
Args:
keys: The tensor for the keys.
values: The tensor for the values.
key_dtype: The `keys` data type. Used when `keys` is a python array.
value_dtype: The `values` data type. Used when `values` is a python array.
name: A name for the operation (optional).
"""
with ops.name_scope(name, "key_value_init", [keys, values]) as scope:
self._keys = ops.convert_to_tensor(keys, dtype=key_dtype, name="keys")
self._values = ops.convert_to_tensor(
values, dtype=value_dtype, name="values")
self._name = scope
super(KeyValueTensorInitializer, self).__init__(self._keys.dtype,
self._values.dtype) | [
"def",
"__init__",
"(",
"self",
",",
"keys",
",",
"values",
",",
"key_dtype",
"=",
"None",
",",
"value_dtype",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"key_value_init\"",
",",
"[",
"keys",
",",
"values",
"]",
")",
"as",
"scope",
":",
"self",
".",
"_keys",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"keys",
",",
"dtype",
"=",
"key_dtype",
",",
"name",
"=",
"\"keys\"",
")",
"self",
".",
"_values",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"values",
",",
"dtype",
"=",
"value_dtype",
",",
"name",
"=",
"\"values\"",
")",
"self",
".",
"_name",
"=",
"scope",
"super",
"(",
"KeyValueTensorInitializer",
",",
"self",
")",
".",
"__init__",
"(",
"self",
".",
"_keys",
".",
"dtype",
",",
"self",
".",
"_values",
".",
"dtype",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/lookup_ops.py#L310-L327 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/stringold.py | python | find | (s, *args) | return _apply(s.find, args) | find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure. | find(s, sub [,start [,end]]) -> in | [
"find",
"(",
"s",
"sub",
"[",
"start",
"[",
"end",
"]]",
")",
"-",
">",
"in"
] | def find(s, *args):
"""find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return _apply(s.find, args) | [
"def",
"find",
"(",
"s",
",",
"*",
"args",
")",
":",
"return",
"_apply",
"(",
"s",
".",
"find",
",",
"args",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/stringold.py#L165-L175 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/ttk.py | python | Treeview.delete | (self, *items) | Delete all specified items and all their descendants. The root
item may not be deleted. | Delete all specified items and all their descendants. The root
item may not be deleted. | [
"Delete",
"all",
"specified",
"items",
"and",
"all",
"their",
"descendants",
".",
"The",
"root",
"item",
"may",
"not",
"be",
"deleted",
"."
] | def delete(self, *items):
"""Delete all specified items and all their descendants. The root
item may not be deleted."""
self.tk.call(self._w, "delete", items) | [
"def",
"delete",
"(",
"self",
",",
"*",
"items",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"\"delete\"",
",",
"items",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/ttk.py#L1250-L1253 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/re.py | python | escape | (pattern) | Escape special characters in a string. | Escape special characters in a string. | [
"Escape",
"special",
"characters",
"in",
"a",
"string",
"."
] | def escape(pattern):
"""
Escape special characters in a string.
"""
if isinstance(pattern, str):
return pattern.translate(_special_chars_map)
else:
pattern = str(pattern, 'latin1')
return pattern.translate(_special_chars_map).encode('latin1') | [
"def",
"escape",
"(",
"pattern",
")",
":",
"if",
"isinstance",
"(",
"pattern",
",",
"str",
")",
":",
"return",
"pattern",
".",
"translate",
"(",
"_special_chars_map",
")",
"else",
":",
"pattern",
"=",
"str",
"(",
"pattern",
",",
"'latin1'",
")",
"return",
"pattern",
".",
"translate",
"(",
"_special_chars_map",
")",
".",
"encode",
"(",
"'latin1'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/re.py#L254-L262 | ||
FEniCS/dolfinx | 3dfdf038cccdb70962865b58a63bf29c2e55ec6e | utils/pylit/pylit.py | python | execute | (infile="-", txt2code=True, **keyw) | Execute the input file. Convert first, if it is a text source. | Execute the input file. Convert first, if it is a text source. | [
"Execute",
"the",
"input",
"file",
".",
"Convert",
"first",
"if",
"it",
"is",
"a",
"text",
"source",
"."
] | def execute(infile="-", txt2code=True, **keyw):
"""Execute the input file. Convert first, if it is a text source.
"""
data = open(infile)
if txt2code:
data = str(Text2Code(data, **keyw))
# print("executing " + options.infile)
exec(data) | [
"def",
"execute",
"(",
"infile",
"=",
"\"-\"",
",",
"txt2code",
"=",
"True",
",",
"*",
"*",
"keyw",
")",
":",
"data",
"=",
"open",
"(",
"infile",
")",
"if",
"txt2code",
":",
"data",
"=",
"str",
"(",
"Text2Code",
"(",
"data",
",",
"*",
"*",
"keyw",
")",
")",
"# print(\"executing \" + options.infile)",
"exec",
"(",
"data",
")"
] | https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/utils/pylit/pylit.py#L1670-L1678 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.