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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | demo/BERT/helpers/tokenization.py | python | BertTokenizer.convert_ids_to_tokens | (self, ids) | return tokens | Converts a sequence of ids in wordpiece tokens using the vocab. | Converts a sequence of ids in wordpiece tokens using the vocab. | [
"Converts",
"a",
"sequence",
"of",
"ids",
"in",
"wordpiece",
"tokens",
"using",
"the",
"vocab",
"."
] | def convert_ids_to_tokens(self, ids):
"""Converts a sequence of ids in wordpiece tokens using the vocab."""
tokens = []
for i in ids:
tokens.append(self.ids_to_tokens[i])
return tokens | [
"def",
"convert_ids_to_tokens",
"(",
"self",
",",
"ids",
")",
":",
"tokens",
"=",
"[",
"]",
"for",
"i",
"in",
"ids",
":",
"tokens",
".",
"append",
"(",
"self",
".",
"ids_to_tokens",
"[",
"i",
"]",
")",
"return",
"tokens"
] | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/demo/BERT/helpers/tokenization.py#L208-L213 | |
adventuregamestudio/ags | efa89736d868e9dfda4200149d33ba8637746399 | Common/libsrc/freetype-2.1.3/src/tools/docmaker/tohtml.py | python | HtmlFormatter.make_html_words | ( self, words ) | return line | convert a series of simple words into some HTML text | convert a series of simple words into some HTML text | [
"convert",
"a",
"series",
"of",
"simple",
"words",
"into",
"some",
"HTML",
"text"
] | def make_html_words( self, words ):
""" convert a series of simple words into some HTML text """
line = ""
if words:
line = html_quote( words[0] )
for w in words[1:]:
line = line + " " + html_quote( w )
return line | [
"def",
"make_html_words",
"(",
"self",
",",
"words",
")",
":",
"line",
"=",
"\"\"",
"if",
"words",
":",
"line",
"=",
"html_quote",
"(",
"words",
"[",
"0",
"]",
")",
"for",
"w",
"in",
"words",
"[",
"1",
":",
"]",
":",
"line",
"=",
"line",
"+",
"\" \"",
"+",
"html_quote",
"(",
"w",
")",
"return",
"line"
] | https://github.com/adventuregamestudio/ags/blob/efa89736d868e9dfda4200149d33ba8637746399/Common/libsrc/freetype-2.1.3/src/tools/docmaker/tohtml.py#L156-L164 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/incubate/fleet/parameter_server/ir/trainer_pass.py | python | _get_output_map_from_op | (varmap, op) | return iomap | Returns a dict from op output name to the vars in varmap. | Returns a dict from op output name to the vars in varmap. | [
"Returns",
"a",
"dict",
"from",
"op",
"output",
"name",
"to",
"the",
"vars",
"in",
"varmap",
"."
] | def _get_output_map_from_op(varmap, op):
"""Returns a dict from op output name to the vars in varmap."""
iomap = collections.OrderedDict()
for key in op.output_names:
vars = []
for varname in op.output(key):
if varname == "@EMPTY@":
continue
if "lod_tensor_blocking_queue" in varname:
continue
vars.append(varmap[varname])
if len(vars) == 1:
iomap[key] = vars[0]
else:
iomap[key] = vars
return iomap | [
"def",
"_get_output_map_from_op",
"(",
"varmap",
",",
"op",
")",
":",
"iomap",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"key",
"in",
"op",
".",
"output_names",
":",
"vars",
"=",
"[",
"]",
"for",
"varname",
"in",
"op",
".",
"output",
"(",
"key",
")",
":",
"if",
"varname",
"==",
"\"@EMPTY@\"",
":",
"continue",
"if",
"\"lod_tensor_blocking_queue\"",
"in",
"varname",
":",
"continue",
"vars",
".",
"append",
"(",
"varmap",
"[",
"varname",
"]",
")",
"if",
"len",
"(",
"vars",
")",
"==",
"1",
":",
"iomap",
"[",
"key",
"]",
"=",
"vars",
"[",
"0",
"]",
"else",
":",
"iomap",
"[",
"key",
"]",
"=",
"vars",
"return",
"iomap"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/parameter_server/ir/trainer_pass.py#L1941-L1956 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | DatePickerCtrlBase.GetUpperLimit | (*args, **kwargs) | return _controls_.DatePickerCtrlBase_GetUpperLimit(*args, **kwargs) | GetUpperLimit(self) -> DateTime
Get the upper limit of the valid range for the date selection, if any.
If there is no range or there is no upper limit, then the
`wx.DateTime` value returned will be invalid. | GetUpperLimit(self) -> DateTime | [
"GetUpperLimit",
"(",
"self",
")",
"-",
">",
"DateTime"
] | def GetUpperLimit(*args, **kwargs):
"""
GetUpperLimit(self) -> DateTime
Get the upper limit of the valid range for the date selection, if any.
If there is no range or there is no upper limit, then the
`wx.DateTime` value returned will be invalid.
"""
return _controls_.DatePickerCtrlBase_GetUpperLimit(*args, **kwargs) | [
"def",
"GetUpperLimit",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"DatePickerCtrlBase_GetUpperLimit",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L6486-L6494 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.GetCaretLineVisible | (*args, **kwargs) | return _stc.StyledTextCtrl_GetCaretLineVisible(*args, **kwargs) | GetCaretLineVisible(self) -> bool
Is the background of the line containing the caret in a different colour? | GetCaretLineVisible(self) -> bool | [
"GetCaretLineVisible",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetCaretLineVisible(*args, **kwargs):
"""
GetCaretLineVisible(self) -> bool
Is the background of the line containing the caret in a different colour?
"""
return _stc.StyledTextCtrl_GetCaretLineVisible(*args, **kwargs) | [
"def",
"GetCaretLineVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetCaretLineVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L2987-L2993 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/client/timeline.py | python | _ChromeTraceFormatter.emit_counters | (self, category, name, pid, timestamp, counters) | Emits a counter record for the dictionary 'counters'.
Args:
category: The event category as a string.
name: The event name as a string.
pid: Identifier of the process generating this event as an integer.
timestamp: The timestamp of this event as a long integer.
counters: Dictionary of counter values. | Emits a counter record for the dictionary 'counters'. | [
"Emits",
"a",
"counter",
"record",
"for",
"the",
"dictionary",
"counters",
"."
] | def emit_counters(self, category, name, pid, timestamp, counters):
"""Emits a counter record for the dictionary 'counters'.
Args:
category: The event category as a string.
name: The event name as a string.
pid: Identifier of the process generating this event as an integer.
timestamp: The timestamp of this event as a long integer.
counters: Dictionary of counter values.
"""
event = self._create_event('C', category, name, pid, 0, timestamp)
event['args'] = counters.copy()
self._events.append(event) | [
"def",
"emit_counters",
"(",
"self",
",",
"category",
",",
"name",
",",
"pid",
",",
"timestamp",
",",
"counters",
")",
":",
"event",
"=",
"self",
".",
"_create_event",
"(",
"'C'",
",",
"category",
",",
"name",
",",
"pid",
",",
"0",
",",
"timestamp",
")",
"event",
"[",
"'args'",
"]",
"=",
"counters",
".",
"copy",
"(",
")",
"self",
".",
"_events",
".",
"append",
"(",
"event",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/client/timeline.py#L231-L243 | ||
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/MSVSSettings.py | python | _MovedAndRenamed | (tool, msvs_settings_name, msbuild_tool_name,
msbuild_settings_name, setting_type) | Defines a setting that may have moved to a new section.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
msvs_settings_name: the MSVS name of the setting.
msbuild_tool_name: the name of the MSBuild tool to place the setting under.
msbuild_settings_name: the MSBuild name of the setting.
setting_type: the type of this setting. | Defines a setting that may have moved to a new section. | [
"Defines",
"a",
"setting",
"that",
"may",
"have",
"moved",
"to",
"a",
"new",
"section",
"."
] | def _MovedAndRenamed(tool, msvs_settings_name, msbuild_tool_name,
msbuild_settings_name, setting_type):
"""Defines a setting that may have moved to a new section.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
msvs_settings_name: the MSVS name of the setting.
msbuild_tool_name: the name of the MSBuild tool to place the setting under.
msbuild_settings_name: the MSBuild name of the setting.
setting_type: the type of this setting.
"""
def _Translate(value, msbuild_settings):
tool_settings = msbuild_settings.setdefault(msbuild_tool_name, {})
tool_settings[msbuild_settings_name] = setting_type.ConvertToMSBuild(value)
_msvs_validators[tool.msvs_name][msvs_settings_name] = (
setting_type.ValidateMSVS)
validator = setting_type.ValidateMSBuild
_msbuild_validators[msbuild_tool_name][msbuild_settings_name] = validator
_msvs_to_msbuild_converters[tool.msvs_name][msvs_settings_name] = _Translate | [
"def",
"_MovedAndRenamed",
"(",
"tool",
",",
"msvs_settings_name",
",",
"msbuild_tool_name",
",",
"msbuild_settings_name",
",",
"setting_type",
")",
":",
"def",
"_Translate",
"(",
"value",
",",
"msbuild_settings",
")",
":",
"tool_settings",
"=",
"msbuild_settings",
".",
"setdefault",
"(",
"msbuild_tool_name",
",",
"{",
"}",
")",
"tool_settings",
"[",
"msbuild_settings_name",
"]",
"=",
"setting_type",
".",
"ConvertToMSBuild",
"(",
"value",
")",
"_msvs_validators",
"[",
"tool",
".",
"msvs_name",
"]",
"[",
"msvs_settings_name",
"]",
"=",
"(",
"setting_type",
".",
"ValidateMSVS",
")",
"validator",
"=",
"setting_type",
".",
"ValidateMSBuild",
"_msbuild_validators",
"[",
"msbuild_tool_name",
"]",
"[",
"msbuild_settings_name",
"]",
"=",
"validator",
"_msvs_to_msbuild_converters",
"[",
"tool",
".",
"msvs_name",
"]",
"[",
"msvs_settings_name",
"]",
"=",
"_Translate"
] | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/MSVSSettings.py#L269-L289 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.DocLineFromVisible | (*args, **kwargs) | return _stc.StyledTextCtrl_DocLineFromVisible(*args, **kwargs) | DocLineFromVisible(self, int lineDisplay) -> int
Find the document line of a display line taking hidden lines into account. | DocLineFromVisible(self, int lineDisplay) -> int | [
"DocLineFromVisible",
"(",
"self",
"int",
"lineDisplay",
")",
"-",
">",
"int"
] | def DocLineFromVisible(*args, **kwargs):
"""
DocLineFromVisible(self, int lineDisplay) -> int
Find the document line of a display line taking hidden lines into account.
"""
return _stc.StyledTextCtrl_DocLineFromVisible(*args, **kwargs) | [
"def",
"DocLineFromVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_DocLineFromVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3880-L3886 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/base.py | python | c2pyerror | (err_msg) | return out_msg, err_type | Translate C API error message to python style.
Parameters
----------
err_msg : str
The error message.
Returns
-------
new_msg : str
Translated message.
err_type : str
Detected error type. | Translate C API error message to python style. | [
"Translate",
"C",
"API",
"error",
"message",
"to",
"python",
"style",
"."
] | def c2pyerror(err_msg):
"""Translate C API error message to python style.
Parameters
----------
err_msg : str
The error message.
Returns
-------
new_msg : str
Translated message.
err_type : str
Detected error type.
"""
arr = err_msg.split("\n")
if arr[-1] == "":
arr.pop()
err_type = _find_error_type(arr[0])
trace_mode = False
stack_trace = []
message = []
for line in arr:
if trace_mode:
if line.startswith(" "):
stack_trace.append(line)
else:
trace_mode = False
if not trace_mode:
if line.startswith("Stack trace"):
trace_mode = True
else:
message.append(line)
out_msg = ""
if stack_trace:
out_msg += "Traceback (most recent call last):\n"
out_msg += "\n".join(reversed(stack_trace)) + "\n"
out_msg += "\n".join(message)
return out_msg, err_type | [
"def",
"c2pyerror",
"(",
"err_msg",
")",
":",
"arr",
"=",
"err_msg",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"arr",
"[",
"-",
"1",
"]",
"==",
"\"\"",
":",
"arr",
".",
"pop",
"(",
")",
"err_type",
"=",
"_find_error_type",
"(",
"arr",
"[",
"0",
"]",
")",
"trace_mode",
"=",
"False",
"stack_trace",
"=",
"[",
"]",
"message",
"=",
"[",
"]",
"for",
"line",
"in",
"arr",
":",
"if",
"trace_mode",
":",
"if",
"line",
".",
"startswith",
"(",
"\" \"",
")",
":",
"stack_trace",
".",
"append",
"(",
"line",
")",
"else",
":",
"trace_mode",
"=",
"False",
"if",
"not",
"trace_mode",
":",
"if",
"line",
".",
"startswith",
"(",
"\"Stack trace\"",
")",
":",
"trace_mode",
"=",
"True",
"else",
":",
"message",
".",
"append",
"(",
"line",
")",
"out_msg",
"=",
"\"\"",
"if",
"stack_trace",
":",
"out_msg",
"+=",
"\"Traceback (most recent call last):\\n\"",
"out_msg",
"+=",
"\"\\n\"",
".",
"join",
"(",
"reversed",
"(",
"stack_trace",
")",
")",
"+",
"\"\\n\"",
"out_msg",
"+=",
"\"\\n\"",
".",
"join",
"(",
"message",
")",
"return",
"out_msg",
",",
"err_type"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/base.py#L166-L205 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/bayesflow/python/ops/stochastic_gradient_estimators.py | python | get_score_function_with_advantage | (advantage_fn=None,
name="ScoreFunctionWithAdvantage") | return score_function_with_advantage | Score function estimator with advantage function.
Args:
advantage_fn: callable that takes the `StochasticTensor` and the
downstream `loss` and returns a `Tensor` advantage
(e.g. `loss - baseline`).
name: name to prepend ops with.
Returns:
Callable score function estimator that takes the `StochasticTensor`, the
sampled `value`, and the downstream `loss`, and uses the provided advantage. | Score function estimator with advantage function. | [
"Score",
"function",
"estimator",
"with",
"advantage",
"function",
"."
] | def get_score_function_with_advantage(advantage_fn=None,
name="ScoreFunctionWithAdvantage"):
"""Score function estimator with advantage function.
Args:
advantage_fn: callable that takes the `StochasticTensor` and the
downstream `loss` and returns a `Tensor` advantage
(e.g. `loss - baseline`).
name: name to prepend ops with.
Returns:
Callable score function estimator that takes the `StochasticTensor`, the
sampled `value`, and the downstream `loss`, and uses the provided advantage.
"""
def score_function_with_advantage(stochastic_tensor, value, loss):
with ops.name_scope(name, values=[value, loss]):
advantage = advantage_fn(stochastic_tensor, loss)
advantage = array_ops.stop_gradient(advantage)
return stochastic_tensor.distribution.log_prob(value) * advantage
return score_function_with_advantage | [
"def",
"get_score_function_with_advantage",
"(",
"advantage_fn",
"=",
"None",
",",
"name",
"=",
"\"ScoreFunctionWithAdvantage\"",
")",
":",
"def",
"score_function_with_advantage",
"(",
"stochastic_tensor",
",",
"value",
",",
"loss",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"values",
"=",
"[",
"value",
",",
"loss",
"]",
")",
":",
"advantage",
"=",
"advantage_fn",
"(",
"stochastic_tensor",
",",
"loss",
")",
"advantage",
"=",
"array_ops",
".",
"stop_gradient",
"(",
"advantage",
")",
"return",
"stochastic_tensor",
".",
"distribution",
".",
"log_prob",
"(",
"value",
")",
"*",
"advantage",
"return",
"score_function_with_advantage"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/bayesflow/python/ops/stochastic_gradient_estimators.py#L102-L123 | |
p4lang/PI | 38d87e81253feff9fff0660d662c885be78fb719 | proto/ptf/ptf_runner.py | python | run_test | (config_path, p4info_path, grpc_addr, device_id,
ptfdir, port_map_path, extra_args=[]) | return p.returncode == 0 | Runs PTF tests included in provided directory.
Device must be running and configfured with appropriate P4 program. | Runs PTF tests included in provided directory.
Device must be running and configfured with appropriate P4 program. | [
"Runs",
"PTF",
"tests",
"included",
"in",
"provided",
"directory",
".",
"Device",
"must",
"be",
"running",
"and",
"configfured",
"with",
"appropriate",
"P4",
"program",
"."
] | def run_test(config_path, p4info_path, grpc_addr, device_id,
ptfdir, port_map_path, extra_args=[]):
'''
Runs PTF tests included in provided directory.
Device must be running and configfured with appropriate P4 program.
'''
# TODO: check schema?
# "p4_port" is ignored for now, we assume that ports are provided by
# increasing values of p4_port, in the range [0, NUM_IFACES[.
port_map = OrderedDict()
with open(port_map_path, 'r') as port_map_f:
port_list = json.load(port_map_f)
for entry in port_list:
ptf_port = entry["ptf_port"]
p4_port = entry["p4_port"] # ignored
iface_name = entry["iface_name"]
port_map[p4_port] = iface_name
if not check_ifaces(port_map.values()):
error("Some interfaces are missing")
return False
ifaces = []
# FIXME
# find base_test.py
pypath = os.path.dirname(os.path.abspath(__file__))
if 'PYTHONPATH' in os.environ:
os.environ['PYTHONPATH'] += ":" + pypath
else:
os.environ['PYTHONPATH'] = pypath
for iface_idx, iface_name in port_map.items():
ifaces.extend(['-i', '{}@{}'.format(iface_idx, iface_name)])
cmd = ['ptf']
cmd.extend(['--test-dir', ptfdir])
cmd.extend(ifaces)
test_params = 'p4info=\'{}\''.format(p4info_path)
test_params += ';grpcaddr=\'{}\''.format(grpc_addr)
cmd.append('--test-params={}'.format(test_params))
cmd.extend(extra_args)
info("Executing PTF command: {}".format(' '.join(cmd)))
try:
# we want the ptf output to be sent to stdout
p = subprocess.Popen(cmd)
p.wait()
except:
error("Error when running PTF tests")
return False
return p.returncode == 0 | [
"def",
"run_test",
"(",
"config_path",
",",
"p4info_path",
",",
"grpc_addr",
",",
"device_id",
",",
"ptfdir",
",",
"port_map_path",
",",
"extra_args",
"=",
"[",
"]",
")",
":",
"# TODO: check schema?",
"# \"p4_port\" is ignored for now, we assume that ports are provided by",
"# increasing values of p4_port, in the range [0, NUM_IFACES[.",
"port_map",
"=",
"OrderedDict",
"(",
")",
"with",
"open",
"(",
"port_map_path",
",",
"'r'",
")",
"as",
"port_map_f",
":",
"port_list",
"=",
"json",
".",
"load",
"(",
"port_map_f",
")",
"for",
"entry",
"in",
"port_list",
":",
"ptf_port",
"=",
"entry",
"[",
"\"ptf_port\"",
"]",
"p4_port",
"=",
"entry",
"[",
"\"p4_port\"",
"]",
"# ignored",
"iface_name",
"=",
"entry",
"[",
"\"iface_name\"",
"]",
"port_map",
"[",
"p4_port",
"]",
"=",
"iface_name",
"if",
"not",
"check_ifaces",
"(",
"port_map",
".",
"values",
"(",
")",
")",
":",
"error",
"(",
"\"Some interfaces are missing\"",
")",
"return",
"False",
"ifaces",
"=",
"[",
"]",
"# FIXME",
"# find base_test.py",
"pypath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"if",
"'PYTHONPATH'",
"in",
"os",
".",
"environ",
":",
"os",
".",
"environ",
"[",
"'PYTHONPATH'",
"]",
"+=",
"\":\"",
"+",
"pypath",
"else",
":",
"os",
".",
"environ",
"[",
"'PYTHONPATH'",
"]",
"=",
"pypath",
"for",
"iface_idx",
",",
"iface_name",
"in",
"port_map",
".",
"items",
"(",
")",
":",
"ifaces",
".",
"extend",
"(",
"[",
"'-i'",
",",
"'{}@{}'",
".",
"format",
"(",
"iface_idx",
",",
"iface_name",
")",
"]",
")",
"cmd",
"=",
"[",
"'ptf'",
"]",
"cmd",
".",
"extend",
"(",
"[",
"'--test-dir'",
",",
"ptfdir",
"]",
")",
"cmd",
".",
"extend",
"(",
"ifaces",
")",
"test_params",
"=",
"'p4info=\\'{}\\''",
".",
"format",
"(",
"p4info_path",
")",
"test_params",
"+=",
"';grpcaddr=\\'{}\\''",
".",
"format",
"(",
"grpc_addr",
")",
"cmd",
".",
"append",
"(",
"'--test-params={}'",
".",
"format",
"(",
"test_params",
")",
")",
"cmd",
".",
"extend",
"(",
"extra_args",
")",
"info",
"(",
"\"Executing PTF command: {}\"",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
")",
"try",
":",
"# we want the ptf output to be sent to stdout",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
")",
"p",
".",
"wait",
"(",
")",
"except",
":",
"error",
"(",
"\"Error when running PTF tests\"",
")",
"return",
"False",
"return",
"p",
".",
"returncode",
"==",
"0"
] | https://github.com/p4lang/PI/blob/38d87e81253feff9fff0660d662c885be78fb719/proto/ptf/ptf_runner.py#L90-L138 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/platform/benchmark.py | python | TensorFlowBenchmark.run_op_benchmark | (self,
sess,
op_or_tensor,
feed_dict=None,
burn_iters=2,
min_iters=10,
store_trace=False,
name=None,
extras=None) | return benchmark_values | Run an op or tensor in the given session. Report the results.
Args:
sess: `Session` object to use for timing.
op_or_tensor: `Operation` or `Tensor` to benchmark.
feed_dict: A `dict` of values to feed for each op iteration (see the
`feed_dict` parameter of `Session.run`).
burn_iters: Number of burn-in iterations to run.
min_iters: Minimum number of iterations to use for timing.
store_trace: Boolean, whether to run an extra untimed iteration and
store the trace of iteration in the benchmark report.
The trace will be stored as a string in Google Chrome trace format
in the extras field "full_trace_chrome_format".
name: (optional) Override the BenchmarkEntry name with `name`.
Otherwise it is inferred from the top-level method name.
extras: (optional) Dict mapping string keys to additional benchmark info.
Values may be either floats or values that are convertible to strings.
Returns:
A `dict` containing the key-value pairs that were passed to
`report_benchmark`. | Run an op or tensor in the given session. Report the results. | [
"Run",
"an",
"op",
"or",
"tensor",
"in",
"the",
"given",
"session",
".",
"Report",
"the",
"results",
"."
] | def run_op_benchmark(self,
sess,
op_or_tensor,
feed_dict=None,
burn_iters=2,
min_iters=10,
store_trace=False,
name=None,
extras=None):
"""Run an op or tensor in the given session. Report the results.
Args:
sess: `Session` object to use for timing.
op_or_tensor: `Operation` or `Tensor` to benchmark.
feed_dict: A `dict` of values to feed for each op iteration (see the
`feed_dict` parameter of `Session.run`).
burn_iters: Number of burn-in iterations to run.
min_iters: Minimum number of iterations to use for timing.
store_trace: Boolean, whether to run an extra untimed iteration and
store the trace of iteration in the benchmark report.
The trace will be stored as a string in Google Chrome trace format
in the extras field "full_trace_chrome_format".
name: (optional) Override the BenchmarkEntry name with `name`.
Otherwise it is inferred from the top-level method name.
extras: (optional) Dict mapping string keys to additional benchmark info.
Values may be either floats or values that are convertible to strings.
Returns:
A `dict` containing the key-value pairs that were passed to
`report_benchmark`.
"""
for _ in range(burn_iters):
sess.run(op_or_tensor, feed_dict=feed_dict)
deltas = [None] * min_iters
for i in range(min_iters):
start_time = time.time()
sess.run(op_or_tensor, feed_dict=feed_dict)
end_time = time.time()
delta = end_time - start_time
deltas[i] = delta
extras = extras if extras is not None else {}
if store_trace:
run_options = config_pb2.RunOptions(
trace_level=config_pb2.RunOptions.FULL_TRACE)
run_metadata = config_pb2.RunMetadata()
sess.run(op_or_tensor, feed_dict=feed_dict,
options=run_options, run_metadata=run_metadata)
tl = timeline.Timeline(run_metadata.step_stats)
extras["full_trace_chrome_format"] = tl.generate_chrome_trace_format()
def _median(x):
if not x:
return -1
s = sorted(x)
l = len(x)
lm1 = l - 1
return (s[l//2] + s[lm1//2]) / 2.0
median_delta = _median(deltas)
benchmark_values = {"iters": min_iters,
"wall_time": median_delta,
"extras": extras,
"name": name}
self.report_benchmark(**benchmark_values)
return benchmark_values | [
"def",
"run_op_benchmark",
"(",
"self",
",",
"sess",
",",
"op_or_tensor",
",",
"feed_dict",
"=",
"None",
",",
"burn_iters",
"=",
"2",
",",
"min_iters",
"=",
"10",
",",
"store_trace",
"=",
"False",
",",
"name",
"=",
"None",
",",
"extras",
"=",
"None",
")",
":",
"for",
"_",
"in",
"range",
"(",
"burn_iters",
")",
":",
"sess",
".",
"run",
"(",
"op_or_tensor",
",",
"feed_dict",
"=",
"feed_dict",
")",
"deltas",
"=",
"[",
"None",
"]",
"*",
"min_iters",
"for",
"i",
"in",
"range",
"(",
"min_iters",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"sess",
".",
"run",
"(",
"op_or_tensor",
",",
"feed_dict",
"=",
"feed_dict",
")",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"delta",
"=",
"end_time",
"-",
"start_time",
"deltas",
"[",
"i",
"]",
"=",
"delta",
"extras",
"=",
"extras",
"if",
"extras",
"is",
"not",
"None",
"else",
"{",
"}",
"if",
"store_trace",
":",
"run_options",
"=",
"config_pb2",
".",
"RunOptions",
"(",
"trace_level",
"=",
"config_pb2",
".",
"RunOptions",
".",
"FULL_TRACE",
")",
"run_metadata",
"=",
"config_pb2",
".",
"RunMetadata",
"(",
")",
"sess",
".",
"run",
"(",
"op_or_tensor",
",",
"feed_dict",
"=",
"feed_dict",
",",
"options",
"=",
"run_options",
",",
"run_metadata",
"=",
"run_metadata",
")",
"tl",
"=",
"timeline",
".",
"Timeline",
"(",
"run_metadata",
".",
"step_stats",
")",
"extras",
"[",
"\"full_trace_chrome_format\"",
"]",
"=",
"tl",
".",
"generate_chrome_trace_format",
"(",
")",
"def",
"_median",
"(",
"x",
")",
":",
"if",
"not",
"x",
":",
"return",
"-",
"1",
"s",
"=",
"sorted",
"(",
"x",
")",
"l",
"=",
"len",
"(",
"x",
")",
"lm1",
"=",
"l",
"-",
"1",
"return",
"(",
"s",
"[",
"l",
"//",
"2",
"]",
"+",
"s",
"[",
"lm1",
"//",
"2",
"]",
")",
"/",
"2.0",
"median_delta",
"=",
"_median",
"(",
"deltas",
")",
"benchmark_values",
"=",
"{",
"\"iters\"",
":",
"min_iters",
",",
"\"wall_time\"",
":",
"median_delta",
",",
"\"extras\"",
":",
"extras",
",",
"\"name\"",
":",
"name",
"}",
"self",
".",
"report_benchmark",
"(",
"*",
"*",
"benchmark_values",
")",
"return",
"benchmark_values"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/platform/benchmark.py#L196-L264 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/copy.py | python | _keep_alive | (x, memo) | Keeps a reference to the object x in the memo.
Because we remember objects by their id, we have
to assure that possibly temporary objects are kept
alive by referencing them.
We store a reference at the id of the memo, which should
normally not be used unless someone tries to deepcopy
the memo itself... | Keeps a reference to the object x in the memo. | [
"Keeps",
"a",
"reference",
"to",
"the",
"object",
"x",
"in",
"the",
"memo",
"."
] | def _keep_alive(x, memo):
"""Keeps a reference to the object x in the memo.
Because we remember objects by their id, we have
to assure that possibly temporary objects are kept
alive by referencing them.
We store a reference at the id of the memo, which should
normally not be used unless someone tries to deepcopy
the memo itself...
"""
try:
memo[id(memo)].append(x)
except KeyError:
# aha, this is the first one :-)
memo[id(memo)]=[x] | [
"def",
"_keep_alive",
"(",
"x",
",",
"memo",
")",
":",
"try",
":",
"memo",
"[",
"id",
"(",
"memo",
")",
"]",
".",
"append",
"(",
"x",
")",
"except",
"KeyError",
":",
"# aha, this is the first one :-)",
"memo",
"[",
"id",
"(",
"memo",
")",
"]",
"=",
"[",
"x",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/copy.py#L267-L281 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | dom/bindings/parser/WebIDL.py | python | Parser.p_TypeSuffixBrackets | (self, p) | TypeSuffix : LBRACKET RBRACKET TypeSuffix | TypeSuffix : LBRACKET RBRACKET TypeSuffix | [
"TypeSuffix",
":",
"LBRACKET",
"RBRACKET",
"TypeSuffix"
] | def p_TypeSuffixBrackets(self, p):
"""
TypeSuffix : LBRACKET RBRACKET TypeSuffix
"""
p[0] = [(IDLMethod.TypeSuffixModifier.Brackets, self.getLocation(p, 1))]
p[0].extend(p[3]) | [
"def",
"p_TypeSuffixBrackets",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"(",
"IDLMethod",
".",
"TypeSuffixModifier",
".",
"Brackets",
",",
"self",
".",
"getLocation",
"(",
"p",
",",
"1",
")",
")",
"]",
"p",
"[",
"0",
"]",
".",
"extend",
"(",
"p",
"[",
"3",
"]",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/parser/WebIDL.py#L5421-L5426 | ||
thunil/tempoGAN | a9b92181e28a82c2029049791f875a6c1341d62b | tensorflow/tools/fluiddataloader.py | python | FluidDataLoader.collectFilenamesFromDir | (self, list_index) | Build filename list from single dir
list_index: number in index list (or alternatively label list) | Build filename list from single dir
list_index: number in index list (or alternatively label list) | [
"Build",
"filename",
"list",
"from",
"single",
"dir",
"list_index",
":",
"number",
"in",
"index",
"list",
"(",
"or",
"alternatively",
"label",
"list",
")"
] | def collectFilenamesFromDir(self, list_index):
""" Build filename list from single dir
list_index: number in index list (or alternatively label list)
"""
sim_index = self.indices[list_index] # get simulation directory index from list
labelstr = "" # debug info only
foundCnt = 0
if self.wildcard is not None:
search_dir = os.path.join( self.base_path, (self.simdirname % sim_index) )
os.chdir(search_dir)
allFiles = [f for f in glob.glob("*") if os.path.isfile(f)] # list all files
files = []
for f in allFiles:
match = re.search(self.wildcard, f) # note, matched again below...
if match:
files.append(f)
if len(files)<1:
raise FluidDataLoaderError("Error - no files found in directory '%s' with wildcard '%s' " %(search_dir, self.wildcard) )
files = sorted(files) # sort by name
n = max(1, int(len(files)*self.data_fraction))
tf = float(len(files))/n # spread over time range (eg 200 frames)
fcnt = 0
for t in range(0,n):
filelist_index = int(t*tf) # full range
fn = files[filelist_index]
self.xfn.append(os.path.join(search_dir, fn))
foundCnt += 1
# construct label, closely follows index version below
if self.filename_y is not None:
mx = re.search(self.wildcard, fn)
listy = self.filename_y.split("$")
if(len(listy)!=2):
raise FluidDataLoaderError("Error - when using a wildcard for x, filename_y needs to contain exactly one '$' where the file id string from x will be inserted to build the filename for y. Current, invalid, filename_y is '%s' " %(self.filename_y) )
fny = listy[0] + mx.group(1) + listy[1]
if not os.path.isfile(fny): # make sure file for y exists
raise FluidDataLoaderError("Error - y file '%s' for x file '%s' doesnt exist in search dir '%s' " %(fny, fn, search_dir ) )
fny = os.path.join(search_dir, fny)
self.yfn.append(fny)
self.have_y_npz = True # flag to indicate we have np arrays in y
if self.array_y is not None:
if self.y is None:
self.y = []
self.y.append( self.array_y[list_index] )
labelstr = " with label " + format( self.array_y[list_index] )
if self.func_y is not None:
print("NYI! test...")
else:
# "simple" index range
n = max(1, int((self.filename_index_max-self.filename_index_min)*self.data_fraction))
tf = float(self.filename_index_max-self.filename_index_min)/n
for t in range(0,n):
filelist_index = int(self.filename_index_min + t*tf) # full range
fn = self.getFilename(sim_index, self.filename, filelist_index)
self.xfn.append(fn)
foundCnt += 1
if self.filename_y is not None:
fny = self.getFilename(sim_index, self.filename_y, filelist_index)
self.yfn.append(fny)
self.have_y_npz = True # flag to indicate we have np arrays in y
if self.array_y is not None:
if self.y is None:
self.y = []
self.y.append( self.array_y[list_index] )
labelstr = " with label " + format( self.array_y[list_index] )
if self.func_y is not None:
print("NYI! test...")
if self.y is None:
self.y = []
self.y.append( self.func_y(list_index, sim_index, t, fn) )
if self.print_info:
print("Found " +format(foundCnt) +" files from sim ID "+format(sim_index) + labelstr ) | [
"def",
"collectFilenamesFromDir",
"(",
"self",
",",
"list_index",
")",
":",
"sim_index",
"=",
"self",
".",
"indices",
"[",
"list_index",
"]",
"# get simulation directory index from list",
"labelstr",
"=",
"\"\"",
"# debug info only",
"foundCnt",
"=",
"0",
"if",
"self",
".",
"wildcard",
"is",
"not",
"None",
":",
"search_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"base_path",
",",
"(",
"self",
".",
"simdirname",
"%",
"sim_index",
")",
")",
"os",
".",
"chdir",
"(",
"search_dir",
")",
"allFiles",
"=",
"[",
"f",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"\"*\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"f",
")",
"]",
"# list all files",
"files",
"=",
"[",
"]",
"for",
"f",
"in",
"allFiles",
":",
"match",
"=",
"re",
".",
"search",
"(",
"self",
".",
"wildcard",
",",
"f",
")",
"# note, matched again below...",
"if",
"match",
":",
"files",
".",
"append",
"(",
"f",
")",
"if",
"len",
"(",
"files",
")",
"<",
"1",
":",
"raise",
"FluidDataLoaderError",
"(",
"\"Error - no files found in directory '%s' with wildcard '%s' \"",
"%",
"(",
"search_dir",
",",
"self",
".",
"wildcard",
")",
")",
"files",
"=",
"sorted",
"(",
"files",
")",
"# sort by name",
"n",
"=",
"max",
"(",
"1",
",",
"int",
"(",
"len",
"(",
"files",
")",
"*",
"self",
".",
"data_fraction",
")",
")",
"tf",
"=",
"float",
"(",
"len",
"(",
"files",
")",
")",
"/",
"n",
"# spread over time range (eg 200 frames) ",
"fcnt",
"=",
"0",
"for",
"t",
"in",
"range",
"(",
"0",
",",
"n",
")",
":",
"filelist_index",
"=",
"int",
"(",
"t",
"*",
"tf",
")",
"# full range",
"fn",
"=",
"files",
"[",
"filelist_index",
"]",
"self",
".",
"xfn",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"search_dir",
",",
"fn",
")",
")",
"foundCnt",
"+=",
"1",
"# construct label, closely follows index version below",
"if",
"self",
".",
"filename_y",
"is",
"not",
"None",
":",
"mx",
"=",
"re",
".",
"search",
"(",
"self",
".",
"wildcard",
",",
"fn",
")",
"listy",
"=",
"self",
".",
"filename_y",
".",
"split",
"(",
"\"$\"",
")",
"if",
"(",
"len",
"(",
"listy",
")",
"!=",
"2",
")",
":",
"raise",
"FluidDataLoaderError",
"(",
"\"Error - when using a wildcard for x, filename_y needs to contain exactly one '$' where the file id string from x will be inserted to build the filename for y. Current, invalid, filename_y is '%s' \"",
"%",
"(",
"self",
".",
"filename_y",
")",
")",
"fny",
"=",
"listy",
"[",
"0",
"]",
"+",
"mx",
".",
"group",
"(",
"1",
")",
"+",
"listy",
"[",
"1",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"fny",
")",
":",
"# make sure file for y exists",
"raise",
"FluidDataLoaderError",
"(",
"\"Error - y file '%s' for x file '%s' doesnt exist in search dir '%s' \"",
"%",
"(",
"fny",
",",
"fn",
",",
"search_dir",
")",
")",
"fny",
"=",
"os",
".",
"path",
".",
"join",
"(",
"search_dir",
",",
"fny",
")",
"self",
".",
"yfn",
".",
"append",
"(",
"fny",
")",
"self",
".",
"have_y_npz",
"=",
"True",
"# flag to indicate we have np arrays in y",
"if",
"self",
".",
"array_y",
"is",
"not",
"None",
":",
"if",
"self",
".",
"y",
"is",
"None",
":",
"self",
".",
"y",
"=",
"[",
"]",
"self",
".",
"y",
".",
"append",
"(",
"self",
".",
"array_y",
"[",
"list_index",
"]",
")",
"labelstr",
"=",
"\" with label \"",
"+",
"format",
"(",
"self",
".",
"array_y",
"[",
"list_index",
"]",
")",
"if",
"self",
".",
"func_y",
"is",
"not",
"None",
":",
"print",
"(",
"\"NYI! test...\"",
")",
"else",
":",
"# \"simple\" index range ",
"n",
"=",
"max",
"(",
"1",
",",
"int",
"(",
"(",
"self",
".",
"filename_index_max",
"-",
"self",
".",
"filename_index_min",
")",
"*",
"self",
".",
"data_fraction",
")",
")",
"tf",
"=",
"float",
"(",
"self",
".",
"filename_index_max",
"-",
"self",
".",
"filename_index_min",
")",
"/",
"n",
"for",
"t",
"in",
"range",
"(",
"0",
",",
"n",
")",
":",
"filelist_index",
"=",
"int",
"(",
"self",
".",
"filename_index_min",
"+",
"t",
"*",
"tf",
")",
"# full range",
"fn",
"=",
"self",
".",
"getFilename",
"(",
"sim_index",
",",
"self",
".",
"filename",
",",
"filelist_index",
")",
"self",
".",
"xfn",
".",
"append",
"(",
"fn",
")",
"foundCnt",
"+=",
"1",
"if",
"self",
".",
"filename_y",
"is",
"not",
"None",
":",
"fny",
"=",
"self",
".",
"getFilename",
"(",
"sim_index",
",",
"self",
".",
"filename_y",
",",
"filelist_index",
")",
"self",
".",
"yfn",
".",
"append",
"(",
"fny",
")",
"self",
".",
"have_y_npz",
"=",
"True",
"# flag to indicate we have np arrays in y",
"if",
"self",
".",
"array_y",
"is",
"not",
"None",
":",
"if",
"self",
".",
"y",
"is",
"None",
":",
"self",
".",
"y",
"=",
"[",
"]",
"self",
".",
"y",
".",
"append",
"(",
"self",
".",
"array_y",
"[",
"list_index",
"]",
")",
"labelstr",
"=",
"\" with label \"",
"+",
"format",
"(",
"self",
".",
"array_y",
"[",
"list_index",
"]",
")",
"if",
"self",
".",
"func_y",
"is",
"not",
"None",
":",
"print",
"(",
"\"NYI! test...\"",
")",
"if",
"self",
".",
"y",
"is",
"None",
":",
"self",
".",
"y",
"=",
"[",
"]",
"self",
".",
"y",
".",
"append",
"(",
"self",
".",
"func_y",
"(",
"list_index",
",",
"sim_index",
",",
"t",
",",
"fn",
")",
")",
"if",
"self",
".",
"print_info",
":",
"print",
"(",
"\"Found \"",
"+",
"format",
"(",
"foundCnt",
")",
"+",
"\" files from sim ID \"",
"+",
"format",
"(",
"sim_index",
")",
"+",
"labelstr",
")"
] | https://github.com/thunil/tempoGAN/blob/a9b92181e28a82c2029049791f875a6c1341d62b/tensorflow/tools/fluiddataloader.py#L165-L251 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/pydoc.py | python | pathdirs | () | return dirs | Convert sys.path into a list of absolute, existing, unique paths. | Convert sys.path into a list of absolute, existing, unique paths. | [
"Convert",
"sys",
".",
"path",
"into",
"a",
"list",
"of",
"absolute",
"existing",
"unique",
"paths",
"."
] | def pathdirs():
"""Convert sys.path into a list of absolute, existing, unique paths."""
dirs = []
normdirs = []
for dir in sys.path:
dir = os.path.abspath(dir or '.')
normdir = os.path.normcase(dir)
if normdir not in normdirs and os.path.isdir(dir):
dirs.append(dir)
normdirs.append(normdir)
return dirs | [
"def",
"pathdirs",
"(",
")",
":",
"dirs",
"=",
"[",
"]",
"normdirs",
"=",
"[",
"]",
"for",
"dir",
"in",
"sys",
".",
"path",
":",
"dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dir",
"or",
"'.'",
")",
"normdir",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"dir",
")",
"if",
"normdir",
"not",
"in",
"normdirs",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"dir",
")",
":",
"dirs",
".",
"append",
"(",
"dir",
")",
"normdirs",
".",
"append",
"(",
"normdir",
")",
"return",
"dirs"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pydoc.py#L81-L91 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/genpy/src/genpy/rostime.py | python | Time.__init__ | (self, secs=0, nsecs=0) | Constructor: secs and nsecs are integers. You may prefer to use the static L{from_sec()} factory
method instead.
:param secs: seconds since epoch, ``int``
:param nsecs: nanoseconds since seconds (since epoch), ``int`` | Constructor: secs and nsecs are integers. You may prefer to use the static L{from_sec()} factory
method instead.
:param secs: seconds since epoch, ``int``
:param nsecs: nanoseconds since seconds (since epoch), ``int`` | [
"Constructor",
":",
"secs",
"and",
"nsecs",
"are",
"integers",
".",
"You",
"may",
"prefer",
"to",
"use",
"the",
"static",
"L",
"{",
"from_sec",
"()",
"}",
"factory",
"method",
"instead",
".",
":",
"param",
"secs",
":",
"seconds",
"since",
"epoch",
"int",
":",
"param",
"nsecs",
":",
"nanoseconds",
"since",
"seconds",
"(",
"since",
"epoch",
")",
"int"
] | def __init__(self, secs=0, nsecs=0):
"""
Constructor: secs and nsecs are integers. You may prefer to use the static L{from_sec()} factory
method instead.
:param secs: seconds since epoch, ``int``
:param nsecs: nanoseconds since seconds (since epoch), ``int``
"""
super(Time, self).__init__(secs, nsecs)
if self.secs < 0:
raise TypeError("time values must be positive") | [
"def",
"__init__",
"(",
"self",
",",
"secs",
"=",
"0",
",",
"nsecs",
"=",
"0",
")",
":",
"super",
"(",
"Time",
",",
"self",
")",
".",
"__init__",
"(",
"secs",
",",
"nsecs",
")",
"if",
"self",
".",
"secs",
"<",
"0",
":",
"raise",
"TypeError",
"(",
"\"time values must be positive\"",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/genpy/src/genpy/rostime.py#L195-L205 | ||
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | clang/bindings/python/clang/cindex.py | python | Cursor.referenced | (self) | return self._referenced | For a cursor that is a reference, returns a cursor
representing the entity that it references. | For a cursor that is a reference, returns a cursor
representing the entity that it references. | [
"For",
"a",
"cursor",
"that",
"is",
"a",
"reference",
"returns",
"a",
"cursor",
"representing",
"the",
"entity",
"that",
"it",
"references",
"."
] | def referenced(self):
"""
For a cursor that is a reference, returns a cursor
representing the entity that it references.
"""
if not hasattr(self, '_referenced'):
self._referenced = conf.lib.clang_getCursorReferenced(self)
return self._referenced | [
"def",
"referenced",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_referenced'",
")",
":",
"self",
".",
"_referenced",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorReferenced",
"(",
"self",
")",
"return",
"self",
".",
"_referenced"
] | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/bindings/python/clang/cindex.py#L1780-L1788 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | VarScrollHelperBase.RefreshAll | (*args, **kwargs) | return _windows_.VarScrollHelperBase_RefreshAll(*args, **kwargs) | RefreshAll(self) | RefreshAll(self) | [
"RefreshAll",
"(",
"self",
")"
] | def RefreshAll(*args, **kwargs):
"""RefreshAll(self)"""
return _windows_.VarScrollHelperBase_RefreshAll(*args, **kwargs) | [
"def",
"RefreshAll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"VarScrollHelperBase_RefreshAll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L2214-L2216 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/abins/io.py | python | IO.get_previous_ab_initio_program | (self) | return self.load(list_of_attributes=["ab_initio_program"])["attributes"]["ab_initio_program"] | :returns: name of ab initio program which was used in the previous calculation. | :returns: name of ab initio program which was used in the previous calculation. | [
":",
"returns",
":",
"name",
"of",
"ab",
"initio",
"program",
"which",
"was",
"used",
"in",
"the",
"previous",
"calculation",
"."
] | def get_previous_ab_initio_program(self):
"""
:returns: name of ab initio program which was used in the previous calculation.
"""
return self.load(list_of_attributes=["ab_initio_program"])["attributes"]["ab_initio_program"] | [
"def",
"get_previous_ab_initio_program",
"(",
"self",
")",
":",
"return",
"self",
".",
"load",
"(",
"list_of_attributes",
"=",
"[",
"\"ab_initio_program\"",
"]",
")",
"[",
"\"attributes\"",
"]",
"[",
"\"ab_initio_program\"",
"]"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/io.py#L137-L141 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListMainWindow.HighlightAll | (self, on=True) | Highlights/unhighlights all the lines in :class:`UltimateListCtrl`.
:param `on`: ``True`` to highlight all the lines, ``False`` to unhighlight them. | Highlights/unhighlights all the lines in :class:`UltimateListCtrl`. | [
"Highlights",
"/",
"unhighlights",
"all",
"the",
"lines",
"in",
":",
"class",
":",
"UltimateListCtrl",
"."
] | def HighlightAll(self, on=True):
"""
Highlights/unhighlights all the lines in :class:`UltimateListCtrl`.
:param `on`: ``True`` to highlight all the lines, ``False`` to unhighlight them.
"""
if self.IsSingleSel():
if on:
raise Exception("can't do this in a single sel control")
# we just have one item to turn off
if self.HasCurrent() and self.IsHighlighted(self._current):
self.HighlightLine(self._current, False)
self.RefreshLine(self._current)
else: # multi sel
if not self.IsEmpty():
self.HighlightLines(0, self.GetItemCount() - 1, on) | [
"def",
"HighlightAll",
"(",
"self",
",",
"on",
"=",
"True",
")",
":",
"if",
"self",
".",
"IsSingleSel",
"(",
")",
":",
"if",
"on",
":",
"raise",
"Exception",
"(",
"\"can't do this in a single sel control\"",
")",
"# we just have one item to turn off",
"if",
"self",
".",
"HasCurrent",
"(",
")",
"and",
"self",
".",
"IsHighlighted",
"(",
"self",
".",
"_current",
")",
":",
"self",
".",
"HighlightLine",
"(",
"self",
".",
"_current",
",",
"False",
")",
"self",
".",
"RefreshLine",
"(",
"self",
".",
"_current",
")",
"else",
":",
"# multi sel",
"if",
"not",
"self",
".",
"IsEmpty",
"(",
")",
":",
"self",
".",
"HighlightLines",
"(",
"0",
",",
"self",
".",
"GetItemCount",
"(",
")",
"-",
"1",
",",
"on",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L7259-L7278 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/textwrap.py | python | wrap | (text, width=70, **kwargs) | return w.wrap(text) | Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
space. See TextWrapper class for available keyword args to customize
wrapping behaviour. | Wrap a single paragraph of text, returning a list of wrapped lines. | [
"Wrap",
"a",
"single",
"paragraph",
"of",
"text",
"returning",
"a",
"list",
"of",
"wrapped",
"lines",
"."
] | def wrap(text, width=70, **kwargs):
"""Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
space. See TextWrapper class for available keyword args to customize
wrapping behaviour.
"""
w = TextWrapper(width=width, **kwargs)
return w.wrap(text) | [
"def",
"wrap",
"(",
"text",
",",
"width",
"=",
"70",
",",
"*",
"*",
"kwargs",
")",
":",
"w",
"=",
"TextWrapper",
"(",
"width",
"=",
"width",
",",
"*",
"*",
"kwargs",
")",
"return",
"w",
".",
"wrap",
"(",
"text",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/textwrap.py#L343-L354 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/socks.py | python | SOCKSConnection._new_conn | (self) | return conn | Establish a new connection via the SOCKS proxy. | [] | def _new_conn(self):
"""
Establish a new connection via the SOCKS proxy.
"""
extra_kw = {}
if self.source_address:
extra_kw["source_address"] = self.source_address
if self.socket_options:
extra_kw["socket_options"] = self.socket_options
try:
conn = socks.create_connection(
(self.host, self.port),
proxy_type=self._socks_options["socks_version"],
proxy_addr=self._socks_options["proxy_host"],
proxy_port=self._socks_options["proxy_port"],
proxy_username=self._socks_options["username"],
proxy_password=self._socks_options["password"],
proxy_rdns=self._socks_options["rdns"],
timeout=self.timeout,
**extra_kw
)
except SocketTimeout:
raise ConnectTimeoutError(
self,
"Connection to %s timed out. (connect timeout=%s)"
% (self.host, self.timeout),
)
except socks.ProxyError as e:
# This is fragile as hell, but it seems to be the only way to raise
# useful errors here.
if e.socket_err:
error = e.socket_err
if isinstance(error, SocketTimeout):
raise ConnectTimeoutError(
self,
"Connection to %s timed out. (connect timeout=%s)"
% (self.host, self.timeout),
)
else:
raise NewConnectionError(
self, "Failed to establish a new connection: %s" % error
)
else:
raise NewConnectionError(
self, "Failed to establish a new connection: %s" % e
)
except SocketError as e: # Defensive: PySocks should catch all these.
raise NewConnectionError(
self, "Failed to establish a new connection: %s" % e
)
return conn | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"extra_kw",
"=",
"{",
"}",
"if",
"self",
".",
"source_address",
":",
"extra_kw",
"[",
"\"source_address\"",
"]",
"=",
"self",
".",
"source_address",
"if",
"self",
".",
"socket_options",
":",
"extra_kw",
"[",
"\"socket_options\"",
"]",
"=",
"self",
".",
"socket_options",
"try",
":",
"conn",
"=",
"socks",
".",
"create_connection",
"(",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
",",
"proxy_type",
"=",
"self",
".",
"_socks_options",
"[",
"\"socks_version\"",
"]",
",",
"proxy_addr",
"=",
"self",
".",
"_socks_options",
"[",
"\"proxy_host\"",
"]",
",",
"proxy_port",
"=",
"self",
".",
"_socks_options",
"[",
"\"proxy_port\"",
"]",
",",
"proxy_username",
"=",
"self",
".",
"_socks_options",
"[",
"\"username\"",
"]",
",",
"proxy_password",
"=",
"self",
".",
"_socks_options",
"[",
"\"password\"",
"]",
",",
"proxy_rdns",
"=",
"self",
".",
"_socks_options",
"[",
"\"rdns\"",
"]",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"*",
"*",
"extra_kw",
")",
"except",
"SocketTimeout",
":",
"raise",
"ConnectTimeoutError",
"(",
"self",
",",
"\"Connection to %s timed out. (connect timeout=%s)\"",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"timeout",
")",
",",
")",
"except",
"socks",
".",
"ProxyError",
"as",
"e",
":",
"# This is fragile as hell, but it seems to be the only way to raise",
"# useful errors here.",
"if",
"e",
".",
"socket_err",
":",
"error",
"=",
"e",
".",
"socket_err",
"if",
"isinstance",
"(",
"error",
",",
"SocketTimeout",
")",
":",
"raise",
"ConnectTimeoutError",
"(",
"self",
",",
"\"Connection to %s timed out. (connect timeout=%s)\"",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"timeout",
")",
",",
")",
"else",
":",
"raise",
"NewConnectionError",
"(",
"self",
",",
"\"Failed to establish a new connection: %s\"",
"%",
"error",
")",
"else",
":",
"raise",
"NewConnectionError",
"(",
"self",
",",
"\"Failed to establish a new connection: %s\"",
"%",
"e",
")",
"except",
"SocketError",
"as",
"e",
":",
"# Defensive: PySocks should catch all these.",
"raise",
"NewConnectionError",
"(",
"self",
",",
"\"Failed to establish a new connection: %s\"",
"%",
"e",
")",
"return",
"conn"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/socks.py#L167-L279 | ||
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_parser.py | python | p_tterm_term_colon_symbol | (p) | tterm : tapp COLON atype | tterm : tapp COLON atype | [
"tterm",
":",
"tapp",
"COLON",
"atype"
] | def p_tterm_term_colon_symbol(p):
'tterm : tapp COLON atype'
p[0] = p[1]
p[0].sort = p[3] | [
"def",
"p_tterm_term_colon_symbol",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"p",
"[",
"0",
"]",
".",
"sort",
"=",
"p",
"[",
"3",
"]"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L1424-L1427 | ||
ukoethe/vigra | 093d57d15c8c237adf1704d96daa6393158ce299 | vigranumpy/lib/arraytypes.py | python | VigraArray.take | (self, indices, axis=None, out=None, mode='raise') | The array is always transposed to 'C' order before flattening.
The 'axis' parameter can be an int (axis position) or string (axis key). | The array is always transposed to 'C' order before flattening.
The 'axis' parameter can be an int (axis position) or string (axis key). | [
"The",
"array",
"is",
"always",
"transposed",
"to",
"C",
"order",
"before",
"flattening",
".",
"The",
"axis",
"parameter",
"can",
"be",
"an",
"int",
"(",
"axis",
"position",
")",
"or",
"string",
"(",
"axis",
"key",
")",
"."
] | def take(self, indices, axis=None, out=None, mode='raise'):
'''
The array is always transposed to 'C' order before flattening.
The 'axis' parameter can be an int (axis position) or string (axis key).
'''
if type(axis) == str:
axis = self.axistags.index(axis)
if axis is None:
return numpy.ndarray.take(self.ravel(), indices, axis, out, mode)
else:
return numpy.ndarray.take(self, indices, axis, out, mode) | [
"def",
"take",
"(",
"self",
",",
"indices",
",",
"axis",
"=",
"None",
",",
"out",
"=",
"None",
",",
"mode",
"=",
"'raise'",
")",
":",
"if",
"type",
"(",
"axis",
")",
"==",
"str",
":",
"axis",
"=",
"self",
".",
"axistags",
".",
"index",
"(",
"axis",
")",
"if",
"axis",
"is",
"None",
":",
"return",
"numpy",
".",
"ndarray",
".",
"take",
"(",
"self",
".",
"ravel",
"(",
")",
",",
"indices",
",",
"axis",
",",
"out",
",",
"mode",
")",
"else",
":",
"return",
"numpy",
".",
"ndarray",
".",
"take",
"(",
"self",
",",
"indices",
",",
"axis",
",",
"out",
",",
"mode",
")"
] | https://github.com/ukoethe/vigra/blob/093d57d15c8c237adf1704d96daa6393158ce299/vigranumpy/lib/arraytypes.py#L1558-L1568 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/serial/serialwin32.py | python | Serial.reset_output_buffer | (self) | \
Clear output buffer, aborting the current output and discarding all
that is in the buffer. | \
Clear output buffer, aborting the current output and discarding all
that is in the buffer. | [
"\\",
"Clear",
"output",
"buffer",
"aborting",
"the",
"current",
"output",
"and",
"discarding",
"all",
"that",
"is",
"in",
"the",
"buffer",
"."
] | def reset_output_buffer(self):
"""\
Clear output buffer, aborting the current output and discarding all
that is in the buffer.
"""
if not self.is_open:
raise portNotOpenError
win32.PurgeComm(self._port_handle, win32.PURGE_TXCLEAR | win32.PURGE_TXABORT) | [
"def",
"reset_output_buffer",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"raise",
"portNotOpenError",
"win32",
".",
"PurgeComm",
"(",
"self",
".",
"_port_handle",
",",
"win32",
".",
"PURGE_TXCLEAR",
"|",
"win32",
".",
"PURGE_TXABORT",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/serialwin32.py#L355-L362 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | tools/sampcd_processor.py | python | get_filenames | (full_test=False) | return all_sample_code_filenames | this function will get the sample code files that pending for check.
Args:
full_test: the full apis or the increment
Returns:
dict: the sample code files pending for check . | this function will get the sample code files that pending for check. | [
"this",
"function",
"will",
"get",
"the",
"sample",
"code",
"files",
"that",
"pending",
"for",
"check",
"."
] | def get_filenames(full_test=False):
'''
this function will get the sample code files that pending for check.
Args:
full_test: the full apis or the increment
Returns:
dict: the sample code files pending for check .
'''
global whl_error
import paddle
import paddle.fluid.contrib.slim.quantization
whl_error = []
if full_test:
get_full_api_from_pr_spec()
else:
get_incrementapi()
all_sample_code_filenames = {}
with open(API_DIFF_SPEC_FN) as f:
for line in f.readlines():
api = line.replace('\n', '')
try:
api_obj = eval(api)
except AttributeError:
whl_error.append(api)
continue
except SyntaxError:
logger.warning('line:%s, api:%s', line, api)
# paddle.Tensor.<lambda>
continue
if hasattr(api_obj, '__doc__') and api_obj.__doc__:
sample_code_filenames = sampcd_extract_to_file(api_obj.__doc__,
api)
for tfname in sample_code_filenames:
all_sample_code_filenames[tfname] = api
return all_sample_code_filenames | [
"def",
"get_filenames",
"(",
"full_test",
"=",
"False",
")",
":",
"global",
"whl_error",
"import",
"paddle",
"import",
"paddle",
".",
"fluid",
".",
"contrib",
".",
"slim",
".",
"quantization",
"whl_error",
"=",
"[",
"]",
"if",
"full_test",
":",
"get_full_api_from_pr_spec",
"(",
")",
"else",
":",
"get_incrementapi",
"(",
")",
"all_sample_code_filenames",
"=",
"{",
"}",
"with",
"open",
"(",
"API_DIFF_SPEC_FN",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"api",
"=",
"line",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"try",
":",
"api_obj",
"=",
"eval",
"(",
"api",
")",
"except",
"AttributeError",
":",
"whl_error",
".",
"append",
"(",
"api",
")",
"continue",
"except",
"SyntaxError",
":",
"logger",
".",
"warning",
"(",
"'line:%s, api:%s'",
",",
"line",
",",
"api",
")",
"# paddle.Tensor.<lambda>",
"continue",
"if",
"hasattr",
"(",
"api_obj",
",",
"'__doc__'",
")",
"and",
"api_obj",
".",
"__doc__",
":",
"sample_code_filenames",
"=",
"sampcd_extract_to_file",
"(",
"api_obj",
".",
"__doc__",
",",
"api",
")",
"for",
"tfname",
"in",
"sample_code_filenames",
":",
"all_sample_code_filenames",
"[",
"tfname",
"]",
"=",
"api",
"return",
"all_sample_code_filenames"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/tools/sampcd_processor.py#L429-L467 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.StyleGetBold | (*args, **kwargs) | return _stc.StyledTextCtrl_StyleGetBold(*args, **kwargs) | StyleGetBold(self, int style) -> bool
Get is a style bold or not. | StyleGetBold(self, int style) -> bool | [
"StyleGetBold",
"(",
"self",
"int",
"style",
")",
"-",
">",
"bool"
] | def StyleGetBold(*args, **kwargs):
"""
StyleGetBold(self, int style) -> bool
Get is a style bold or not.
"""
return _stc.StyledTextCtrl_StyleGetBold(*args, **kwargs) | [
"def",
"StyleGetBold",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_StyleGetBold",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L2602-L2608 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/numbers.py | python | Real.__divmod__ | (self, other) | return (self // other, self % other) | divmod(self, other): The pair (self // other, self % other).
Sometimes this can be computed faster than the pair of
operations. | divmod(self, other): The pair (self // other, self % other). | [
"divmod",
"(",
"self",
"other",
")",
":",
"The",
"pair",
"(",
"self",
"//",
"other",
"self",
"%",
"other",
")",
"."
] | def __divmod__(self, other):
"""divmod(self, other): The pair (self // other, self % other).
Sometimes this can be computed faster than the pair of
operations.
"""
return (self // other, self % other) | [
"def",
"__divmod__",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"self",
"//",
"other",
",",
"self",
"%",
"other",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/numbers.py#L200-L206 | |
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/nn/fast_masked_linear.py | python | FastMaskedConv1D.update_site | (self, inputs: Array, index: int) | return y_i | Adds an input site into the cache, and applies the masked convolution to the cache.
Args:
inputs: an input site to be added into the cache with dimensions (batch, features).
index: the index of the output site. The index of the input site should be `index - self.exclusive`.
Returns:
The next output site with dimensions (batch, features). | Adds an input site into the cache, and applies the masked convolution to the cache. | [
"Adds",
"an",
"input",
"site",
"into",
"the",
"cache",
"and",
"applies",
"the",
"masked",
"convolution",
"to",
"the",
"cache",
"."
] | def update_site(self, inputs: Array, index: int) -> Array:
"""
Adds an input site into the cache, and applies the masked convolution to the cache.
Args:
inputs: an input site to be added into the cache with dimensions (batch, features).
index: the index of the output site. The index of the input site should be `index - self.exclusive`.
Returns:
The next output site with dimensions (batch, features).
"""
dtype = jnp.promote_types(inputs.dtype, self.dtype)
inputs = jnp.asarray(inputs, dtype)
kernel_size = self.kernel_size - self.exclusive
dilation = self.kernel_dilation
is_single_input = False
if inputs.ndim == 1:
is_single_input = True
inputs = jnp.expand_dims(inputs, axis=0)
batch, in_features = inputs.shape
assert in_features % self.feature_group_count == 0
cache_size = kernel_size * dilation - (not self.exclusive) * (dilation - 1)
# Initialize the cache with zeros, and the RNG key is None
# `cache.dtype` must be the same as `inputs.dtype` (no promotion)
_cache = self.variable(
"cache",
"inputs",
zeros,
None,
(batch, cache_size, in_features),
inputs.dtype,
)
initializing = self.is_mutable_collection("params")
if not initializing:
# Add the input site into the cache
# To write the cache, use `_cache.value` as the left value of the assignment
_cache.value = lax.cond(
index - self.exclusive >= 0,
lambda _: jnp.concatenate(
[_cache.value[:, 1:, :], jnp.expand_dims(inputs, axis=1)], axis=1
),
lambda _: _cache.value,
None,
)
cache = _cache.value
cache = jnp.asarray(cache, dtype)
kernel_shape = (
kernel_size,
in_features // self.feature_group_count,
self.features,
)
kernel = self.param("kernel", self.kernel_init, kernel_shape, self.dtype)
kernel = jnp.asarray(kernel, dtype)
if self.exclusive and dilation > 1:
cache = cache[:, : -(dilation - 1), :]
dimension_numbers = flax.linen.linear._conv_dimension_numbers(cache.shape)
y_i = lax.conv_general_dilated(
cache,
kernel,
window_strides=(1,),
padding="VALID",
lhs_dilation=(1,),
rhs_dilation=(dilation,),
dimension_numbers=dimension_numbers,
feature_group_count=self.feature_group_count,
precision=self.precision,
)
if self.use_bias:
bias = self.param("bias", self.bias_init, (self.features,), self.dtype)
bias = jnp.asarray(bias, dtype)
y_i = y_i + bias
y_i = y_i.squeeze(axis=1)
if is_single_input:
y_i = y_i.squeeze(axis=0)
return y_i | [
"def",
"update_site",
"(",
"self",
",",
"inputs",
":",
"Array",
",",
"index",
":",
"int",
")",
"->",
"Array",
":",
"dtype",
"=",
"jnp",
".",
"promote_types",
"(",
"inputs",
".",
"dtype",
",",
"self",
".",
"dtype",
")",
"inputs",
"=",
"jnp",
".",
"asarray",
"(",
"inputs",
",",
"dtype",
")",
"kernel_size",
"=",
"self",
".",
"kernel_size",
"-",
"self",
".",
"exclusive",
"dilation",
"=",
"self",
".",
"kernel_dilation",
"is_single_input",
"=",
"False",
"if",
"inputs",
".",
"ndim",
"==",
"1",
":",
"is_single_input",
"=",
"True",
"inputs",
"=",
"jnp",
".",
"expand_dims",
"(",
"inputs",
",",
"axis",
"=",
"0",
")",
"batch",
",",
"in_features",
"=",
"inputs",
".",
"shape",
"assert",
"in_features",
"%",
"self",
".",
"feature_group_count",
"==",
"0",
"cache_size",
"=",
"kernel_size",
"*",
"dilation",
"-",
"(",
"not",
"self",
".",
"exclusive",
")",
"*",
"(",
"dilation",
"-",
"1",
")",
"# Initialize the cache with zeros, and the RNG key is None",
"# `cache.dtype` must be the same as `inputs.dtype` (no promotion)",
"_cache",
"=",
"self",
".",
"variable",
"(",
"\"cache\"",
",",
"\"inputs\"",
",",
"zeros",
",",
"None",
",",
"(",
"batch",
",",
"cache_size",
",",
"in_features",
")",
",",
"inputs",
".",
"dtype",
",",
")",
"initializing",
"=",
"self",
".",
"is_mutable_collection",
"(",
"\"params\"",
")",
"if",
"not",
"initializing",
":",
"# Add the input site into the cache",
"# To write the cache, use `_cache.value` as the left value of the assignment",
"_cache",
".",
"value",
"=",
"lax",
".",
"cond",
"(",
"index",
"-",
"self",
".",
"exclusive",
">=",
"0",
",",
"lambda",
"_",
":",
"jnp",
".",
"concatenate",
"(",
"[",
"_cache",
".",
"value",
"[",
":",
",",
"1",
":",
",",
":",
"]",
",",
"jnp",
".",
"expand_dims",
"(",
"inputs",
",",
"axis",
"=",
"1",
")",
"]",
",",
"axis",
"=",
"1",
")",
",",
"lambda",
"_",
":",
"_cache",
".",
"value",
",",
"None",
",",
")",
"cache",
"=",
"_cache",
".",
"value",
"cache",
"=",
"jnp",
".",
"asarray",
"(",
"cache",
",",
"dtype",
")",
"kernel_shape",
"=",
"(",
"kernel_size",
",",
"in_features",
"//",
"self",
".",
"feature_group_count",
",",
"self",
".",
"features",
",",
")",
"kernel",
"=",
"self",
".",
"param",
"(",
"\"kernel\"",
",",
"self",
".",
"kernel_init",
",",
"kernel_shape",
",",
"self",
".",
"dtype",
")",
"kernel",
"=",
"jnp",
".",
"asarray",
"(",
"kernel",
",",
"dtype",
")",
"if",
"self",
".",
"exclusive",
"and",
"dilation",
">",
"1",
":",
"cache",
"=",
"cache",
"[",
":",
",",
":",
"-",
"(",
"dilation",
"-",
"1",
")",
",",
":",
"]",
"dimension_numbers",
"=",
"flax",
".",
"linen",
".",
"linear",
".",
"_conv_dimension_numbers",
"(",
"cache",
".",
"shape",
")",
"y_i",
"=",
"lax",
".",
"conv_general_dilated",
"(",
"cache",
",",
"kernel",
",",
"window_strides",
"=",
"(",
"1",
",",
")",
",",
"padding",
"=",
"\"VALID\"",
",",
"lhs_dilation",
"=",
"(",
"1",
",",
")",
",",
"rhs_dilation",
"=",
"(",
"dilation",
",",
")",
",",
"dimension_numbers",
"=",
"dimension_numbers",
",",
"feature_group_count",
"=",
"self",
".",
"feature_group_count",
",",
"precision",
"=",
"self",
".",
"precision",
",",
")",
"if",
"self",
".",
"use_bias",
":",
"bias",
"=",
"self",
".",
"param",
"(",
"\"bias\"",
",",
"self",
".",
"bias_init",
",",
"(",
"self",
".",
"features",
",",
")",
",",
"self",
".",
"dtype",
")",
"bias",
"=",
"jnp",
".",
"asarray",
"(",
"bias",
",",
"dtype",
")",
"y_i",
"=",
"y_i",
"+",
"bias",
"y_i",
"=",
"y_i",
".",
"squeeze",
"(",
"axis",
"=",
"1",
")",
"if",
"is_single_input",
":",
"y_i",
"=",
"y_i",
".",
"squeeze",
"(",
"axis",
"=",
"0",
")",
"return",
"y_i"
] | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/nn/fast_masked_linear.py#L194-L282 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/distribute_coordinator.py | python | _run_single_worker | (worker_fn,
strategy,
cluster_spec,
task_type,
task_id,
session_config,
rpc_layer="",
worker_barrier=None,
coord=None) | Runs a single worker by calling `worker_fn` under context. | Runs a single worker by calling `worker_fn` under context. | [
"Runs",
"a",
"single",
"worker",
"by",
"calling",
"worker_fn",
"under",
"context",
"."
] | def _run_single_worker(worker_fn,
strategy,
cluster_spec,
task_type,
task_id,
session_config,
rpc_layer="",
worker_barrier=None,
coord=None):
"""Runs a single worker by calling `worker_fn` under context."""
session_config = copy.deepcopy(session_config)
strategy = copy.deepcopy(strategy)
# If there is an EVALUATOR task, we run single-machine eval on that task.
if task_type == _TaskType.EVALUATOR:
# It is possible to not have a strategy object for EVALUATOR task.
if strategy:
strategy.configure(session_config)
else:
assert strategy
strategy.configure(session_config, cluster_spec, task_type, task_id)
context = _WorkerContext(
strategy,
cluster_spec,
task_type,
task_id,
session_config=session_config,
rpc_layer=rpc_layer,
worker_barrier=worker_barrier)
with context:
if coord:
with coord.stop_on_exception():
return worker_fn(strategy)
else:
return worker_fn(strategy) | [
"def",
"_run_single_worker",
"(",
"worker_fn",
",",
"strategy",
",",
"cluster_spec",
",",
"task_type",
",",
"task_id",
",",
"session_config",
",",
"rpc_layer",
"=",
"\"\"",
",",
"worker_barrier",
"=",
"None",
",",
"coord",
"=",
"None",
")",
":",
"session_config",
"=",
"copy",
".",
"deepcopy",
"(",
"session_config",
")",
"strategy",
"=",
"copy",
".",
"deepcopy",
"(",
"strategy",
")",
"# If there is an EVALUATOR task, we run single-machine eval on that task.",
"if",
"task_type",
"==",
"_TaskType",
".",
"EVALUATOR",
":",
"# It is possible to not have a strategy object for EVALUATOR task.",
"if",
"strategy",
":",
"strategy",
".",
"configure",
"(",
"session_config",
")",
"else",
":",
"assert",
"strategy",
"strategy",
".",
"configure",
"(",
"session_config",
",",
"cluster_spec",
",",
"task_type",
",",
"task_id",
")",
"context",
"=",
"_WorkerContext",
"(",
"strategy",
",",
"cluster_spec",
",",
"task_type",
",",
"task_id",
",",
"session_config",
"=",
"session_config",
",",
"rpc_layer",
"=",
"rpc_layer",
",",
"worker_barrier",
"=",
"worker_barrier",
")",
"with",
"context",
":",
"if",
"coord",
":",
"with",
"coord",
".",
"stop_on_exception",
"(",
")",
":",
"return",
"worker_fn",
"(",
"strategy",
")",
"else",
":",
"return",
"worker_fn",
"(",
"strategy",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/distribute_coordinator.py#L322-L356 | ||
eric612/MobileNet-YOLO | 69b4441cb3ec8d553fbdef788ad033e246f901bd | examples/ssd/ssd_detect.py | python | parse_args | () | return parser.parse_args() | parse args | parse args | [
"parse",
"args"
] | def parse_args():
'''parse args'''
parser = argparse.ArgumentParser()
parser.add_argument('--gpu_id', type=int, default=0, help='gpu id')
parser.add_argument('--labelmap_file',
default='data/VOC0712/labelmap_voc.prototxt')
parser.add_argument('--model_def',
default='models/VGGNet/VOC0712/SSD_300x300/deploy.prototxt')
parser.add_argument('--image_resize', default=300, type=int)
parser.add_argument('--model_weights',
default='models/VGGNet/VOC0712/SSD_300x300/'
'VGG_VOC0712_SSD_300x300_iter_120000.caffemodel')
parser.add_argument('--image_file', default='examples/images/fish-bike.jpg')
return parser.parse_args() | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--gpu_id'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"0",
",",
"help",
"=",
"'gpu id'",
")",
"parser",
".",
"add_argument",
"(",
"'--labelmap_file'",
",",
"default",
"=",
"'data/VOC0712/labelmap_voc.prototxt'",
")",
"parser",
".",
"add_argument",
"(",
"'--model_def'",
",",
"default",
"=",
"'models/VGGNet/VOC0712/SSD_300x300/deploy.prototxt'",
")",
"parser",
".",
"add_argument",
"(",
"'--image_resize'",
",",
"default",
"=",
"300",
",",
"type",
"=",
"int",
")",
"parser",
".",
"add_argument",
"(",
"'--model_weights'",
",",
"default",
"=",
"'models/VGGNet/VOC0712/SSD_300x300/'",
"'VGG_VOC0712_SSD_300x300_iter_120000.caffemodel'",
")",
"parser",
".",
"add_argument",
"(",
"'--image_file'",
",",
"default",
"=",
"'examples/images/fish-bike.jpg'",
")",
"return",
"parser",
".",
"parse_args",
"(",
")"
] | https://github.com/eric612/MobileNet-YOLO/blob/69b4441cb3ec8d553fbdef788ad033e246f901bd/examples/ssd/ssd_detect.py#L133-L146 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/core/generator/FlowGraphProxy.py | python | FlowGraphProxy.get_hier_block_io | (self, direction) | return ports | Get a list of io ports for this flow graph.
Args:
direction: a string of 'in' or 'out'
Returns:
a list of dicts with: type, label, vlen, size, optional | Get a list of io ports for this flow graph. | [
"Get",
"a",
"list",
"of",
"io",
"ports",
"for",
"this",
"flow",
"graph",
"."
] | def get_hier_block_io(self, direction):
"""
Get a list of io ports for this flow graph.
Args:
direction: a string of 'in' or 'out'
Returns:
a list of dicts with: type, label, vlen, size, optional
"""
pads = self.get_pad_sources() if direction in ('sink', 'in') else \
self.get_pad_sinks() if direction in ('source', 'out') else []
ports = []
for pad in pads:
type_param = pad.params['type']
master = {
'label': str(pad.params['label'].get_evaluated()),
'type': str(pad.params['type'].get_evaluated()),
'vlen': str(pad.params['vlen'].get_value()),
'size': type_param.options.attributes[type_param.get_value()]['size'],
'cpp_size': type_param.options.attributes[type_param.get_value()]['cpp_size'],
'optional': bool(pad.params['optional'].get_evaluated()),
}
num_ports = pad.params['num_streams'].get_evaluated()
if num_ports > 1:
for i in range(num_ports):
clone = master.copy()
clone['label'] += str(i)
ports.append(clone)
else:
ports.append(master)
return ports | [
"def",
"get_hier_block_io",
"(",
"self",
",",
"direction",
")",
":",
"pads",
"=",
"self",
".",
"get_pad_sources",
"(",
")",
"if",
"direction",
"in",
"(",
"'sink'",
",",
"'in'",
")",
"else",
"self",
".",
"get_pad_sinks",
"(",
")",
"if",
"direction",
"in",
"(",
"'source'",
",",
"'out'",
")",
"else",
"[",
"]",
"ports",
"=",
"[",
"]",
"for",
"pad",
"in",
"pads",
":",
"type_param",
"=",
"pad",
".",
"params",
"[",
"'type'",
"]",
"master",
"=",
"{",
"'label'",
":",
"str",
"(",
"pad",
".",
"params",
"[",
"'label'",
"]",
".",
"get_evaluated",
"(",
")",
")",
",",
"'type'",
":",
"str",
"(",
"pad",
".",
"params",
"[",
"'type'",
"]",
".",
"get_evaluated",
"(",
")",
")",
",",
"'vlen'",
":",
"str",
"(",
"pad",
".",
"params",
"[",
"'vlen'",
"]",
".",
"get_value",
"(",
")",
")",
",",
"'size'",
":",
"type_param",
".",
"options",
".",
"attributes",
"[",
"type_param",
".",
"get_value",
"(",
")",
"]",
"[",
"'size'",
"]",
",",
"'cpp_size'",
":",
"type_param",
".",
"options",
".",
"attributes",
"[",
"type_param",
".",
"get_value",
"(",
")",
"]",
"[",
"'cpp_size'",
"]",
",",
"'optional'",
":",
"bool",
"(",
"pad",
".",
"params",
"[",
"'optional'",
"]",
".",
"get_evaluated",
"(",
")",
")",
",",
"}",
"num_ports",
"=",
"pad",
".",
"params",
"[",
"'num_streams'",
"]",
".",
"get_evaluated",
"(",
")",
"if",
"num_ports",
">",
"1",
":",
"for",
"i",
"in",
"range",
"(",
"num_ports",
")",
":",
"clone",
"=",
"master",
".",
"copy",
"(",
")",
"clone",
"[",
"'label'",
"]",
"+=",
"str",
"(",
"i",
")",
"ports",
".",
"append",
"(",
"clone",
")",
"else",
":",
"ports",
".",
"append",
"(",
"master",
")",
"return",
"ports"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/generator/FlowGraphProxy.py#L44-L75 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | _AddPrefix | (element, prefix) | Add |prefix| to |element| or each subelement if element is iterable. | Add |prefix| to |element| or each subelement if element is iterable. | [
"Add",
"|prefix|",
"to",
"|element|",
"or",
"each",
"subelement",
"if",
"element",
"is",
"iterable",
"."
] | def _AddPrefix(element, prefix):
"""Add |prefix| to |element| or each subelement if element is iterable."""
if element is None:
return element
# Note, not Iterable because we don't want to handle strings like that.
if isinstance(element, list) or isinstance(element, tuple):
return [prefix + e for e in element]
else:
return prefix + element | [
"def",
"_AddPrefix",
"(",
"element",
",",
"prefix",
")",
":",
"if",
"element",
"is",
"None",
":",
"return",
"element",
"# Note, not Iterable because we don't want to handle strings like that.",
"if",
"isinstance",
"(",
"element",
",",
"list",
")",
"or",
"isinstance",
"(",
"element",
",",
"tuple",
")",
":",
"return",
"[",
"prefix",
"+",
"e",
"for",
"e",
"in",
"element",
"]",
"else",
":",
"return",
"prefix",
"+",
"element"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L79-L87 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/polynomial/legendre.py | python | legder | (c, m=1, scl=1, axis=0) | return c | Differentiate a Legendre series.
Returns the Legendre series coefficients `c` differentiated `m` times
along `axis`. At each iteration the result is multiplied by `scl` (the
scaling factor is for use in a linear change of variable). The argument
`c` is an array of coefficients from low to high degree along each
axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2``
while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) +
2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is
``y``.
Parameters
----------
c : array_like
Array of Legendre series coefficients. If c is multidimensional the
different axis correspond to different variables with the degree in
each axis given by the corresponding index.
m : int, optional
Number of derivatives taken, must be non-negative. (Default: 1)
scl : scalar, optional
Each differentiation is multiplied by `scl`. The end result is
multiplication by ``scl**m``. This is for use in a linear change of
variable. (Default: 1)
axis : int, optional
Axis over which the derivative is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
der : ndarray
Legendre series of the derivative.
See Also
--------
legint
Notes
-----
In general, the result of differentiating a Legendre series does not
resemble the same operation on a power series. Thus the result of this
function may be "unintuitive," albeit correct; see Examples section
below.
Examples
--------
>>> from numpy.polynomial import legendre as L
>>> c = (1,2,3,4)
>>> L.legder(c)
array([ 6., 9., 20.])
>>> L.legder(c, 3)
array([60.])
>>> L.legder(c, scl=-1)
array([ -6., -9., -20.])
>>> L.legder(c, 2,-1)
array([ 9., 60.]) | Differentiate a Legendre series. | [
"Differentiate",
"a",
"Legendre",
"series",
"."
] | def legder(c, m=1, scl=1, axis=0):
"""
Differentiate a Legendre series.
Returns the Legendre series coefficients `c` differentiated `m` times
along `axis`. At each iteration the result is multiplied by `scl` (the
scaling factor is for use in a linear change of variable). The argument
`c` is an array of coefficients from low to high degree along each
axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2``
while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) +
2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is
``y``.
Parameters
----------
c : array_like
Array of Legendre series coefficients. If c is multidimensional the
different axis correspond to different variables with the degree in
each axis given by the corresponding index.
m : int, optional
Number of derivatives taken, must be non-negative. (Default: 1)
scl : scalar, optional
Each differentiation is multiplied by `scl`. The end result is
multiplication by ``scl**m``. This is for use in a linear change of
variable. (Default: 1)
axis : int, optional
Axis over which the derivative is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
der : ndarray
Legendre series of the derivative.
See Also
--------
legint
Notes
-----
In general, the result of differentiating a Legendre series does not
resemble the same operation on a power series. Thus the result of this
function may be "unintuitive," albeit correct; see Examples section
below.
Examples
--------
>>> from numpy.polynomial import legendre as L
>>> c = (1,2,3,4)
>>> L.legder(c)
array([ 6., 9., 20.])
>>> L.legder(c, 3)
array([60.])
>>> L.legder(c, scl=-1)
array([ -6., -9., -20.])
>>> L.legder(c, 2,-1)
array([ 9., 60.])
"""
c = np.array(c, ndmin=1, copy=True)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
cnt = pu._deprecate_as_int(m, "the order of derivation")
iaxis = pu._deprecate_as_int(axis, "the axis")
if cnt < 0:
raise ValueError("The order of derivation must be non-negative")
iaxis = normalize_axis_index(iaxis, c.ndim)
if cnt == 0:
return c
c = np.moveaxis(c, iaxis, 0)
n = len(c)
if cnt >= n:
c = c[:1]*0
else:
for i in range(cnt):
n = n - 1
c *= scl
der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
for j in range(n, 2, -1):
der[j - 1] = (2*j - 1)*c[j]
c[j - 2] += c[j]
if n > 1:
der[1] = 3*c[2]
der[0] = c[1]
c = der
c = np.moveaxis(c, 0, iaxis)
return c | [
"def",
"legder",
"(",
"c",
",",
"m",
"=",
"1",
",",
"scl",
"=",
"1",
",",
"axis",
"=",
"0",
")",
":",
"c",
"=",
"np",
".",
"array",
"(",
"c",
",",
"ndmin",
"=",
"1",
",",
"copy",
"=",
"True",
")",
"if",
"c",
".",
"dtype",
".",
"char",
"in",
"'?bBhHiIlLqQpP'",
":",
"c",
"=",
"c",
".",
"astype",
"(",
"np",
".",
"double",
")",
"cnt",
"=",
"pu",
".",
"_deprecate_as_int",
"(",
"m",
",",
"\"the order of derivation\"",
")",
"iaxis",
"=",
"pu",
".",
"_deprecate_as_int",
"(",
"axis",
",",
"\"the axis\"",
")",
"if",
"cnt",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"The order of derivation must be non-negative\"",
")",
"iaxis",
"=",
"normalize_axis_index",
"(",
"iaxis",
",",
"c",
".",
"ndim",
")",
"if",
"cnt",
"==",
"0",
":",
"return",
"c",
"c",
"=",
"np",
".",
"moveaxis",
"(",
"c",
",",
"iaxis",
",",
"0",
")",
"n",
"=",
"len",
"(",
"c",
")",
"if",
"cnt",
">=",
"n",
":",
"c",
"=",
"c",
"[",
":",
"1",
"]",
"*",
"0",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"cnt",
")",
":",
"n",
"=",
"n",
"-",
"1",
"c",
"*=",
"scl",
"der",
"=",
"np",
".",
"empty",
"(",
"(",
"n",
",",
")",
"+",
"c",
".",
"shape",
"[",
"1",
":",
"]",
",",
"dtype",
"=",
"c",
".",
"dtype",
")",
"for",
"j",
"in",
"range",
"(",
"n",
",",
"2",
",",
"-",
"1",
")",
":",
"der",
"[",
"j",
"-",
"1",
"]",
"=",
"(",
"2",
"*",
"j",
"-",
"1",
")",
"*",
"c",
"[",
"j",
"]",
"c",
"[",
"j",
"-",
"2",
"]",
"+=",
"c",
"[",
"j",
"]",
"if",
"n",
">",
"1",
":",
"der",
"[",
"1",
"]",
"=",
"3",
"*",
"c",
"[",
"2",
"]",
"der",
"[",
"0",
"]",
"=",
"c",
"[",
"1",
"]",
"c",
"=",
"der",
"c",
"=",
"np",
".",
"moveaxis",
"(",
"c",
",",
"0",
",",
"iaxis",
")",
"return",
"c"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/legendre.py#L612-L701 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/AlignAndFocusPowderFromFiles.py | python | AlignAndFocusPowderFromFiles.__loadCacheFile | (self, filename, wkspname) | return True | @returns True if a file was loaded | [] | def __loadCacheFile(self, filename, wkspname):
'''@returns True if a file was loaded'''
if os.path.exists(filename):
self.log().notice('Loading cache from {}'.format(filename))
else:
return False
LoadNexusProcessed(Filename=filename, OutputWorkspace=wkspname)
# TODO LoadNexusProcessed has a bug. When it finds the
# instrument name without xml it reads in from an IDF
# in the instrument directory.
editinstrargs = {}
for name in PROPS_FOR_INSTR:
prop = self.getProperty(name)
if not prop.isDefault:
editinstrargs[name] = prop.value
if editinstrargs:
try:
EditInstrumentGeometry(Workspace=wkspname, **editinstrargs)
except RuntimeError as e:
# treat this as a non-fatal error
self.log().warning('Failed to update instrument geometry in cache file: {}'.format(e))
return True | [
"def",
"__loadCacheFile",
"(",
"self",
",",
"filename",
",",
"wkspname",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"self",
".",
"log",
"(",
")",
".",
"notice",
"(",
"'Loading cache from {}'",
".",
"format",
"(",
"filename",
")",
")",
"else",
":",
"return",
"False",
"LoadNexusProcessed",
"(",
"Filename",
"=",
"filename",
",",
"OutputWorkspace",
"=",
"wkspname",
")",
"# TODO LoadNexusProcessed has a bug. When it finds the",
"# instrument name without xml it reads in from an IDF",
"# in the instrument directory.",
"editinstrargs",
"=",
"{",
"}",
"for",
"name",
"in",
"PROPS_FOR_INSTR",
":",
"prop",
"=",
"self",
".",
"getProperty",
"(",
"name",
")",
"if",
"not",
"prop",
".",
"isDefault",
":",
"editinstrargs",
"[",
"name",
"]",
"=",
"prop",
".",
"value",
"if",
"editinstrargs",
":",
"try",
":",
"EditInstrumentGeometry",
"(",
"Workspace",
"=",
"wkspname",
",",
"*",
"*",
"editinstrargs",
")",
"except",
"RuntimeError",
"as",
"e",
":",
"# treat this as a non-fatal error",
"self",
".",
"log",
"(",
")",
".",
"warning",
"(",
"'Failed to update instrument geometry in cache file: {}'",
".",
"format",
"(",
"e",
")",
")",
"return",
"True"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/AlignAndFocusPowderFromFiles.py#L620-L643 | ||
gemrb/gemrb | 730206eed8d1dd358ca5e69a62f9e099aa22ffc6 | gemrb/GUIScripts/pst/GUIOPT.py | python | OpenAudioOptionsWindow | () | Open audio options window | Open audio options window | [
"Open",
"audio",
"options",
"window"
] | def OpenAudioOptionsWindow ():
"""Open audio options window"""
global AudioHelpText
Window = GemRB.LoadWindow (5, "GUIOPT")
def OnClose(Window):
global AudioHelpText
# Restore values in case of cancel
if GemRB.GetVar ("Cancel") == 1:
for k, v in list(saved_audio_options.items ()):
GemRB.SetVar (k, v)
AudioHelpText = None
UpdateVolume (31210)
TrySavingConfiguration()
Window.SetAction(OnClose, ACTION_WINDOW_CLOSED)
# save values, so we can restore them on cancel
for v in "Volume Ambients", "Volume SFX", "Volume Voices", "Volume Music", "Volume Movie", "Sound Processing", "Music Processing":
saved_audio_options[v] = GemRB.GetVar (v)
AudioHelpText = GUIOPTControls.OptHelpText ('AudioOptions', Window, 9, 31210)
GUIOPTControls.OptDone (lambda: Window.Close(), Window, 7)
GUIOPTControls.OptCancel (lambda: Window.Close(), Window, 8)
GUIOPTControls.OptSlider (31210, 31227, AudioHelpText, Window, 1, 10, 31460, "Volume Ambients", lambda: UpdateVolume(31227))
GUIOPTControls.OptSlider (31210, 31228, AudioHelpText, Window, 2, 11, 31466, "Volume SFX", lambda: UpdateVolume(31228))
GUIOPTControls.OptSlider (31210, 31226, AudioHelpText, Window, 3, 12, 31467, "Volume Voices", lambda: UpdateVolume(31226))
GUIOPTControls.OptSlider (31210, 31225, AudioHelpText, Window, 4, 13, 31468, "Volume Music", lambda: UpdateVolume(31225))
GUIOPTControls.OptSlider (31210, 31229, AudioHelpText, Window, 5, 14, 31469, "Volume Movie", lambda: UpdateVolume(31229))
GUIOPTControls.OptCheckbox (31210, 31224, AudioHelpText, Window, 6, 15, 30900, "Environmental Audio")
GUIOPTControls.OptCheckbox (31210, 63244, AudioHelpText, Window, 16, 17, 63242, "Sound Processing")
GUIOPTControls.OptCheckbox (31210, 63247, AudioHelpText, Window, 18, 19, 63243, "Music Processing")
Window.ShowModal (MODAL_SHADOW_GRAY) | [
"def",
"OpenAudioOptionsWindow",
"(",
")",
":",
"global",
"AudioHelpText",
"Window",
"=",
"GemRB",
".",
"LoadWindow",
"(",
"5",
",",
"\"GUIOPT\"",
")",
"def",
"OnClose",
"(",
"Window",
")",
":",
"global",
"AudioHelpText",
"# Restore values in case of cancel",
"if",
"GemRB",
".",
"GetVar",
"(",
"\"Cancel\"",
")",
"==",
"1",
":",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"saved_audio_options",
".",
"items",
"(",
")",
")",
":",
"GemRB",
".",
"SetVar",
"(",
"k",
",",
"v",
")",
"AudioHelpText",
"=",
"None",
"UpdateVolume",
"(",
"31210",
")",
"TrySavingConfiguration",
"(",
")",
"Window",
".",
"SetAction",
"(",
"OnClose",
",",
"ACTION_WINDOW_CLOSED",
")",
"# save values, so we can restore them on cancel",
"for",
"v",
"in",
"\"Volume Ambients\"",
",",
"\"Volume SFX\"",
",",
"\"Volume Voices\"",
",",
"\"Volume Music\"",
",",
"\"Volume Movie\"",
",",
"\"Sound Processing\"",
",",
"\"Music Processing\"",
":",
"saved_audio_options",
"[",
"v",
"]",
"=",
"GemRB",
".",
"GetVar",
"(",
"v",
")",
"AudioHelpText",
"=",
"GUIOPTControls",
".",
"OptHelpText",
"(",
"'AudioOptions'",
",",
"Window",
",",
"9",
",",
"31210",
")",
"GUIOPTControls",
".",
"OptDone",
"(",
"lambda",
":",
"Window",
".",
"Close",
"(",
")",
",",
"Window",
",",
"7",
")",
"GUIOPTControls",
".",
"OptCancel",
"(",
"lambda",
":",
"Window",
".",
"Close",
"(",
")",
",",
"Window",
",",
"8",
")",
"GUIOPTControls",
".",
"OptSlider",
"(",
"31210",
",",
"31227",
",",
"AudioHelpText",
",",
"Window",
",",
"1",
",",
"10",
",",
"31460",
",",
"\"Volume Ambients\"",
",",
"lambda",
":",
"UpdateVolume",
"(",
"31227",
")",
")",
"GUIOPTControls",
".",
"OptSlider",
"(",
"31210",
",",
"31228",
",",
"AudioHelpText",
",",
"Window",
",",
"2",
",",
"11",
",",
"31466",
",",
"\"Volume SFX\"",
",",
"lambda",
":",
"UpdateVolume",
"(",
"31228",
")",
")",
"GUIOPTControls",
".",
"OptSlider",
"(",
"31210",
",",
"31226",
",",
"AudioHelpText",
",",
"Window",
",",
"3",
",",
"12",
",",
"31467",
",",
"\"Volume Voices\"",
",",
"lambda",
":",
"UpdateVolume",
"(",
"31226",
")",
")",
"GUIOPTControls",
".",
"OptSlider",
"(",
"31210",
",",
"31225",
",",
"AudioHelpText",
",",
"Window",
",",
"4",
",",
"13",
",",
"31468",
",",
"\"Volume Music\"",
",",
"lambda",
":",
"UpdateVolume",
"(",
"31225",
")",
")",
"GUIOPTControls",
".",
"OptSlider",
"(",
"31210",
",",
"31229",
",",
"AudioHelpText",
",",
"Window",
",",
"5",
",",
"14",
",",
"31469",
",",
"\"Volume Movie\"",
",",
"lambda",
":",
"UpdateVolume",
"(",
"31229",
")",
")",
"GUIOPTControls",
".",
"OptCheckbox",
"(",
"31210",
",",
"31224",
",",
"AudioHelpText",
",",
"Window",
",",
"6",
",",
"15",
",",
"30900",
",",
"\"Environmental Audio\"",
")",
"GUIOPTControls",
".",
"OptCheckbox",
"(",
"31210",
",",
"63244",
",",
"AudioHelpText",
",",
"Window",
",",
"16",
",",
"17",
",",
"63242",
",",
"\"Sound Processing\"",
")",
"GUIOPTControls",
".",
"OptCheckbox",
"(",
"31210",
",",
"63247",
",",
"AudioHelpText",
",",
"Window",
",",
"18",
",",
"19",
",",
"63243",
",",
"\"Music Processing\"",
")",
"Window",
".",
"ShowModal",
"(",
"MODAL_SHADOW_GRAY",
")"
] | https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/pst/GUIOPT.py#L136-L175 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/third_party/jinja2/filters.py | python | do_list | (value) | return list(value) | Convert the value into a list. If it was a string the returned list
will be a list of characters. | Convert the value into a list. If it was a string the returned list
will be a list of characters. | [
"Convert",
"the",
"value",
"into",
"a",
"list",
".",
"If",
"it",
"was",
"a",
"string",
"the",
"returned",
"list",
"will",
"be",
"a",
"list",
"of",
"characters",
"."
] | def do_list(value):
"""Convert the value into a list. If it was a string the returned list
will be a list of characters.
"""
return list(value) | [
"def",
"do_list",
"(",
"value",
")",
":",
"return",
"list",
"(",
"value",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/filters.py#L876-L880 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/tokenizer.py | python | Tokenizer.unget | (self, token) | Unget a token.
The unget buffer for tokens is only one token large; it is
an error to try to unget a token when the unget buffer is not
empty.
@param token: the token to unget
@type token: Token object
@raises UngetBufferFull: there is already an ungotten token | Unget a token. | [
"Unget",
"a",
"token",
"."
] | def unget(self, token):
"""Unget a token.
The unget buffer for tokens is only one token large; it is
an error to try to unget a token when the unget buffer is not
empty.
@param token: the token to unget
@type token: Token object
@raises UngetBufferFull: there is already an ungotten token
"""
if not self.ungotten_token is None:
raise UngetBufferFull
self.ungotten_token = token | [
"def",
"unget",
"(",
"self",
",",
"token",
")",
":",
"if",
"not",
"self",
".",
"ungotten_token",
"is",
"None",
":",
"raise",
"UngetBufferFull",
"self",
".",
"ungotten_token",
"=",
"token"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/tokenizer.py#L406-L420 | ||
OpenGenus/quark | 225ad96efdfcc66cb6584a756c17eb3871e6eb62 | code/code/data_structures/src/hashs/bloom_filter/bloom_filter.py | python | bloomFilter.__contains__ | (self, value) | return True | Determine whether a value is present. A false positive might be returned even if the element is
not present. However, a false negative will never be returned. | Determine whether a value is present. A false positive might be returned even if the element is
not present. However, a false negative will never be returned. | [
"Determine",
"whether",
"a",
"value",
"is",
"present",
".",
"A",
"false",
"positive",
"might",
"be",
"returned",
"even",
"if",
"the",
"element",
"is",
"not",
"present",
".",
"However",
"a",
"false",
"negative",
"will",
"never",
"be",
"returned",
"."
] | def __contains__(self, value):
"""
Determine whether a value is present. A false positive might be returned even if the element is
not present. However, a false negative will never be returned.
"""
for hf in self.hashFunctions:
if self.bits & 1 << hf(value, self.M) == 0:
return False
return True | [
"def",
"__contains__",
"(",
"self",
",",
"value",
")",
":",
"for",
"hf",
"in",
"self",
".",
"hashFunctions",
":",
"if",
"self",
".",
"bits",
"&",
"1",
"<<",
"hf",
"(",
"value",
",",
"self",
".",
"M",
")",
"==",
"0",
":",
"return",
"False",
"return",
"True"
] | https://github.com/OpenGenus/quark/blob/225ad96efdfcc66cb6584a756c17eb3871e6eb62/code/code/data_structures/src/hashs/bloom_filter/bloom_filter.py#L25-L33 | |
nasa/trick | 7b85aa66329d62fe8816462627c09a353aac8299 | share/trick/trickops/WorkflowCommon.py | python | tprint | (line, color='ENDC', verbosity='INFO') | Utility method for writing text to both the log and stdout, with optional
color for stdout
Parameters
----------
line : str
Line of string to both print and log
color : str
Color/style of text. Options are listed in Colorstr() class. | Utility method for writing text to both the log and stdout, with optional
color for stdout | [
"Utility",
"method",
"for",
"writing",
"text",
"to",
"both",
"the",
"log",
"and",
"stdout",
"with",
"optional",
"color",
"for",
"stdout"
] | def tprint(line, color='ENDC', verbosity='INFO'):
"""
Utility method for writing text to both the log and stdout, with optional
color for stdout
Parameters
----------
line : str
Line of string to both print and log
color : str
Color/style of text. Options are listed in Colorstr() class.
"""
colorLine = printer.colorstr(line, color)
sys.stdout.write(colorLine+"\n")
if verbosity == 'INFO':
logging.info(line)
elif verbosity == 'DEBUG':
logging.debug(line)
elif verbosity == 'ERROR':
logging.error(line)
elif verbosity == 'WARNING':
logging.warning(line)
else:
pass | [
"def",
"tprint",
"(",
"line",
",",
"color",
"=",
"'ENDC'",
",",
"verbosity",
"=",
"'INFO'",
")",
":",
"colorLine",
"=",
"printer",
".",
"colorstr",
"(",
"line",
",",
"color",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"colorLine",
"+",
"\"\\n\"",
")",
"if",
"verbosity",
"==",
"'INFO'",
":",
"logging",
".",
"info",
"(",
"line",
")",
"elif",
"verbosity",
"==",
"'DEBUG'",
":",
"logging",
".",
"debug",
"(",
"line",
")",
"elif",
"verbosity",
"==",
"'ERROR'",
":",
"logging",
".",
"error",
"(",
"line",
")",
"elif",
"verbosity",
"==",
"'WARNING'",
":",
"logging",
".",
"warning",
"(",
"line",
")",
"else",
":",
"pass"
] | https://github.com/nasa/trick/blob/7b85aa66329d62fe8816462627c09a353aac8299/share/trick/trickops/WorkflowCommon.py#L85-L108 | ||
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/third_party/depot_tools/cpplint.py | python | _IncludeState.FindHeader | (self, header) | return -1 | Check if a header has already been included.
Args:
header: header to check.
Returns:
Line number of previous occurrence, or -1 if the header has not
been seen before. | Check if a header has already been included. | [
"Check",
"if",
"a",
"header",
"has",
"already",
"been",
"included",
"."
] | def FindHeader(self, header):
"""Check if a header has already been included.
Args:
header: header to check.
Returns:
Line number of previous occurrence, or -1 if the header has not
been seen before.
"""
for section_list in self.include_list:
for f in section_list:
if f[0] == header:
return f[1]
return -1 | [
"def",
"FindHeader",
"(",
"self",
",",
"header",
")",
":",
"for",
"section_list",
"in",
"self",
".",
"include_list",
":",
"for",
"f",
"in",
"section_list",
":",
"if",
"f",
"[",
"0",
"]",
"==",
"header",
":",
"return",
"f",
"[",
"1",
"]",
"return",
"-",
"1"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/depot_tools/cpplint.py#L701-L714 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/MultichannelLookup.py | python | MultichannelLookup.set_embeddings | (self, index, blob) | return self._internal.set_embeddings(index, blob._internal) | Sets the representation table with the given index
as a blob of the dimensions:
- BatchLength * BatchWidth * ListSize is dimensions[i].VectorCount
- Height * Width * Depth * Channels is dimensions[i].VectorSize | Sets the representation table with the given index
as a blob of the dimensions: | [
"Sets",
"the",
"representation",
"table",
"with",
"the",
"given",
"index",
"as",
"a",
"blob",
"of",
"the",
"dimensions",
":"
] | def set_embeddings(self, index, blob):
"""Sets the representation table with the given index
as a blob of the dimensions:
- BatchLength * BatchWidth * ListSize is dimensions[i].VectorCount
- Height * Width * Depth * Channels is dimensions[i].VectorSize
"""
if not type(blob) is Blob.Blob:
raise ValueError('The `blob` must be neoml.Blob.')
return self._internal.set_embeddings(index, blob._internal) | [
"def",
"set_embeddings",
"(",
"self",
",",
"index",
",",
"blob",
")",
":",
"if",
"not",
"type",
"(",
"blob",
")",
"is",
"Blob",
".",
"Blob",
":",
"raise",
"ValueError",
"(",
"'The `blob` must be neoml.Blob.'",
")",
"return",
"self",
".",
"_internal",
".",
"set_embeddings",
"(",
"index",
",",
"blob",
".",
"_internal",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/MultichannelLookup.py#L121-L131 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rosservice/src/rosservice/__init__.py | python | _rosservice_cmd_type | (argv) | Parse 'type' command arguments and run command Will cause a system
exit if command-line argument parsing fails.
@param argv: command-line arguments
@type argv: [str]
@raise ROSServiceException: if type command cannot be executed | Parse 'type' command arguments and run command Will cause a system
exit if command-line argument parsing fails. | [
"Parse",
"type",
"command",
"arguments",
"and",
"run",
"command",
"Will",
"cause",
"a",
"system",
"exit",
"if",
"command",
"-",
"line",
"argument",
"parsing",
"fails",
"."
] | def _rosservice_cmd_type(argv):
"""
Parse 'type' command arguments and run command Will cause a system
exit if command-line argument parsing fails.
@param argv: command-line arguments
@type argv: [str]
@raise ROSServiceException: if type command cannot be executed
"""
_rosservice_type(_optparse_service_only('type', argv=argv)) | [
"def",
"_rosservice_cmd_type",
"(",
"argv",
")",
":",
"_rosservice_type",
"(",
"_optparse_service_only",
"(",
"'type'",
",",
"argv",
"=",
"argv",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosservice/src/rosservice/__init__.py#L519-L527 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/queues/feeding_queue_runner.py | python | FeedingQueueRunner.__init__ | (self, queue=None, enqueue_ops=None, close_op=None,
cancel_op=None, feed_fns=None) | Initialize the queue runner.
For further documentation, see `queue_runner.py`. Note that
`FeedingQueueRunner` does not support construction from protobuffer nor
serialization to protobuffer.
Args:
queue: A `Queue`.
enqueue_ops: List of enqueue ops to run in threads later.
close_op: Op to close the queue. Pending enqueue ops are preserved.
cancel_op: Op to close the queue and cancel pending enqueue ops.
feed_fns: a list of functions that return a dictionary mapping fed
`Tensor`s to values. Must be the same length as `enqueue_ops`.
Raises:
ValueError: `feed_fns` is not `None` and has different length than
`enqueue_ops`. | Initialize the queue runner. | [
"Initialize",
"the",
"queue",
"runner",
"."
] | def __init__(self, queue=None, enqueue_ops=None, close_op=None,
cancel_op=None, feed_fns=None):
"""Initialize the queue runner.
For further documentation, see `queue_runner.py`. Note that
`FeedingQueueRunner` does not support construction from protobuffer nor
serialization to protobuffer.
Args:
queue: A `Queue`.
enqueue_ops: List of enqueue ops to run in threads later.
close_op: Op to close the queue. Pending enqueue ops are preserved.
cancel_op: Op to close the queue and cancel pending enqueue ops.
feed_fns: a list of functions that return a dictionary mapping fed
`Tensor`s to values. Must be the same length as `enqueue_ops`.
Raises:
ValueError: `feed_fns` is not `None` and has different length than
`enqueue_ops`.
"""
super(FeedingQueueRunner, self).__init__(queue, enqueue_ops, close_op,
cancel_op)
if feed_fns is None:
self._feed_fns = [None for _ in enqueue_ops]
else:
if len(feed_fns) != len(enqueue_ops):
raise ValueError(
"If feed_fns is not None, it must have the same length as "
"enqueue_ops.")
self._feed_fns = feed_fns | [
"def",
"__init__",
"(",
"self",
",",
"queue",
"=",
"None",
",",
"enqueue_ops",
"=",
"None",
",",
"close_op",
"=",
"None",
",",
"cancel_op",
"=",
"None",
",",
"feed_fns",
"=",
"None",
")",
":",
"super",
"(",
"FeedingQueueRunner",
",",
"self",
")",
".",
"__init__",
"(",
"queue",
",",
"enqueue_ops",
",",
"close_op",
",",
"cancel_op",
")",
"if",
"feed_fns",
"is",
"None",
":",
"self",
".",
"_feed_fns",
"=",
"[",
"None",
"for",
"_",
"in",
"enqueue_ops",
"]",
"else",
":",
"if",
"len",
"(",
"feed_fns",
")",
"!=",
"len",
"(",
"enqueue_ops",
")",
":",
"raise",
"ValueError",
"(",
"\"If feed_fns is not None, it must have the same length as \"",
"\"enqueue_ops.\"",
")",
"self",
".",
"_feed_fns",
"=",
"feed_fns"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/queues/feeding_queue_runner.py#L32-L61 | ||
zhaoweicai/mscnn | 534bcac5710a579d60827f192035f7eef6d8c585 | python/caffe/io.py | python | array_to_blobproto | (arr, diff=None) | return blob | Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check. | Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check. | [
"Converts",
"a",
"N",
"-",
"dimensional",
"array",
"to",
"blob",
"proto",
".",
"If",
"diff",
"is",
"given",
"also",
"convert",
"the",
"diff",
".",
"You",
"need",
"to",
"make",
"sure",
"that",
"arr",
"and",
"diff",
"have",
"the",
"same",
"shape",
"and",
"this",
"function",
"does",
"not",
"do",
"sanity",
"check",
"."
] | def array_to_blobproto(arr, diff=None):
"""Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check.
"""
blob = caffe_pb2.BlobProto()
blob.shape.dim.extend(arr.shape)
blob.data.extend(arr.astype(float).flat)
if diff is not None:
blob.diff.extend(diff.astype(float).flat)
return blob | [
"def",
"array_to_blobproto",
"(",
"arr",
",",
"diff",
"=",
"None",
")",
":",
"blob",
"=",
"caffe_pb2",
".",
"BlobProto",
"(",
")",
"blob",
".",
"shape",
".",
"dim",
".",
"extend",
"(",
"arr",
".",
"shape",
")",
"blob",
".",
"data",
".",
"extend",
"(",
"arr",
".",
"astype",
"(",
"float",
")",
".",
"flat",
")",
"if",
"diff",
"is",
"not",
"None",
":",
"blob",
".",
"diff",
".",
"extend",
"(",
"diff",
".",
"astype",
"(",
"float",
")",
".",
"flat",
")",
"return",
"blob"
] | https://github.com/zhaoweicai/mscnn/blob/534bcac5710a579d60827f192035f7eef6d8c585/python/caffe/io.py#L36-L46 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py | python | Helper.getline | (self, prompt) | Read one line, using raw_input when available. | Read one line, using raw_input when available. | [
"Read",
"one",
"line",
"using",
"raw_input",
"when",
"available",
"."
] | def getline(self, prompt):
"""Read one line, using raw_input when available."""
if self.input is sys.stdin:
return raw_input(prompt)
else:
self.output.write(prompt)
self.output.flush()
return self.input.readline() | [
"def",
"getline",
"(",
"self",
",",
"prompt",
")",
":",
"if",
"self",
".",
"input",
"is",
"sys",
".",
"stdin",
":",
"return",
"raw_input",
"(",
"prompt",
")",
"else",
":",
"self",
".",
"output",
".",
"write",
"(",
"prompt",
")",
"self",
".",
"output",
".",
"flush",
"(",
")",
"return",
"self",
".",
"input",
".",
"readline",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py#L1771-L1778 | ||
Qihoo360/mongosync | 55b647e81c072ebe91daaa3b9dc1a953c3c22e19 | dep/mongo-cxx-driver/site_scons/buildscripts/docs.py | python | version | () | Get the server version from doxygenConfig. | Get the server version from doxygenConfig. | [
"Get",
"the",
"server",
"version",
"from",
"doxygenConfig",
"."
] | def version():
"""Get the server version from doxygenConfig.
"""
with open("etc/doxygen/config") as f:
for line in f.readlines():
if line.startswith("PROJECT_NUMBER"):
return line.split("=")[1].strip() | [
"def",
"version",
"(",
")",
":",
"with",
"open",
"(",
"\"etc/doxygen/config\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"\"PROJECT_NUMBER\"",
")",
":",
"return",
"line",
".",
"split",
"(",
"\"=\"",
")",
"[",
"1",
"]",
".",
"strip",
"(",
")"
] | https://github.com/Qihoo360/mongosync/blob/55b647e81c072ebe91daaa3b9dc1a953c3c22e19/dep/mongo-cxx-driver/site_scons/buildscripts/docs.py#L27-L33 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | chrome/common/extensions/docs/build/directory.py | python | sorted_walk | (path) | A version of os.walk that yields results in order sorted by name.
This is to prevent spurious docs changes due to os.walk returning items in a
filesystem dependent order (by inode creation time, etc). | A version of os.walk that yields results in order sorted by name. | [
"A",
"version",
"of",
"os",
".",
"walk",
"that",
"yields",
"results",
"in",
"order",
"sorted",
"by",
"name",
"."
] | def sorted_walk(path):
""" A version of os.walk that yields results in order sorted by name.
This is to prevent spurious docs changes due to os.walk returning items in a
filesystem dependent order (by inode creation time, etc).
"""
for base, dirs, files in os.walk(path):
dirs.sort()
files.sort()
yield base, dirs, files | [
"def",
"sorted_walk",
"(",
"path",
")",
":",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"dirs",
".",
"sort",
"(",
")",
"files",
".",
"sort",
"(",
")",
"yield",
"base",
",",
"dirs",
",",
"files"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/common/extensions/docs/build/directory.py#L37-L46 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | TextBoxAttr.IsFloating | (*args, **kwargs) | return _richtext.TextBoxAttr_IsFloating(*args, **kwargs) | IsFloating(self) -> bool | IsFloating(self) -> bool | [
"IsFloating",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsFloating(*args, **kwargs):
"""IsFloating(self) -> bool"""
return _richtext.TextBoxAttr_IsFloating(*args, **kwargs) | [
"def",
"IsFloating",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"TextBoxAttr_IsFloating",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L588-L590 | |
esa/pagmo | 80281d549c8f1b470e1489a5d37c8f06b2e429c0 | PyGMO/util/_analysis.py | python | analysis.__init__ | (self, input_object, npoints=0, method='sobol', first=1, output_to_file=False) | Constructor of the analysis class from a problem or population object. Also calls
analysis.sample when npoints>0 or by default when a population object is input.
**USAGE:**
analysis(input_object=prob [, npoints=1000, method='sobol', first=1, output_to_file=False])
* input_object: problem or population object used to initialise the analysis.
* npoints: number of points of the search space to sample. If a population is input,
a random subset of its individuals of size npoints will be sampled. Option npoints=='all' will
sample the whole population. If a problem is input, a set of size npoints will be
selected using the specified method. If set to zero, no sampling will be conducted.
* method: method used to sample the normalized search space. Used only when input_object is a problem, otherwise ignored. Options are:
* 'sobol': sampling based on sobol low-discrepancy sequence. Default option.
* 'faure': sampling based on faure low-discrepancy sequence. Dim [2,23].
* 'halton': sampling based on halton low-discrepancy sequence. Dim <10.
* 'lhs': latin hypersquare sampling.
* 'montecarlo': Monte Carlo (random) sampling.
* first: used only when sampling with 'sobol', 'faure' or 'halton'. Index of the first element
of the sequence that will be included in the sample. Defaults to 1. Set to >1 to skip. If set
to 0 with 'sobol' method, point (0,0,...,0) will also be sampled.
* output_to_file: if True, all outputs generated by this class will be written to the file
log.txt and all plots saved as .png images in the directory ./analysis_X/ which is specified
in attribute analysis.dir. If False, all of them will be shown on screen. | Constructor of the analysis class from a problem or population object. Also calls
analysis.sample when npoints>0 or by default when a population object is input. | [
"Constructor",
"of",
"the",
"analysis",
"class",
"from",
"a",
"problem",
"or",
"population",
"object",
".",
"Also",
"calls",
"analysis",
".",
"sample",
"when",
"npoints",
">",
"0",
"or",
"by",
"default",
"when",
"a",
"population",
"object",
"is",
"input",
"."
] | def __init__(self, input_object, npoints=0, method='sobol', first=1, output_to_file=False):
"""
Constructor of the analysis class from a problem or population object. Also calls
analysis.sample when npoints>0 or by default when a population object is input.
**USAGE:**
analysis(input_object=prob [, npoints=1000, method='sobol', first=1, output_to_file=False])
* input_object: problem or population object used to initialise the analysis.
* npoints: number of points of the search space to sample. If a population is input,
a random subset of its individuals of size npoints will be sampled. Option npoints=='all' will
sample the whole population. If a problem is input, a set of size npoints will be
selected using the specified method. If set to zero, no sampling will be conducted.
* method: method used to sample the normalized search space. Used only when input_object is a problem, otherwise ignored. Options are:
* 'sobol': sampling based on sobol low-discrepancy sequence. Default option.
* 'faure': sampling based on faure low-discrepancy sequence. Dim [2,23].
* 'halton': sampling based on halton low-discrepancy sequence. Dim <10.
* 'lhs': latin hypersquare sampling.
* 'montecarlo': Monte Carlo (random) sampling.
* first: used only when sampling with 'sobol', 'faure' or 'halton'. Index of the first element
of the sequence that will be included in the sample. Defaults to 1. Set to >1 to skip. If set
to 0 with 'sobol' method, point (0,0,...,0) will also be sampled.
* output_to_file: if True, all outputs generated by this class will be written to the file
log.txt and all plots saved as .png images in the directory ./analysis_X/ which is specified
in attribute analysis.dir. If False, all of them will be shown on screen.
"""
self.npoints = 0
self.points = []
self.f = []
self.f_offset = []
self.f_span = []
self.grad_npoints = 0
self.grad_points = []
self.grad = []
self.c = []
self.c_span = []
self.local_nclusters = 0
self.local_initial_npoints = 0
self.dim, self.cont_dim, self.int_dim, self.c_dim, self.ic_dim, self.f_dim = (
0, 0, 0, 0, 0, 0)
self.fignum = 1
self.lin_conv_npairs = 0
self.c_lin_npairs = 0
self.dir = None
if isinstance(input_object, core._core.population):
self.prob = input_object.problem
self.pop = input_object
method = 'pop'
if npoints == 'all':
self.sample(len(self.pop), 'pop')
elif npoints > 0:
self.sample(npoints, 'pop')
elif isinstance(input_object, problem._base):
self.prob = input_object
self.pop = []
if npoints > 0:
self.sample(npoints, method, first)
else:
raise ValueError(
"analysis: input either a problem or a population object to initialise the class")
if output_to_file:
import os
i = 0
while(True):
i += 1
if not os.path.exists('./analysis_' + str(i)):
os.makedirs('./analysis_' + str(i))
self.dir = './analysis_' + str(i)
break
output = open(self.dir + '/log.txt', 'w+')
print(
"===============================================================================", file=output)
print(
" ANALYSIS ", file=output)
print(
"===============================================================================", file=output)
print(
"-------------------------------------------------------------------------------", file=output)
print("PROBLEM PROPERTIES", file=output)
print(
"-------------------------------------------------------------------------------", file=output)
print(self.prob, file=output)
if self.npoints > 0:
print(
"-------------------------------------------------------------------------------", file=output)
print('SAMPLED [' + str(self.npoints) + '] POINTS VIA',
method, 'METHOD FOR THE SUBSEQUENT TESTS', file=output)
output.close() | [
"def",
"__init__",
"(",
"self",
",",
"input_object",
",",
"npoints",
"=",
"0",
",",
"method",
"=",
"'sobol'",
",",
"first",
"=",
"1",
",",
"output_to_file",
"=",
"False",
")",
":",
"self",
".",
"npoints",
"=",
"0",
"self",
".",
"points",
"=",
"[",
"]",
"self",
".",
"f",
"=",
"[",
"]",
"self",
".",
"f_offset",
"=",
"[",
"]",
"self",
".",
"f_span",
"=",
"[",
"]",
"self",
".",
"grad_npoints",
"=",
"0",
"self",
".",
"grad_points",
"=",
"[",
"]",
"self",
".",
"grad",
"=",
"[",
"]",
"self",
".",
"c",
"=",
"[",
"]",
"self",
".",
"c_span",
"=",
"[",
"]",
"self",
".",
"local_nclusters",
"=",
"0",
"self",
".",
"local_initial_npoints",
"=",
"0",
"self",
".",
"dim",
",",
"self",
".",
"cont_dim",
",",
"self",
".",
"int_dim",
",",
"self",
".",
"c_dim",
",",
"self",
".",
"ic_dim",
",",
"self",
".",
"f_dim",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"self",
".",
"fignum",
"=",
"1",
"self",
".",
"lin_conv_npairs",
"=",
"0",
"self",
".",
"c_lin_npairs",
"=",
"0",
"self",
".",
"dir",
"=",
"None",
"if",
"isinstance",
"(",
"input_object",
",",
"core",
".",
"_core",
".",
"population",
")",
":",
"self",
".",
"prob",
"=",
"input_object",
".",
"problem",
"self",
".",
"pop",
"=",
"input_object",
"method",
"=",
"'pop'",
"if",
"npoints",
"==",
"'all'",
":",
"self",
".",
"sample",
"(",
"len",
"(",
"self",
".",
"pop",
")",
",",
"'pop'",
")",
"elif",
"npoints",
">",
"0",
":",
"self",
".",
"sample",
"(",
"npoints",
",",
"'pop'",
")",
"elif",
"isinstance",
"(",
"input_object",
",",
"problem",
".",
"_base",
")",
":",
"self",
".",
"prob",
"=",
"input_object",
"self",
".",
"pop",
"=",
"[",
"]",
"if",
"npoints",
">",
"0",
":",
"self",
".",
"sample",
"(",
"npoints",
",",
"method",
",",
"first",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"analysis: input either a problem or a population object to initialise the class\"",
")",
"if",
"output_to_file",
":",
"import",
"os",
"i",
"=",
"0",
"while",
"(",
"True",
")",
":",
"i",
"+=",
"1",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"'./analysis_'",
"+",
"str",
"(",
"i",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"'./analysis_'",
"+",
"str",
"(",
"i",
")",
")",
"self",
".",
"dir",
"=",
"'./analysis_'",
"+",
"str",
"(",
"i",
")",
"break",
"output",
"=",
"open",
"(",
"self",
".",
"dir",
"+",
"'/log.txt'",
",",
"'w+'",
")",
"print",
"(",
"\"===============================================================================\"",
",",
"file",
"=",
"output",
")",
"print",
"(",
"\" ANALYSIS \"",
",",
"file",
"=",
"output",
")",
"print",
"(",
"\"===============================================================================\"",
",",
"file",
"=",
"output",
")",
"print",
"(",
"\"-------------------------------------------------------------------------------\"",
",",
"file",
"=",
"output",
")",
"print",
"(",
"\"PROBLEM PROPERTIES\"",
",",
"file",
"=",
"output",
")",
"print",
"(",
"\"-------------------------------------------------------------------------------\"",
",",
"file",
"=",
"output",
")",
"print",
"(",
"self",
".",
"prob",
",",
"file",
"=",
"output",
")",
"if",
"self",
".",
"npoints",
">",
"0",
":",
"print",
"(",
"\"-------------------------------------------------------------------------------\"",
",",
"file",
"=",
"output",
")",
"print",
"(",
"'SAMPLED ['",
"+",
"str",
"(",
"self",
".",
"npoints",
")",
"+",
"'] POINTS VIA'",
",",
"method",
",",
"'METHOD FOR THE SUBSEQUENT TESTS'",
",",
"file",
"=",
"output",
")",
"output",
".",
"close",
"(",
")"
] | https://github.com/esa/pagmo/blob/80281d549c8f1b470e1489a5d37c8f06b2e429c0/PyGMO/util/_analysis.py#L15-L105 | ||
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/inputs/outputs.py | python | InputCheckpoint.store | (self, chk) | Stores a CheckpointOutput object. | Stores a CheckpointOutput object. | [
"Stores",
"a",
"CheckpointOutput",
"object",
"."
] | def store(self, chk):
"""Stores a CheckpointOutput object."""
super(InputCheckpoint,self).store(chk.step)
self.stride.store(chk.stride)
self.filename.store(chk.filename)
self.overwrite.store(chk.overwrite) | [
"def",
"store",
"(",
"self",
",",
"chk",
")",
":",
"super",
"(",
"InputCheckpoint",
",",
"self",
")",
".",
"store",
"(",
"chk",
".",
"step",
")",
"self",
".",
"stride",
".",
"store",
"(",
"chk",
".",
"stride",
")",
"self",
".",
"filename",
".",
"store",
"(",
"chk",
".",
"filename",
")",
"self",
".",
"overwrite",
".",
"store",
"(",
"chk",
".",
"overwrite",
")"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/inputs/outputs.py#L217-L223 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/idl/idl/generator.py | python | _CppSourceFileWriter.gen_bson_serializer_method | (self, struct) | Generate the serialize method definition. | Generate the serialize method definition. | [
"Generate",
"the",
"serialize",
"method",
"definition",
"."
] | def gen_bson_serializer_method(self, struct):
# type: (ast.Struct) -> None
"""Generate the serialize method definition."""
struct_type_info = struct_types.get_struct_info(struct)
with self._block('%s {' % (struct_type_info.get_serializer_method().get_definition()), '}'):
self._gen_serializer_methods_common(struct, False) | [
"def",
"gen_bson_serializer_method",
"(",
"self",
",",
"struct",
")",
":",
"# type: (ast.Struct) -> None",
"struct_type_info",
"=",
"struct_types",
".",
"get_struct_info",
"(",
"struct",
")",
"with",
"self",
".",
"_block",
"(",
"'%s {'",
"%",
"(",
"struct_type_info",
".",
"get_serializer_method",
"(",
")",
".",
"get_definition",
"(",
")",
")",
",",
"'}'",
")",
":",
"self",
".",
"_gen_serializer_methods_common",
"(",
"struct",
",",
"False",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/generator.py#L1251-L1258 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/python_gflags/gflags.py | python | _StrOrUnicode | (value) | Converts value to a python string or, if necessary, unicode-string. | Converts value to a python string or, if necessary, unicode-string. | [
"Converts",
"value",
"to",
"a",
"python",
"string",
"or",
"if",
"necessary",
"unicode",
"-",
"string",
"."
] | def _StrOrUnicode(value):
"""Converts value to a python string or, if necessary, unicode-string."""
try:
return str(value)
except UnicodeEncodeError:
return unicode(value) | [
"def",
"_StrOrUnicode",
"(",
"value",
")",
":",
"try",
":",
"return",
"str",
"(",
"value",
")",
"except",
"UnicodeEncodeError",
":",
"return",
"unicode",
"(",
"value",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/python_gflags/gflags.py#L1767-L1772 | ||
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/port/base.py | python | Port.version | (self) | return self._version | Returns a string indicating the version of a given platform, e.g.
'leopard' or 'xp'.
This is used to help identify the exact port when parsing test
expectations, determining search paths, and logging information. | Returns a string indicating the version of a given platform, e.g.
'leopard' or 'xp'. | [
"Returns",
"a",
"string",
"indicating",
"the",
"version",
"of",
"a",
"given",
"platform",
"e",
".",
"g",
".",
"leopard",
"or",
"xp",
"."
] | def version(self):
"""Returns a string indicating the version of a given platform, e.g.
'leopard' or 'xp'.
This is used to help identify the exact port when parsing test
expectations, determining search paths, and logging information."""
return self._version | [
"def",
"version",
"(",
"self",
")",
":",
"return",
"self",
".",
"_version"
] | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/port/base.py#L737-L743 | |
alexgkendall/caffe-segnet | 344c113bf1832886f1cbe9f33ffe28a3beeaf412 | python/caffe/draw.py | python | get_pooling_types_dict | () | return d | Get dictionary mapping pooling type number to type name | Get dictionary mapping pooling type number to type name | [
"Get",
"dictionary",
"mapping",
"pooling",
"type",
"number",
"to",
"type",
"name"
] | def get_pooling_types_dict():
"""Get dictionary mapping pooling type number to type name
"""
desc = caffe_pb2.PoolingParameter.PoolMethod.DESCRIPTOR
d = {}
for k, v in desc.values_by_name.items():
d[v.number] = k
return d | [
"def",
"get_pooling_types_dict",
"(",
")",
":",
"desc",
"=",
"caffe_pb2",
".",
"PoolingParameter",
".",
"PoolMethod",
".",
"DESCRIPTOR",
"d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"desc",
".",
"values_by_name",
".",
"items",
"(",
")",
":",
"d",
"[",
"v",
".",
"number",
"]",
"=",
"k",
"return",
"d"
] | https://github.com/alexgkendall/caffe-segnet/blob/344c113bf1832886f1cbe9f33ffe28a3beeaf412/python/caffe/draw.py#L27-L34 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/ccompiler.py | python | CCompiler.undefine_macro | (self, name) | Undefine a preprocessor macro for all compilations driven by
this compiler object. If the same macro is defined by
'define_macro()' and undefined by 'undefine_macro()' the last call
takes precedence (including multiple redefinitions or
undefinitions). If the macro is redefined/undefined on a
per-compilation basis (ie. in the call to 'compile()'), then that
takes precedence. | Undefine a preprocessor macro for all compilations driven by
this compiler object. If the same macro is defined by
'define_macro()' and undefined by 'undefine_macro()' the last call
takes precedence (including multiple redefinitions or
undefinitions). If the macro is redefined/undefined on a
per-compilation basis (ie. in the call to 'compile()'), then that
takes precedence. | [
"Undefine",
"a",
"preprocessor",
"macro",
"for",
"all",
"compilations",
"driven",
"by",
"this",
"compiler",
"object",
".",
"If",
"the",
"same",
"macro",
"is",
"defined",
"by",
"define_macro",
"()",
"and",
"undefined",
"by",
"undefine_macro",
"()",
"the",
"last",
"call",
"takes",
"precedence",
"(",
"including",
"multiple",
"redefinitions",
"or",
"undefinitions",
")",
".",
"If",
"the",
"macro",
"is",
"redefined",
"/",
"undefined",
"on",
"a",
"per",
"-",
"compilation",
"basis",
"(",
"ie",
".",
"in",
"the",
"call",
"to",
"compile",
"()",
")",
"then",
"that",
"takes",
"precedence",
"."
] | def undefine_macro(self, name):
"""Undefine a preprocessor macro for all compilations driven by
this compiler object. If the same macro is defined by
'define_macro()' and undefined by 'undefine_macro()' the last call
takes precedence (including multiple redefinitions or
undefinitions). If the macro is redefined/undefined on a
per-compilation basis (ie. in the call to 'compile()'), then that
takes precedence.
"""
# Delete from the list of macro definitions/undefinitions if
# already there (so that this one will take precedence).
i = self._find_macro (name)
if i is not None:
del self.macros[i]
undefn = (name,)
self.macros.append (undefn) | [
"def",
"undefine_macro",
"(",
"self",
",",
"name",
")",
":",
"# Delete from the list of macro definitions/undefinitions if",
"# already there (so that this one will take precedence).",
"i",
"=",
"self",
".",
"_find_macro",
"(",
"name",
")",
"if",
"i",
"is",
"not",
"None",
":",
"del",
"self",
".",
"macros",
"[",
"i",
"]",
"undefn",
"=",
"(",
"name",
",",
")",
"self",
".",
"macros",
".",
"append",
"(",
"undefn",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/ccompiler.py#L211-L227 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/fftpack/basic.py | python | ifft2 | (x, shape=None, axes=(-2,-1), overwrite_x=False) | return ifftn(x,shape,axes,overwrite_x) | 2-D discrete inverse Fourier transform of real or complex sequence.
Return inverse two-dimensional discrete Fourier transform of
arbitrary type sequence x.
See `ifft` for more information.
See also
--------
fft2, ifft | 2-D discrete inverse Fourier transform of real or complex sequence. | [
"2",
"-",
"D",
"discrete",
"inverse",
"Fourier",
"transform",
"of",
"real",
"or",
"complex",
"sequence",
"."
] | def ifft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
"""
2-D discrete inverse Fourier transform of real or complex sequence.
Return inverse two-dimensional discrete Fourier transform of
arbitrary type sequence x.
See `ifft` for more information.
See also
--------
fft2, ifft
"""
return ifftn(x,shape,axes,overwrite_x) | [
"def",
"ifft2",
"(",
"x",
",",
"shape",
"=",
"None",
",",
"axes",
"=",
"(",
"-",
"2",
",",
"-",
"1",
")",
",",
"overwrite_x",
"=",
"False",
")",
":",
"return",
"ifftn",
"(",
"x",
",",
"shape",
",",
"axes",
",",
"overwrite_x",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/fftpack/basic.py#L651-L665 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/numpy/math_ops.py | python | exp | (x, dtype=None) | return _apply_tensor_op(F.tensor_exp, x, dtype=dtype) | Calculates the exponential of all elements in the input array.
Note:
Numpy arguments `casting`, `order`, `subok`, `signature`, and `extobj` are
not supported.
When `where` is provided, `out` must have a tensor value. `out` is not supported
for storing the result, however it can be used in combination with `where` to set
the value at indices for which `where` is set to False.
On GPU, the supported dtypes are np.float16, and np.float32.
On CPU, the supported dtypes are np.float16, np.float32, np.float64.
Args:
x (Tensor): input data.
dtype (:class:`mindspore.dtype`, optional): Defaults to None. Overrides the dtype of the
output Tensor.
Returns:
Tensor or scalar, element-wise exponential of `x`. This is a scalar if both
`x1` and `x2` are scalars.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.numpy as np
>>> output = np.exp(np.arange(5).astype(np.float32))
>>> print(output)
[ 1. 2.718282 7.3890557 20.085537 54.598145 ] | Calculates the exponential of all elements in the input array. | [
"Calculates",
"the",
"exponential",
"of",
"all",
"elements",
"in",
"the",
"input",
"array",
"."
] | def exp(x, dtype=None):
"""
Calculates the exponential of all elements in the input array.
Note:
Numpy arguments `casting`, `order`, `subok`, `signature`, and `extobj` are
not supported.
When `where` is provided, `out` must have a tensor value. `out` is not supported
for storing the result, however it can be used in combination with `where` to set
the value at indices for which `where` is set to False.
On GPU, the supported dtypes are np.float16, and np.float32.
On CPU, the supported dtypes are np.float16, np.float32, np.float64.
Args:
x (Tensor): input data.
dtype (:class:`mindspore.dtype`, optional): Defaults to None. Overrides the dtype of the
output Tensor.
Returns:
Tensor or scalar, element-wise exponential of `x`. This is a scalar if both
`x1` and `x2` are scalars.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.numpy as np
>>> output = np.exp(np.arange(5).astype(np.float32))
>>> print(output)
[ 1. 2.718282 7.3890557 20.085537 54.598145 ]
"""
return _apply_tensor_op(F.tensor_exp, x, dtype=dtype) | [
"def",
"exp",
"(",
"x",
",",
"dtype",
"=",
"None",
")",
":",
"return",
"_apply_tensor_op",
"(",
"F",
".",
"tensor_exp",
",",
"x",
",",
"dtype",
"=",
"dtype",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/math_ops.py#L1780-L1811 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/aui.py | python | AuiTabContainer.GetFlags | (*args, **kwargs) | return _aui.AuiTabContainer_GetFlags(*args, **kwargs) | GetFlags(self) -> int | GetFlags(self) -> int | [
"GetFlags",
"(",
"self",
")",
"-",
">",
"int"
] | def GetFlags(*args, **kwargs):
"""GetFlags(self) -> int"""
return _aui.AuiTabContainer_GetFlags(*args, **kwargs) | [
"def",
"GetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiTabContainer_GetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L1141-L1143 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | site_scons/site_tools/auto_install_binaries.py | python | list_components | (env, **kwargs) | List registered components for env. | List registered components for env. | [
"List",
"registered",
"components",
"for",
"env",
"."
] | def list_components(env, **kwargs):
"""List registered components for env."""
print("Known AIB components:")
for key in env[ALIAS_MAP]:
print("\t", key) | [
"def",
"list_components",
"(",
"env",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"\"Known AIB components:\"",
")",
"for",
"key",
"in",
"env",
"[",
"ALIAS_MAP",
"]",
":",
"print",
"(",
"\"\\t\"",
",",
"key",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/site_scons/site_tools/auto_install_binaries.py#L532-L536 | ||
PaddlePaddle/PaddleOCR | b756bf5f8c90142e0d89d3db0163965c686b6ffe | ppstructure/table/tablepyxl/tablepyxl.py | python | document_to_workbook | (doc, wb=None, base_url=None) | return wb | Takes a string representation of an html document and writes one sheet for
every table in the document.
The workbook is returned | Takes a string representation of an html document and writes one sheet for
every table in the document.
The workbook is returned | [
"Takes",
"a",
"string",
"representation",
"of",
"an",
"html",
"document",
"and",
"writes",
"one",
"sheet",
"for",
"every",
"table",
"in",
"the",
"document",
".",
"The",
"workbook",
"is",
"returned"
] | def document_to_workbook(doc, wb=None, base_url=None):
"""
Takes a string representation of an html document and writes one sheet for
every table in the document.
The workbook is returned
"""
if not wb:
wb = Workbook()
wb.remove(wb.active)
inline_styles_doc = Premailer(doc, base_url=base_url, remove_classes=False).transform()
tables = get_Tables(inline_styles_doc)
for table in tables:
table_to_sheet(table, wb)
return wb | [
"def",
"document_to_workbook",
"(",
"doc",
",",
"wb",
"=",
"None",
",",
"base_url",
"=",
"None",
")",
":",
"if",
"not",
"wb",
":",
"wb",
"=",
"Workbook",
"(",
")",
"wb",
".",
"remove",
"(",
"wb",
".",
"active",
")",
"inline_styles_doc",
"=",
"Premailer",
"(",
"doc",
",",
"base_url",
"=",
"base_url",
",",
"remove_classes",
"=",
"False",
")",
".",
"transform",
"(",
")",
"tables",
"=",
"get_Tables",
"(",
"inline_styles_doc",
")",
"for",
"table",
"in",
"tables",
":",
"table_to_sheet",
"(",
"table",
",",
"wb",
")",
"return",
"wb"
] | https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppstructure/table/tablepyxl/tablepyxl.py#L77-L93 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/google_appengine_cloudstorage/cloudstorage/common.py | python | dt_str_to_posix | (dt_str) | return calendar.timegm(dt.utctimetuple()) | format str to posix.
datetime str is of format %Y-%m-%dT%H:%M:%S.%fZ,
e.g. 2013-04-12T00:22:27.978Z. According to ISO 8601, T is a separator
between date and time when they are on the same line.
Z indicates UTC (zero meridian).
A pointer: http://www.cl.cam.ac.uk/~mgk25/iso-time.html
This is used to parse LastModified node from GCS's GET bucket XML response.
Args:
dt_str: A datetime str.
Returns:
A float of secs from unix epoch. By posix definition, epoch is midnight
1970/1/1 UTC. | format str to posix. | [
"format",
"str",
"to",
"posix",
"."
] | def dt_str_to_posix(dt_str):
"""format str to posix.
datetime str is of format %Y-%m-%dT%H:%M:%S.%fZ,
e.g. 2013-04-12T00:22:27.978Z. According to ISO 8601, T is a separator
between date and time when they are on the same line.
Z indicates UTC (zero meridian).
A pointer: http://www.cl.cam.ac.uk/~mgk25/iso-time.html
This is used to parse LastModified node from GCS's GET bucket XML response.
Args:
dt_str: A datetime str.
Returns:
A float of secs from unix epoch. By posix definition, epoch is midnight
1970/1/1 UTC.
"""
parsable, _ = dt_str.split('.')
dt = datetime.datetime.strptime(parsable, _DT_FORMAT)
return calendar.timegm(dt.utctimetuple()) | [
"def",
"dt_str_to_posix",
"(",
"dt_str",
")",
":",
"parsable",
",",
"_",
"=",
"dt_str",
".",
"split",
"(",
"'.'",
")",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"parsable",
",",
"_DT_FORMAT",
")",
"return",
"calendar",
".",
"timegm",
"(",
"dt",
".",
"utctimetuple",
"(",
")",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/google_appengine_cloudstorage/cloudstorage/common.py#L327-L348 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/NinjaWriter.py | python | NinjaWriter._GetSortedXcodeEnv | (self, additional_settings=None) | return gyp.xcode_emulation.GetSortedXcodeEnv(self.xcode_settings, self.abs_build_dir, path, self.config_name, additional_settings) | Returns the variables Xcode would set for build steps. | Returns the variables Xcode would set for build steps. | [
"Returns",
"the",
"variables",
"Xcode",
"would",
"set",
"for",
"build",
"steps",
"."
] | def _GetSortedXcodeEnv(self, additional_settings=None):
"""Returns the variables Xcode would set for build steps."""
assert self.abs_build_dir
path = os.path.join(self.abs_build_dir, self.build_to_base)
return gyp.xcode_emulation.GetSortedXcodeEnv(self.xcode_settings, self.abs_build_dir, path, self.config_name, additional_settings) | [
"def",
"_GetSortedXcodeEnv",
"(",
"self",
",",
"additional_settings",
"=",
"None",
")",
":",
"assert",
"self",
".",
"abs_build_dir",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"abs_build_dir",
",",
"self",
".",
"build_to_base",
")",
"return",
"gyp",
".",
"xcode_emulation",
".",
"GetSortedXcodeEnv",
"(",
"self",
".",
"xcode_settings",
",",
"self",
".",
"abs_build_dir",
",",
"path",
",",
"self",
".",
"config_name",
",",
"additional_settings",
")"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/NinjaWriter.py#L1024-L1028 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/value.py | python | TypeRef.name | (self) | return ffi.ret_string(ffi.lib.LLVMPY_GetTypeName(self)) | Get type name | Get type name | [
"Get",
"type",
"name"
] | def name(self):
"""
Get type name
"""
return ffi.ret_string(ffi.lib.LLVMPY_GetTypeName(self)) | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"ffi",
".",
"ret_string",
"(",
"ffi",
".",
"lib",
".",
"LLVMPY_GetTypeName",
"(",
"self",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/binding/value.py#L50-L54 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/impl/broadcast_manager.py | python | BroadcastManager.unregisterSubscriber | (self, name, topic, uri) | return 1, "unregisterSubscriber" ,0 | unregisterSubscriber | unregisterSubscriber | [
"unregisterSubscriber"
] | def unregisterSubscriber(self, name, topic, uri):
"""
unregisterSubscriber
"""
data = self._generate_message("unregisterSubscriber")
data[NODE_NAME] = name
data[TOPIC_NAME] = topic
data[TOPIC_URI] = uri
self._send(self._encode(data))
try:
self._subs[topic].remove(data[XMLRPC_URI])
except KeyError:
pass
return 1, "unregisterSubscriber" ,0 | [
"def",
"unregisterSubscriber",
"(",
"self",
",",
"name",
",",
"topic",
",",
"uri",
")",
":",
"data",
"=",
"self",
".",
"_generate_message",
"(",
"\"unregisterSubscriber\"",
")",
"data",
"[",
"NODE_NAME",
"]",
"=",
"name",
"data",
"[",
"TOPIC_NAME",
"]",
"=",
"topic",
"data",
"[",
"TOPIC_URI",
"]",
"=",
"uri",
"self",
".",
"_send",
"(",
"self",
".",
"_encode",
"(",
"data",
")",
")",
"try",
":",
"self",
".",
"_subs",
"[",
"topic",
"]",
".",
"remove",
"(",
"data",
"[",
"XMLRPC_URI",
"]",
")",
"except",
"KeyError",
":",
"pass",
"return",
"1",
",",
"\"unregisterSubscriber\"",
",",
"0"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/broadcast_manager.py#L259-L272 | |
plaidml/plaidml | f3c6681db21460e5fdc11ae651d6d7b6c27f8262 | cmake/git-clang-format.py | python | run_clang_format_and_save_to_tree | (changed_lines,
revision=None,
binary='clang-format',
style=None) | return create_tree(index_info_generator(), '--index-info') | Run clang-format on each file and save the result to a git tree.
Returns the object ID (SHA-1) of the created tree. | Run clang-format on each file and save the result to a git tree. | [
"Run",
"clang",
"-",
"format",
"on",
"each",
"file",
"and",
"save",
"the",
"result",
"to",
"a",
"git",
"tree",
"."
] | def run_clang_format_and_save_to_tree(changed_lines,
revision=None,
binary='clang-format',
style=None):
"""Run clang-format on each file and save the result to a git tree.
Returns the object ID (SHA-1) of the created tree."""
def iteritems(container):
try:
return container.iteritems() # Python 2
except AttributeError:
return container.items() # Python 3
def index_info_generator():
for filename, line_ranges in iteritems(changed_lines):
if revision:
git_metadata_cmd = [
'git', 'ls-tree',
'%s:%s' % (revision, os.path.dirname(filename)),
os.path.basename(filename)
]
git_metadata = subprocess.Popen(git_metadata_cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
stdout = git_metadata.communicate()[0]
mode = oct(int(stdout.split()[0], 8))
else:
mode = oct(os.stat(filename).st_mode)
# Adjust python3 octal format so that it matches what git expects
if mode.startswith('0o'):
mode = '0' + mode[2:]
blob_id = clang_format_to_blob(filename,
line_ranges,
revision=revision,
binary=binary,
style=style)
yield '%s %s\t%s' % (mode, blob_id, filename)
return create_tree(index_info_generator(), '--index-info') | [
"def",
"run_clang_format_and_save_to_tree",
"(",
"changed_lines",
",",
"revision",
"=",
"None",
",",
"binary",
"=",
"'clang-format'",
",",
"style",
"=",
"None",
")",
":",
"def",
"iteritems",
"(",
"container",
")",
":",
"try",
":",
"return",
"container",
".",
"iteritems",
"(",
")",
"# Python 2",
"except",
"AttributeError",
":",
"return",
"container",
".",
"items",
"(",
")",
"# Python 3",
"def",
"index_info_generator",
"(",
")",
":",
"for",
"filename",
",",
"line_ranges",
"in",
"iteritems",
"(",
"changed_lines",
")",
":",
"if",
"revision",
":",
"git_metadata_cmd",
"=",
"[",
"'git'",
",",
"'ls-tree'",
",",
"'%s:%s'",
"%",
"(",
"revision",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
")",
",",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"]",
"git_metadata",
"=",
"subprocess",
".",
"Popen",
"(",
"git_metadata_cmd",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"stdout",
"=",
"git_metadata",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"mode",
"=",
"oct",
"(",
"int",
"(",
"stdout",
".",
"split",
"(",
")",
"[",
"0",
"]",
",",
"8",
")",
")",
"else",
":",
"mode",
"=",
"oct",
"(",
"os",
".",
"stat",
"(",
"filename",
")",
".",
"st_mode",
")",
"# Adjust python3 octal format so that it matches what git expects",
"if",
"mode",
".",
"startswith",
"(",
"'0o'",
")",
":",
"mode",
"=",
"'0'",
"+",
"mode",
"[",
"2",
":",
"]",
"blob_id",
"=",
"clang_format_to_blob",
"(",
"filename",
",",
"line_ranges",
",",
"revision",
"=",
"revision",
",",
"binary",
"=",
"binary",
",",
"style",
"=",
"style",
")",
"yield",
"'%s %s\\t%s'",
"%",
"(",
"mode",
",",
"blob_id",
",",
"filename",
")",
"return",
"create_tree",
"(",
"index_info_generator",
"(",
")",
",",
"'--index-info'",
")"
] | https://github.com/plaidml/plaidml/blob/f3c6681db21460e5fdc11ae651d6d7b6c27f8262/cmake/git-clang-format.py#L357-L396 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/rnn/python/ops/lstm_ops.py | python | _block_lstm | (seq_len_max,
x,
w,
b,
cs_prev=None,
h_prev=None,
wci=None,
wcf=None,
wco=None,
forget_bias=None,
cell_clip=None,
use_peephole=None,
name=None) | return array_ops.unpack(i), array_ops.unpack(cs), array_ops.unpack(
f), array_ops.unpack(o), array_ops.unpack(ci), array_ops.unpack(
co), array_ops.unpack(h) | r"""TODO(williamchan): add doc.
Args:
seq_len_max: A `Tensor` of type `int64`.
x: A list of at least 1 `Tensor` objects of the same type in: `float32`.
w: A `Tensor`. Must have the same type as `x`.
b: A `Tensor`. Must have the same type as `x`.
cs_prev: A `Tensor`. Must have the same type as `x`.
h_prev: A `Tensor`. Must have the same type as `x`.
wci: A `Tensor`. Must have the same type as `x`.
wcf: A `Tensor`. Must have the same type as `x`.
wco: A `Tensor`. Must have the same type as `x`.
forget_bias: An optional `float`. Defaults to `1`.
cell_clip: An optional `float`. Defaults to `3`.
use_peephole: An optional `bool`. Defaults to `False`.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (i, cs, f, o, ci, co, h).
i: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
cs: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
f: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
o: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
ci: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
co: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
h: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
Raises:
ValueError: If `b` does not have a valid shape. | r"""TODO(williamchan): add doc. | [
"r",
"TODO",
"(",
"williamchan",
")",
":",
"add",
"doc",
"."
] | def _block_lstm(seq_len_max,
x,
w,
b,
cs_prev=None,
h_prev=None,
wci=None,
wcf=None,
wco=None,
forget_bias=None,
cell_clip=None,
use_peephole=None,
name=None):
r"""TODO(williamchan): add doc.
Args:
seq_len_max: A `Tensor` of type `int64`.
x: A list of at least 1 `Tensor` objects of the same type in: `float32`.
w: A `Tensor`. Must have the same type as `x`.
b: A `Tensor`. Must have the same type as `x`.
cs_prev: A `Tensor`. Must have the same type as `x`.
h_prev: A `Tensor`. Must have the same type as `x`.
wci: A `Tensor`. Must have the same type as `x`.
wcf: A `Tensor`. Must have the same type as `x`.
wco: A `Tensor`. Must have the same type as `x`.
forget_bias: An optional `float`. Defaults to `1`.
cell_clip: An optional `float`. Defaults to `3`.
use_peephole: An optional `bool`. Defaults to `False`.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (i, cs, f, o, ci, co, h).
i: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
cs: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
f: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
o: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
ci: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
co: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
h: A list with the same number of `Tensor` objects as `x` of `Tensor`
objects of the same type as x.
Raises:
ValueError: If `b` does not have a valid shape.
"""
batch_size = x[0].get_shape().with_rank(2)[0].value
cell_size4 = b.get_shape().with_rank(1)[0].value
if cell_size4 is None:
raise ValueError("`b` shape must not be None.")
cell_size = cell_size4 / 4
zero_state = None
if cs_prev is None or h_prev is None:
zero_state = array_ops.constant(
0, dtype=dtypes.float32, shape=[batch_size, cell_size])
if cs_prev is None:
cs_prev = zero_state
if h_prev is None:
h_prev = zero_state
if wci is None:
wci = array_ops.constant(0, dtype=dtypes.float32, shape=[cell_size])
wco = wci
wcf = wci
# pylint: disable=protected-access
i, cs, f, o, ci, co, h = _lstm_ops_so.block_lstm(
seq_len_max=seq_len_max,
x=array_ops.pack(x),
cs_prev=cs_prev,
h_prev=h_prev,
w=w,
wci=wci,
wco=wco,
wcf=wcf,
b=b,
forget_bias=forget_bias,
cell_clip=cell_clip,
name=name,
use_peephole=use_peephole)
return array_ops.unpack(i), array_ops.unpack(cs), array_ops.unpack(
f), array_ops.unpack(o), array_ops.unpack(ci), array_ops.unpack(
co), array_ops.unpack(h) | [
"def",
"_block_lstm",
"(",
"seq_len_max",
",",
"x",
",",
"w",
",",
"b",
",",
"cs_prev",
"=",
"None",
",",
"h_prev",
"=",
"None",
",",
"wci",
"=",
"None",
",",
"wcf",
"=",
"None",
",",
"wco",
"=",
"None",
",",
"forget_bias",
"=",
"None",
",",
"cell_clip",
"=",
"None",
",",
"use_peephole",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"batch_size",
"=",
"x",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"2",
")",
"[",
"0",
"]",
".",
"value",
"cell_size4",
"=",
"b",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"1",
")",
"[",
"0",
"]",
".",
"value",
"if",
"cell_size4",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"`b` shape must not be None.\"",
")",
"cell_size",
"=",
"cell_size4",
"/",
"4",
"zero_state",
"=",
"None",
"if",
"cs_prev",
"is",
"None",
"or",
"h_prev",
"is",
"None",
":",
"zero_state",
"=",
"array_ops",
".",
"constant",
"(",
"0",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
",",
"shape",
"=",
"[",
"batch_size",
",",
"cell_size",
"]",
")",
"if",
"cs_prev",
"is",
"None",
":",
"cs_prev",
"=",
"zero_state",
"if",
"h_prev",
"is",
"None",
":",
"h_prev",
"=",
"zero_state",
"if",
"wci",
"is",
"None",
":",
"wci",
"=",
"array_ops",
".",
"constant",
"(",
"0",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
",",
"shape",
"=",
"[",
"cell_size",
"]",
")",
"wco",
"=",
"wci",
"wcf",
"=",
"wci",
"# pylint: disable=protected-access",
"i",
",",
"cs",
",",
"f",
",",
"o",
",",
"ci",
",",
"co",
",",
"h",
"=",
"_lstm_ops_so",
".",
"block_lstm",
"(",
"seq_len_max",
"=",
"seq_len_max",
",",
"x",
"=",
"array_ops",
".",
"pack",
"(",
"x",
")",
",",
"cs_prev",
"=",
"cs_prev",
",",
"h_prev",
"=",
"h_prev",
",",
"w",
"=",
"w",
",",
"wci",
"=",
"wci",
",",
"wco",
"=",
"wco",
",",
"wcf",
"=",
"wcf",
",",
"b",
"=",
"b",
",",
"forget_bias",
"=",
"forget_bias",
",",
"cell_clip",
"=",
"cell_clip",
",",
"name",
"=",
"name",
",",
"use_peephole",
"=",
"use_peephole",
")",
"return",
"array_ops",
".",
"unpack",
"(",
"i",
")",
",",
"array_ops",
".",
"unpack",
"(",
"cs",
")",
",",
"array_ops",
".",
"unpack",
"(",
"f",
")",
",",
"array_ops",
".",
"unpack",
"(",
"o",
")",
",",
"array_ops",
".",
"unpack",
"(",
"ci",
")",
",",
"array_ops",
".",
"unpack",
"(",
"co",
")",
",",
"array_ops",
".",
"unpack",
"(",
"h",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/rnn/python/ops/lstm_ops.py#L140-L226 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/dygraph/dygraph_to_static/function_spec.py | python | get_buffers | (layer_instance, include_sublayer=True) | return buffers | Returns Variable buffers of decorated layers. If set `include_sublayer` True,
the Variable buffers created in sub layers will be added. | Returns Variable buffers of decorated layers. If set `include_sublayer` True,
the Variable buffers created in sub layers will be added. | [
"Returns",
"Variable",
"buffers",
"of",
"decorated",
"layers",
".",
"If",
"set",
"include_sublayer",
"True",
"the",
"Variable",
"buffers",
"created",
"in",
"sub",
"layers",
"will",
"be",
"added",
"."
] | def get_buffers(layer_instance, include_sublayer=True):
"""
Returns Variable buffers of decorated layers. If set `include_sublayer` True,
the Variable buffers created in sub layers will be added.
"""
buffers = collections.OrderedDict()
if layer_instance is not None:
if isinstance(layer_instance, layers.Layer):
if include_sublayer:
buffers = layer_instance.buffers()
names = [buffer.name for buffer in buffers]
buffers = collections.OrderedDict(zip(names, buffers))
else:
buffers = layer_instance._buffers
else:
raise TypeError(
"Type of `layer_instance` should be nn.Layer, but received {}".
format(type_name(layer_instance)))
return buffers | [
"def",
"get_buffers",
"(",
"layer_instance",
",",
"include_sublayer",
"=",
"True",
")",
":",
"buffers",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"if",
"layer_instance",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"layer_instance",
",",
"layers",
".",
"Layer",
")",
":",
"if",
"include_sublayer",
":",
"buffers",
"=",
"layer_instance",
".",
"buffers",
"(",
")",
"names",
"=",
"[",
"buffer",
".",
"name",
"for",
"buffer",
"in",
"buffers",
"]",
"buffers",
"=",
"collections",
".",
"OrderedDict",
"(",
"zip",
"(",
"names",
",",
"buffers",
")",
")",
"else",
":",
"buffers",
"=",
"layer_instance",
".",
"_buffers",
"else",
":",
"raise",
"TypeError",
"(",
"\"Type of `layer_instance` should be nn.Layer, but received {}\"",
".",
"format",
"(",
"type_name",
"(",
"layer_instance",
")",
")",
")",
"return",
"buffers"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dygraph/dygraph_to_static/function_spec.py#L252-L270 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PropertyGridInterface.AutoFill | (self,obj,parent=None) | Clears properties and re-fills to match members and\nvalues of | Clears properties and re-fills to match members and\nvalues of | [
"Clears",
"properties",
"and",
"re",
"-",
"fills",
"to",
"match",
"members",
"and",
"\\",
"nvalues",
"of"
] | def AutoFill(self,obj,parent=None):
"Clears properties and re-fills to match members and\nvalues of "
"given object or dictionary obj."
self.edited_objects[parent] = obj
cur_page = False
is_manager = isinstance(self,PropertyGridManager)
if not parent:
if is_manager:
page = self.GetCurrentPage()
page.Clear()
parent = page.GetRoot()
else:
self.Clear()
parent = self.GetGrid().GetRoot()
else:
it = self.GetIterator(PG_ITERATE_PROPERTIES, parent)
it.Next() # Skip the parent
while not it.AtEnd():
p = it.GetProperty()
if not p.IsSomeParent(parent):
break
self.DeleteProperty(p)
name = p.GetName()
it.Next()
if not is_manager or page == self.GetCurrentPage():
self.Freeze()
cur_page = True
try:
self._AutoFillMany(parent,obj.__dict__)
except:
import traceback
traceback.print_exc()
if cur_page:
self.Thaw() | [
"def",
"AutoFill",
"(",
"self",
",",
"obj",
",",
"parent",
"=",
"None",
")",
":",
"\"given object or dictionary obj.\"",
"self",
".",
"edited_objects",
"[",
"parent",
"]",
"=",
"obj",
"cur_page",
"=",
"False",
"is_manager",
"=",
"isinstance",
"(",
"self",
",",
"PropertyGridManager",
")",
"if",
"not",
"parent",
":",
"if",
"is_manager",
":",
"page",
"=",
"self",
".",
"GetCurrentPage",
"(",
")",
"page",
".",
"Clear",
"(",
")",
"parent",
"=",
"page",
".",
"GetRoot",
"(",
")",
"else",
":",
"self",
".",
"Clear",
"(",
")",
"parent",
"=",
"self",
".",
"GetGrid",
"(",
")",
".",
"GetRoot",
"(",
")",
"else",
":",
"it",
"=",
"self",
".",
"GetIterator",
"(",
"PG_ITERATE_PROPERTIES",
",",
"parent",
")",
"it",
".",
"Next",
"(",
")",
"# Skip the parent",
"while",
"not",
"it",
".",
"AtEnd",
"(",
")",
":",
"p",
"=",
"it",
".",
"GetProperty",
"(",
")",
"if",
"not",
"p",
".",
"IsSomeParent",
"(",
"parent",
")",
":",
"break",
"self",
".",
"DeleteProperty",
"(",
"p",
")",
"name",
"=",
"p",
".",
"GetName",
"(",
")",
"it",
".",
"Next",
"(",
")",
"if",
"not",
"is_manager",
"or",
"page",
"==",
"self",
".",
"GetCurrentPage",
"(",
")",
":",
"self",
".",
"Freeze",
"(",
")",
"cur_page",
"=",
"True",
"try",
":",
"self",
".",
"_AutoFillMany",
"(",
"parent",
",",
"obj",
".",
"__dict__",
")",
"except",
":",
"import",
"traceback",
"traceback",
".",
"print_exc",
"(",
")",
"if",
"cur_page",
":",
"self",
".",
"Thaw",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L1660-L1701 | ||
nvdla/sw | 79538ba1b52b040a4a4645f630e457fa01839e90 | umd/external/protobuf-2.6/python/google/protobuf/internal/containers.py | python | RepeatedCompositeFieldContainer.__delslice__ | (self, start, stop) | Deletes the subset of items from between the specified indices. | Deletes the subset of items from between the specified indices. | [
"Deletes",
"the",
"subset",
"of",
"items",
"from",
"between",
"the",
"specified",
"indices",
"."
] | def __delslice__(self, start, stop):
"""Deletes the subset of items from between the specified indices."""
del self._values[start:stop]
self._message_listener.Modified() | [
"def",
"__delslice__",
"(",
"self",
",",
"start",
",",
"stop",
")",
":",
"del",
"self",
".",
"_values",
"[",
"start",
":",
"stop",
"]",
"self",
".",
"_message_listener",
".",
"Modified",
"(",
")"
] | https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/internal/containers.py#L257-L260 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/numbers.py | python | Real.__le__ | (self, other) | self <= other | self <= other | [
"self",
"<",
"=",
"other"
] | def __le__(self, other):
"""self <= other"""
raise NotImplementedError | [
"def",
"__le__",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/numbers.py#L244-L246 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/packaging/rpm.py | python | SimpleTagCompiler.compile | (self, values) | return str | Compiles the tagset and returns a str containing the result | Compiles the tagset and returns a str containing the result | [
"Compiles",
"the",
"tagset",
"and",
"returns",
"a",
"str",
"containing",
"the",
"result"
] | def compile(self, values):
""" Compiles the tagset and returns a str containing the result
"""
def is_international(tag):
return tag.endswith('_')
def get_country_code(tag):
return tag[-2:]
def strip_country_code(tag):
return tag[:-2]
replacements = list(self.tagset.items())
str = ""
domestic = [t for t in replacements if not is_international(t[0])]
for key, replacement in domestic:
try:
str = str + replacement % values[key]
except KeyError, e:
if self.mandatory:
raise e
international = [t for t in replacements if is_international(t[0])]
for key, replacement in international:
try:
x = [t for t in values.items() if strip_country_code(t[0]) == key]
int_values_for_key = [(get_country_code(t[0]),t[1]) for t in x]
for v in int_values_for_key:
str = str + replacement % v
except KeyError, e:
if self.mandatory:
raise e
return str | [
"def",
"compile",
"(",
"self",
",",
"values",
")",
":",
"def",
"is_international",
"(",
"tag",
")",
":",
"return",
"tag",
".",
"endswith",
"(",
"'_'",
")",
"def",
"get_country_code",
"(",
"tag",
")",
":",
"return",
"tag",
"[",
"-",
"2",
":",
"]",
"def",
"strip_country_code",
"(",
"tag",
")",
":",
"return",
"tag",
"[",
":",
"-",
"2",
"]",
"replacements",
"=",
"list",
"(",
"self",
".",
"tagset",
".",
"items",
"(",
")",
")",
"str",
"=",
"\"\"",
"domestic",
"=",
"[",
"t",
"for",
"t",
"in",
"replacements",
"if",
"not",
"is_international",
"(",
"t",
"[",
"0",
"]",
")",
"]",
"for",
"key",
",",
"replacement",
"in",
"domestic",
":",
"try",
":",
"str",
"=",
"str",
"+",
"replacement",
"%",
"values",
"[",
"key",
"]",
"except",
"KeyError",
",",
"e",
":",
"if",
"self",
".",
"mandatory",
":",
"raise",
"e",
"international",
"=",
"[",
"t",
"for",
"t",
"in",
"replacements",
"if",
"is_international",
"(",
"t",
"[",
"0",
"]",
")",
"]",
"for",
"key",
",",
"replacement",
"in",
"international",
":",
"try",
":",
"x",
"=",
"[",
"t",
"for",
"t",
"in",
"values",
".",
"items",
"(",
")",
"if",
"strip_country_code",
"(",
"t",
"[",
"0",
"]",
")",
"==",
"key",
"]",
"int_values_for_key",
"=",
"[",
"(",
"get_country_code",
"(",
"t",
"[",
"0",
"]",
")",
",",
"t",
"[",
"1",
"]",
")",
"for",
"t",
"in",
"x",
"]",
"for",
"v",
"in",
"int_values_for_key",
":",
"str",
"=",
"str",
"+",
"replacement",
"%",
"v",
"except",
"KeyError",
",",
"e",
":",
"if",
"self",
".",
"mandatory",
":",
"raise",
"e",
"return",
"str"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/packaging/rpm.py#L308-L342 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/aui.py | python | AuiPaneInfo.Movable | (*args, **kwargs) | return _aui.AuiPaneInfo_Movable(*args, **kwargs) | Movable(self, bool b=True) -> AuiPaneInfo | Movable(self, bool b=True) -> AuiPaneInfo | [
"Movable",
"(",
"self",
"bool",
"b",
"=",
"True",
")",
"-",
">",
"AuiPaneInfo"
] | def Movable(*args, **kwargs):
"""Movable(self, bool b=True) -> AuiPaneInfo"""
return _aui.AuiPaneInfo_Movable(*args, **kwargs) | [
"def",
"Movable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_Movable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L497-L499 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/clang/utils/check_cfc/obj_diff.py | python | compare_debug_info | (objfilea, objfileb) | return first_diff(dbga, dbgb, objfilea, objfileb) | Compare debug info of two different files.
Allowing unavoidable differences, such as filenames.
Return the first difference if the debug info differs, or None.
If there are differences in the code, there will almost certainly be differences in the debug info too. | Compare debug info of two different files.
Allowing unavoidable differences, such as filenames.
Return the first difference if the debug info differs, or None.
If there are differences in the code, there will almost certainly be differences in the debug info too. | [
"Compare",
"debug",
"info",
"of",
"two",
"different",
"files",
".",
"Allowing",
"unavoidable",
"differences",
"such",
"as",
"filenames",
".",
"Return",
"the",
"first",
"difference",
"if",
"the",
"debug",
"info",
"differs",
"or",
"None",
".",
"If",
"there",
"are",
"differences",
"in",
"the",
"code",
"there",
"will",
"almost",
"certainly",
"be",
"differences",
"in",
"the",
"debug",
"info",
"too",
"."
] | def compare_debug_info(objfilea, objfileb):
"""Compare debug info of two different files.
Allowing unavoidable differences, such as filenames.
Return the first difference if the debug info differs, or None.
If there are differences in the code, there will almost certainly be differences in the debug info too.
"""
dbga = dump_debug(objfilea)
dbgb = dump_debug(objfileb)
return first_diff(dbga, dbgb, objfilea, objfileb) | [
"def",
"compare_debug_info",
"(",
"objfilea",
",",
"objfileb",
")",
":",
"dbga",
"=",
"dump_debug",
"(",
"objfilea",
")",
"dbgb",
"=",
"dump_debug",
"(",
"objfileb",
")",
"return",
"first_diff",
"(",
"dbga",
",",
"dbgb",
",",
"objfilea",
",",
"objfileb",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/utils/check_cfc/obj_diff.py#L76-L84 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Compiler/Optimize.py | python | OptimizeBuiltinCalls._handle_simple_method_object_pop | (self, node, function, args, is_unbound_method, is_list=False) | return node | Optimistic optimisation as X.pop([n]) is almost always
referring to a list. | Optimistic optimisation as X.pop([n]) is almost always
referring to a list. | [
"Optimistic",
"optimisation",
"as",
"X",
".",
"pop",
"(",
"[",
"n",
"]",
")",
"is",
"almost",
"always",
"referring",
"to",
"a",
"list",
"."
] | def _handle_simple_method_object_pop(self, node, function, args, is_unbound_method, is_list=False):
"""Optimistic optimisation as X.pop([n]) is almost always
referring to a list.
"""
if not args:
return node
obj = args[0]
if is_list:
type_name = 'List'
obj = obj.as_none_safe_node(
"'NoneType' object has no attribute '%.30s'",
error="PyExc_AttributeError",
format_args=['pop'])
else:
type_name = 'Object'
if len(args) == 1:
return ExprNodes.PythonCapiCallNode(
node.pos, "__Pyx_Py%s_Pop" % type_name,
self.PyObject_Pop_func_type,
args=[obj],
may_return_none=True,
is_temp=node.is_temp,
utility_code=load_c_utility('pop'),
)
elif len(args) == 2:
index = unwrap_coerced_node(args[1])
py_index = ExprNodes.NoneNode(index.pos)
orig_index_type = index.type
if not index.type.is_int:
if isinstance(index, ExprNodes.IntNode):
py_index = index.coerce_to_pyobject(self.current_env())
index = index.coerce_to(PyrexTypes.c_py_ssize_t_type, self.current_env())
elif is_list:
if index.type.is_pyobject:
py_index = index.coerce_to_simple(self.current_env())
index = ExprNodes.CloneNode(py_index)
index = index.coerce_to(PyrexTypes.c_py_ssize_t_type, self.current_env())
else:
return node
elif not PyrexTypes.numeric_type_fits(index.type, PyrexTypes.c_py_ssize_t_type):
return node
elif isinstance(index, ExprNodes.IntNode):
py_index = index.coerce_to_pyobject(self.current_env())
# real type might still be larger at runtime
if not orig_index_type.is_int:
orig_index_type = index.type
if not orig_index_type.create_to_py_utility_code(self.current_env()):
return node
convert_func = orig_index_type.to_py_function
conversion_type = PyrexTypes.CFuncType(
PyrexTypes.py_object_type, [PyrexTypes.CFuncTypeArg("intval", orig_index_type, None)])
return ExprNodes.PythonCapiCallNode(
node.pos, "__Pyx_Py%s_PopIndex" % type_name,
self.PyObject_PopIndex_func_type,
args=[obj, py_index, index,
ExprNodes.IntNode(index.pos, value=str(orig_index_type.signed and 1 or 0),
constant_result=orig_index_type.signed and 1 or 0,
type=PyrexTypes.c_int_type),
ExprNodes.RawCNameExprNode(index.pos, PyrexTypes.c_void_type,
orig_index_type.empty_declaration_code()),
ExprNodes.RawCNameExprNode(index.pos, conversion_type, convert_func)],
may_return_none=True,
is_temp=node.is_temp,
utility_code=load_c_utility("pop_index"),
)
return node | [
"def",
"_handle_simple_method_object_pop",
"(",
"self",
",",
"node",
",",
"function",
",",
"args",
",",
"is_unbound_method",
",",
"is_list",
"=",
"False",
")",
":",
"if",
"not",
"args",
":",
"return",
"node",
"obj",
"=",
"args",
"[",
"0",
"]",
"if",
"is_list",
":",
"type_name",
"=",
"'List'",
"obj",
"=",
"obj",
".",
"as_none_safe_node",
"(",
"\"'NoneType' object has no attribute '%.30s'\"",
",",
"error",
"=",
"\"PyExc_AttributeError\"",
",",
"format_args",
"=",
"[",
"'pop'",
"]",
")",
"else",
":",
"type_name",
"=",
"'Object'",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"return",
"ExprNodes",
".",
"PythonCapiCallNode",
"(",
"node",
".",
"pos",
",",
"\"__Pyx_Py%s_Pop\"",
"%",
"type_name",
",",
"self",
".",
"PyObject_Pop_func_type",
",",
"args",
"=",
"[",
"obj",
"]",
",",
"may_return_none",
"=",
"True",
",",
"is_temp",
"=",
"node",
".",
"is_temp",
",",
"utility_code",
"=",
"load_c_utility",
"(",
"'pop'",
")",
",",
")",
"elif",
"len",
"(",
"args",
")",
"==",
"2",
":",
"index",
"=",
"unwrap_coerced_node",
"(",
"args",
"[",
"1",
"]",
")",
"py_index",
"=",
"ExprNodes",
".",
"NoneNode",
"(",
"index",
".",
"pos",
")",
"orig_index_type",
"=",
"index",
".",
"type",
"if",
"not",
"index",
".",
"type",
".",
"is_int",
":",
"if",
"isinstance",
"(",
"index",
",",
"ExprNodes",
".",
"IntNode",
")",
":",
"py_index",
"=",
"index",
".",
"coerce_to_pyobject",
"(",
"self",
".",
"current_env",
"(",
")",
")",
"index",
"=",
"index",
".",
"coerce_to",
"(",
"PyrexTypes",
".",
"c_py_ssize_t_type",
",",
"self",
".",
"current_env",
"(",
")",
")",
"elif",
"is_list",
":",
"if",
"index",
".",
"type",
".",
"is_pyobject",
":",
"py_index",
"=",
"index",
".",
"coerce_to_simple",
"(",
"self",
".",
"current_env",
"(",
")",
")",
"index",
"=",
"ExprNodes",
".",
"CloneNode",
"(",
"py_index",
")",
"index",
"=",
"index",
".",
"coerce_to",
"(",
"PyrexTypes",
".",
"c_py_ssize_t_type",
",",
"self",
".",
"current_env",
"(",
")",
")",
"else",
":",
"return",
"node",
"elif",
"not",
"PyrexTypes",
".",
"numeric_type_fits",
"(",
"index",
".",
"type",
",",
"PyrexTypes",
".",
"c_py_ssize_t_type",
")",
":",
"return",
"node",
"elif",
"isinstance",
"(",
"index",
",",
"ExprNodes",
".",
"IntNode",
")",
":",
"py_index",
"=",
"index",
".",
"coerce_to_pyobject",
"(",
"self",
".",
"current_env",
"(",
")",
")",
"# real type might still be larger at runtime",
"if",
"not",
"orig_index_type",
".",
"is_int",
":",
"orig_index_type",
"=",
"index",
".",
"type",
"if",
"not",
"orig_index_type",
".",
"create_to_py_utility_code",
"(",
"self",
".",
"current_env",
"(",
")",
")",
":",
"return",
"node",
"convert_func",
"=",
"orig_index_type",
".",
"to_py_function",
"conversion_type",
"=",
"PyrexTypes",
".",
"CFuncType",
"(",
"PyrexTypes",
".",
"py_object_type",
",",
"[",
"PyrexTypes",
".",
"CFuncTypeArg",
"(",
"\"intval\"",
",",
"orig_index_type",
",",
"None",
")",
"]",
")",
"return",
"ExprNodes",
".",
"PythonCapiCallNode",
"(",
"node",
".",
"pos",
",",
"\"__Pyx_Py%s_PopIndex\"",
"%",
"type_name",
",",
"self",
".",
"PyObject_PopIndex_func_type",
",",
"args",
"=",
"[",
"obj",
",",
"py_index",
",",
"index",
",",
"ExprNodes",
".",
"IntNode",
"(",
"index",
".",
"pos",
",",
"value",
"=",
"str",
"(",
"orig_index_type",
".",
"signed",
"and",
"1",
"or",
"0",
")",
",",
"constant_result",
"=",
"orig_index_type",
".",
"signed",
"and",
"1",
"or",
"0",
",",
"type",
"=",
"PyrexTypes",
".",
"c_int_type",
")",
",",
"ExprNodes",
".",
"RawCNameExprNode",
"(",
"index",
".",
"pos",
",",
"PyrexTypes",
".",
"c_void_type",
",",
"orig_index_type",
".",
"empty_declaration_code",
"(",
")",
")",
",",
"ExprNodes",
".",
"RawCNameExprNode",
"(",
"index",
".",
"pos",
",",
"conversion_type",
",",
"convert_func",
")",
"]",
",",
"may_return_none",
"=",
"True",
",",
"is_temp",
"=",
"node",
".",
"is_temp",
",",
"utility_code",
"=",
"load_c_utility",
"(",
"\"pop_index\"",
")",
",",
")",
"return",
"node"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/Optimize.py#L3003-L3069 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/codecs.py | python | StreamReader.__init__ | (self, stream, errors='strict') | Creates a StreamReader instance.
stream must be a file-like object open for reading
(binary) data.
The StreamReader may use different error handling
schemes by providing the errors keyword argument. These
parameters are predefined:
'strict' - raise a ValueError (or a subclass)
'ignore' - ignore the character and continue with the next
'replace'- replace with a suitable replacement character;
The set of allowed parameter values can be extended via
register_error. | Creates a StreamReader instance. | [
"Creates",
"a",
"StreamReader",
"instance",
"."
] | def __init__(self, stream, errors='strict'):
""" Creates a StreamReader instance.
stream must be a file-like object open for reading
(binary) data.
The StreamReader may use different error handling
schemes by providing the errors keyword argument. These
parameters are predefined:
'strict' - raise a ValueError (or a subclass)
'ignore' - ignore the character and continue with the next
'replace'- replace with a suitable replacement character;
The set of allowed parameter values can be extended via
register_error.
"""
self.stream = stream
self.errors = errors
self.bytebuffer = ""
# For str->str decoding this will stay a str
# For str->unicode decoding the first read will promote it to unicode
self.charbuffer = ""
self.linebuffer = None | [
"def",
"__init__",
"(",
"self",
",",
"stream",
",",
"errors",
"=",
"'strict'",
")",
":",
"self",
".",
"stream",
"=",
"stream",
"self",
".",
"errors",
"=",
"errors",
"self",
".",
"bytebuffer",
"=",
"\"\"",
"# For str->str decoding this will stay a str",
"# For str->unicode decoding the first read will promote it to unicode",
"self",
".",
"charbuffer",
"=",
"\"\"",
"self",
".",
"linebuffer",
"=",
"None"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/codecs.py#L395-L419 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/launch.py | python | run | () | Run the script in sys.argv[1] as if it had
been invoked naturally. | Run the script in sys.argv[1] as if it had
been invoked naturally. | [
"Run",
"the",
"script",
"in",
"sys",
".",
"argv",
"[",
"1",
"]",
"as",
"if",
"it",
"had",
"been",
"invoked",
"naturally",
"."
] | def run():
"""
Run the script in sys.argv[1] as if it had
been invoked naturally.
"""
__builtins__
script_name = sys.argv[1]
namespace = dict(
__file__=script_name,
__name__='__main__',
__doc__=None,
)
sys.argv[:] = sys.argv[1:]
open_ = getattr(tokenize, 'open', open)
script = open_(script_name).read()
norm_script = script.replace('\\r\\n', '\\n')
code = compile(norm_script, script_name, 'exec')
exec(code, namespace) | [
"def",
"run",
"(",
")",
":",
"__builtins__",
"script_name",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"namespace",
"=",
"dict",
"(",
"__file__",
"=",
"script_name",
",",
"__name__",
"=",
"'__main__'",
",",
"__doc__",
"=",
"None",
",",
")",
"sys",
".",
"argv",
"[",
":",
"]",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"open_",
"=",
"getattr",
"(",
"tokenize",
",",
"'open'",
",",
"open",
")",
"script",
"=",
"open_",
"(",
"script_name",
")",
".",
"read",
"(",
")",
"norm_script",
"=",
"script",
".",
"replace",
"(",
"'\\\\r\\\\n'",
",",
"'\\\\n'",
")",
"code",
"=",
"compile",
"(",
"norm_script",
",",
"script_name",
",",
"'exec'",
")",
"exec",
"(",
"code",
",",
"namespace",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/launch.py#L13-L31 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/logging/handlers.py | python | TimedRotatingFileHandler.computeRollover | (self, currentTime) | return result | Work out the rollover time based on the specified time. | Work out the rollover time based on the specified time. | [
"Work",
"out",
"the",
"rollover",
"time",
"based",
"on",
"the",
"specified",
"time",
"."
] | def computeRollover(self, currentTime):
"""
Work out the rollover time based on the specified time.
"""
result = currentTime + self.interval
# If we are rolling over at midnight or weekly, then the interval is already known.
# What we need to figure out is WHEN the next interval is. In other words,
# if you are rolling over at midnight, then your base interval is 1 day,
# but you want to start that one day clock at midnight, not now. So, we
# have to fudge the rolloverAt value in order to trigger the first rollover
# at the right time. After that, the regular interval will take care of
# the rest. Note that this code doesn't care about leap seconds. :)
if self.when == 'MIDNIGHT' or self.when.startswith('W'):
# This could be done with less code, but I wanted it to be clear
if self.utc:
t = time.gmtime(currentTime)
else:
t = time.localtime(currentTime)
currentHour = t[3]
currentMinute = t[4]
currentSecond = t[5]
# r is the number of seconds left between now and midnight
r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 +
currentSecond)
result = currentTime + r
# If we are rolling over on a certain day, add in the number of days until
# the next rollover, but offset by 1 since we just calculated the time
# until the next day starts. There are three cases:
# Case 1) The day to rollover is today; in this case, do nothing
# Case 2) The day to rollover is further in the interval (i.e., today is
# day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
# next rollover is simply 6 - 2 - 1, or 3.
# Case 3) The day to rollover is behind us in the interval (i.e., today
# is day 5 (Saturday) and rollover is on day 3 (Thursday).
# Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
# number of days left in the current week (1) plus the number
# of days in the next week until the rollover day (3).
# The calculations described in 2) and 3) above need to have a day added.
# This is because the above time calculation takes us to midnight on this
# day, i.e. the start of the next day.
if self.when.startswith('W'):
day = t[6] # 0 is Monday
if day != self.dayOfWeek:
if day < self.dayOfWeek:
daysToWait = self.dayOfWeek - day
else:
daysToWait = 6 - day + self.dayOfWeek + 1
newRolloverAt = result + (daysToWait * (60 * 60 * 24))
if not self.utc:
dstNow = t[-1]
dstAtRollover = time.localtime(newRolloverAt)[-1]
if dstNow != dstAtRollover:
if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
newRolloverAt = newRolloverAt - 3600
else: # DST bows out before next rollover, so we need to add an hour
newRolloverAt = newRolloverAt + 3600
result = newRolloverAt
return result | [
"def",
"computeRollover",
"(",
"self",
",",
"currentTime",
")",
":",
"result",
"=",
"currentTime",
"+",
"self",
".",
"interval",
"# If we are rolling over at midnight or weekly, then the interval is already known.",
"# What we need to figure out is WHEN the next interval is. In other words,",
"# if you are rolling over at midnight, then your base interval is 1 day,",
"# but you want to start that one day clock at midnight, not now. So, we",
"# have to fudge the rolloverAt value in order to trigger the first rollover",
"# at the right time. After that, the regular interval will take care of",
"# the rest. Note that this code doesn't care about leap seconds. :)",
"if",
"self",
".",
"when",
"==",
"'MIDNIGHT'",
"or",
"self",
".",
"when",
".",
"startswith",
"(",
"'W'",
")",
":",
"# This could be done with less code, but I wanted it to be clear",
"if",
"self",
".",
"utc",
":",
"t",
"=",
"time",
".",
"gmtime",
"(",
"currentTime",
")",
"else",
":",
"t",
"=",
"time",
".",
"localtime",
"(",
"currentTime",
")",
"currentHour",
"=",
"t",
"[",
"3",
"]",
"currentMinute",
"=",
"t",
"[",
"4",
"]",
"currentSecond",
"=",
"t",
"[",
"5",
"]",
"# r is the number of seconds left between now and midnight",
"r",
"=",
"_MIDNIGHT",
"-",
"(",
"(",
"currentHour",
"*",
"60",
"+",
"currentMinute",
")",
"*",
"60",
"+",
"currentSecond",
")",
"result",
"=",
"currentTime",
"+",
"r",
"# If we are rolling over on a certain day, add in the number of days until",
"# the next rollover, but offset by 1 since we just calculated the time",
"# until the next day starts. There are three cases:",
"# Case 1) The day to rollover is today; in this case, do nothing",
"# Case 2) The day to rollover is further in the interval (i.e., today is",
"# day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to",
"# next rollover is simply 6 - 2 - 1, or 3.",
"# Case 3) The day to rollover is behind us in the interval (i.e., today",
"# is day 5 (Saturday) and rollover is on day 3 (Thursday).",
"# Days to rollover is 6 - 5 + 3, or 4. In this case, it's the",
"# number of days left in the current week (1) plus the number",
"# of days in the next week until the rollover day (3).",
"# The calculations described in 2) and 3) above need to have a day added.",
"# This is because the above time calculation takes us to midnight on this",
"# day, i.e. the start of the next day.",
"if",
"self",
".",
"when",
".",
"startswith",
"(",
"'W'",
")",
":",
"day",
"=",
"t",
"[",
"6",
"]",
"# 0 is Monday",
"if",
"day",
"!=",
"self",
".",
"dayOfWeek",
":",
"if",
"day",
"<",
"self",
".",
"dayOfWeek",
":",
"daysToWait",
"=",
"self",
".",
"dayOfWeek",
"-",
"day",
"else",
":",
"daysToWait",
"=",
"6",
"-",
"day",
"+",
"self",
".",
"dayOfWeek",
"+",
"1",
"newRolloverAt",
"=",
"result",
"+",
"(",
"daysToWait",
"*",
"(",
"60",
"*",
"60",
"*",
"24",
")",
")",
"if",
"not",
"self",
".",
"utc",
":",
"dstNow",
"=",
"t",
"[",
"-",
"1",
"]",
"dstAtRollover",
"=",
"time",
".",
"localtime",
"(",
"newRolloverAt",
")",
"[",
"-",
"1",
"]",
"if",
"dstNow",
"!=",
"dstAtRollover",
":",
"if",
"not",
"dstNow",
":",
"# DST kicks in before next rollover, so we need to deduct an hour",
"newRolloverAt",
"=",
"newRolloverAt",
"-",
"3600",
"else",
":",
"# DST bows out before next rollover, so we need to add an hour",
"newRolloverAt",
"=",
"newRolloverAt",
"+",
"3600",
"result",
"=",
"newRolloverAt",
"return",
"result"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/logging/handlers.py#L210-L267 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/appstats.py | python | OutputBeautifier.__PrintNetworkStatsHeader | (self) | return self.__ColorString(headers, 'BOLD') | Returns a header string for network usage statistics. | Returns a header string for network usage statistics. | [
"Returns",
"a",
"header",
"string",
"for",
"network",
"usage",
"statistics",
"."
] | def __PrintNetworkStatsHeader(self):
"""Returns a header string for network usage statistics."""
headers = ''
for header in self.__NETWORK_COLUMN_TITLES:
headers += self.__PadString(header, 8, True) + ' '
headers += self.__PadString('(kB)', 8, False)
return self.__ColorString(headers, 'BOLD') | [
"def",
"__PrintNetworkStatsHeader",
"(",
"self",
")",
":",
"headers",
"=",
"''",
"for",
"header",
"in",
"self",
".",
"__NETWORK_COLUMN_TITLES",
":",
"headers",
"+=",
"self",
".",
"__PadString",
"(",
"header",
",",
"8",
",",
"True",
")",
"+",
"' '",
"headers",
"+=",
"self",
".",
"__PadString",
"(",
"'(kB)'",
",",
"8",
",",
"False",
")",
"return",
"self",
".",
"__ColorString",
"(",
"headers",
",",
"'BOLD'",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/appstats.py#L575-L581 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_stc.py | python | EditraStc.ExpandAll | (self) | Expand all folded code blocks | Expand all folded code blocks | [
"Expand",
"all",
"folded",
"code",
"blocks"
] | def ExpandAll(self):
"""Expand all folded code blocks"""
line_count = self.GetLineCount()
for line_num in xrange(line_count):
if self.GetFoldLevel(line_num) & wx.stc.STC_FOLDLEVELHEADERFLAG:
if not self.GetFoldExpanded(line_num):
self.Expand(line_num, True) | [
"def",
"ExpandAll",
"(",
"self",
")",
":",
"line_count",
"=",
"self",
".",
"GetLineCount",
"(",
")",
"for",
"line_num",
"in",
"xrange",
"(",
"line_count",
")",
":",
"if",
"self",
".",
"GetFoldLevel",
"(",
"line_num",
")",
"&",
"wx",
".",
"stc",
".",
"STC_FOLDLEVELHEADERFLAG",
":",
"if",
"not",
"self",
".",
"GetFoldExpanded",
"(",
"line_num",
")",
":",
"self",
".",
"Expand",
"(",
"line_num",
",",
"True",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_stc.py#L1063-L1069 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/polynomial/polynomial.py | python | polycompanion | (c) | return mat | Return the companion matrix of c.
The companion matrix for power series cannot be made symmetric by
scaling the basis, so this function differs from those for the
orthogonal polynomials.
Parameters
----------
c : array_like
1-D array of polynomial coefficients ordered from low to high
degree.
Returns
-------
mat : ndarray
Companion matrix of dimensions (deg, deg).
Notes
-----
.. versionadded:: 1.7.0 | Return the companion matrix of c. | [
"Return",
"the",
"companion",
"matrix",
"of",
"c",
"."
] | def polycompanion(c):
"""
Return the companion matrix of c.
The companion matrix for power series cannot be made symmetric by
scaling the basis, so this function differs from those for the
orthogonal polynomials.
Parameters
----------
c : array_like
1-D array of polynomial coefficients ordered from low to high
degree.
Returns
-------
mat : ndarray
Companion matrix of dimensions (deg, deg).
Notes
-----
.. versionadded:: 1.7.0
"""
# c is a trimmed copy
[c] = pu.as_series([c])
if len(c) < 2:
raise ValueError('Series must have maximum degree of at least 1.')
if len(c) == 2:
return np.array([[-c[0]/c[1]]])
n = len(c) - 1
mat = np.zeros((n, n), dtype=c.dtype)
bot = mat.reshape(-1)[n::n+1]
bot[...] = 1
mat[:, -1] -= c[:-1]/c[-1]
return mat | [
"def",
"polycompanion",
"(",
"c",
")",
":",
"# c is a trimmed copy",
"[",
"c",
"]",
"=",
"pu",
".",
"as_series",
"(",
"[",
"c",
"]",
")",
"if",
"len",
"(",
"c",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"'Series must have maximum degree of at least 1.'",
")",
"if",
"len",
"(",
"c",
")",
"==",
"2",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"-",
"c",
"[",
"0",
"]",
"/",
"c",
"[",
"1",
"]",
"]",
"]",
")",
"n",
"=",
"len",
"(",
"c",
")",
"-",
"1",
"mat",
"=",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"n",
")",
",",
"dtype",
"=",
"c",
".",
"dtype",
")",
"bot",
"=",
"mat",
".",
"reshape",
"(",
"-",
"1",
")",
"[",
"n",
":",
":",
"n",
"+",
"1",
"]",
"bot",
"[",
"...",
"]",
"=",
"1",
"mat",
"[",
":",
",",
"-",
"1",
"]",
"-=",
"c",
"[",
":",
"-",
"1",
"]",
"/",
"c",
"[",
"-",
"1",
"]",
"return",
"mat"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/polynomial.py#L1364-L1401 | |
nucleic/atom | 9f0cb2a8101dd63c354a98ebc7489b2c616dc82a | atom/atom.py | python | ObserveHandler.clone | (self) | return clone | Create a clone of the sentinel. | Create a clone of the sentinel. | [
"Create",
"a",
"clone",
"of",
"the",
"sentinel",
"."
] | def clone(self) -> "ObserveHandler":
"""Create a clone of the sentinel."""
clone = type(self)(self.pairs)
clone.func = self.func
return clone | [
"def",
"clone",
"(",
"self",
")",
"->",
"\"ObserveHandler\"",
":",
"clone",
"=",
"type",
"(",
"self",
")",
"(",
"self",
".",
"pairs",
")",
"clone",
".",
"func",
"=",
"self",
".",
"func",
"return",
"clone"
] | https://github.com/nucleic/atom/blob/9f0cb2a8101dd63c354a98ebc7489b2c616dc82a/atom/atom.py#L105-L109 | |
raspberrypi/tools | 13474ee775d0c5ec8a7da4fb0a9fa84187abfc87 | arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/share/gdb/python/gdb/command/explore.py | python | ReferenceExplorer.explore_type | (name, datatype, is_child) | return False | Function to explore pointer types.
See Explorer.explore_type for more information. | Function to explore pointer types.
See Explorer.explore_type for more information. | [
"Function",
"to",
"explore",
"pointer",
"types",
".",
"See",
"Explorer",
".",
"explore_type",
"for",
"more",
"information",
"."
] | def explore_type(name, datatype, is_child):
"""Function to explore pointer types.
See Explorer.explore_type for more information.
"""
target_type = datatype.target()
Explorer.explore_type(name, target_type, is_child)
return False | [
"def",
"explore_type",
"(",
"name",
",",
"datatype",
",",
"is_child",
")",
":",
"target_type",
"=",
"datatype",
".",
"target",
"(",
")",
"Explorer",
".",
"explore_type",
"(",
"name",
",",
"target_type",
",",
"is_child",
")",
"return",
"False"
] | https://github.com/raspberrypi/tools/blob/13474ee775d0c5ec8a7da4fb0a9fa84187abfc87/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/share/gdb/python/gdb/command/explore.py#L313-L319 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/telnetlib.py | python | Telnet.process_rawq | (self) | Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence. | Transfer from raw queue to cooked queue. | [
"Transfer",
"from",
"raw",
"queue",
"to",
"cooked",
"queue",
"."
] | def process_rawq(self):
"""Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence.
"""
buf = [b'', b'']
try:
while self.rawq:
c = self.rawq_getchar()
if not self.iacseq:
if c == theNULL:
continue
if c == b"\021":
continue
if c != IAC:
buf[self.sb] = buf[self.sb] + c
continue
else:
self.iacseq += c
elif len(self.iacseq) == 1:
# 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
if c in (DO, DONT, WILL, WONT):
self.iacseq += c
continue
self.iacseq = b''
if c == IAC:
buf[self.sb] = buf[self.sb] + c
else:
if c == SB: # SB ... SE start.
self.sb = 1
self.sbdataq = b''
elif c == SE:
self.sb = 0
self.sbdataq = self.sbdataq + buf[1]
buf[1] = b''
if self.option_callback:
# Callback is supposed to look into
# the sbdataq
self.option_callback(self.sock, c, NOOPT)
else:
# We can't offer automatic processing of
# suboptions. Alas, we should not get any
# unless we did a WILL/DO before.
self.msg('IAC %d not recognized' % ord(c))
elif len(self.iacseq) == 2:
cmd = self.iacseq[1:2]
self.iacseq = b''
opt = c
if cmd in (DO, DONT):
self.msg('IAC %s %d',
cmd == DO and 'DO' or 'DONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + WONT + opt)
elif cmd in (WILL, WONT):
self.msg('IAC %s %d',
cmd == WILL and 'WILL' or 'WONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + DONT + opt)
except EOFError: # raised by self.rawq_getchar()
self.iacseq = b'' # Reset on EOF
self.sb = 0
pass
self.cookedq = self.cookedq + buf[0]
self.sbdataq = self.sbdataq + buf[1] | [
"def",
"process_rawq",
"(",
"self",
")",
":",
"buf",
"=",
"[",
"b''",
",",
"b''",
"]",
"try",
":",
"while",
"self",
".",
"rawq",
":",
"c",
"=",
"self",
".",
"rawq_getchar",
"(",
")",
"if",
"not",
"self",
".",
"iacseq",
":",
"if",
"c",
"==",
"theNULL",
":",
"continue",
"if",
"c",
"==",
"b\"\\021\"",
":",
"continue",
"if",
"c",
"!=",
"IAC",
":",
"buf",
"[",
"self",
".",
"sb",
"]",
"=",
"buf",
"[",
"self",
".",
"sb",
"]",
"+",
"c",
"continue",
"else",
":",
"self",
".",
"iacseq",
"+=",
"c",
"elif",
"len",
"(",
"self",
".",
"iacseq",
")",
"==",
"1",
":",
"# 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'",
"if",
"c",
"in",
"(",
"DO",
",",
"DONT",
",",
"WILL",
",",
"WONT",
")",
":",
"self",
".",
"iacseq",
"+=",
"c",
"continue",
"self",
".",
"iacseq",
"=",
"b''",
"if",
"c",
"==",
"IAC",
":",
"buf",
"[",
"self",
".",
"sb",
"]",
"=",
"buf",
"[",
"self",
".",
"sb",
"]",
"+",
"c",
"else",
":",
"if",
"c",
"==",
"SB",
":",
"# SB ... SE start.",
"self",
".",
"sb",
"=",
"1",
"self",
".",
"sbdataq",
"=",
"b''",
"elif",
"c",
"==",
"SE",
":",
"self",
".",
"sb",
"=",
"0",
"self",
".",
"sbdataq",
"=",
"self",
".",
"sbdataq",
"+",
"buf",
"[",
"1",
"]",
"buf",
"[",
"1",
"]",
"=",
"b''",
"if",
"self",
".",
"option_callback",
":",
"# Callback is supposed to look into",
"# the sbdataq",
"self",
".",
"option_callback",
"(",
"self",
".",
"sock",
",",
"c",
",",
"NOOPT",
")",
"else",
":",
"# We can't offer automatic processing of",
"# suboptions. Alas, we should not get any",
"# unless we did a WILL/DO before.",
"self",
".",
"msg",
"(",
"'IAC %d not recognized'",
"%",
"ord",
"(",
"c",
")",
")",
"elif",
"len",
"(",
"self",
".",
"iacseq",
")",
"==",
"2",
":",
"cmd",
"=",
"self",
".",
"iacseq",
"[",
"1",
":",
"2",
"]",
"self",
".",
"iacseq",
"=",
"b''",
"opt",
"=",
"c",
"if",
"cmd",
"in",
"(",
"DO",
",",
"DONT",
")",
":",
"self",
".",
"msg",
"(",
"'IAC %s %d'",
",",
"cmd",
"==",
"DO",
"and",
"'DO'",
"or",
"'DONT'",
",",
"ord",
"(",
"opt",
")",
")",
"if",
"self",
".",
"option_callback",
":",
"self",
".",
"option_callback",
"(",
"self",
".",
"sock",
",",
"cmd",
",",
"opt",
")",
"else",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"IAC",
"+",
"WONT",
"+",
"opt",
")",
"elif",
"cmd",
"in",
"(",
"WILL",
",",
"WONT",
")",
":",
"self",
".",
"msg",
"(",
"'IAC %s %d'",
",",
"cmd",
"==",
"WILL",
"and",
"'WILL'",
"or",
"'WONT'",
",",
"ord",
"(",
"opt",
")",
")",
"if",
"self",
".",
"option_callback",
":",
"self",
".",
"option_callback",
"(",
"self",
".",
"sock",
",",
"cmd",
",",
"opt",
")",
"else",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"IAC",
"+",
"DONT",
"+",
"opt",
")",
"except",
"EOFError",
":",
"# raised by self.rawq_getchar()",
"self",
".",
"iacseq",
"=",
"b''",
"# Reset on EOF",
"self",
".",
"sb",
"=",
"0",
"pass",
"self",
".",
"cookedq",
"=",
"self",
".",
"cookedq",
"+",
"buf",
"[",
"0",
"]",
"self",
".",
"sbdataq",
"=",
"self",
".",
"sbdataq",
"+",
"buf",
"[",
"1",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/telnetlib.py#L422-L492 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/aui.py | python | AuiNotebook.SetTabCtrlHeight | (*args, **kwargs) | return _aui.AuiNotebook_SetTabCtrlHeight(*args, **kwargs) | SetTabCtrlHeight(self, int height) | SetTabCtrlHeight(self, int height) | [
"SetTabCtrlHeight",
"(",
"self",
"int",
"height",
")"
] | def SetTabCtrlHeight(*args, **kwargs):
"""SetTabCtrlHeight(self, int height)"""
return _aui.AuiNotebook_SetTabCtrlHeight(*args, **kwargs) | [
"def",
"SetTabCtrlHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiNotebook_SetTabCtrlHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L1317-L1319 | |
ros-industrial/industrial_training | e6761c7bee65d3802fee6cf7c99e3113d3dc1af2 | gh_pages/_themes/sphinx_rtd_theme/__init__.py | python | get_html_theme_path | () | return cur_dir | Return list of HTML theme paths. | Return list of HTML theme paths. | [
"Return",
"list",
"of",
"HTML",
"theme",
"paths",
"."
] | def get_html_theme_path():
"""Return list of HTML theme paths."""
cur_dir = path.abspath(path.dirname(path.dirname(__file__)))
return cur_dir | [
"def",
"get_html_theme_path",
"(",
")",
":",
"cur_dir",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"dirname",
"(",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")",
"return",
"cur_dir"
] | https://github.com/ros-industrial/industrial_training/blob/e6761c7bee65d3802fee6cf7c99e3113d3dc1af2/gh_pages/_themes/sphinx_rtd_theme/__init__.py#L12-L15 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/application/application.py | python | Application.exit | (
self,
result: Optional[_AppResult] = None,
exception: Optional[Union[BaseException, Type[BaseException]]] = None,
style: str = "",
) | Exit application.
.. note::
If `Application.exit` is called before `Application.run()` is
called, then the `Application` won't exit (because the
`Application.future` doesn't correspond to the current run). Use a
`pre_run` hook and an event to synchronize the closing if there's a
chance this can happen.
:param result: Set this result for the application.
:param exception: Set this exception as the result for an application. For
a prompt, this is often `EOFError` or `KeyboardInterrupt`.
:param style: Apply this style on the whole content when quitting,
often this is 'class:exiting' for a prompt. (Used when
`erase_when_done` is not set.) | Exit application. | [
"Exit",
"application",
"."
] | def exit(
self,
result: Optional[_AppResult] = None,
exception: Optional[Union[BaseException, Type[BaseException]]] = None,
style: str = "",
) -> None:
"""
Exit application.
.. note::
If `Application.exit` is called before `Application.run()` is
called, then the `Application` won't exit (because the
`Application.future` doesn't correspond to the current run). Use a
`pre_run` hook and an event to synchronize the closing if there's a
chance this can happen.
:param result: Set this result for the application.
:param exception: Set this exception as the result for an application. For
a prompt, this is often `EOFError` or `KeyboardInterrupt`.
:param style: Apply this style on the whole content when quitting,
often this is 'class:exiting' for a prompt. (Used when
`erase_when_done` is not set.)
"""
assert result is None or exception is None
if self.future is None:
raise Exception("Application is not running. Application.exit() failed.")
if self.future.done():
raise Exception("Return value already set. Application.exit() failed.")
self.exit_style = style
if exception is not None:
self.future.set_exception(exception)
else:
self.future.set_result(cast(_AppResult, result)) | [
"def",
"exit",
"(",
"self",
",",
"result",
":",
"Optional",
"[",
"_AppResult",
"]",
"=",
"None",
",",
"exception",
":",
"Optional",
"[",
"Union",
"[",
"BaseException",
",",
"Type",
"[",
"BaseException",
"]",
"]",
"]",
"=",
"None",
",",
"style",
":",
"str",
"=",
"\"\"",
",",
")",
"->",
"None",
":",
"assert",
"result",
"is",
"None",
"or",
"exception",
"is",
"None",
"if",
"self",
".",
"future",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Application is not running. Application.exit() failed.\"",
")",
"if",
"self",
".",
"future",
".",
"done",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"Return value already set. Application.exit() failed.\"",
")",
"self",
".",
"exit_style",
"=",
"style",
"if",
"exception",
"is",
"not",
"None",
":",
"self",
".",
"future",
".",
"set_exception",
"(",
"exception",
")",
"else",
":",
"self",
".",
"future",
".",
"set_result",
"(",
"cast",
"(",
"_AppResult",
",",
"result",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/application.py#L1103-L1140 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | uCSIsTamil | (code) | return ret | Check whether the character is part of Tamil UCS Block | Check whether the character is part of Tamil UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"Tamil",
"UCS",
"Block"
] | def uCSIsTamil(code):
"""Check whether the character is part of Tamil UCS Block """
ret = libxml2mod.xmlUCSIsTamil(code)
return ret | [
"def",
"uCSIsTamil",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsTamil",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L2933-L2936 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PGProperty.GetChildrenHeight | (*args, **kwargs) | return _propgrid.PGProperty_GetChildrenHeight(*args, **kwargs) | GetChildrenHeight(self, int lh, int iMax=-1) -> int | GetChildrenHeight(self, int lh, int iMax=-1) -> int | [
"GetChildrenHeight",
"(",
"self",
"int",
"lh",
"int",
"iMax",
"=",
"-",
"1",
")",
"-",
">",
"int"
] | def GetChildrenHeight(*args, **kwargs):
"""GetChildrenHeight(self, int lh, int iMax=-1) -> int"""
return _propgrid.PGProperty_GetChildrenHeight(*args, **kwargs) | [
"def",
"GetChildrenHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_GetChildrenHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L806-L808 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | FileCtrl.HasMultipleFileSelection | (*args, **kwargs) | return _controls_.FileCtrl_HasMultipleFileSelection(*args, **kwargs) | HasMultipleFileSelection(self) -> bool | HasMultipleFileSelection(self) -> bool | [
"HasMultipleFileSelection",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasMultipleFileSelection(*args, **kwargs):
"""HasMultipleFileSelection(self) -> bool"""
return _controls_.FileCtrl_HasMultipleFileSelection(*args, **kwargs) | [
"def",
"HasMultipleFileSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"FileCtrl_HasMultipleFileSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L7703-L7705 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/core.py | python | CherryTree.link_check_around_cursor_iter | (self, text_iter) | return "" | Check if the text iter is on a link | Check if the text iter is on a link | [
"Check",
"if",
"the",
"text",
"iter",
"is",
"on",
"a",
"link"
] | def link_check_around_cursor_iter(self, text_iter):
"""Check if the text iter is on a link"""
tags = text_iter.get_tags()
for tag in tags:
tag_name = tag.get_property("name")
if tag_name and tag_name[0:4] == cons.TAG_LINK: return tag_name
return "" | [
"def",
"link_check_around_cursor_iter",
"(",
"self",
",",
"text_iter",
")",
":",
"tags",
"=",
"text_iter",
".",
"get_tags",
"(",
")",
"for",
"tag",
"in",
"tags",
":",
"tag_name",
"=",
"tag",
".",
"get_property",
"(",
"\"name\"",
")",
"if",
"tag_name",
"and",
"tag_name",
"[",
"0",
":",
"4",
"]",
"==",
"cons",
".",
"TAG_LINK",
":",
"return",
"tag_name",
"return",
"\"\""
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L4865-L4871 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.GetFullLayoutTime | (*args, **kwargs) | return _richtext.RichTextCtrl_GetFullLayoutTime(*args, **kwargs) | GetFullLayoutTime(self) -> wxLongLong | GetFullLayoutTime(self) -> wxLongLong | [
"GetFullLayoutTime",
"(",
"self",
")",
"-",
">",
"wxLongLong"
] | def GetFullLayoutTime(*args, **kwargs):
"""GetFullLayoutTime(self) -> wxLongLong"""
return _richtext.RichTextCtrl_GetFullLayoutTime(*args, **kwargs) | [
"def",
"GetFullLayoutTime",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_GetFullLayoutTime",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2969-L2971 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/config.py | python | ConfigOptionsHandler.parse_section_entry_points | (self, section_options) | Parses `entry_points` configuration file section.
:param dict section_options: | Parses `entry_points` configuration file section. | [
"Parses",
"entry_points",
"configuration",
"file",
"section",
"."
] | def parse_section_entry_points(self, section_options):
"""Parses `entry_points` configuration file section.
:param dict section_options:
"""
parsed = self._parse_section_to_dict(section_options, self._parse_list)
self['entry_points'] = parsed | [
"def",
"parse_section_entry_points",
"(",
"self",
",",
"section_options",
")",
":",
"parsed",
"=",
"self",
".",
"_parse_section_to_dict",
"(",
"section_options",
",",
"self",
".",
"_parse_list",
")",
"self",
"[",
"'entry_points'",
"]",
"=",
"parsed"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/config.py#L611-L617 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | caffe2/python/dataset.py | python | Dataset.field_types | (self) | return self.field_types | Return the list of field dtypes for this dataset.
If a list of strings, not a schema.Struct, was passed to the
constructor, this will return a list of dtype(np.void). | Return the list of field dtypes for this dataset. | [
"Return",
"the",
"list",
"of",
"field",
"dtypes",
"for",
"this",
"dataset",
"."
] | def field_types(self):
"""
Return the list of field dtypes for this dataset.
If a list of strings, not a schema.Struct, was passed to the
constructor, this will return a list of dtype(np.void).
"""
return self.field_types | [
"def",
"field_types",
"(",
"self",
")",
":",
"return",
"self",
".",
"field_types"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/dataset.py#L267-L274 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/user_preferences.py | python | UserPreferences.animations_enabled | (self) | return self._animations_enabled | Gets the animations_enabled of this UserPreferences. # noqa: E501
:return: The animations_enabled of this UserPreferences. # noqa: E501
:rtype: bool | Gets the animations_enabled of this UserPreferences. # noqa: E501 | [
"Gets",
"the",
"animations_enabled",
"of",
"this",
"UserPreferences",
".",
"#",
"noqa",
":",
"E501"
] | def animations_enabled(self):
"""Gets the animations_enabled of this UserPreferences. # noqa: E501
:return: The animations_enabled of this UserPreferences. # noqa: E501
:rtype: bool
"""
return self._animations_enabled | [
"def",
"animations_enabled",
"(",
"self",
")",
":",
"return",
"self",
".",
"_animations_enabled"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/user_preferences.py#L202-L209 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/agilepy/lib_wx/toolbox.py | python | BaseTool.get_optionspanel | (self, parent, size=wx.DefaultSize) | return self._optionspanel | Return tool option widgets on given parent | Return tool option widgets on given parent | [
"Return",
"tool",
"option",
"widgets",
"on",
"given",
"parent"
] | def get_optionspanel(self, parent, size=wx.DefaultSize):
"""
Return tool option widgets on given parent
"""
size = (200, -1)
self._optionspanel = ObjPanel(parent, obj=self,
attrconfigs=None,
#tables = None,
# table = None, id=None, ids=None,
groupnames=['options'],
func_change_obj=None,
show_groupnames=False, show_title=True, is_modal=False,
mainframe=self.parent.get_mainframe(),
pos=wx.DefaultPosition, size=size, style=wx.MAXIMIZE_BOX | wx.RESIZE_BORDER,
immediate_apply=False, panelstyle='default', # 'instrumental'
standartbuttons=['apply', 'restore'])
return self._optionspanel | [
"def",
"get_optionspanel",
"(",
"self",
",",
"parent",
",",
"size",
"=",
"wx",
".",
"DefaultSize",
")",
":",
"size",
"=",
"(",
"200",
",",
"-",
"1",
")",
"self",
".",
"_optionspanel",
"=",
"ObjPanel",
"(",
"parent",
",",
"obj",
"=",
"self",
",",
"attrconfigs",
"=",
"None",
",",
"#tables = None,",
"# table = None, id=None, ids=None,",
"groupnames",
"=",
"[",
"'options'",
"]",
",",
"func_change_obj",
"=",
"None",
",",
"show_groupnames",
"=",
"False",
",",
"show_title",
"=",
"True",
",",
"is_modal",
"=",
"False",
",",
"mainframe",
"=",
"self",
".",
"parent",
".",
"get_mainframe",
"(",
")",
",",
"pos",
"=",
"wx",
".",
"DefaultPosition",
",",
"size",
"=",
"size",
",",
"style",
"=",
"wx",
".",
"MAXIMIZE_BOX",
"|",
"wx",
".",
"RESIZE_BORDER",
",",
"immediate_apply",
"=",
"False",
",",
"panelstyle",
"=",
"'default'",
",",
"# 'instrumental'",
"standartbuttons",
"=",
"[",
"'apply'",
",",
"'restore'",
"]",
")",
"return",
"self",
".",
"_optionspanel"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/toolbox.py#L121-L138 | |
herbstluftwm/herbstluftwm | 23ef0274bd4d317208eae5fea72b21478a71431b | doc/gendoc.py | python | TokenGroup.IsTokenGroup | (tokenStringOrGroup, opening_token=None) | returns whether the given object is a token group.
if an 'opening_token' is given, it is additionally checked
whether the opening_token matches | returns whether the given object is a token group.
if an 'opening_token' is given, it is additionally checked
whether the opening_token matches | [
"returns",
"whether",
"the",
"given",
"object",
"is",
"a",
"token",
"group",
".",
"if",
"an",
"opening_token",
"is",
"given",
"it",
"is",
"additionally",
"checked",
"whether",
"the",
"opening_token",
"matches"
] | def IsTokenGroup(tokenStringOrGroup, opening_token=None):
"""returns whether the given object is a token group.
if an 'opening_token' is given, it is additionally checked
whether the opening_token matches"""
if isinstance(tokenStringOrGroup, TokenGroup):
if opening_token is not None:
return tokenStringOrGroup.opening_token == opening_token
else:
return True
else:
return False | [
"def",
"IsTokenGroup",
"(",
"tokenStringOrGroup",
",",
"opening_token",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"tokenStringOrGroup",
",",
"TokenGroup",
")",
":",
"if",
"opening_token",
"is",
"not",
"None",
":",
"return",
"tokenStringOrGroup",
".",
"opening_token",
"==",
"opening_token",
"else",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/herbstluftwm/herbstluftwm/blob/23ef0274bd4d317208eae5fea72b21478a71431b/doc/gendoc.py#L120-L130 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/closure_linter/closure_linter/statetracker.py | python | _GetNextIdentifierToken | (start_token) | return None | Searches for and returns the first identifier at the beginning of a token.
Searches each token after the start to see if it starts with an identifier.
If found, will split the token into at most 3 piecies: leading whitespace,
identifier, rest of token, returning the identifier token. If no identifier is
found returns None and changes no tokens. Search is abandoned when a
FLAG_ENDING_TYPE token is found.
Args:
start_token: The token to start searching after.
Returns:
The identifier token is found, None otherwise. | Searches for and returns the first identifier at the beginning of a token. | [
"Searches",
"for",
"and",
"returns",
"the",
"first",
"identifier",
"at",
"the",
"beginning",
"of",
"a",
"token",
"."
] | def _GetNextIdentifierToken(start_token):
"""Searches for and returns the first identifier at the beginning of a token.
Searches each token after the start to see if it starts with an identifier.
If found, will split the token into at most 3 piecies: leading whitespace,
identifier, rest of token, returning the identifier token. If no identifier is
found returns None and changes no tokens. Search is abandoned when a
FLAG_ENDING_TYPE token is found.
Args:
start_token: The token to start searching after.
Returns:
The identifier token is found, None otherwise.
"""
token = start_token.next
while token and not token.type in Type.FLAG_ENDING_TYPES:
match = javascripttokenizer.JavaScriptTokenizer.IDENTIFIER.match(
token.string)
if (match is not None and token.type == Type.COMMENT and
len(token.string) == len(match.group(0))):
return token
token = token.next
return None | [
"def",
"_GetNextIdentifierToken",
"(",
"start_token",
")",
":",
"token",
"=",
"start_token",
".",
"next",
"while",
"token",
"and",
"not",
"token",
".",
"type",
"in",
"Type",
".",
"FLAG_ENDING_TYPES",
":",
"match",
"=",
"javascripttokenizer",
".",
"JavaScriptTokenizer",
".",
"IDENTIFIER",
".",
"match",
"(",
"token",
".",
"string",
")",
"if",
"(",
"match",
"is",
"not",
"None",
"and",
"token",
".",
"type",
"==",
"Type",
".",
"COMMENT",
"and",
"len",
"(",
"token",
".",
"string",
")",
"==",
"len",
"(",
"match",
".",
"group",
"(",
"0",
")",
")",
")",
":",
"return",
"token",
"token",
"=",
"token",
".",
"next",
"return",
"None"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/statetracker.py#L438-L464 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/scipy/linalg.py | python | lu | (a, permute_l=False, overwrite_a=False, check_finite=True) | return p, l, u | Compute pivoted LU decomposition of a general matrix.
The decomposition is:
.. math::
A = P L U
where :math:`P` is a permutation matrix, :math:`L` lower triangular with unit
diagonal elements, and :math:`U` upper triangular.
Args:
a (Tensor): a :math:`(M, N)` matrix to decompose.
permute_l (bool, optional): Perform the multiplication :math:`P L` (Default: do not permute). Default: False.
overwrite_a (bool, optional): Whether to overwrite data in :math:`A` (may improve performance). Default: False.
check_finite (bool, optional): Whether to check that the input matrix contains
only finite numbers. Disabling may give a performance gain, but may result
in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Default: True.
Returns:
**If permute_l == False**
- Tensor, :math:`(M, M)` permutation matrix.
- Tensor, :math:`(M, K)` lower triangular or trapezoidal matrix with unit diagonal. :math:`K = min(M, N)`.
- Tensor, :math:`(K, N)` upper triangular or trapezoidal matrix.
**If permute_l == True**
- Tensor, :math:`(M, K)` permuted L matrix. :math:`K = min(M, N)`.
- Tensor, :math:`(K, N)` upper triangular or trapezoidal matrix.
Supported Platforms:
``CPU`` ``GPU``
Examples:
>>> import numpy as onp
>>> from mindspore.common import Tensor
>>> from mindspore.scipy.linalg import lu
>>> A = Tensor(onp.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]]).astype(onp.float64))
>>> p, l, u = lu(A)
>>> p
Tensor(shape=[4, 4], dtype=Int32, value=
[[0, 1, 0, 0],
[0, 0, 0, 1],
[1, 0, 0, 0],
[0, 0, 1, 0]])
>>> l
Tensor(shape=[4, 4], dtype=Float64, value=
[[ 1.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[ 2.85714298e-01, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[ 7.14285731e-01, 1.19999997e-01, 1.00000000e+00, 0.00000000e+00],
[ 7.14285731e-01, -4.39999998e-01, -4.61538464e-01, 1.00000000e+00]])
>>> u
Tensor(shape=[4, 4], dtype=Float64, value=
[[ 7.00000000e+00, 5.00000000e+00, 6.00000000e+00, 6.00000000e+00],
[ 0.00000000e+00, 3.57142854e+00, 6.28571415e+00, 5.28571415e+00],
[ 0.00000000e+00, 0.00000000e+00, -1.03999996e+00, 3.07999992e+00],
[ 0.00000000e+00, -0.00000000e+00, -0.00000000e+00, 7.46153831e+00]]) | Compute pivoted LU decomposition of a general matrix. | [
"Compute",
"pivoted",
"LU",
"decomposition",
"of",
"a",
"general",
"matrix",
"."
] | def lu(a, permute_l=False, overwrite_a=False, check_finite=True):
"""
Compute pivoted LU decomposition of a general matrix.
The decomposition is:
.. math::
A = P L U
where :math:`P` is a permutation matrix, :math:`L` lower triangular with unit
diagonal elements, and :math:`U` upper triangular.
Args:
a (Tensor): a :math:`(M, N)` matrix to decompose.
permute_l (bool, optional): Perform the multiplication :math:`P L` (Default: do not permute). Default: False.
overwrite_a (bool, optional): Whether to overwrite data in :math:`A` (may improve performance). Default: False.
check_finite (bool, optional): Whether to check that the input matrix contains
only finite numbers. Disabling may give a performance gain, but may result
in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Default: True.
Returns:
**If permute_l == False**
- Tensor, :math:`(M, M)` permutation matrix.
- Tensor, :math:`(M, K)` lower triangular or trapezoidal matrix with unit diagonal. :math:`K = min(M, N)`.
- Tensor, :math:`(K, N)` upper triangular or trapezoidal matrix.
**If permute_l == True**
- Tensor, :math:`(M, K)` permuted L matrix. :math:`K = min(M, N)`.
- Tensor, :math:`(K, N)` upper triangular or trapezoidal matrix.
Supported Platforms:
``CPU`` ``GPU``
Examples:
>>> import numpy as onp
>>> from mindspore.common import Tensor
>>> from mindspore.scipy.linalg import lu
>>> A = Tensor(onp.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]]).astype(onp.float64))
>>> p, l, u = lu(A)
>>> p
Tensor(shape=[4, 4], dtype=Int32, value=
[[0, 1, 0, 0],
[0, 0, 0, 1],
[1, 0, 0, 0],
[0, 0, 1, 0]])
>>> l
Tensor(shape=[4, 4], dtype=Float64, value=
[[ 1.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[ 2.85714298e-01, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[ 7.14285731e-01, 1.19999997e-01, 1.00000000e+00, 0.00000000e+00],
[ 7.14285731e-01, -4.39999998e-01, -4.61538464e-01, 1.00000000e+00]])
>>> u
Tensor(shape=[4, 4], dtype=Float64, value=
[[ 7.00000000e+00, 5.00000000e+00, 6.00000000e+00, 6.00000000e+00],
[ 0.00000000e+00, 3.57142854e+00, 6.28571415e+00, 5.28571415e+00],
[ 0.00000000e+00, 0.00000000e+00, -1.03999996e+00, 3.07999992e+00],
[ 0.00000000e+00, -0.00000000e+00, -0.00000000e+00, 7.46153831e+00]])
"""
msp_lu = LU()
m_lu, _, p = msp_lu(a)
m = a.shape[-2]
n = a.shape[-1]
k = min(m, n)
a_dtype = a.dtype
l = mnp.tril(m_lu, -1)[:, :k] + mnp.eye(m, k, dtype=a_dtype)
u = mnp.triu(m_lu)[:k, :]
if permute_l:
return mnp.dot(p, l), u
return p, l, u | [
"def",
"lu",
"(",
"a",
",",
"permute_l",
"=",
"False",
",",
"overwrite_a",
"=",
"False",
",",
"check_finite",
"=",
"True",
")",
":",
"msp_lu",
"=",
"LU",
"(",
")",
"m_lu",
",",
"_",
",",
"p",
"=",
"msp_lu",
"(",
"a",
")",
"m",
"=",
"a",
".",
"shape",
"[",
"-",
"2",
"]",
"n",
"=",
"a",
".",
"shape",
"[",
"-",
"1",
"]",
"k",
"=",
"min",
"(",
"m",
",",
"n",
")",
"a_dtype",
"=",
"a",
".",
"dtype",
"l",
"=",
"mnp",
".",
"tril",
"(",
"m_lu",
",",
"-",
"1",
")",
"[",
":",
",",
":",
"k",
"]",
"+",
"mnp",
".",
"eye",
"(",
"m",
",",
"k",
",",
"dtype",
"=",
"a_dtype",
")",
"u",
"=",
"mnp",
".",
"triu",
"(",
"m_lu",
")",
"[",
":",
"k",
",",
":",
"]",
"if",
"permute_l",
":",
"return",
"mnp",
".",
"dot",
"(",
"p",
",",
"l",
")",
",",
"u",
"return",
"p",
",",
"l",
",",
"u"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/scipy/linalg.py#L520-L590 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.