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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateTime.GetNextWeekDay | (*args, **kwargs) | return _misc_.DateTime_GetNextWeekDay(*args, **kwargs) | GetNextWeekDay(self, int weekday) -> DateTime | GetNextWeekDay(self, int weekday) -> DateTime | [
"GetNextWeekDay",
"(",
"self",
"int",
"weekday",
")",
"-",
">",
"DateTime"
] | def GetNextWeekDay(*args, **kwargs):
"""GetNextWeekDay(self, int weekday) -> DateTime"""
return _misc_.DateTime_GetNextWeekDay(*args, **kwargs) | [
"def",
"GetNextWeekDay",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_GetNextWeekDay",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3857-L3859 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBFunction.__eq__ | (self, *args) | return _lldb.SBFunction___eq__(self, *args) | __eq__(self, SBFunction rhs) -> bool | __eq__(self, SBFunction rhs) -> bool | [
"__eq__",
"(",
"self",
"SBFunction",
"rhs",
")",
"-",
">",
"bool"
] | def __eq__(self, *args):
"""__eq__(self, SBFunction rhs) -> bool"""
return _lldb.SBFunction___eq__(self, *args) | [
"def",
"__eq__",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBFunction___eq__",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L5000-L5002 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus3.in.py | python | exodus.get_ids | (self, objType) | return ids | get mapping of exodus block/set index to user- or application-
defined block/set id; ids is ordered
by the *INDEX* ordering, a 1-based system going from
1 to number_set_or_block, used by exodus for storage
and input/output of array data stored on the blocks/sets; a
user or application can optionally use a separate block/set
*ID* numbering system, so the ids array points to the
block/set *ID* for each set *INDEX*
>>> node_set_ids = exo.get_ids('EX_NODE_SET')
Returns
-------
if array_type == 'ctype':
<list<int>> ids
if array_type == 'numpy':
<np_array<int>> ids | get mapping of exodus block/set index to user- or application-
defined block/set id; ids is ordered
by the *INDEX* ordering, a 1-based system going from
1 to number_set_or_block, used by exodus for storage
and input/output of array data stored on the blocks/sets; a
user or application can optionally use a separate block/set
*ID* numbering system, so the ids array points to the
block/set *ID* for each set *INDEX* | [
"get",
"mapping",
"of",
"exodus",
"block",
"/",
"set",
"index",
"to",
"user",
"-",
"or",
"application",
"-",
"defined",
"block",
"/",
"set",
"id",
";",
"ids",
"is",
"ordered",
"by",
"the",
"*",
"INDEX",
"*",
"ordering",
"a",
"1",
"-",
"based",
"system",
"going",
"from",
"1",
"to",
"number_set_or_block",
"used",
"by",
"exodus",
"for",
"storage",
"and",
"input",
"/",
"output",
"of",
"array",
"data",
"stored",
"on",
"the",
"blocks",
"/",
"sets",
";",
"a",
"user",
"or",
"application",
"can",
"optionally",
"use",
"a",
"separate",
"block",
"/",
"set",
"*",
"ID",
"*",
"numbering",
"system",
"so",
"the",
"ids",
"array",
"points",
"to",
"the",
"block",
"/",
"set",
"*",
"ID",
"*",
"for",
"each",
"set",
"*",
"INDEX",
"*"
] | def get_ids(self, objType):
"""
get mapping of exodus block/set index to user- or application-
defined block/set id; ids is ordered
by the *INDEX* ordering, a 1-based system going from
1 to number_set_or_block, used by exodus for storage
and input/output of array data stored on the blocks/sets; a
user or application can optionally use a separate block/set
*ID* numbering system, so the ids array points to the
block/set *ID* for each set *INDEX*
>>> node_set_ids = exo.get_ids('EX_NODE_SET')
Returns
-------
if array_type == 'ctype':
<list<int>> ids
if array_type == 'numpy':
<np_array<int>> ids
"""
ids = self.__ex_get_ids(objType)
if self.use_numpy:
ids = self.np.array(ids)
return ids | [
"def",
"get_ids",
"(",
"self",
",",
"objType",
")",
":",
"ids",
"=",
"self",
".",
"__ex_get_ids",
"(",
"objType",
")",
"if",
"self",
".",
"use_numpy",
":",
"ids",
"=",
"self",
".",
"np",
".",
"array",
"(",
"ids",
")",
"return",
"ids"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus3.in.py#L1888-L1913 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | GetDefaultConcurrentLinks | () | Returns a best-guess for a number of concurrent links. | Returns a best-guess for a number of concurrent links. | [
"Returns",
"a",
"best",
"-",
"guess",
"for",
"a",
"number",
"of",
"concurrent",
"links",
"."
] | def GetDefaultConcurrentLinks():
"""Returns a best-guess for a number of concurrent links."""
pool_size = int(os.environ.get('GYP_LINK_CONCURRENCY', 0))
if pool_size:
return pool_size
if sys.platform in ('win32', 'cygwin'):
import ctypes
class MEMORYSTATUSEX(ctypes.Structure):
_fields_ = [
("dwLength", ctypes.c_ulong),
("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong),
("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong),
("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong),
("ullAvailVirtual", ctypes.c_ulonglong),
("sullAvailExtendedVirtual", ctypes.c_ulonglong),
]
stat = MEMORYSTATUSEX()
stat.dwLength = ctypes.sizeof(stat)
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
# VS 2015 uses 20% more working set than VS 2013 and can consume all RAM
# on a 64 GB machine.
mem_limit = max(1, stat.ullTotalPhys / (5 * (2 ** 30))) # total / 5GB
hard_cap = max(1, int(os.environ.get('GYP_LINK_CONCURRENCY_MAX', 2**32)))
return min(mem_limit, hard_cap)
elif sys.platform.startswith('linux'):
if os.path.exists("/proc/meminfo"):
with open("/proc/meminfo") as meminfo:
memtotal_re = re.compile(r'^MemTotal:\s*(\d*)\s*kB')
for line in meminfo:
match = memtotal_re.match(line)
if not match:
continue
# Allow 8Gb per link on Linux because Gold is quite memory hungry
return max(1, int(match.group(1)) / (8 * (2 ** 20)))
return 1
elif sys.platform == 'darwin':
try:
avail_bytes = int(subprocess.check_output(['sysctl', '-n', 'hw.memsize']))
# A static library debug build of Chromium's unit_tests takes ~2.7GB, so
# 4GB per ld process allows for some more bloat.
return max(1, avail_bytes / (4 * (2 ** 30))) # total / 4GB
except:
return 1
else:
# TODO(scottmg): Implement this for other platforms.
return 1 | [
"def",
"GetDefaultConcurrentLinks",
"(",
")",
":",
"pool_size",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'GYP_LINK_CONCURRENCY'",
",",
"0",
")",
")",
"if",
"pool_size",
":",
"return",
"pool_size",
"if",
"sys",
".",
"platform",
"in",
"(",
"'win32'",
",",
"'cygwin'",
")",
":",
"import",
"ctypes",
"class",
"MEMORYSTATUSEX",
"(",
"ctypes",
".",
"Structure",
")",
":",
"_fields_",
"=",
"[",
"(",
"\"dwLength\"",
",",
"ctypes",
".",
"c_ulong",
")",
",",
"(",
"\"dwMemoryLoad\"",
",",
"ctypes",
".",
"c_ulong",
")",
",",
"(",
"\"ullTotalPhys\"",
",",
"ctypes",
".",
"c_ulonglong",
")",
",",
"(",
"\"ullAvailPhys\"",
",",
"ctypes",
".",
"c_ulonglong",
")",
",",
"(",
"\"ullTotalPageFile\"",
",",
"ctypes",
".",
"c_ulonglong",
")",
",",
"(",
"\"ullAvailPageFile\"",
",",
"ctypes",
".",
"c_ulonglong",
")",
",",
"(",
"\"ullTotalVirtual\"",
",",
"ctypes",
".",
"c_ulonglong",
")",
",",
"(",
"\"ullAvailVirtual\"",
",",
"ctypes",
".",
"c_ulonglong",
")",
",",
"(",
"\"sullAvailExtendedVirtual\"",
",",
"ctypes",
".",
"c_ulonglong",
")",
",",
"]",
"stat",
"=",
"MEMORYSTATUSEX",
"(",
")",
"stat",
".",
"dwLength",
"=",
"ctypes",
".",
"sizeof",
"(",
"stat",
")",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"GlobalMemoryStatusEx",
"(",
"ctypes",
".",
"byref",
"(",
"stat",
")",
")",
"# VS 2015 uses 20% more working set than VS 2013 and can consume all RAM",
"# on a 64 GB machine.",
"mem_limit",
"=",
"max",
"(",
"1",
",",
"stat",
".",
"ullTotalPhys",
"/",
"(",
"5",
"*",
"(",
"2",
"**",
"30",
")",
")",
")",
"# total / 5GB",
"hard_cap",
"=",
"max",
"(",
"1",
",",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'GYP_LINK_CONCURRENCY_MAX'",
",",
"2",
"**",
"32",
")",
")",
")",
"return",
"min",
"(",
"mem_limit",
",",
"hard_cap",
")",
"elif",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'linux'",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"\"/proc/meminfo\"",
")",
":",
"with",
"open",
"(",
"\"/proc/meminfo\"",
")",
"as",
"meminfo",
":",
"memtotal_re",
"=",
"re",
".",
"compile",
"(",
"r'^MemTotal:\\s*(\\d*)\\s*kB'",
")",
"for",
"line",
"in",
"meminfo",
":",
"match",
"=",
"memtotal_re",
".",
"match",
"(",
"line",
")",
"if",
"not",
"match",
":",
"continue",
"# Allow 8Gb per link on Linux because Gold is quite memory hungry",
"return",
"max",
"(",
"1",
",",
"int",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
"/",
"(",
"8",
"*",
"(",
"2",
"**",
"20",
")",
")",
")",
"return",
"1",
"elif",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"try",
":",
"avail_bytes",
"=",
"int",
"(",
"subprocess",
".",
"check_output",
"(",
"[",
"'sysctl'",
",",
"'-n'",
",",
"'hw.memsize'",
"]",
")",
")",
"# A static library debug build of Chromium's unit_tests takes ~2.7GB, so",
"# 4GB per ld process allows for some more bloat.",
"return",
"max",
"(",
"1",
",",
"avail_bytes",
"/",
"(",
"4",
"*",
"(",
"2",
"**",
"30",
")",
")",
")",
"# total / 4GB",
"except",
":",
"return",
"1",
"else",
":",
"# TODO(scottmg): Implement this for other platforms.",
"return",
"1"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L1686-L1738 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/commands.py | python | getoutput | (cmd) | return getstatusoutput(cmd)[1] | Return output (stdout or stderr) of executing cmd in a shell. | Return output (stdout or stderr) of executing cmd in a shell. | [
"Return",
"output",
"(",
"stdout",
"or",
"stderr",
")",
"of",
"executing",
"cmd",
"in",
"a",
"shell",
"."
] | def getoutput(cmd):
"""Return output (stdout or stderr) of executing cmd in a shell."""
return getstatusoutput(cmd)[1] | [
"def",
"getoutput",
"(",
"cmd",
")",
":",
"return",
"getstatusoutput",
"(",
"cmd",
")",
"[",
"1",
"]"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/commands.py#L44-L46 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_editv.py | python | EdEditorView.OnMenuEvent | (self, evt) | Handle context menu events | Handle context menu events | [
"Handle",
"context",
"menu",
"events"
] | def OnMenuEvent(self, evt):
"""Handle context menu events"""
e_id = evt.GetId()
handler = self._menu.GetHandler(e_id)
# Handle custom menu items
if handler is not None:
handler(self, evt)
else:
self.ControlDispatch(evt)
if evt.GetSkipped():
evt.Skip() | [
"def",
"OnMenuEvent",
"(",
"self",
",",
"evt",
")",
":",
"e_id",
"=",
"evt",
".",
"GetId",
"(",
")",
"handler",
"=",
"self",
".",
"_menu",
".",
"GetHandler",
"(",
"e_id",
")",
"# Handle custom menu items",
"if",
"handler",
"is",
"not",
"None",
":",
"handler",
"(",
"self",
",",
"evt",
")",
"else",
":",
"self",
".",
"ControlDispatch",
"(",
"evt",
")",
"if",
"evt",
".",
"GetSkipped",
"(",
")",
":",
"evt",
".",
"Skip",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_editv.py#L532-L543 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/eager/context.py | python | get_config | () | return context().config | Get the ConfigProto of Context.
Returns:
The ConfigProto of Context. | Get the ConfigProto of Context. | [
"Get",
"the",
"ConfigProto",
"of",
"Context",
"."
] | def get_config():
"""Get the ConfigProto of Context.
Returns:
The ConfigProto of Context.
"""
return context().config | [
"def",
"get_config",
"(",
")",
":",
"return",
"context",
"(",
")",
".",
"config"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/context.py#L2308-L2314 | |
CNugteren/CLBlast | 4500a03440e2cc54998c0edab366babf5e504d67 | scripts/generator/generator/routine.py | python | Routine.buffers_without_ld_inc | (self) | return self.scalar_buffers_first() + self.scalar_buffers_second() + ["ap", "im", "col", "kernel", "result"] | List of buffers without 'inc' or 'ld | List of buffers without 'inc' or 'ld | [
"List",
"of",
"buffers",
"without",
"inc",
"or",
"ld"
] | def buffers_without_ld_inc(self):
"""List of buffers without 'inc' or 'ld'"""
return self.scalar_buffers_first() + self.scalar_buffers_second() + ["ap", "im", "col", "kernel", "result"] | [
"def",
"buffers_without_ld_inc",
"(",
"self",
")",
":",
"return",
"self",
".",
"scalar_buffers_first",
"(",
")",
"+",
"self",
".",
"scalar_buffers_second",
"(",
")",
"+",
"[",
"\"ap\"",
",",
"\"im\"",
",",
"\"col\"",
",",
"\"kernel\"",
",",
"\"result\"",
"]"
] | https://github.com/CNugteren/CLBlast/blob/4500a03440e2cc54998c0edab366babf5e504d67/scripts/generator/generator/routine.py#L193-L195 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/logging/__init__.py | python | Logger.error | (self, msg, *args, **kwargs) | Log 'msg % args' with severity 'ERROR'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.error("Houston, we have a %s", "major problem", exc_info=1) | Log 'msg % args' with severity 'ERROR'. | [
"Log",
"msg",
"%",
"args",
"with",
"severity",
"ERROR",
"."
] | def error(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'ERROR'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.error("Houston, we have a %s", "major problem", exc_info=1)
"""
if self.isEnabledFor(ERROR):
self._log(ERROR, msg, args, **kwargs) | [
"def",
"error",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"isEnabledFor",
"(",
"ERROR",
")",
":",
"self",
".",
"_log",
"(",
"ERROR",
",",
"msg",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/__init__.py#L1465-L1475 | ||
sigmaai/self-driving-golf-cart | 8d891600af3d851add27a10ae45cf3c2108bb87c | ros/src/ros_carla_bridge/carla_ackermann_control/src/carla_ackermann_control/carla_control_physics.py | python | get_engine_brake_force | (_) | return 500.0 | Calculate the engine brake force of a carla vehicle if the gas pedal would be layed off
As this heavily depends on the engine, the current gear and velocity, this is not
trivial to calculate. Maybe one can get this from within Unreal to the outside,
to enable better vehicle control.
For the moment we just put a constant force.
:param vehicle_info: the vehicle info
:type vehicle_info: carla_ros_bridge.CarlaEgoVehicleInfo
:return: engine braking force [N]
:rtype: float64 | Calculate the engine brake force of a carla vehicle if the gas pedal would be layed off | [
"Calculate",
"the",
"engine",
"brake",
"force",
"of",
"a",
"carla",
"vehicle",
"if",
"the",
"gas",
"pedal",
"would",
"be",
"layed",
"off"
] | def get_engine_brake_force(_):
"""
Calculate the engine brake force of a carla vehicle if the gas pedal would be layed off
As this heavily depends on the engine, the current gear and velocity, this is not
trivial to calculate. Maybe one can get this from within Unreal to the outside,
to enable better vehicle control.
For the moment we just put a constant force.
:param vehicle_info: the vehicle info
:type vehicle_info: carla_ros_bridge.CarlaEgoVehicleInfo
:return: engine braking force [N]
:rtype: float64
"""
return 500.0 | [
"def",
"get_engine_brake_force",
"(",
"_",
")",
":",
"return",
"500.0"
] | https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/carla_ackermann_control/src/carla_ackermann_control/carla_control_physics.py#L32-L46 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/process.py | python | Process.terminate | (self) | Terminate process; sends SIGTERM signal or uses TerminateProcess() | Terminate process; sends SIGTERM signal or uses TerminateProcess() | [
"Terminate",
"process",
";",
"sends",
"SIGTERM",
"signal",
"or",
"uses",
"TerminateProcess",
"()"
] | def terminate(self):
'''
Terminate process; sends SIGTERM signal or uses TerminateProcess()
'''
self._popen.terminate() | [
"def",
"terminate",
"(",
"self",
")",
":",
"self",
".",
"_popen",
".",
"terminate",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/process.py#L133-L137 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/client/timeline.py | python | Timeline._allocate_pids | (self) | Allocate fake process ids for each device in the StepStats. | Allocate fake process ids for each device in the StepStats. | [
"Allocate",
"fake",
"process",
"ids",
"for",
"each",
"device",
"in",
"the",
"StepStats",
"."
] | def _allocate_pids(self):
"""Allocate fake process ids for each device in the StepStats."""
self._allocators_pid = self._alloc_pid()
self._chrome_trace.emit_pid('Allocators', self._allocators_pid)
# Add processes in the Chrome trace to show compute and data activity.
for dev_stats in self._step_stats.dev_stats:
device_pid = self._alloc_pid()
self._device_pids[dev_stats.device] = device_pid
tensors_pid = self._alloc_pid()
self._tensor_pids[dev_stats.device] = tensors_pid
self._chrome_trace.emit_pid(dev_stats.device + ' Compute', device_pid)
self._chrome_trace.emit_pid(dev_stats.device + ' Tensors', tensors_pid) | [
"def",
"_allocate_pids",
"(",
"self",
")",
":",
"self",
".",
"_allocators_pid",
"=",
"self",
".",
"_alloc_pid",
"(",
")",
"self",
".",
"_chrome_trace",
".",
"emit_pid",
"(",
"'Allocators'",
",",
"self",
".",
"_allocators_pid",
")",
"# Add processes in the Chrome trace to show compute and data activity.",
"for",
"dev_stats",
"in",
"self",
".",
"_step_stats",
".",
"dev_stats",
":",
"device_pid",
"=",
"self",
".",
"_alloc_pid",
"(",
")",
"self",
".",
"_device_pids",
"[",
"dev_stats",
".",
"device",
"]",
"=",
"device_pid",
"tensors_pid",
"=",
"self",
".",
"_alloc_pid",
"(",
")",
"self",
".",
"_tensor_pids",
"[",
"dev_stats",
".",
"device",
"]",
"=",
"tensors_pid",
"self",
".",
"_chrome_trace",
".",
"emit_pid",
"(",
"dev_stats",
".",
"device",
"+",
"' Compute'",
",",
"device_pid",
")",
"self",
".",
"_chrome_trace",
".",
"emit_pid",
"(",
"dev_stats",
".",
"device",
"+",
"' Tensors'",
",",
"tensors_pid",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/client/timeline.py#L462-L474 | ||
fritzsedlazeck/Sniffles | 82d885e5a74b526e18dd87b52554aea8139dd3aa | src/sniffles/leadprov.py | python | CIGAR_listreadstart_rev | (ops) | Position in query read where CIGAR alignment starts (i.e. taking into account start clipping) | Position in query read where CIGAR alignment starts (i.e. taking into account start clipping) | [
"Position",
"in",
"query",
"read",
"where",
"CIGAR",
"alignment",
"starts",
"(",
"i",
".",
"e",
".",
"taking",
"into",
"account",
"start",
"clipping",
")"
] | def CIGAR_listreadstart_rev(ops):
#TODO: Obsolete (see CIGAR_analyze)
"""
Position in query read where CIGAR alignment starts (i.e. taking into account start clipping)
"""
op,oplen=ops[-1]
op2,op2len=ops[-2]
if op=="H" or op=="S":
assert(op2!="H" and op2!="S")
return oplen
else:
return 0 | [
"def",
"CIGAR_listreadstart_rev",
"(",
"ops",
")",
":",
"#TODO: Obsolete (see CIGAR_analyze)",
"op",
",",
"oplen",
"=",
"ops",
"[",
"-",
"1",
"]",
"op2",
",",
"op2len",
"=",
"ops",
"[",
"-",
"2",
"]",
"if",
"op",
"==",
"\"H\"",
"or",
"op",
"==",
"\"S\"",
":",
"assert",
"(",
"op2",
"!=",
"\"H\"",
"and",
"op2",
"!=",
"\"S\"",
")",
"return",
"oplen",
"else",
":",
"return",
"0"
] | https://github.com/fritzsedlazeck/Sniffles/blob/82d885e5a74b526e18dd87b52554aea8139dd3aa/src/sniffles/leadprov.py#L124-L135 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/XRCed/component.py | python | Container.requireImplicit | (self, node) | return False | If there are implicit nodes for this particular node. | If there are implicit nodes for this particular node. | [
"If",
"there",
"are",
"implicit",
"nodes",
"for",
"this",
"particular",
"node",
"."
] | def requireImplicit(self, node):
'''If there are implicit nodes for this particular node.'''
return False | [
"def",
"requireImplicit",
"(",
"self",
",",
"node",
")",
":",
"return",
"False"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/XRCed/component.py#L376-L378 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/labeled_tensor/python/ops/ops.py | python | ones_like | (labeled_tensor, dtype=None, name=None) | Creates an identical tensor with all elements set to one.
Args:
labeled_tensor: The input tensor.
dtype: The type of the returned tensor.
name: Optional op name.
Returns:
The tensor with elements set to one. | Creates an identical tensor with all elements set to one. | [
"Creates",
"an",
"identical",
"tensor",
"with",
"all",
"elements",
"set",
"to",
"one",
"."
] | def ones_like(labeled_tensor, dtype=None, name=None):
"""Creates an identical tensor with all elements set to one.
Args:
labeled_tensor: The input tensor.
dtype: The type of the returned tensor.
name: Optional op name.
Returns:
The tensor with elements set to one.
"""
with ops.name_scope(name, 'lt_ones_like', [labeled_tensor]) as scope:
labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor)
op = array_ops.ones_like(labeled_tensor.tensor, dtype=dtype, name=scope)
return core.LabeledTensor(op, labeled_tensor.axes) | [
"def",
"ones_like",
"(",
"labeled_tensor",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"'lt_ones_like'",
",",
"[",
"labeled_tensor",
"]",
")",
"as",
"scope",
":",
"labeled_tensor",
"=",
"core",
".",
"convert_to_labeled_tensor",
"(",
"labeled_tensor",
")",
"op",
"=",
"array_ops",
".",
"ones_like",
"(",
"labeled_tensor",
".",
"tensor",
",",
"dtype",
"=",
"dtype",
",",
"name",
"=",
"scope",
")",
"return",
"core",
".",
"LabeledTensor",
"(",
"op",
",",
"labeled_tensor",
".",
"axes",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/labeled_tensor/python/ops/ops.py#L1150-L1164 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/interpolate/interpolate.py | python | _do_extrapolate | (fill_value) | return (isinstance(fill_value, string_types) and
fill_value == 'extrapolate') | Helper to check if fill_value == "extrapolate" without warnings | Helper to check if fill_value == "extrapolate" without warnings | [
"Helper",
"to",
"check",
"if",
"fill_value",
"==",
"extrapolate",
"without",
"warnings"
] | def _do_extrapolate(fill_value):
"""Helper to check if fill_value == "extrapolate" without warnings"""
return (isinstance(fill_value, string_types) and
fill_value == 'extrapolate') | [
"def",
"_do_extrapolate",
"(",
"fill_value",
")",
":",
"return",
"(",
"isinstance",
"(",
"fill_value",
",",
"string_types",
")",
"and",
"fill_value",
"==",
"'extrapolate'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/interpolate/interpolate.py#L322-L325 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/pyprogress.py | python | PyProgress.OnCancel | (self, event) | Handles the ``wx.EVT_BUTTON`` event for the dialog.
:param `event`: a :class:`CommandEvent` event to be processed.
:note: This method handles the ``Cancel`` button press. | Handles the ``wx.EVT_BUTTON`` event for the dialog. | [
"Handles",
"the",
"wx",
".",
"EVT_BUTTON",
"event",
"for",
"the",
"dialog",
"."
] | def OnCancel(self, event):
"""
Handles the ``wx.EVT_BUTTON`` event for the dialog.
:param `event`: a :class:`CommandEvent` event to be processed.
:note: This method handles the ``Cancel`` button press.
"""
if self._state == Finished:
# this means that the count down is already finished and we're being
# shown as a modal dialog - so just let the default handler do the job
event.Skip()
else:
# request to cancel was received, the next time Update() is called we
# will handle it
self._state = Canceled
# update the buttons state immediately so that the user knows that the
# request has been noticed
self.DisableAbort()
# save the time when the dialog was stopped
self._timeStop = wx.GetCurrentTime()
self.ReenableOtherWindows() | [
"def",
"OnCancel",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"_state",
"==",
"Finished",
":",
"# this means that the count down is already finished and we're being",
"# shown as a modal dialog - so just let the default handler do the job",
"event",
".",
"Skip",
"(",
")",
"else",
":",
"# request to cancel was received, the next time Update() is called we",
"# will handle it",
"self",
".",
"_state",
"=",
"Canceled",
"# update the buttons state immediately so that the user knows that the",
"# request has been noticed",
"self",
".",
"DisableAbort",
"(",
")",
"# save the time when the dialog was stopped",
"self",
".",
"_timeStop",
"=",
"wx",
".",
"GetCurrentTime",
"(",
")",
"self",
".",
"ReenableOtherWindows",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/pyprogress.py#L747-L775 | ||
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/generator/make.py | python | MakefileWriter.Pchify | (self, path, lang) | return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path) | Convert a prefix header path to its output directory form. | Convert a prefix header path to its output directory form. | [
"Convert",
"a",
"prefix",
"header",
"path",
"to",
"its",
"output",
"directory",
"form",
"."
] | def Pchify(self, path, lang):
"""Convert a prefix header path to its output directory form."""
path = self.Absolutify(path)
if '$(' in path:
path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/pch-%s' %
(self.toolset, lang))
return path
return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path) | [
"def",
"Pchify",
"(",
"self",
",",
"path",
",",
"lang",
")",
":",
"path",
"=",
"self",
".",
"Absolutify",
"(",
"path",
")",
"if",
"'$('",
"in",
"path",
":",
"path",
"=",
"path",
".",
"replace",
"(",
"'$(obj)/'",
",",
"'$(obj).%s/$(TARGET)/pch-%s'",
"%",
"(",
"self",
".",
"toolset",
",",
"lang",
")",
")",
"return",
"path",
"return",
"'$(obj).%s/$(TARGET)/pch-%s/%s'",
"%",
"(",
"self",
".",
"toolset",
",",
"lang",
",",
"path",
")"
] | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/generator/make.py#L1885-L1892 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/formats/style_render.py | python | _wrap_decimal_thousands | (
formatter: Callable, decimal: str, thousands: str | None
) | return wrapper | Takes a string formatting function and wraps logic to deal with thousands and
decimal parameters, in the case that they are non-standard and that the input
is a (float, complex, int). | Takes a string formatting function and wraps logic to deal with thousands and
decimal parameters, in the case that they are non-standard and that the input
is a (float, complex, int). | [
"Takes",
"a",
"string",
"formatting",
"function",
"and",
"wraps",
"logic",
"to",
"deal",
"with",
"thousands",
"and",
"decimal",
"parameters",
"in",
"the",
"case",
"that",
"they",
"are",
"non",
"-",
"standard",
"and",
"that",
"the",
"input",
"is",
"a",
"(",
"float",
"complex",
"int",
")",
"."
] | def _wrap_decimal_thousands(
formatter: Callable, decimal: str, thousands: str | None
) -> Callable:
"""
Takes a string formatting function and wraps logic to deal with thousands and
decimal parameters, in the case that they are non-standard and that the input
is a (float, complex, int).
"""
def wrapper(x):
if isinstance(x, (float, complex, int)):
if decimal != "." and thousands is not None and thousands != ",":
return (
formatter(x)
.replace(",", "§_§-") # rare string to avoid "," <-> "." clash.
.replace(".", decimal)
.replace("§_§-", thousands)
)
elif decimal != "." and (thousands is None or thousands == ","):
return formatter(x).replace(".", decimal)
elif decimal == "." and thousands is not None and thousands != ",":
return formatter(x).replace(",", thousands)
return formatter(x)
return wrapper | [
"def",
"_wrap_decimal_thousands",
"(",
"formatter",
":",
"Callable",
",",
"decimal",
":",
"str",
",",
"thousands",
":",
"str",
"|",
"None",
")",
"->",
"Callable",
":",
"def",
"wrapper",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"(",
"float",
",",
"complex",
",",
"int",
")",
")",
":",
"if",
"decimal",
"!=",
"\".\"",
"and",
"thousands",
"is",
"not",
"None",
"and",
"thousands",
"!=",
"\",\"",
":",
"return",
"(",
"formatter",
"(",
"x",
")",
".",
"replace",
"(",
"\",\"",
",",
"\"§_§-\") ",
" ",
"rare string to avoid \",\" <-> \".\" clash.",
".",
"replace",
"(",
"\".\"",
",",
"decimal",
")",
".",
"replace",
"(",
"\"§_§-\", ",
"t",
"ousands)",
"",
")",
"elif",
"decimal",
"!=",
"\".\"",
"and",
"(",
"thousands",
"is",
"None",
"or",
"thousands",
"==",
"\",\"",
")",
":",
"return",
"formatter",
"(",
"x",
")",
".",
"replace",
"(",
"\".\"",
",",
"decimal",
")",
"elif",
"decimal",
"==",
"\".\"",
"and",
"thousands",
"is",
"not",
"None",
"and",
"thousands",
"!=",
"\",\"",
":",
"return",
"formatter",
"(",
"x",
")",
".",
"replace",
"(",
"\",\"",
",",
"thousands",
")",
"return",
"formatter",
"(",
"x",
")",
"return",
"wrapper"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/style_render.py#L921-L945 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_fragment.py | python | check_feu | (assumes,asserts,macros) | Take a list of assumes, assert and macros, and determines
whether collectively they are in the FEU fragment, raising an error
exception if not. | Take a list of assumes, assert and macros, and determines
whether collectively they are in the FEU fragment, raising an error
exception if not. | [
"Take",
"a",
"list",
"of",
"assumes",
"assert",
"and",
"macros",
"and",
"determines",
"whether",
"collectively",
"they",
"are",
"in",
"the",
"FEU",
"fragment",
"raising",
"an",
"error",
"exception",
"if",
"not",
"."
] | def check_feu(assumes,asserts,macros):
""" Take a list of assumes, assert and macros, and determines
whether collectively they are in the FEU fragment, raising an error
exception if not. """
# Alpha convert so that all the variables have unique names,
global var_uniq
var_uniq = il.VariableUniqifier()
def vupair(p):
return (var_uniq(p[0]),p[1])
assumes = map(vupair,assumes)
asserts = map(vupair,asserts)
macros = map(vupair,macros)
# Create the stratificaiton graph, as described above.
create_strat_map(assumes,asserts,macros)
# Check for cycles in the stratification graph.
report_cycle(iu.cycle(arcs, first = lambda x: find(x[0]), second = lambda x: find(x[1]))) | [
"def",
"check_feu",
"(",
"assumes",
",",
"asserts",
",",
"macros",
")",
":",
"# Alpha convert so that all the variables have unique names,",
"global",
"var_uniq",
"var_uniq",
"=",
"il",
".",
"VariableUniqifier",
"(",
")",
"def",
"vupair",
"(",
"p",
")",
":",
"return",
"(",
"var_uniq",
"(",
"p",
"[",
"0",
"]",
")",
",",
"p",
"[",
"1",
"]",
")",
"assumes",
"=",
"map",
"(",
"vupair",
",",
"assumes",
")",
"asserts",
"=",
"map",
"(",
"vupair",
",",
"asserts",
")",
"macros",
"=",
"map",
"(",
"vupair",
",",
"macros",
")",
"# Create the stratificaiton graph, as described above.",
"create_strat_map",
"(",
"assumes",
",",
"asserts",
",",
"macros",
")",
"# Check for cycles in the stratification graph.",
"report_cycle",
"(",
"iu",
".",
"cycle",
"(",
"arcs",
",",
"first",
"=",
"lambda",
"x",
":",
"find",
"(",
"x",
"[",
"0",
"]",
")",
",",
"second",
"=",
"lambda",
"x",
":",
"find",
"(",
"x",
"[",
"1",
"]",
")",
")",
")"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_fragment.py#L441-L464 | ||
linkingvision/rapidvms | 20a80c2aa78bd005a8a1556b47c2c50ee530c730 | velib/3rdparty/libyuv/tools/valgrind-libyuv/memcheck/PRESUBMIT.py | python | CheckChange | (input_api, output_api) | return [] | Checks the memcheck suppressions files for bad data. | Checks the memcheck suppressions files for bad data. | [
"Checks",
"the",
"memcheck",
"suppressions",
"files",
"for",
"bad",
"data",
"."
] | def CheckChange(input_api, output_api):
"""Checks the memcheck suppressions files for bad data."""
# Add the path to the Chrome valgrind dir to the import path:
tools_vg_path = os.path.join(input_api.PresubmitLocalPath(), '..', '..',
'valgrind')
sys.path.append(tools_vg_path)
import suppressions
sup_regex = re.compile('suppressions.*\.txt$')
suppressions = {}
errors = []
check_for_memcheck = False
# skip_next_line has 3 possible values:
# - False: don't skip the next line.
# - 'skip_suppression_name': the next line is a suppression name, skip.
# - 'skip_param': the next line is a system call parameter error, skip.
skip_next_line = False
for f in filter(lambda x: sup_regex.search(x.LocalPath()),
input_api.AffectedFiles()):
for line, line_num in zip(f.NewContents(),
xrange(1, len(f.NewContents()) + 1)):
line = line.lstrip()
if line.startswith('#') or not line:
continue
if skip_next_line:
if skip_next_line == 'skip_suppression_name':
if 'insert_a_suppression_name_here' in line:
errors.append('"insert_a_suppression_name_here" is not a valid '
'suppression name')
if suppressions.has_key(line):
if f.LocalPath() == suppressions[line][1]:
errors.append('suppression with name "%s" at %s line %s '
'has already been defined at line %s' %
(line, f.LocalPath(), line_num,
suppressions[line][1]))
else:
errors.append('suppression with name "%s" at %s line %s '
'has already been defined at %s line %s' %
(line, f.LocalPath(), line_num,
suppressions[line][0], suppressions[line][1]))
else:
suppressions[line] = (f, line_num)
check_for_memcheck = True;
skip_next_line = False
continue
if check_for_memcheck:
if not line.startswith('Memcheck:'):
errors.append('"%s" should be "Memcheck:..." in %s line %s' %
(line, f.LocalPath(), line_num))
check_for_memcheck = False;
if line == '{':
skip_next_line = 'skip_suppression_name'
continue
if line == "Memcheck:Param":
skip_next_line = 'skip_param'
continue
if (line.startswith('fun:') or line.startswith('obj:') or
line.startswith('Memcheck:') or line == '}' or
line == '...'):
continue
errors.append('"%s" is probably wrong: %s line %s' % (line, f.LocalPath(),
line_num))
if errors:
return [output_api.PresubmitError('\n'.join(errors))]
return [] | [
"def",
"CheckChange",
"(",
"input_api",
",",
"output_api",
")",
":",
"# Add the path to the Chrome valgrind dir to the import path:",
"tools_vg_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"input_api",
".",
"PresubmitLocalPath",
"(",
")",
",",
"'..'",
",",
"'..'",
",",
"'valgrind'",
")",
"sys",
".",
"path",
".",
"append",
"(",
"tools_vg_path",
")",
"import",
"suppressions",
"sup_regex",
"=",
"re",
".",
"compile",
"(",
"'suppressions.*\\.txt$'",
")",
"suppressions",
"=",
"{",
"}",
"errors",
"=",
"[",
"]",
"check_for_memcheck",
"=",
"False",
"# skip_next_line has 3 possible values:",
"# - False: don't skip the next line.",
"# - 'skip_suppression_name': the next line is a suppression name, skip.",
"# - 'skip_param': the next line is a system call parameter error, skip.",
"skip_next_line",
"=",
"False",
"for",
"f",
"in",
"filter",
"(",
"lambda",
"x",
":",
"sup_regex",
".",
"search",
"(",
"x",
".",
"LocalPath",
"(",
")",
")",
",",
"input_api",
".",
"AffectedFiles",
"(",
")",
")",
":",
"for",
"line",
",",
"line_num",
"in",
"zip",
"(",
"f",
".",
"NewContents",
"(",
")",
",",
"xrange",
"(",
"1",
",",
"len",
"(",
"f",
".",
"NewContents",
"(",
")",
")",
"+",
"1",
")",
")",
":",
"line",
"=",
"line",
".",
"lstrip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
"or",
"not",
"line",
":",
"continue",
"if",
"skip_next_line",
":",
"if",
"skip_next_line",
"==",
"'skip_suppression_name'",
":",
"if",
"'insert_a_suppression_name_here'",
"in",
"line",
":",
"errors",
".",
"append",
"(",
"'\"insert_a_suppression_name_here\" is not a valid '",
"'suppression name'",
")",
"if",
"suppressions",
".",
"has_key",
"(",
"line",
")",
":",
"if",
"f",
".",
"LocalPath",
"(",
")",
"==",
"suppressions",
"[",
"line",
"]",
"[",
"1",
"]",
":",
"errors",
".",
"append",
"(",
"'suppression with name \"%s\" at %s line %s '",
"'has already been defined at line %s'",
"%",
"(",
"line",
",",
"f",
".",
"LocalPath",
"(",
")",
",",
"line_num",
",",
"suppressions",
"[",
"line",
"]",
"[",
"1",
"]",
")",
")",
"else",
":",
"errors",
".",
"append",
"(",
"'suppression with name \"%s\" at %s line %s '",
"'has already been defined at %s line %s'",
"%",
"(",
"line",
",",
"f",
".",
"LocalPath",
"(",
")",
",",
"line_num",
",",
"suppressions",
"[",
"line",
"]",
"[",
"0",
"]",
",",
"suppressions",
"[",
"line",
"]",
"[",
"1",
"]",
")",
")",
"else",
":",
"suppressions",
"[",
"line",
"]",
"=",
"(",
"f",
",",
"line_num",
")",
"check_for_memcheck",
"=",
"True",
"skip_next_line",
"=",
"False",
"continue",
"if",
"check_for_memcheck",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"'Memcheck:'",
")",
":",
"errors",
".",
"append",
"(",
"'\"%s\" should be \"Memcheck:...\" in %s line %s'",
"%",
"(",
"line",
",",
"f",
".",
"LocalPath",
"(",
")",
",",
"line_num",
")",
")",
"check_for_memcheck",
"=",
"False",
"if",
"line",
"==",
"'{'",
":",
"skip_next_line",
"=",
"'skip_suppression_name'",
"continue",
"if",
"line",
"==",
"\"Memcheck:Param\"",
":",
"skip_next_line",
"=",
"'skip_param'",
"continue",
"if",
"(",
"line",
".",
"startswith",
"(",
"'fun:'",
")",
"or",
"line",
".",
"startswith",
"(",
"'obj:'",
")",
"or",
"line",
".",
"startswith",
"(",
"'Memcheck:'",
")",
"or",
"line",
"==",
"'}'",
"or",
"line",
"==",
"'...'",
")",
":",
"continue",
"errors",
".",
"append",
"(",
"'\"%s\" is probably wrong: %s line %s'",
"%",
"(",
"line",
",",
"f",
".",
"LocalPath",
"(",
")",
",",
"line_num",
")",
")",
"if",
"errors",
":",
"return",
"[",
"output_api",
".",
"PresubmitError",
"(",
"'\\n'",
".",
"join",
"(",
"errors",
")",
")",
"]",
"return",
"[",
"]"
] | https://github.com/linkingvision/rapidvms/blob/20a80c2aa78bd005a8a1556b47c2c50ee530c730/velib/3rdparty/libyuv/tools/valgrind-libyuv/memcheck/PRESUBMIT.py#L21-L88 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/cpplint.py | python | IsOutOfLineMethodDefinition | (clean_lines, linenum) | return False | Check if current line contains an out-of-line method definition.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains an out-of-line method definition. | Check if current line contains an out-of-line method definition. | [
"Check",
"if",
"current",
"line",
"contains",
"an",
"out",
"-",
"of",
"-",
"line",
"method",
"definition",
"."
] | def IsOutOfLineMethodDefinition(clean_lines, linenum):
"""Check if current line contains an out-of-line method definition.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains an out-of-line method definition.
"""
# Scan back a few lines for start of current function
for i in xrange(linenum, max(-1, linenum - 10), -1):
if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
return False | [
"def",
"IsOutOfLineMethodDefinition",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"# Scan back a few lines for start of current function",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
",",
"max",
"(",
"-",
"1",
",",
"linenum",
"-",
"10",
")",
",",
"-",
"1",
")",
":",
"if",
"Match",
"(",
"r'^([^()]*\\w+)\\('",
",",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
")",
":",
"return",
"Match",
"(",
"r'^[^()]*\\w+::\\w+\\('",
",",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
")",
"is",
"not",
"None",
"return",
"False"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/cpplint.py#L5155-L5168 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/third_party/jinja2/compiler.py | python | CodeGenerator.pop_parameter_definitions | (self) | Pops the current parameter definitions set. | Pops the current parameter definitions set. | [
"Pops",
"the",
"current",
"parameter",
"definitions",
"set",
"."
] | def pop_parameter_definitions(self):
"""Pops the current parameter definitions set."""
self._param_def_block.pop() | [
"def",
"pop_parameter_definitions",
"(",
"self",
")",
":",
"self",
".",
"_param_def_block",
".",
"pop",
"(",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/compiler.py#L623-L625 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/fftpack/basic.py | python | _raw_fft | (x, n, axis, direction, overwrite_x, work_function) | return r | Internal auxiliary function for fft, ifft, rfft, irfft. | Internal auxiliary function for fft, ifft, rfft, irfft. | [
"Internal",
"auxiliary",
"function",
"for",
"fft",
"ifft",
"rfft",
"irfft",
"."
] | def _raw_fft(x, n, axis, direction, overwrite_x, work_function):
""" Internal auxiliary function for fft, ifft, rfft, irfft."""
if n is None:
n = x.shape[axis]
elif n != x.shape[axis]:
x, copy_made = _fix_shape(x,n,axis)
overwrite_x = overwrite_x or copy_made
if n < 1:
raise ValueError("Invalid number of FFT data points "
"(%d) specified." % n)
if axis == -1 or axis == len(x.shape)-1:
r = work_function(x,n,direction,overwrite_x=overwrite_x)
else:
x = swapaxes(x, axis, -1)
r = work_function(x,n,direction,overwrite_x=overwrite_x)
r = swapaxes(r, axis, -1)
return r | [
"def",
"_raw_fft",
"(",
"x",
",",
"n",
",",
"axis",
",",
"direction",
",",
"overwrite_x",
",",
"work_function",
")",
":",
"if",
"n",
"is",
"None",
":",
"n",
"=",
"x",
".",
"shape",
"[",
"axis",
"]",
"elif",
"n",
"!=",
"x",
".",
"shape",
"[",
"axis",
"]",
":",
"x",
",",
"copy_made",
"=",
"_fix_shape",
"(",
"x",
",",
"n",
",",
"axis",
")",
"overwrite_x",
"=",
"overwrite_x",
"or",
"copy_made",
"if",
"n",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Invalid number of FFT data points \"",
"\"(%d) specified.\"",
"%",
"n",
")",
"if",
"axis",
"==",
"-",
"1",
"or",
"axis",
"==",
"len",
"(",
"x",
".",
"shape",
")",
"-",
"1",
":",
"r",
"=",
"work_function",
"(",
"x",
",",
"n",
",",
"direction",
",",
"overwrite_x",
"=",
"overwrite_x",
")",
"else",
":",
"x",
"=",
"swapaxes",
"(",
"x",
",",
"axis",
",",
"-",
"1",
")",
"r",
"=",
"work_function",
"(",
"x",
",",
"n",
",",
"direction",
",",
"overwrite_x",
"=",
"overwrite_x",
")",
"r",
"=",
"swapaxes",
"(",
"r",
",",
"axis",
",",
"-",
"1",
")",
"return",
"r"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/fftpack/basic.py#L165-L183 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/_pyio.py | python | IOBase._unsupported | (self, name) | Internal: raise an exception for unsupported operations. | Internal: raise an exception for unsupported operations. | [
"Internal",
":",
"raise",
"an",
"exception",
"for",
"unsupported",
"operations",
"."
] | def _unsupported(self, name):
"""Internal: raise an exception for unsupported operations."""
raise UnsupportedOperation("%s.%s() not supported" %
(self.__class__.__name__, name)) | [
"def",
"_unsupported",
"(",
"self",
",",
"name",
")",
":",
"raise",
"UnsupportedOperation",
"(",
"\"%s.%s() not supported\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"name",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/_pyio.py#L291-L294 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListCtrl.GetItemBackgroundColour | (self, item) | return info.GetBackgroundColour() | Returns the item background colour.
:param `item`: the index of the item. | Returns the item background colour. | [
"Returns",
"the",
"item",
"background",
"colour",
"."
] | def GetItemBackgroundColour(self, item):
"""
Returns the item background colour.
:param `item`: the index of the item.
"""
info = UltimateListItem()
info._itemId = item
info = self._mainWin.GetItem(info)
return info.GetBackgroundColour() | [
"def",
"GetItemBackgroundColour",
"(",
"self",
",",
"item",
")",
":",
"info",
"=",
"UltimateListItem",
"(",
")",
"info",
".",
"_itemId",
"=",
"item",
"info",
"=",
"self",
".",
"_mainWin",
".",
"GetItem",
"(",
"info",
")",
"return",
"info",
".",
"GetBackgroundColour",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L11694-L11704 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/examples/bridge_supervised_learning.py | python | net_fn | (x) | return net(x) | Haiku module for our network. | Haiku module for our network. | [
"Haiku",
"module",
"for",
"our",
"network",
"."
] | def net_fn(x):
"""Haiku module for our network."""
net = hk.Sequential([
hk.Linear(1024),
jax.nn.relu,
hk.Linear(1024),
jax.nn.relu,
hk.Linear(1024),
jax.nn.relu,
hk.Linear(1024),
jax.nn.relu,
hk.Linear(NUM_ACTIONS),
jax.nn.log_softmax,
])
return net(x) | [
"def",
"net_fn",
"(",
"x",
")",
":",
"net",
"=",
"hk",
".",
"Sequential",
"(",
"[",
"hk",
".",
"Linear",
"(",
"1024",
")",
",",
"jax",
".",
"nn",
".",
"relu",
",",
"hk",
".",
"Linear",
"(",
"1024",
")",
",",
"jax",
".",
"nn",
".",
"relu",
",",
"hk",
".",
"Linear",
"(",
"1024",
")",
",",
"jax",
".",
"nn",
".",
"relu",
",",
"hk",
".",
"Linear",
"(",
"1024",
")",
",",
"jax",
".",
"nn",
".",
"relu",
",",
"hk",
".",
"Linear",
"(",
"NUM_ACTIONS",
")",
",",
"jax",
".",
"nn",
".",
"log_softmax",
",",
"]",
")",
"return",
"net",
"(",
"x",
")"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/examples/bridge_supervised_learning.py#L101-L115 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/sparse_ops.py | python | sparse_split | (split_dim, num_split, sp_input, name=None) | return sparse_tensors | Split a `SparseTensor` into `num_split` tensors along `split_dim`.
If the `sp_input.shape[split_dim]` is not an integer multiple of `num_split`
each slice starting from 0:`shape[split_dim] % num_split` gets extra one
dimension. For example, if `split_dim = 1` and `num_split = 2` and the
input is:
input_tensor = shape = [2, 7]
[ a d e ]
[b c ]
Graphically the output tensors are:
output_tensor[0] =
[ a ]
[b c ]
output_tensor[1] =
[ d e ]
[ ]
Args:
split_dim: A 0-D `int32` `Tensor`. The dimension along which to split.
num_split: A Python integer. The number of ways to split.
sp_input: The `SparseTensor` to split.
name: A name for the operation (optional).
Returns:
`num_split` `SparseTensor` objects resulting from splitting `value`.
Raises:
TypeError: If `sp_input` is not a `SparseTensor`. | Split a `SparseTensor` into `num_split` tensors along `split_dim`. | [
"Split",
"a",
"SparseTensor",
"into",
"num_split",
"tensors",
"along",
"split_dim",
"."
] | def sparse_split(split_dim, num_split, sp_input, name=None):
"""Split a `SparseTensor` into `num_split` tensors along `split_dim`.
If the `sp_input.shape[split_dim]` is not an integer multiple of `num_split`
each slice starting from 0:`shape[split_dim] % num_split` gets extra one
dimension. For example, if `split_dim = 1` and `num_split = 2` and the
input is:
input_tensor = shape = [2, 7]
[ a d e ]
[b c ]
Graphically the output tensors are:
output_tensor[0] =
[ a ]
[b c ]
output_tensor[1] =
[ d e ]
[ ]
Args:
split_dim: A 0-D `int32` `Tensor`. The dimension along which to split.
num_split: A Python integer. The number of ways to split.
sp_input: The `SparseTensor` to split.
name: A name for the operation (optional).
Returns:
`num_split` `SparseTensor` objects resulting from splitting `value`.
Raises:
TypeError: If `sp_input` is not a `SparseTensor`.
"""
if not isinstance(sp_input, ops.SparseTensor):
raise TypeError("Input must be a SparseTensor")
output_inds, output_vals, output_shapes = (
gen_sparse_ops._sparse_split(split_dim,
sp_input.indices,
sp_input.values,
sp_input.shape,
num_split,
name=name))
sparse_tensors = []
for i in range(0, num_split):
sparse_tensors.append(ops.SparseTensor(output_inds[i], output_vals[i],
output_shapes[i]))
return sparse_tensors | [
"def",
"sparse_split",
"(",
"split_dim",
",",
"num_split",
",",
"sp_input",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"sp_input",
",",
"ops",
".",
"SparseTensor",
")",
":",
"raise",
"TypeError",
"(",
"\"Input must be a SparseTensor\"",
")",
"output_inds",
",",
"output_vals",
",",
"output_shapes",
"=",
"(",
"gen_sparse_ops",
".",
"_sparse_split",
"(",
"split_dim",
",",
"sp_input",
".",
"indices",
",",
"sp_input",
".",
"values",
",",
"sp_input",
".",
"shape",
",",
"num_split",
",",
"name",
"=",
"name",
")",
")",
"sparse_tensors",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"num_split",
")",
":",
"sparse_tensors",
".",
"append",
"(",
"ops",
".",
"SparseTensor",
"(",
"output_inds",
"[",
"i",
"]",
",",
"output_vals",
"[",
"i",
"]",
",",
"output_shapes",
"[",
"i",
"]",
")",
")",
"return",
"sparse_tensors"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/sparse_ops.py#L479-L527 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/customtreectrl.py | python | CustomTreeCtrl.SetItemHyperText | (self, item, hyper=True) | Sets whether the item is hypertext or not.
:param `item`: an instance of :class:`GenericTreeItem`;
:param bool `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise. | Sets whether the item is hypertext or not. | [
"Sets",
"whether",
"the",
"item",
"is",
"hypertext",
"or",
"not",
"."
] | def SetItemHyperText(self, item, hyper=True):
"""
Sets whether the item is hypertext or not.
:param `item`: an instance of :class:`GenericTreeItem`;
:param bool `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
"""
item.SetHyperText(hyper)
self.RefreshLine(item) | [
"def",
"SetItemHyperText",
"(",
"self",
",",
"item",
",",
"hyper",
"=",
"True",
")",
":",
"item",
".",
"SetHyperText",
"(",
"hyper",
")",
"self",
".",
"RefreshLine",
"(",
"item",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L3818-L3827 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_simulation.py | python | SimulationDomain.getCurrentTime | (self) | return self._getUniversal(tc.VAR_TIME_STEP) | getCurrentTime() -> integer
Returns the current simulation time in ms. | getCurrentTime() -> integer | [
"getCurrentTime",
"()",
"-",
">",
"integer"
] | def getCurrentTime(self):
"""getCurrentTime() -> integer
Returns the current simulation time in ms.
"""
warnings.warn("getCurrentTime is deprecated, please use getTime which returns floating point seconds",
stacklevel=2)
return self._getUniversal(tc.VAR_TIME_STEP) | [
"def",
"getCurrentTime",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"getCurrentTime is deprecated, please use getTime which returns floating point seconds\"",
",",
"stacklevel",
"=",
"2",
")",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_TIME_STEP",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_simulation.py#L276-L283 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/util/deprecation.py | python | _wrap_decorator | (wrapped_function) | return wrapper | Indicate that one function wraps another.
This decorator wraps a function using `tf_decorator.make_decorator`
so that doc generation scripts can pick up original function
signature.
It would be better to use @functools.wrap decorator, but it would
not update function signature to match wrapped function in Python 2.
Args:
wrapped_function: The function that decorated function wraps.
Returns:
Function that accepts wrapper function as an argument and returns
`TFDecorator` instance. | Indicate that one function wraps another. | [
"Indicate",
"that",
"one",
"function",
"wraps",
"another",
"."
] | def _wrap_decorator(wrapped_function):
"""Indicate that one function wraps another.
This decorator wraps a function using `tf_decorator.make_decorator`
so that doc generation scripts can pick up original function
signature.
It would be better to use @functools.wrap decorator, but it would
not update function signature to match wrapped function in Python 2.
Args:
wrapped_function: The function that decorated function wraps.
Returns:
Function that accepts wrapper function as an argument and returns
`TFDecorator` instance.
"""
def wrapper(wrapper_func):
return tf_decorator.make_decorator(wrapped_function, wrapper_func)
return wrapper | [
"def",
"_wrap_decorator",
"(",
"wrapped_function",
")",
":",
"def",
"wrapper",
"(",
"wrapper_func",
")",
":",
"return",
"tf_decorator",
".",
"make_decorator",
"(",
"wrapped_function",
",",
"wrapper_func",
")",
"return",
"wrapper"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/util/deprecation.py#L118-L136 | |
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/style/error_handlers.py | python | DefaultStyleErrorHandler.__eq__ | (self, other) | return True | Return whether this instance is equal to another. | Return whether this instance is equal to another. | [
"Return",
"whether",
"this",
"instance",
"is",
"equal",
"to",
"another",
"."
] | def __eq__(self, other):
"""Return whether this instance is equal to another."""
if self._configuration != other._configuration:
return False
if self._file_path != other._file_path:
return False
if self._increment_error_count != other._increment_error_count:
return False
if self._line_numbers != other._line_numbers:
return False
return True | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"_configuration",
"!=",
"other",
".",
"_configuration",
":",
"return",
"False",
"if",
"self",
".",
"_file_path",
"!=",
"other",
".",
"_file_path",
":",
"return",
"False",
"if",
"self",
".",
"_increment_error_count",
"!=",
"other",
".",
"_increment_error_count",
":",
"return",
"False",
"if",
"self",
".",
"_line_numbers",
"!=",
"other",
".",
"_line_numbers",
":",
"return",
"False",
"return",
"True"
] | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/style/error_handlers.py#L94-L105 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiToolBarArt.ShowDropDown | (*args, **kwargs) | return _aui.AuiToolBarArt_ShowDropDown(*args, **kwargs) | ShowDropDown(self, Window wnd, wxAuiToolBarItemArray items) -> int | ShowDropDown(self, Window wnd, wxAuiToolBarItemArray items) -> int | [
"ShowDropDown",
"(",
"self",
"Window",
"wnd",
"wxAuiToolBarItemArray",
"items",
")",
"-",
">",
"int"
] | def ShowDropDown(*args, **kwargs):
"""ShowDropDown(self, Window wnd, wxAuiToolBarItemArray items) -> int"""
return _aui.AuiToolBarArt_ShowDropDown(*args, **kwargs) | [
"def",
"ShowDropDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBarArt_ShowDropDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L1970-L1972 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/buildtime_helpers/mac_tool.py | python | MacTool._MergePlist | (self, merged_plist, plist) | Merge |plist| into |merged_plist|. | Merge |plist| into |merged_plist|. | [
"Merge",
"|plist|",
"into",
"|merged_plist|",
"."
] | def _MergePlist(self, merged_plist, plist):
"""Merge |plist| into |merged_plist|."""
for key, value in plist.items():
if isinstance(value, dict):
merged_value = merged_plist.get(key, {})
if isinstance(merged_value, dict):
self._MergePlist(merged_value, value)
merged_plist[key] = merged_value
else:
merged_plist[key] = value
else:
merged_plist[key] = value | [
"def",
"_MergePlist",
"(",
"self",
",",
"merged_plist",
",",
"plist",
")",
":",
"for",
"key",
",",
"value",
"in",
"plist",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"merged_value",
"=",
"merged_plist",
".",
"get",
"(",
"key",
",",
"{",
"}",
")",
"if",
"isinstance",
"(",
"merged_value",
",",
"dict",
")",
":",
"self",
".",
"_MergePlist",
"(",
"merged_value",
",",
"value",
")",
"merged_plist",
"[",
"key",
"]",
"=",
"merged_value",
"else",
":",
"merged_plist",
"[",
"key",
"]",
"=",
"value",
"else",
":",
"merged_plist",
"[",
"key",
"]",
"=",
"value"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/buildtime_helpers/mac_tool.py#L531-L542 | ||
s9xie/DSN | 065e49898d239f5c96be558616b2556eabc50351 | scripts/cpp_lint.py | python | _NestingState.UpdatePreprocessor | (self, line) | Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check. | Update preprocessor stack. | [
"Update",
"preprocessor",
"stack",
"."
] | def UpdatePreprocessor(self, line):
"""Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check.
"""
if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
# Beginning of #if block, save the nesting stack here. The saved
# stack will allow us to restore the parsing state in the #else case.
self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
elif Match(r'^\s*#\s*(else|elif)\b', line):
# Beginning of #else block
if self.pp_stack:
if not self.pp_stack[-1].seen_else:
# This is the first #else or #elif block. Remember the
# whole nesting stack up to this point. This is what we
# keep after the #endif.
self.pp_stack[-1].seen_else = True
self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
# Restore the stack to how it was before the #if
self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
else:
# TODO(unknown): unexpected #else, issue warning?
pass
elif Match(r'^\s*#\s*endif\b', line):
# End of #if or #else blocks.
if self.pp_stack:
# If we saw an #else, we will need to restore the nesting
# stack to its former state before the #else, otherwise we
# will just continue from where we left off.
if self.pp_stack[-1].seen_else:
# Here we can just use a shallow copy since we are the last
# reference to it.
self.stack = self.pp_stack[-1].stack_before_else
# Drop the corresponding #if
self.pp_stack.pop()
else:
# TODO(unknown): unexpected #endif, issue warning?
pass | [
"def",
"UpdatePreprocessor",
"(",
"self",
",",
"line",
")",
":",
"if",
"Match",
"(",
"r'^\\s*#\\s*(if|ifdef|ifndef)\\b'",
",",
"line",
")",
":",
"# Beginning of #if block, save the nesting stack here. The saved",
"# stack will allow us to restore the parsing state in the #else case.",
"self",
".",
"pp_stack",
".",
"append",
"(",
"_PreprocessorInfo",
"(",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"stack",
")",
")",
")",
"elif",
"Match",
"(",
"r'^\\s*#\\s*(else|elif)\\b'",
",",
"line",
")",
":",
"# Beginning of #else block",
"if",
"self",
".",
"pp_stack",
":",
"if",
"not",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"seen_else",
":",
"# This is the first #else or #elif block. Remember the",
"# whole nesting stack up to this point. This is what we",
"# keep after the #endif.",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"seen_else",
"=",
"True",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"stack_before_else",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"stack",
")",
"# Restore the stack to how it was before the #if",
"self",
".",
"stack",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"stack_before_if",
")",
"else",
":",
"# TODO(unknown): unexpected #else, issue warning?",
"pass",
"elif",
"Match",
"(",
"r'^\\s*#\\s*endif\\b'",
",",
"line",
")",
":",
"# End of #if or #else blocks.",
"if",
"self",
".",
"pp_stack",
":",
"# If we saw an #else, we will need to restore the nesting",
"# stack to its former state before the #else, otherwise we",
"# will just continue from where we left off.",
"if",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"seen_else",
":",
"# Here we can just use a shallow copy since we are the last",
"# reference to it.",
"self",
".",
"stack",
"=",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"stack_before_else",
"# Drop the corresponding #if",
"self",
".",
"pp_stack",
".",
"pop",
"(",
")",
"else",
":",
"# TODO(unknown): unexpected #endif, issue warning?",
"pass"
] | https://github.com/s9xie/DSN/blob/065e49898d239f5c96be558616b2556eabc50351/scripts/cpp_lint.py#L1843-L1897 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_utils.py | python | assert_not_batched | (dataset) | Asserts that `dataset` is not batched.
The algorithm used by this method is sound but not complete. In other words,
if the method fails to establish the assertion, it does not mean the dataset
is batched.
Example usage:
```python
try:
assert_not_batched(dataset)
# safe to assume `dataset` it not batched here
expect ValueError:
# make no assumptions about `dataset`
```
Args:
dataset: The dataset to analyze.
Raises:
ValueError: If the method cannot establish the assertion. | Asserts that `dataset` is not batched. | [
"Asserts",
"that",
"dataset",
"is",
"not",
"batched",
"."
] | def assert_not_batched(dataset):
"""Asserts that `dataset` is not batched.
The algorithm used by this method is sound but not complete. In other words,
if the method fails to establish the assertion, it does not mean the dataset
is batched.
Example usage:
```python
try:
assert_not_batched(dataset)
# safe to assume `dataset` it not batched here
expect ValueError:
# make no assumptions about `dataset`
```
Args:
dataset: The dataset to analyze.
Raises:
ValueError: If the method cannot establish the assertion.
"""
if isinstance(dataset, dataset_ops.DatasetV1Adapter):
return assert_not_batched(dataset._dataset)
else:
whitelisted_types = [
dataset_ops._OptionsDataset,
dataset_ops.ConcatenateDataset,
dataset_ops.CacheDataset,
dataset_ops.FilterDataset,
dataset_ops.MapDataset,
dataset_ops.ParallelMapDataset,
dataset_ops.PrefetchDataset,
dataset_ops.RangeDataset,
dataset_ops.RepeatDataset,
dataset_ops.ShuffleDataset,
dataset_ops.SkipDataset,
dataset_ops.SparseTensorSliceDataset,
dataset_ops.TakeDataset,
dataset_ops.TensorDataset,
dataset_ops.TensorSliceDataset,
dataset_ops.ZipDataset,
readers.FixedLengthRecordDatasetV2,
readers.TextLineDatasetV2,
readers.TFRecordDatasetV2,
]
for ty in whitelisted_types:
if isinstance(dataset, ty):
for input_dataset in dataset._inputs():
assert_not_batched(input_dataset)
return
raise ValueError('Could not assert that dataset is not batched.') | [
"def",
"assert_not_batched",
"(",
"dataset",
")",
":",
"if",
"isinstance",
"(",
"dataset",
",",
"dataset_ops",
".",
"DatasetV1Adapter",
")",
":",
"return",
"assert_not_batched",
"(",
"dataset",
".",
"_dataset",
")",
"else",
":",
"whitelisted_types",
"=",
"[",
"dataset_ops",
".",
"_OptionsDataset",
",",
"dataset_ops",
".",
"ConcatenateDataset",
",",
"dataset_ops",
".",
"CacheDataset",
",",
"dataset_ops",
".",
"FilterDataset",
",",
"dataset_ops",
".",
"MapDataset",
",",
"dataset_ops",
".",
"ParallelMapDataset",
",",
"dataset_ops",
".",
"PrefetchDataset",
",",
"dataset_ops",
".",
"RangeDataset",
",",
"dataset_ops",
".",
"RepeatDataset",
",",
"dataset_ops",
".",
"ShuffleDataset",
",",
"dataset_ops",
".",
"SkipDataset",
",",
"dataset_ops",
".",
"SparseTensorSliceDataset",
",",
"dataset_ops",
".",
"TakeDataset",
",",
"dataset_ops",
".",
"TensorDataset",
",",
"dataset_ops",
".",
"TensorSliceDataset",
",",
"dataset_ops",
".",
"ZipDataset",
",",
"readers",
".",
"FixedLengthRecordDatasetV2",
",",
"readers",
".",
"TextLineDatasetV2",
",",
"readers",
".",
"TFRecordDatasetV2",
",",
"]",
"for",
"ty",
"in",
"whitelisted_types",
":",
"if",
"isinstance",
"(",
"dataset",
",",
"ty",
")",
":",
"for",
"input_dataset",
"in",
"dataset",
".",
"_inputs",
"(",
")",
":",
"assert_not_batched",
"(",
"input_dataset",
")",
"return",
"raise",
"ValueError",
"(",
"'Could not assert that dataset is not batched.'",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_utils.py#L1418-L1469 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/array_ops.py | python | _TileGradShape | (op) | Shape function for the TileGrad op. | Shape function for the TileGrad op. | [
"Shape",
"function",
"for",
"the",
"TileGrad",
"op",
"."
] | def _TileGradShape(op):
"""Shape function for the TileGrad op."""
multiples_shape = op.inputs[1].get_shape().with_rank(1)
input_shape = op.inputs[0].get_shape().with_rank(multiples_shape[0])
multiples = tensor_util.constant_value(op.inputs[1])
if multiples is None:
return [tensor_shape.unknown_shape(ndims=input_shape.ndims)]
else:
output_dims = []
for i, dim in enumerate(input_shape.dims):
output_dims.append(dim // multiples[i])
return [tensor_shape.TensorShape(output_dims)] | [
"def",
"_TileGradShape",
"(",
"op",
")",
":",
"multiples_shape",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"1",
")",
"input_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"multiples_shape",
"[",
"0",
"]",
")",
"multiples",
"=",
"tensor_util",
".",
"constant_value",
"(",
"op",
".",
"inputs",
"[",
"1",
"]",
")",
"if",
"multiples",
"is",
"None",
":",
"return",
"[",
"tensor_shape",
".",
"unknown_shape",
"(",
"ndims",
"=",
"input_shape",
".",
"ndims",
")",
"]",
"else",
":",
"output_dims",
"=",
"[",
"]",
"for",
"i",
",",
"dim",
"in",
"enumerate",
"(",
"input_shape",
".",
"dims",
")",
":",
"output_dims",
".",
"append",
"(",
"dim",
"//",
"multiples",
"[",
"i",
"]",
")",
"return",
"[",
"tensor_shape",
".",
"TensorShape",
"(",
"output_dims",
")",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L2123-L2134 | ||
xieyufei1993/FOTS | 9881966697fd5e2936d2cca8aa04309e4b64f77c | data/dataset.py | python | shrink_poly | (poly, r) | return poly | fit a poly inside the origin poly, maybe bugs here...
used for generate the score map
:param poly: the text poly
:param r: r in the paper
:return: the shrinked poly | fit a poly inside the origin poly, maybe bugs here...
used for generate the score map
:param poly: the text poly
:param r: r in the paper
:return: the shrinked poly | [
"fit",
"a",
"poly",
"inside",
"the",
"origin",
"poly",
"maybe",
"bugs",
"here",
"...",
"used",
"for",
"generate",
"the",
"score",
"map",
":",
"param",
"poly",
":",
"the",
"text",
"poly",
":",
"param",
"r",
":",
"r",
"in",
"the",
"paper",
":",
"return",
":",
"the",
"shrinked",
"poly"
] | def shrink_poly(poly, r):
'''
fit a poly inside the origin poly, maybe bugs here...
used for generate the score map
:param poly: the text poly
:param r: r in the paper
:return: the shrinked poly
'''
# shrink ratio
R = 0.3
# find the longer pair
if np.linalg.norm(poly[0] - poly[1]) + np.linalg.norm(poly[2] - poly[3]) > \
np.linalg.norm(poly[0] - poly[3]) + np.linalg.norm(poly[1] - poly[2]):
# first move (p0, p1), (p2, p3), then (p0, p3), (p1, p2)
## p0, p1
theta = np.arctan2((poly[1][1] - poly[0][1]), (poly[1][0] - poly[0][0]))
poly[0][0] += R * r[0] * np.cos(theta)
poly[0][1] += R * r[0] * np.sin(theta)
poly[1][0] -= R * r[1] * np.cos(theta)
poly[1][1] -= R * r[1] * np.sin(theta)
## p2, p3
theta = np.arctan2((poly[2][1] - poly[3][1]), (poly[2][0] - poly[3][0]))
poly[3][0] += R * r[3] * np.cos(theta)
poly[3][1] += R * r[3] * np.sin(theta)
poly[2][0] -= R * r[2] * np.cos(theta)
poly[2][1] -= R * r[2] * np.sin(theta)
## p0, p3
theta = np.arctan2((poly[3][0] - poly[0][0]), (poly[3][1] - poly[0][1]))
poly[0][0] += R * r[0] * np.sin(theta)
poly[0][1] += R * r[0] * np.cos(theta)
poly[3][0] -= R * r[3] * np.sin(theta)
poly[3][1] -= R * r[3] * np.cos(theta)
## p1, p2
theta = np.arctan2((poly[2][0] - poly[1][0]), (poly[2][1] - poly[1][1]))
poly[1][0] += R * r[1] * np.sin(theta)
poly[1][1] += R * r[1] * np.cos(theta)
poly[2][0] -= R * r[2] * np.sin(theta)
poly[2][1] -= R * r[2] * np.cos(theta)
else:
## p0, p3
# print poly
theta = np.arctan2((poly[3][0] - poly[0][0]), (poly[3][1] - poly[0][1]))
poly[0][0] += R * r[0] * np.sin(theta)
poly[0][1] += R * r[0] * np.cos(theta)
poly[3][0] -= R * r[3] * np.sin(theta)
poly[3][1] -= R * r[3] * np.cos(theta)
## p1, p2
theta = np.arctan2((poly[2][0] - poly[1][0]), (poly[2][1] - poly[1][1]))
poly[1][0] += R * r[1] * np.sin(theta)
poly[1][1] += R * r[1] * np.cos(theta)
poly[2][0] -= R * r[2] * np.sin(theta)
poly[2][1] -= R * r[2] * np.cos(theta)
## p0, p1
theta = np.arctan2((poly[1][1] - poly[0][1]), (poly[1][0] - poly[0][0]))
poly[0][0] += R * r[0] * np.cos(theta)
poly[0][1] += R * r[0] * np.sin(theta)
poly[1][0] -= R * r[1] * np.cos(theta)
poly[1][1] -= R * r[1] * np.sin(theta)
## p2, p3
theta = np.arctan2((poly[2][1] - poly[3][1]), (poly[2][0] - poly[3][0]))
poly[3][0] += R * r[3] * np.cos(theta)
poly[3][1] += R * r[3] * np.sin(theta)
poly[2][0] -= R * r[2] * np.cos(theta)
poly[2][1] -= R * r[2] * np.sin(theta)
return poly | [
"def",
"shrink_poly",
"(",
"poly",
",",
"r",
")",
":",
"# shrink ratio",
"R",
"=",
"0.3",
"# find the longer pair",
"if",
"np",
".",
"linalg",
".",
"norm",
"(",
"poly",
"[",
"0",
"]",
"-",
"poly",
"[",
"1",
"]",
")",
"+",
"np",
".",
"linalg",
".",
"norm",
"(",
"poly",
"[",
"2",
"]",
"-",
"poly",
"[",
"3",
"]",
")",
">",
"np",
".",
"linalg",
".",
"norm",
"(",
"poly",
"[",
"0",
"]",
"-",
"poly",
"[",
"3",
"]",
")",
"+",
"np",
".",
"linalg",
".",
"norm",
"(",
"poly",
"[",
"1",
"]",
"-",
"poly",
"[",
"2",
"]",
")",
":",
"# first move (p0, p1), (p2, p3), then (p0, p3), (p1, p2)",
"## p0, p1",
"theta",
"=",
"np",
".",
"arctan2",
"(",
"(",
"poly",
"[",
"1",
"]",
"[",
"1",
"]",
"-",
"poly",
"[",
"0",
"]",
"[",
"1",
"]",
")",
",",
"(",
"poly",
"[",
"1",
"]",
"[",
"0",
"]",
"-",
"poly",
"[",
"0",
"]",
"[",
"0",
"]",
")",
")",
"poly",
"[",
"0",
"]",
"[",
"0",
"]",
"+=",
"R",
"*",
"r",
"[",
"0",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"0",
"]",
"[",
"1",
"]",
"+=",
"R",
"*",
"r",
"[",
"0",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"1",
"]",
"[",
"0",
"]",
"-=",
"R",
"*",
"r",
"[",
"1",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"1",
"]",
"[",
"1",
"]",
"-=",
"R",
"*",
"r",
"[",
"1",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"## p2, p3",
"theta",
"=",
"np",
".",
"arctan2",
"(",
"(",
"poly",
"[",
"2",
"]",
"[",
"1",
"]",
"-",
"poly",
"[",
"3",
"]",
"[",
"1",
"]",
")",
",",
"(",
"poly",
"[",
"2",
"]",
"[",
"0",
"]",
"-",
"poly",
"[",
"3",
"]",
"[",
"0",
"]",
")",
")",
"poly",
"[",
"3",
"]",
"[",
"0",
"]",
"+=",
"R",
"*",
"r",
"[",
"3",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"3",
"]",
"[",
"1",
"]",
"+=",
"R",
"*",
"r",
"[",
"3",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"2",
"]",
"[",
"0",
"]",
"-=",
"R",
"*",
"r",
"[",
"2",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"2",
"]",
"[",
"1",
"]",
"-=",
"R",
"*",
"r",
"[",
"2",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"## p0, p3",
"theta",
"=",
"np",
".",
"arctan2",
"(",
"(",
"poly",
"[",
"3",
"]",
"[",
"0",
"]",
"-",
"poly",
"[",
"0",
"]",
"[",
"0",
"]",
")",
",",
"(",
"poly",
"[",
"3",
"]",
"[",
"1",
"]",
"-",
"poly",
"[",
"0",
"]",
"[",
"1",
"]",
")",
")",
"poly",
"[",
"0",
"]",
"[",
"0",
"]",
"+=",
"R",
"*",
"r",
"[",
"0",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"0",
"]",
"[",
"1",
"]",
"+=",
"R",
"*",
"r",
"[",
"0",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"3",
"]",
"[",
"0",
"]",
"-=",
"R",
"*",
"r",
"[",
"3",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"3",
"]",
"[",
"1",
"]",
"-=",
"R",
"*",
"r",
"[",
"3",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"## p1, p2",
"theta",
"=",
"np",
".",
"arctan2",
"(",
"(",
"poly",
"[",
"2",
"]",
"[",
"0",
"]",
"-",
"poly",
"[",
"1",
"]",
"[",
"0",
"]",
")",
",",
"(",
"poly",
"[",
"2",
"]",
"[",
"1",
"]",
"-",
"poly",
"[",
"1",
"]",
"[",
"1",
"]",
")",
")",
"poly",
"[",
"1",
"]",
"[",
"0",
"]",
"+=",
"R",
"*",
"r",
"[",
"1",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"1",
"]",
"[",
"1",
"]",
"+=",
"R",
"*",
"r",
"[",
"1",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"2",
"]",
"[",
"0",
"]",
"-=",
"R",
"*",
"r",
"[",
"2",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"2",
"]",
"[",
"1",
"]",
"-=",
"R",
"*",
"r",
"[",
"2",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"else",
":",
"## p0, p3",
"# print poly",
"theta",
"=",
"np",
".",
"arctan2",
"(",
"(",
"poly",
"[",
"3",
"]",
"[",
"0",
"]",
"-",
"poly",
"[",
"0",
"]",
"[",
"0",
"]",
")",
",",
"(",
"poly",
"[",
"3",
"]",
"[",
"1",
"]",
"-",
"poly",
"[",
"0",
"]",
"[",
"1",
"]",
")",
")",
"poly",
"[",
"0",
"]",
"[",
"0",
"]",
"+=",
"R",
"*",
"r",
"[",
"0",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"0",
"]",
"[",
"1",
"]",
"+=",
"R",
"*",
"r",
"[",
"0",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"3",
"]",
"[",
"0",
"]",
"-=",
"R",
"*",
"r",
"[",
"3",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"3",
"]",
"[",
"1",
"]",
"-=",
"R",
"*",
"r",
"[",
"3",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"## p1, p2",
"theta",
"=",
"np",
".",
"arctan2",
"(",
"(",
"poly",
"[",
"2",
"]",
"[",
"0",
"]",
"-",
"poly",
"[",
"1",
"]",
"[",
"0",
"]",
")",
",",
"(",
"poly",
"[",
"2",
"]",
"[",
"1",
"]",
"-",
"poly",
"[",
"1",
"]",
"[",
"1",
"]",
")",
")",
"poly",
"[",
"1",
"]",
"[",
"0",
"]",
"+=",
"R",
"*",
"r",
"[",
"1",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"1",
"]",
"[",
"1",
"]",
"+=",
"R",
"*",
"r",
"[",
"1",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"2",
"]",
"[",
"0",
"]",
"-=",
"R",
"*",
"r",
"[",
"2",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"2",
"]",
"[",
"1",
"]",
"-=",
"R",
"*",
"r",
"[",
"2",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"## p0, p1",
"theta",
"=",
"np",
".",
"arctan2",
"(",
"(",
"poly",
"[",
"1",
"]",
"[",
"1",
"]",
"-",
"poly",
"[",
"0",
"]",
"[",
"1",
"]",
")",
",",
"(",
"poly",
"[",
"1",
"]",
"[",
"0",
"]",
"-",
"poly",
"[",
"0",
"]",
"[",
"0",
"]",
")",
")",
"poly",
"[",
"0",
"]",
"[",
"0",
"]",
"+=",
"R",
"*",
"r",
"[",
"0",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"0",
"]",
"[",
"1",
"]",
"+=",
"R",
"*",
"r",
"[",
"0",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"1",
"]",
"[",
"0",
"]",
"-=",
"R",
"*",
"r",
"[",
"1",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"1",
"]",
"[",
"1",
"]",
"-=",
"R",
"*",
"r",
"[",
"1",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"## p2, p3",
"theta",
"=",
"np",
".",
"arctan2",
"(",
"(",
"poly",
"[",
"2",
"]",
"[",
"1",
"]",
"-",
"poly",
"[",
"3",
"]",
"[",
"1",
"]",
")",
",",
"(",
"poly",
"[",
"2",
"]",
"[",
"0",
"]",
"-",
"poly",
"[",
"3",
"]",
"[",
"0",
"]",
")",
")",
"poly",
"[",
"3",
"]",
"[",
"0",
"]",
"+=",
"R",
"*",
"r",
"[",
"3",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"3",
"]",
"[",
"1",
"]",
"+=",
"R",
"*",
"r",
"[",
"3",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"poly",
"[",
"2",
"]",
"[",
"0",
"]",
"-=",
"R",
"*",
"r",
"[",
"2",
"]",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"poly",
"[",
"2",
"]",
"[",
"1",
"]",
"-=",
"R",
"*",
"r",
"[",
"2",
"]",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"return",
"poly"
] | https://github.com/xieyufei1993/FOTS/blob/9881966697fd5e2936d2cca8aa04309e4b64f77c/data/dataset.py#L161-L225 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/stack.py | python | _check_optional | (name, allowXHTML=False) | return check | Validator for optional elements.
:raise: :exc:`InvalidStack` If validation fails | Validator for optional elements. | [
"Validator",
"for",
"optional",
"elements",
"."
] | def _check_optional(name, allowXHTML=False):
"""
Validator for optional elements.
:raise: :exc:`InvalidStack` If validation fails
"""
def check(n, filename):
n = _get_nodes_by_name(n, name)
if len(n) > 1:
raise InvalidStack("Invalid stack.xml file [%s]: must have at most one '%s' element" % (filename, name))
if n:
if allowXHTML:
return ''.join([x.toxml() for x in n[0].childNodes])
return _get_text(n[0].childNodes).strip()
return check | [
"def",
"_check_optional",
"(",
"name",
",",
"allowXHTML",
"=",
"False",
")",
":",
"def",
"check",
"(",
"n",
",",
"filename",
")",
":",
"n",
"=",
"_get_nodes_by_name",
"(",
"n",
",",
"name",
")",
"if",
"len",
"(",
"n",
")",
">",
"1",
":",
"raise",
"InvalidStack",
"(",
"\"Invalid stack.xml file [%s]: must have at most one '%s' element\"",
"%",
"(",
"filename",
",",
"name",
")",
")",
"if",
"n",
":",
"if",
"allowXHTML",
":",
"return",
"''",
".",
"join",
"(",
"[",
"x",
".",
"toxml",
"(",
")",
"for",
"x",
"in",
"n",
"[",
"0",
"]",
".",
"childNodes",
"]",
")",
"return",
"_get_text",
"(",
"n",
"[",
"0",
"]",
".",
"childNodes",
")",
".",
"strip",
"(",
")",
"return",
"check"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/stack.py#L56-L70 | |
OpenChemistry/tomviz | 0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a | tomviz/python/tomviz/io/dm.py | python | FileDM._checkIndex | (self, i) | return | Check index i for sanity, otherwise raise Exception.
Parameters
----------
i : int
Index.
Raises
------
IndexError | Check index i for sanity, otherwise raise Exception. | [
"Check",
"index",
"i",
"for",
"sanity",
"otherwise",
"raise",
"Exception",
"."
] | def _checkIndex(self, i):
"""Check index i for sanity, otherwise raise Exception.
Parameters
----------
i : int
Index.
Raises
------
IndexError
"""
# check type
if not isinstance(i, int):
raise TypeError('index supposed to be integer')
# check whether in range
if i < 0 or i > self.numObjects:
raise IndexError('Index out of range, '
'trying to access element {} of {} \
valid elements'.format(i + 1, self.numObjects))
return | [
"def",
"_checkIndex",
"(",
"self",
",",
"i",
")",
":",
"# check type",
"if",
"not",
"isinstance",
"(",
"i",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"'index supposed to be integer'",
")",
"# check whether in range",
"if",
"i",
"<",
"0",
"or",
"i",
">",
"self",
".",
"numObjects",
":",
"raise",
"IndexError",
"(",
"'Index out of range, '",
"'trying to access element {} of {} \\\n valid elements'",
".",
"format",
"(",
"i",
"+",
"1",
",",
"self",
".",
"numObjects",
")",
")",
"return"
] | https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/tomviz/io/dm.py#L932-L955 | |
tangjianpku/LINE | d5f840941e0f4026090d1b1feeaf15da38e2b24b | windows/evaluate/liblinear/python/liblinear.py | python | toPyModel | (model_ptr) | return m | toPyModel(model_ptr) -> model
Convert a ctypes POINTER(model) to a Python model | toPyModel(model_ptr) -> model | [
"toPyModel",
"(",
"model_ptr",
")",
"-",
">",
"model"
] | def toPyModel(model_ptr):
"""
toPyModel(model_ptr) -> model
Convert a ctypes POINTER(model) to a Python model
"""
if bool(model_ptr) == False:
raise ValueError("Null pointer")
m = model_ptr.contents
m.__createfrom__ = 'C'
return m | [
"def",
"toPyModel",
"(",
"model_ptr",
")",
":",
"if",
"bool",
"(",
"model_ptr",
")",
"==",
"False",
":",
"raise",
"ValueError",
"(",
"\"Null pointer\"",
")",
"m",
"=",
"model_ptr",
".",
"contents",
"m",
".",
"__createfrom__",
"=",
"'C'",
"return",
"m"
] | https://github.com/tangjianpku/LINE/blob/d5f840941e0f4026090d1b1feeaf15da38e2b24b/windows/evaluate/liblinear/python/liblinear.py#L246-L256 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/tensor_array_ops.py | python | _GraphTensorArray.concat | (self, name=None) | return value | See TensorArray. | See TensorArray. | [
"See",
"TensorArray",
"."
] | def concat(self, name=None):
"""See TensorArray."""
value, _ = gen_data_flow_ops.tensor_array_concat_v3(
handle=self._handle,
flow_in=self._flow,
dtype=self._dtype,
name=name,
element_shape_except0=self.element_shape[1:])
if self.element_shape:
value.set_shape([None] + self.element_shape.dims[1:])
return value | [
"def",
"concat",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"value",
",",
"_",
"=",
"gen_data_flow_ops",
".",
"tensor_array_concat_v3",
"(",
"handle",
"=",
"self",
".",
"_handle",
",",
"flow_in",
"=",
"self",
".",
"_flow",
",",
"dtype",
"=",
"self",
".",
"_dtype",
",",
"name",
"=",
"name",
",",
"element_shape_except0",
"=",
"self",
".",
"element_shape",
"[",
"1",
":",
"]",
")",
"if",
"self",
".",
"element_shape",
":",
"value",
".",
"set_shape",
"(",
"[",
"None",
"]",
"+",
"self",
".",
"element_shape",
".",
"dims",
"[",
"1",
":",
"]",
")",
"return",
"value"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/tensor_array_ops.py#L302-L312 | |
timi-liuliang/echo | 40a5a24d430eee4118314459ab7e03afcb3b8719 | thirdparty/protobuf/python/google/protobuf/internal/python_message.py | python | _AddSetListenerMethod | (cls) | Helper for _AddMessageMethods(). | Helper for _AddMessageMethods(). | [
"Helper",
"for",
"_AddMessageMethods",
"()",
"."
] | def _AddSetListenerMethod(cls):
"""Helper for _AddMessageMethods()."""
def SetListener(self, listener):
if listener is None:
self._listener = message_listener_mod.NullMessageListener()
else:
self._listener = listener
cls._SetListener = SetListener | [
"def",
"_AddSetListenerMethod",
"(",
"cls",
")",
":",
"def",
"SetListener",
"(",
"self",
",",
"listener",
")",
":",
"if",
"listener",
"is",
"None",
":",
"self",
".",
"_listener",
"=",
"message_listener_mod",
".",
"NullMessageListener",
"(",
")",
"else",
":",
"self",
".",
"_listener",
"=",
"listener",
"cls",
".",
"_SetListener",
"=",
"SetListener"
] | https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/internal/python_message.py#L752-L759 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/pystache/pystache/renderer.py | python | Renderer._to_unicode_hard | (self, s) | return unicode(self._to_unicode_soft(s)) | Convert a basestring to a string with type unicode (not subclass). | Convert a basestring to a string with type unicode (not subclass). | [
"Convert",
"a",
"basestring",
"to",
"a",
"string",
"with",
"type",
"unicode",
"(",
"not",
"subclass",
")",
"."
] | def _to_unicode_hard(self, s):
"""
Convert a basestring to a string with type unicode (not subclass).
"""
return unicode(self._to_unicode_soft(s)) | [
"def",
"_to_unicode_hard",
"(",
"self",
",",
"s",
")",
":",
"return",
"unicode",
"(",
"self",
".",
"_to_unicode_soft",
"(",
"s",
")",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/pystache/pystache/renderer.py#L184-L189 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/inspect.py | python | isgeneratorfunction | (object) | return bool((isfunction(object) or ismethod(object)) and
object.func_code.co_flags & CO_GENERATOR) | Return true if the object is a user-defined generator function.
Generator function objects provide the same attributes as functions.
See help(isfunction) for a list of attributes. | Return true if the object is a user-defined generator function. | [
"Return",
"true",
"if",
"the",
"object",
"is",
"a",
"user",
"-",
"defined",
"generator",
"function",
"."
] | def isgeneratorfunction(object):
"""Return true if the object is a user-defined generator function.
Generator function objects provide the same attributes as functions.
See help(isfunction) for a list of attributes."""
return bool((isfunction(object) or ismethod(object)) and
object.func_code.co_flags & CO_GENERATOR) | [
"def",
"isgeneratorfunction",
"(",
"object",
")",
":",
"return",
"bool",
"(",
"(",
"isfunction",
"(",
"object",
")",
"or",
"ismethod",
"(",
"object",
")",
")",
"and",
"object",
".",
"func_code",
".",
"co_flags",
"&",
"CO_GENERATOR",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/inspect.py#L155-L161 | |
KhronosGroup/SPIR | f33c27876d9f3d5810162b60fa89cc13d2b55725 | bindings/python/clang/cindex.py | python | TranslationUnit.get_file | (self, filename) | return File.from_name(self, filename) | Obtain a File from this translation unit. | Obtain a File from this translation unit. | [
"Obtain",
"a",
"File",
"from",
"this",
"translation",
"unit",
"."
] | def get_file(self, filename):
"""Obtain a File from this translation unit."""
return File.from_name(self, filename) | [
"def",
"get_file",
"(",
"self",
",",
"filename",
")",
":",
"return",
"File",
".",
"from_name",
"(",
"self",
",",
"filename",
")"
] | https://github.com/KhronosGroup/SPIR/blob/f33c27876d9f3d5810162b60fa89cc13d2b55725/bindings/python/clang/cindex.py#L2038-L2041 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_3_5_0.py | python | MiroInterpreter.do_mythtv_check_downloading | (self, line) | Check if any items are being downloaded. Set True or False | Check if any items are being downloaded. Set True or False | [
"Check",
"if",
"any",
"items",
"are",
"being",
"downloaded",
".",
"Set",
"True",
"or",
"False"
] | def do_mythtv_check_downloading(self, line):
"""Check if any items are being downloaded. Set True or False"""
self.downloading = False
#downloadingItems = views.downloadingItems
downloadingItems = item.Item.only_downloading_view()
count = downloadingItems.count()
for it in downloadingItems:
logging.info(u"(%s - %s) video is downloading with (%0.0f%%) complete" % (it.get_channel_title(True).replace(u'/',u'-'), it.get_title().replace(u'/',u'-'), it.download_progress()))
if not count:
logging.info(u"No items downloading")
if count:
self.downloading = True | [
"def",
"do_mythtv_check_downloading",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"downloading",
"=",
"False",
"#downloadingItems = views.downloadingItems",
"downloadingItems",
"=",
"item",
".",
"Item",
".",
"only_downloading_view",
"(",
")",
"count",
"=",
"downloadingItems",
".",
"count",
"(",
")",
"for",
"it",
"in",
"downloadingItems",
":",
"logging",
".",
"info",
"(",
"u\"(%s - %s) video is downloading with (%0.0f%%) complete\"",
"%",
"(",
"it",
".",
"get_channel_title",
"(",
"True",
")",
".",
"replace",
"(",
"u'/'",
",",
"u'-'",
")",
",",
"it",
".",
"get_title",
"(",
")",
".",
"replace",
"(",
"u'/'",
",",
"u'-'",
")",
",",
"it",
".",
"download_progress",
"(",
")",
")",
")",
"if",
"not",
"count",
":",
"logging",
".",
"info",
"(",
"u\"No items downloading\"",
")",
"if",
"count",
":",
"self",
".",
"downloading",
"=",
"True"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_3_5_0.py#L245-L256 | ||
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py | python | IConversion.SmsTargetStatusToText | (self, Status) | return self._ToText('smsTargetStatus', Status) | Returns SMS target status as text.
@param Status: SMS target status.
@type Status: L{SMS target status<enums.smsTargetStatusUnknown>}
@return: Text describing the SMS target status.
@rtype: unicode | Returns SMS target status as text. | [
"Returns",
"SMS",
"target",
"status",
"as",
"text",
"."
] | def SmsTargetStatusToText(self, Status):
'''Returns SMS target status as text.
@param Status: SMS target status.
@type Status: L{SMS target status<enums.smsTargetStatusUnknown>}
@return: Text describing the SMS target status.
@rtype: unicode
'''
return self._ToText('smsTargetStatus', Status) | [
"def",
"SmsTargetStatusToText",
"(",
"self",
",",
"Status",
")",
":",
"return",
"self",
".",
"_ToText",
"(",
"'smsTargetStatus'",
",",
"Status",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py#L208-L216 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/indexes/multi.py | python | MultiIndexUIntEngine._codes_to_ints | (self, codes) | return np.bitwise_or.reduce(codes, axis=1) | Transform combination(s) of uint64 in one uint64 (each), in a strictly
monotonic way (i.e. respecting the lexicographic order of integer
combinations): see BaseMultiIndexCodesEngine documentation.
Parameters
----------
codes : 1- or 2-dimensional array of dtype uint64
Combinations of integers (one per row)
Returns
------
int_keys : scalar or 1-dimensional array, of dtype uint64
Integer(s) representing one combination (each) | Transform combination(s) of uint64 in one uint64 (each), in a strictly
monotonic way (i.e. respecting the lexicographic order of integer
combinations): see BaseMultiIndexCodesEngine documentation. | [
"Transform",
"combination",
"(",
"s",
")",
"of",
"uint64",
"in",
"one",
"uint64",
"(",
"each",
")",
"in",
"a",
"strictly",
"monotonic",
"way",
"(",
"i",
".",
"e",
".",
"respecting",
"the",
"lexicographic",
"order",
"of",
"integer",
"combinations",
")",
":",
"see",
"BaseMultiIndexCodesEngine",
"documentation",
"."
] | def _codes_to_ints(self, codes):
"""
Transform combination(s) of uint64 in one uint64 (each), in a strictly
monotonic way (i.e. respecting the lexicographic order of integer
combinations): see BaseMultiIndexCodesEngine documentation.
Parameters
----------
codes : 1- or 2-dimensional array of dtype uint64
Combinations of integers (one per row)
Returns
------
int_keys : scalar or 1-dimensional array, of dtype uint64
Integer(s) representing one combination (each)
"""
# Shift the representation of each level by the pre-calculated number
# of bits:
codes <<= self.offsets
# Now sum and OR are in fact interchangeable. This is a simple
# composition of the (disjunct) significant bits of each level (i.e.
# each column in "codes") in a single positive integer:
if codes.ndim == 1:
# Single key
return np.bitwise_or.reduce(codes)
# Multiple keys
return np.bitwise_or.reduce(codes, axis=1) | [
"def",
"_codes_to_ints",
"(",
"self",
",",
"codes",
")",
":",
"# Shift the representation of each level by the pre-calculated number",
"# of bits:",
"codes",
"<<=",
"self",
".",
"offsets",
"# Now sum and OR are in fact interchangeable. This is a simple",
"# composition of the (disjunct) significant bits of each level (i.e.",
"# each column in \"codes\") in a single positive integer:",
"if",
"codes",
".",
"ndim",
"==",
"1",
":",
"# Single key",
"return",
"np",
".",
"bitwise_or",
".",
"reduce",
"(",
"codes",
")",
"# Multiple keys",
"return",
"np",
".",
"bitwise_or",
".",
"reduce",
"(",
"codes",
",",
"axis",
"=",
"1",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/indexes/multi.py#L50-L78 | |
ZhouWeikuan/DouDiZhu | 0d84ff6c0bc54dba6ae37955de9ae9307513dc99 | code/frameworks/cocos2d-x/tools/bindings-generator/generator.py | python | build_namespace | (cursor, namespaces=[]) | return namespaces | build the full namespace for a specific cursor | build the full namespace for a specific cursor | [
"build",
"the",
"full",
"namespace",
"for",
"a",
"specific",
"cursor"
] | def build_namespace(cursor, namespaces=[]):
'''
build the full namespace for a specific cursor
'''
if cursor:
parent = cursor.semantic_parent
if parent:
if parent.kind == cindex.CursorKind.NAMESPACE or parent.kind == cindex.CursorKind.CLASS_DECL:
namespaces.append(parent.displayname)
build_namespace(parent, namespaces)
return namespaces | [
"def",
"build_namespace",
"(",
"cursor",
",",
"namespaces",
"=",
"[",
"]",
")",
":",
"if",
"cursor",
":",
"parent",
"=",
"cursor",
".",
"semantic_parent",
"if",
"parent",
":",
"if",
"parent",
".",
"kind",
"==",
"cindex",
".",
"CursorKind",
".",
"NAMESPACE",
"or",
"parent",
".",
"kind",
"==",
"cindex",
".",
"CursorKind",
".",
"CLASS_DECL",
":",
"namespaces",
".",
"append",
"(",
"parent",
".",
"displayname",
")",
"build_namespace",
"(",
"parent",
",",
"namespaces",
")",
"return",
"namespaces"
] | https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/generator.py#L104-L115 | |
neopenx/Dragon | 0e639a7319035ddc81918bd3df059230436ee0a1 | Dragon/python/dragon/vm/caffe/net.py | python | Net.params | (self) | return OrderedDict([(layer._name, [Blob((blob['data'],blob['diff']))
for blob in layer._blobs]) for layer in self._layers]) | Return the parameters. [**PyCaffe Style**]
Returns
-------
dict
The format of dict is: <layer_name, list of blobs>.
Examples
--------
>>> weights = net.params['conv1'][0].data
>>> bias = net.params['conv1'][1].data
References
----------
The implementation of `Net_params(pycaffe.py, L58)`_. | Return the parameters. [**PyCaffe Style**] | [
"Return",
"the",
"parameters",
".",
"[",
"**",
"PyCaffe",
"Style",
"**",
"]"
] | def params(self):
"""Return the parameters. [**PyCaffe Style**]
Returns
-------
dict
The format of dict is: <layer_name, list of blobs>.
Examples
--------
>>> weights = net.params['conv1'][0].data
>>> bias = net.params['conv1'][1].data
References
----------
The implementation of `Net_params(pycaffe.py, L58)`_.
"""
return OrderedDict([(layer._name, [Blob((blob['data'],blob['diff']))
for blob in layer._blobs]) for layer in self._layers]) | [
"def",
"params",
"(",
"self",
")",
":",
"return",
"OrderedDict",
"(",
"[",
"(",
"layer",
".",
"_name",
",",
"[",
"Blob",
"(",
"(",
"blob",
"[",
"'data'",
"]",
",",
"blob",
"[",
"'diff'",
"]",
")",
")",
"for",
"blob",
"in",
"layer",
".",
"_blobs",
"]",
")",
"for",
"layer",
"in",
"self",
".",
"_layers",
"]",
")"
] | https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/caffe/net.py#L455-L474 | |
15172658790/Blog | 46e5036f5fbcad535af2255dc0e095cebcd8d710 | 计算机与信息类/算法基础/lab-徐云/2018/lab2/redBlackTree.py | python | redBlackTree.rotate | (self,prt,chd) | rotate prt with the center of chd | rotate prt with the center of chd | [
"rotate",
"prt",
"with",
"the",
"center",
"of",
"chd"
] | def rotate(self,prt,chd):
'''rotate prt with the center of chd'''
if self.root is prt:
self.setRoot(chd)
else:
prt.parent.setChild(chd, prt.parent.left is prt)
isLeftChd = prt.left is chd
prt.setChild(chd.getChild(not isLeftChd), isLeftChd)
chd.setChild(prt,not isLeftChd) | [
"def",
"rotate",
"(",
"self",
",",
"prt",
",",
"chd",
")",
":",
"if",
"self",
".",
"root",
"is",
"prt",
":",
"self",
".",
"setRoot",
"(",
"chd",
")",
"else",
":",
"prt",
".",
"parent",
".",
"setChild",
"(",
"chd",
",",
"prt",
".",
"parent",
".",
"left",
"is",
"prt",
")",
"isLeftChd",
"=",
"prt",
".",
"left",
"is",
"chd",
"prt",
".",
"setChild",
"(",
"chd",
".",
"getChild",
"(",
"not",
"isLeftChd",
")",
",",
"isLeftChd",
")",
"chd",
".",
"setChild",
"(",
"prt",
",",
"not",
"isLeftChd",
")"
] | https://github.com/15172658790/Blog/blob/46e5036f5fbcad535af2255dc0e095cebcd8d710/计算机与信息类/算法基础/lab-徐云/2018/lab2/redBlackTree.py#L79-L87 | ||
intel-iot-devkit/how-to-code-samples | b4ea616f36bbfa2e042beb1698f968cfd651d79f | sound-detector/python/iot_sound_detector/hardware/dfrobot.py | python | DfrobotBoard.change_background | (self, color) | Change LCD screen background color.
No effect on the dfrobot. | Change LCD screen background color.
No effect on the dfrobot. | [
"Change",
"LCD",
"screen",
"background",
"color",
".",
"No",
"effect",
"on",
"the",
"dfrobot",
"."
] | def change_background(self, color):
"""
Change LCD screen background color.
No effect on the dfrobot.
"""
pass | [
"def",
"change_background",
"(",
"self",
",",
"color",
")",
":",
"pass"
] | https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/sound-detector/python/iot_sound_detector/hardware/dfrobot.py#L101-L108 | ||
cornell-zhang/heterocl | 6d9e4b4acc2ee2707b2d25b27298c0335bccedfd | python/heterocl/tvm/_ffi/_ctypes/types.py | python | _return_bytes | (x) | return res | return handle | return handle | [
"return",
"handle"
] | def _return_bytes(x):
"""return handle"""
handle = x.v_handle
if not isinstance(handle, ctypes.c_void_p):
handle = ctypes.c_void_p(handle)
arr = ctypes.cast(handle, ctypes.POINTER(TVMByteArray))[0]
size = arr.size
res = bytearray(size)
rptr = (ctypes.c_byte * size).from_buffer(res)
if not ctypes.memmove(rptr, arr.data, size):
raise RuntimeError('memmove failed')
return res | [
"def",
"_return_bytes",
"(",
"x",
")",
":",
"handle",
"=",
"x",
".",
"v_handle",
"if",
"not",
"isinstance",
"(",
"handle",
",",
"ctypes",
".",
"c_void_p",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_void_p",
"(",
"handle",
")",
"arr",
"=",
"ctypes",
".",
"cast",
"(",
"handle",
",",
"ctypes",
".",
"POINTER",
"(",
"TVMByteArray",
")",
")",
"[",
"0",
"]",
"size",
"=",
"arr",
".",
"size",
"res",
"=",
"bytearray",
"(",
"size",
")",
"rptr",
"=",
"(",
"ctypes",
".",
"c_byte",
"*",
"size",
")",
".",
"from_buffer",
"(",
"res",
")",
"if",
"not",
"ctypes",
".",
"memmove",
"(",
"rptr",
",",
"arr",
".",
"data",
",",
"size",
")",
":",
"raise",
"RuntimeError",
"(",
"'memmove failed'",
")",
"return",
"res"
] | https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/_ffi/_ctypes/types.py#L38-L49 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/personGenerator.py | python | PersonRouteElement.get_xml_tag | (cls) | return "personRoute" | :return: The tag of the xml elements corresponding to this class (personRoute) | :return: The tag of the xml elements corresponding to this class (personRoute) | [
":",
"return",
":",
"The",
"tag",
"of",
"the",
"xml",
"elements",
"corresponding",
"to",
"this",
"class",
"(",
"personRoute",
")"
] | def get_xml_tag(cls):
"""
:return: The tag of the xml elements corresponding to this class (personRoute)
"""
return "personRoute" | [
"def",
"get_xml_tag",
"(",
"cls",
")",
":",
"return",
"\"personRoute\""
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/personGenerator.py#L272-L276 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/MultiheadAttention.py | python | MultiheadAttention.output_size | (self, output_size) | Sets the output size. | Sets the output size. | [
"Sets",
"the",
"output",
"size",
"."
] | def output_size(self, output_size):
"""Sets the output size.
"""
if output_size < 1:
raise ValueError('The `output_size` must be > 0.')
self._internal.set_output_size(output_size) | [
"def",
"output_size",
"(",
"self",
",",
"output_size",
")",
":",
"if",
"output_size",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'The `output_size` must be > 0.'",
")",
"self",
".",
"_internal",
".",
"set_output_size",
"(",
"output_size",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/MultiheadAttention.py#L126-L131 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/numeric.py | python | rollaxis | (a, axis, start=0) | return a.transpose(axes) | Roll the specified axis backwards, until it lies in a given position.
This function continues to be supported for backward compatibility, but you
should prefer `moveaxis`. The `moveaxis` function was added in NumPy
1.11.
Parameters
----------
a : ndarray
Input array.
axis : int
The axis to roll backwards. The positions of the other axes do not
change relative to one another.
start : int, optional
The axis is rolled until it lies before this position. The default,
0, results in a "complete" roll.
Returns
-------
res : ndarray
For NumPy >= 1.10.0 a view of `a` is always returned. For earlier
NumPy versions a view of `a` is returned only if the order of the
axes is changed, otherwise the input array is returned.
See Also
--------
moveaxis : Move array axes to new positions.
roll : Roll the elements of an array by a number of positions along a
given axis.
Examples
--------
>>> a = np.ones((3,4,5,6))
>>> np.rollaxis(a, 3, 1).shape
(3, 6, 4, 5)
>>> np.rollaxis(a, 2).shape
(5, 3, 4, 6)
>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4) | Roll the specified axis backwards, until it lies in a given position. | [
"Roll",
"the",
"specified",
"axis",
"backwards",
"until",
"it",
"lies",
"in",
"a",
"given",
"position",
"."
] | def rollaxis(a, axis, start=0):
"""
Roll the specified axis backwards, until it lies in a given position.
This function continues to be supported for backward compatibility, but you
should prefer `moveaxis`. The `moveaxis` function was added in NumPy
1.11.
Parameters
----------
a : ndarray
Input array.
axis : int
The axis to roll backwards. The positions of the other axes do not
change relative to one another.
start : int, optional
The axis is rolled until it lies before this position. The default,
0, results in a "complete" roll.
Returns
-------
res : ndarray
For NumPy >= 1.10.0 a view of `a` is always returned. For earlier
NumPy versions a view of `a` is returned only if the order of the
axes is changed, otherwise the input array is returned.
See Also
--------
moveaxis : Move array axes to new positions.
roll : Roll the elements of an array by a number of positions along a
given axis.
Examples
--------
>>> a = np.ones((3,4,5,6))
>>> np.rollaxis(a, 3, 1).shape
(3, 6, 4, 5)
>>> np.rollaxis(a, 2).shape
(5, 3, 4, 6)
>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4)
"""
n = a.ndim
axis = normalize_axis_index(axis, n)
if start < 0:
start += n
msg = "'%s' arg requires %d <= %s < %d, but %d was passed in"
if not (0 <= start < n + 1):
raise AxisError(msg % ('start', -n, 'start', n + 1, start))
if axis < start:
# it's been removed
start -= 1
if axis == start:
return a[...]
axes = list(range(0, n))
axes.remove(axis)
axes.insert(start, axis)
return a.transpose(axes) | [
"def",
"rollaxis",
"(",
"a",
",",
"axis",
",",
"start",
"=",
"0",
")",
":",
"n",
"=",
"a",
".",
"ndim",
"axis",
"=",
"normalize_axis_index",
"(",
"axis",
",",
"n",
")",
"if",
"start",
"<",
"0",
":",
"start",
"+=",
"n",
"msg",
"=",
"\"'%s' arg requires %d <= %s < %d, but %d was passed in\"",
"if",
"not",
"(",
"0",
"<=",
"start",
"<",
"n",
"+",
"1",
")",
":",
"raise",
"AxisError",
"(",
"msg",
"%",
"(",
"'start'",
",",
"-",
"n",
",",
"'start'",
",",
"n",
"+",
"1",
",",
"start",
")",
")",
"if",
"axis",
"<",
"start",
":",
"# it's been removed",
"start",
"-=",
"1",
"if",
"axis",
"==",
"start",
":",
"return",
"a",
"[",
"...",
"]",
"axes",
"=",
"list",
"(",
"range",
"(",
"0",
",",
"n",
")",
")",
"axes",
".",
"remove",
"(",
"axis",
")",
"axes",
".",
"insert",
"(",
"start",
",",
"axis",
")",
"return",
"a",
".",
"transpose",
"(",
"axes",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/numeric.py#L1216-L1274 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py | python | locatedExpr | (expr) | return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end")) | Helper to decorate a returned token with its starting and ending locations in the input string.
This helper adds the following results names:
- locn_start = location where matched expression begins
- locn_end = location where matched expression ends
- value = the actual parsed results
Be careful if the input text contains C{<TAB>} characters, you may want to call
C{L{ParserElement.parseWithTabs}}
Example::
wd = Word(alphas)
for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
print(match)
prints::
[[0, 'ljsdf', 5]]
[[8, 'lksdjjf', 15]]
[[18, 'lkkjj', 23]] | Helper to decorate a returned token with its starting and ending locations in the input string.
This helper adds the following results names:
- locn_start = location where matched expression begins
- locn_end = location where matched expression ends
- value = the actual parsed results | [
"Helper",
"to",
"decorate",
"a",
"returned",
"token",
"with",
"its",
"starting",
"and",
"ending",
"locations",
"in",
"the",
"input",
"string",
".",
"This",
"helper",
"adds",
"the",
"following",
"results",
"names",
":",
"-",
"locn_start",
"=",
"location",
"where",
"matched",
"expression",
"begins",
"-",
"locn_end",
"=",
"location",
"where",
"matched",
"expression",
"ends",
"-",
"value",
"=",
"the",
"actual",
"parsed",
"results"
] | def locatedExpr(expr):
"""
Helper to decorate a returned token with its starting and ending locations in the input string.
This helper adds the following results names:
- locn_start = location where matched expression begins
- locn_end = location where matched expression ends
- value = the actual parsed results
Be careful if the input text contains C{<TAB>} characters, you may want to call
C{L{ParserElement.parseWithTabs}}
Example::
wd = Word(alphas)
for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
print(match)
prints::
[[0, 'ljsdf', 5]]
[[8, 'lksdjjf', 15]]
[[18, 'lkkjj', 23]]
"""
locator = Empty().setParseAction(lambda s,l,t: l)
return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end")) | [
"def",
"locatedExpr",
"(",
"expr",
")",
":",
"locator",
"=",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"lambda",
"s",
",",
"l",
",",
"t",
":",
"l",
")",
"return",
"Group",
"(",
"locator",
"(",
"\"locn_start\"",
")",
"+",
"expr",
"(",
"\"value\"",
")",
"+",
"locator",
".",
"copy",
"(",
")",
".",
"leaveWhitespace",
"(",
")",
"(",
"\"locn_end\"",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py#L4725-L4746 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Fem/femmesh/meshtools.py | python | compact_mesh | (
old_femmesh
) | return (new_mesh, node_map, elem_map) | removes all gaps in node and element ids, start ids with 1
returns a tuple (FemMesh, node_assignment_map, element_assignment_map) | removes all gaps in node and element ids, start ids with 1
returns a tuple (FemMesh, node_assignment_map, element_assignment_map) | [
"removes",
"all",
"gaps",
"in",
"node",
"and",
"element",
"ids",
"start",
"ids",
"with",
"1",
"returns",
"a",
"tuple",
"(",
"FemMesh",
"node_assignment_map",
"element_assignment_map",
")"
] | def compact_mesh(
old_femmesh
):
"""
removes all gaps in node and element ids, start ids with 1
returns a tuple (FemMesh, node_assignment_map, element_assignment_map)
"""
node_map = {} # {old_node_id: new_node_id, ...}
elem_map = {} # {old_elem_id: new_elem_id, ...}
old_nodes = old_femmesh.Nodes
import Fem
new_mesh = Fem.FemMesh()
if old_nodes:
for i, n in enumerate(old_nodes):
nid = i + 1
new_mesh.addNode(old_nodes[n].x, old_nodes[n].y, old_nodes[n].z, nid)
node_map[n] = nid
# element id is one id for Edges, Faces and Volumes
# thus should not start with 0 for each element type
# because this will give an error for mixed meshes
# because the id is used already
# https://forum.freecadweb.org/viewtopic.php?t=48215
ele_id = 1
if old_femmesh.Edges:
for ed in old_femmesh.Edges:
old_elem_nodes = old_femmesh.getElementNodes(ed)
new_elemnodes = []
for old_node_id in old_elem_nodes:
new_elemnodes.append(node_map[old_node_id])
new_mesh.addEdge(new_elemnodes, ele_id)
elem_map[ed] = ele_id
ele_id += 1
if old_femmesh.Faces:
for fa in old_femmesh.Faces:
ele_id += 1
old_elem_nodes = old_femmesh.getElementNodes(fa)
new_elemnodes = []
for old_node_id in old_elem_nodes:
new_elemnodes.append(node_map[old_node_id])
new_mesh.addFace(new_elemnodes, ele_id)
elem_map[fa] = ele_id
ele_id += 1
if old_femmesh.Volumes:
for vo in old_femmesh.Volumes:
old_elem_nodes = old_femmesh.getElementNodes(vo)
new_elemnodes = []
for old_node_id in old_elem_nodes:
new_elemnodes.append(node_map[old_node_id])
new_mesh.addVolume(new_elemnodes, ele_id)
elem_map[vo] = ele_id
ele_id += 1
# may be return another value if the mesh was compacted, just check last map entries
return (new_mesh, node_map, elem_map) | [
"def",
"compact_mesh",
"(",
"old_femmesh",
")",
":",
"node_map",
"=",
"{",
"}",
"# {old_node_id: new_node_id, ...}",
"elem_map",
"=",
"{",
"}",
"# {old_elem_id: new_elem_id, ...}",
"old_nodes",
"=",
"old_femmesh",
".",
"Nodes",
"import",
"Fem",
"new_mesh",
"=",
"Fem",
".",
"FemMesh",
"(",
")",
"if",
"old_nodes",
":",
"for",
"i",
",",
"n",
"in",
"enumerate",
"(",
"old_nodes",
")",
":",
"nid",
"=",
"i",
"+",
"1",
"new_mesh",
".",
"addNode",
"(",
"old_nodes",
"[",
"n",
"]",
".",
"x",
",",
"old_nodes",
"[",
"n",
"]",
".",
"y",
",",
"old_nodes",
"[",
"n",
"]",
".",
"z",
",",
"nid",
")",
"node_map",
"[",
"n",
"]",
"=",
"nid",
"# element id is one id for Edges, Faces and Volumes",
"# thus should not start with 0 for each element type",
"# because this will give an error for mixed meshes",
"# because the id is used already",
"# https://forum.freecadweb.org/viewtopic.php?t=48215",
"ele_id",
"=",
"1",
"if",
"old_femmesh",
".",
"Edges",
":",
"for",
"ed",
"in",
"old_femmesh",
".",
"Edges",
":",
"old_elem_nodes",
"=",
"old_femmesh",
".",
"getElementNodes",
"(",
"ed",
")",
"new_elemnodes",
"=",
"[",
"]",
"for",
"old_node_id",
"in",
"old_elem_nodes",
":",
"new_elemnodes",
".",
"append",
"(",
"node_map",
"[",
"old_node_id",
"]",
")",
"new_mesh",
".",
"addEdge",
"(",
"new_elemnodes",
",",
"ele_id",
")",
"elem_map",
"[",
"ed",
"]",
"=",
"ele_id",
"ele_id",
"+=",
"1",
"if",
"old_femmesh",
".",
"Faces",
":",
"for",
"fa",
"in",
"old_femmesh",
".",
"Faces",
":",
"ele_id",
"+=",
"1",
"old_elem_nodes",
"=",
"old_femmesh",
".",
"getElementNodes",
"(",
"fa",
")",
"new_elemnodes",
"=",
"[",
"]",
"for",
"old_node_id",
"in",
"old_elem_nodes",
":",
"new_elemnodes",
".",
"append",
"(",
"node_map",
"[",
"old_node_id",
"]",
")",
"new_mesh",
".",
"addFace",
"(",
"new_elemnodes",
",",
"ele_id",
")",
"elem_map",
"[",
"fa",
"]",
"=",
"ele_id",
"ele_id",
"+=",
"1",
"if",
"old_femmesh",
".",
"Volumes",
":",
"for",
"vo",
"in",
"old_femmesh",
".",
"Volumes",
":",
"old_elem_nodes",
"=",
"old_femmesh",
".",
"getElementNodes",
"(",
"vo",
")",
"new_elemnodes",
"=",
"[",
"]",
"for",
"old_node_id",
"in",
"old_elem_nodes",
":",
"new_elemnodes",
".",
"append",
"(",
"node_map",
"[",
"old_node_id",
"]",
")",
"new_mesh",
".",
"addVolume",
"(",
"new_elemnodes",
",",
"ele_id",
")",
"elem_map",
"[",
"vo",
"]",
"=",
"ele_id",
"ele_id",
"+=",
"1",
"# may be return another value if the mesh was compacted, just check last map entries",
"return",
"(",
"new_mesh",
",",
"node_map",
",",
"elem_map",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/femmesh/meshtools.py#L2442-L2497 | |
dicecco1/fpga_caffe | 7a191704efd7873071cfef35772d7e7bf3e3cfd6 | scripts/cpp_lint.py | python | _OutputFormat | () | return _cpplint_state.output_format | Gets the module's output format. | Gets the module's output format. | [
"Gets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format | [
"def",
"_OutputFormat",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"output_format"
] | https://github.com/dicecco1/fpga_caffe/blob/7a191704efd7873071cfef35772d7e7bf3e3cfd6/scripts/cpp_lint.py#L771-L773 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/pynche/ColorDB.py | python | triplet_to_rrggbb | (rgbtuple) | return hexname | Converts a (red, green, blue) tuple to #rrggbb. | Converts a (red, green, blue) tuple to #rrggbb. | [
"Converts",
"a",
"(",
"red",
"green",
"blue",
")",
"tuple",
"to",
"#rrggbb",
"."
] | def triplet_to_rrggbb(rgbtuple):
"""Converts a (red, green, blue) tuple to #rrggbb."""
global _tripdict
hexname = _tripdict.get(rgbtuple)
if hexname is None:
hexname = '#%02x%02x%02x' % rgbtuple
_tripdict[rgbtuple] = hexname
return hexname | [
"def",
"triplet_to_rrggbb",
"(",
"rgbtuple",
")",
":",
"global",
"_tripdict",
"hexname",
"=",
"_tripdict",
".",
"get",
"(",
"rgbtuple",
")",
"if",
"hexname",
"is",
"None",
":",
"hexname",
"=",
"'#%02x%02x%02x'",
"%",
"rgbtuple",
"_tripdict",
"[",
"rgbtuple",
"]",
"=",
"hexname",
"return",
"hexname"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/pynche/ColorDB.py#L222-L229 | |
may0324/DeepCompression-caffe | 0aff6c1287bda4cfc7f378ed8a16524e1afabd8c | scripts/cpp_lint.py | python | ResetNolintSuppressions | () | Resets the set of NOLINT suppressions to empty. | Resets the set of NOLINT suppressions to empty. | [
"Resets",
"the",
"set",
"of",
"NOLINT",
"suppressions",
"to",
"empty",
"."
] | def ResetNolintSuppressions():
"Resets the set of NOLINT suppressions to empty."
_error_suppressions.clear() | [
"def",
"ResetNolintSuppressions",
"(",
")",
":",
"_error_suppressions",
".",
"clear",
"(",
")"
] | https://github.com/may0324/DeepCompression-caffe/blob/0aff6c1287bda4cfc7f378ed8a16524e1afabd8c/scripts/cpp_lint.py#L495-L497 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/multi_threads_helpers.py | python | IntegratePeaksThread.__init__ | (self, main_window, exp_number, scan_tuple_list, mask_det, mask_name, norm_type, num_pt_bg_left,
num_pt_bg_right, scale_factor=1.000) | return | :param main_window:
:param exp_number:
:param scan_tuple_list: list of tuples for scan as (scan number, pt number list, state as merged)
:param mask_det:
:param mask_name:
:param norm_type: type of normalization
:param num_pt_bg_left: number of Pt in the left
:param num_pt_bg_right: number of Pt for background in the right | [] | def __init__(self, main_window, exp_number, scan_tuple_list, mask_det, mask_name, norm_type, num_pt_bg_left,
num_pt_bg_right, scale_factor=1.000):
"""
:param main_window:
:param exp_number:
:param scan_tuple_list: list of tuples for scan as (scan number, pt number list, state as merged)
:param mask_det:
:param mask_name:
:param norm_type: type of normalization
:param num_pt_bg_left: number of Pt in the left
:param num_pt_bg_right: number of Pt for background in the right
"""
# start thread
QThread.__init__(self)
# check
assert main_window is not None, 'Main window cannot be None'
assert isinstance(exp_number, int), 'Experiment number must be an integer.'
assert isinstance(scan_tuple_list, list), 'Scan (info) tuple list must be a list but not %s.' \
'' % str(type(scan_tuple_list))
assert isinstance(mask_det, bool), 'Parameter mask_det must be a boolean but not %s.' \
'' % str(type(mask_det))
assert isinstance(mask_name, str), 'Name of mask must be a string but not %s.' % str(type(mask_name))
assert isinstance(norm_type, str), 'Normalization type must be a string but not %s.' \
'' % str(type(norm_type))
assert isinstance(num_pt_bg_left, int) and num_pt_bg_left >= 0,\
'Number of Pt at left for background {0} must be non-negative integers but not of type {1}.' \
''.format(num_pt_bg_left, type(num_pt_bg_left))
assert isinstance(num_pt_bg_right, int) and num_pt_bg_right >= 0,\
'Number of Pt at right for background {0} must be non-negative integers but not of type {1}.' \
''.format(num_pt_bg_right, type(num_pt_bg_right))
# set values
self._mainWindow = main_window
self._expNumber = exp_number
self._scanTupleList = scan_tuple_list[:]
self._maskDetector = mask_det
self._normalizeType = norm_type
self._selectedMaskName = mask_name
self._numBgPtLeft = num_pt_bg_left
self._numBgPtRight = num_pt_bg_right
self._scaleFactor = scale_factor
# other about preprocessed options
self._checkPreprocessedScans = True
# link signals
self.peakMergeSignal.connect(self._mainWindow.update_merge_value)
self.mergeMsgSignal.connect(self._mainWindow.update_merge_message)
return | [
"def",
"__init__",
"(",
"self",
",",
"main_window",
",",
"exp_number",
",",
"scan_tuple_list",
",",
"mask_det",
",",
"mask_name",
",",
"norm_type",
",",
"num_pt_bg_left",
",",
"num_pt_bg_right",
",",
"scale_factor",
"=",
"1.000",
")",
":",
"# start thread",
"QThread",
".",
"__init__",
"(",
"self",
")",
"# check",
"assert",
"main_window",
"is",
"not",
"None",
",",
"'Main window cannot be None'",
"assert",
"isinstance",
"(",
"exp_number",
",",
"int",
")",
",",
"'Experiment number must be an integer.'",
"assert",
"isinstance",
"(",
"scan_tuple_list",
",",
"list",
")",
",",
"'Scan (info) tuple list must be a list but not %s.'",
"''",
"%",
"str",
"(",
"type",
"(",
"scan_tuple_list",
")",
")",
"assert",
"isinstance",
"(",
"mask_det",
",",
"bool",
")",
",",
"'Parameter mask_det must be a boolean but not %s.'",
"''",
"%",
"str",
"(",
"type",
"(",
"mask_det",
")",
")",
"assert",
"isinstance",
"(",
"mask_name",
",",
"str",
")",
",",
"'Name of mask must be a string but not %s.'",
"%",
"str",
"(",
"type",
"(",
"mask_name",
")",
")",
"assert",
"isinstance",
"(",
"norm_type",
",",
"str",
")",
",",
"'Normalization type must be a string but not %s.'",
"''",
"%",
"str",
"(",
"type",
"(",
"norm_type",
")",
")",
"assert",
"isinstance",
"(",
"num_pt_bg_left",
",",
"int",
")",
"and",
"num_pt_bg_left",
">=",
"0",
",",
"'Number of Pt at left for background {0} must be non-negative integers but not of type {1}.'",
"''",
".",
"format",
"(",
"num_pt_bg_left",
",",
"type",
"(",
"num_pt_bg_left",
")",
")",
"assert",
"isinstance",
"(",
"num_pt_bg_right",
",",
"int",
")",
"and",
"num_pt_bg_right",
">=",
"0",
",",
"'Number of Pt at right for background {0} must be non-negative integers but not of type {1}.'",
"''",
".",
"format",
"(",
"num_pt_bg_right",
",",
"type",
"(",
"num_pt_bg_right",
")",
")",
"# set values",
"self",
".",
"_mainWindow",
"=",
"main_window",
"self",
".",
"_expNumber",
"=",
"exp_number",
"self",
".",
"_scanTupleList",
"=",
"scan_tuple_list",
"[",
":",
"]",
"self",
".",
"_maskDetector",
"=",
"mask_det",
"self",
".",
"_normalizeType",
"=",
"norm_type",
"self",
".",
"_selectedMaskName",
"=",
"mask_name",
"self",
".",
"_numBgPtLeft",
"=",
"num_pt_bg_left",
"self",
".",
"_numBgPtRight",
"=",
"num_pt_bg_right",
"self",
".",
"_scaleFactor",
"=",
"scale_factor",
"# other about preprocessed options",
"self",
".",
"_checkPreprocessedScans",
"=",
"True",
"# link signals",
"self",
".",
"peakMergeSignal",
".",
"connect",
"(",
"self",
".",
"_mainWindow",
".",
"update_merge_value",
")",
"self",
".",
"mergeMsgSignal",
".",
"connect",
"(",
"self",
".",
"_mainWindow",
".",
"update_merge_message",
")",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/multi_threads_helpers.py#L124-L175 | ||
facebook/watchman | 0917460c71b000b96be9b9575d77f06f2f6053bb | build/fbcode_builder/getdeps/builder.py | python | CargoBuilder._resolve_dep_to_git | (self) | return dep_to_git | For each direct dependency of the currently build manifest check if it
is also cargo-builded and if yes then extract it's git configs and
install dir | For each direct dependency of the currently build manifest check if it
is also cargo-builded and if yes then extract it's git configs and
install dir | [
"For",
"each",
"direct",
"dependency",
"of",
"the",
"currently",
"build",
"manifest",
"check",
"if",
"it",
"is",
"also",
"cargo",
"-",
"builded",
"and",
"if",
"yes",
"then",
"extract",
"it",
"s",
"git",
"configs",
"and",
"install",
"dir"
] | def _resolve_dep_to_git(self):
"""
For each direct dependency of the currently build manifest check if it
is also cargo-builded and if yes then extract it's git configs and
install dir
"""
dependencies = self.manifest.get_dependencies(self.ctx)
if not dependencies:
return []
dep_to_git = {}
for dep in dependencies:
dep_manifest = self.loader.load_manifest(dep)
dep_builder = dep_manifest.get("build", "builder", ctx=self.ctx)
if dep_builder not in ["cargo", "nop"] or dep == "rust":
# This is a direct dependency, but it is not build with cargo
# and it is not simply copying files with nop, so ignore it.
# The "rust" dependency is an exception since it contains the
# toolchain.
continue
git_conf = dep_manifest.get_section_as_dict("git", self.ctx)
if "repo_url" not in git_conf:
raise Exception(
"A cargo dependency requires git.repo_url to be defined."
)
source_dir = self.loader.get_project_install_dir(dep_manifest)
if dep_builder == "cargo":
source_dir = os.path.join(source_dir, "source")
git_conf["source_dir"] = source_dir
dep_to_git[dep] = git_conf
return dep_to_git | [
"def",
"_resolve_dep_to_git",
"(",
"self",
")",
":",
"dependencies",
"=",
"self",
".",
"manifest",
".",
"get_dependencies",
"(",
"self",
".",
"ctx",
")",
"if",
"not",
"dependencies",
":",
"return",
"[",
"]",
"dep_to_git",
"=",
"{",
"}",
"for",
"dep",
"in",
"dependencies",
":",
"dep_manifest",
"=",
"self",
".",
"loader",
".",
"load_manifest",
"(",
"dep",
")",
"dep_builder",
"=",
"dep_manifest",
".",
"get",
"(",
"\"build\"",
",",
"\"builder\"",
",",
"ctx",
"=",
"self",
".",
"ctx",
")",
"if",
"dep_builder",
"not",
"in",
"[",
"\"cargo\"",
",",
"\"nop\"",
"]",
"or",
"dep",
"==",
"\"rust\"",
":",
"# This is a direct dependency, but it is not build with cargo",
"# and it is not simply copying files with nop, so ignore it.",
"# The \"rust\" dependency is an exception since it contains the",
"# toolchain.",
"continue",
"git_conf",
"=",
"dep_manifest",
".",
"get_section_as_dict",
"(",
"\"git\"",
",",
"self",
".",
"ctx",
")",
"if",
"\"repo_url\"",
"not",
"in",
"git_conf",
":",
"raise",
"Exception",
"(",
"\"A cargo dependency requires git.repo_url to be defined.\"",
")",
"source_dir",
"=",
"self",
".",
"loader",
".",
"get_project_install_dir",
"(",
"dep_manifest",
")",
"if",
"dep_builder",
"==",
"\"cargo\"",
":",
"source_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"source_dir",
",",
"\"source\"",
")",
"git_conf",
"[",
"\"source_dir\"",
"]",
"=",
"source_dir",
"dep_to_git",
"[",
"dep",
"]",
"=",
"git_conf",
"return",
"dep_to_git"
] | https://github.com/facebook/watchman/blob/0917460c71b000b96be9b9575d77f06f2f6053bb/build/fbcode_builder/getdeps/builder.py#L1397-L1428 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/op_selector.py | python | make_list_of_t | (ts, check_graph=True, allow_graph=True, ignore_ops=False) | Convert ts to a list of `tf.Tensor`.
Args:
ts: can be an iterable of `tf.Tensor`, a `tf.Graph` or a single tensor.
check_graph: if `True` check if all the tensors belong to the same graph.
allow_graph: if `False` a `tf.Graph` cannot be converted.
ignore_ops: if `True`, silently ignore `tf.Operation`.
Returns:
A newly created list of `tf.Tensor`.
Raises:
TypeError: if `ts` cannot be converted to a list of `tf.Tensor` or,
if `check_graph` is `True`, if all the ops do not belong to the same graph. | Convert ts to a list of `tf.Tensor`. | [
"Convert",
"ts",
"to",
"a",
"list",
"of",
"tf",
".",
"Tensor",
"."
] | def make_list_of_t(ts, check_graph=True, allow_graph=True, ignore_ops=False):
"""Convert ts to a list of `tf.Tensor`.
Args:
ts: can be an iterable of `tf.Tensor`, a `tf.Graph` or a single tensor.
check_graph: if `True` check if all the tensors belong to the same graph.
allow_graph: if `False` a `tf.Graph` cannot be converted.
ignore_ops: if `True`, silently ignore `tf.Operation`.
Returns:
A newly created list of `tf.Tensor`.
Raises:
TypeError: if `ts` cannot be converted to a list of `tf.Tensor` or,
if `check_graph` is `True`, if all the ops do not belong to the same graph.
"""
if isinstance(ts, ops.Graph):
if allow_graph:
return get_tensors(ts)
else:
raise TypeError("allow_graph is False: cannot convert a tf.Graph.")
else:
if not is_iterable(ts):
ts = [ts]
if not ts:
return []
if check_graph:
check_types = None if ignore_ops else ops.Tensor
get_unique_graph(ts, check_types=check_types)
return [t for t in ts if isinstance(t, ops.Tensor)] | [
"def",
"make_list_of_t",
"(",
"ts",
",",
"check_graph",
"=",
"True",
",",
"allow_graph",
"=",
"True",
",",
"ignore_ops",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"ts",
",",
"ops",
".",
"Graph",
")",
":",
"if",
"allow_graph",
":",
"return",
"get_tensors",
"(",
"ts",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"allow_graph is False: cannot convert a tf.Graph.\"",
")",
"else",
":",
"if",
"not",
"is_iterable",
"(",
"ts",
")",
":",
"ts",
"=",
"[",
"ts",
"]",
"if",
"not",
"ts",
":",
"return",
"[",
"]",
"if",
"check_graph",
":",
"check_types",
"=",
"None",
"if",
"ignore_ops",
"else",
"ops",
".",
"Tensor",
"get_unique_graph",
"(",
"ts",
",",
"check_types",
"=",
"check_types",
")",
"return",
"[",
"t",
"for",
"t",
"in",
"ts",
"if",
"isinstance",
"(",
"t",
",",
"ops",
".",
"Tensor",
")",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/op_selector.py#L134-L161 | ||
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | hasher-matcher-actioner/hmalib/indexers/s3_indexers.py | python | S3BackedInstrumentedIndexMixin.get_index_max_distance | (cls) | return 0 | Helper to distinguish if the next should be used based on configured thersholds.
Defaults to zero (i.e. only exact matches supported) | Helper to distinguish if the next should be used based on configured thersholds.
Defaults to zero (i.e. only exact matches supported) | [
"Helper",
"to",
"distinguish",
"if",
"the",
"next",
"should",
"be",
"used",
"based",
"on",
"configured",
"thersholds",
".",
"Defaults",
"to",
"zero",
"(",
"i",
".",
"e",
".",
"only",
"exact",
"matches",
"supported",
")"
] | def get_index_max_distance(cls) -> int:
"""
Helper to distinguish if the next should be used based on configured thersholds.
Defaults to zero (i.e. only exact matches supported)
"""
return 0 | [
"def",
"get_index_max_distance",
"(",
"cls",
")",
"->",
"int",
":",
"return",
"0"
] | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/hasher-matcher-actioner/hmalib/indexers/s3_indexers.py#L67-L72 | |
strasdat/Sophus | 36b08885e094fda63e92ad89d65be380c288265a | sympy/sophus/complex.py | python | Complex.inv | (self) | return self.conj() / self.squared_norm() | complex inverse | complex inverse | [
"complex",
"inverse"
] | def inv(self):
""" complex inverse """
return self.conj() / self.squared_norm() | [
"def",
"inv",
"(",
"self",
")",
":",
"return",
"self",
".",
"conj",
"(",
")",
"/",
"self",
".",
"squared_norm",
"(",
")"
] | https://github.com/strasdat/Sophus/blob/36b08885e094fda63e92ad89d65be380c288265a/sympy/sophus/complex.py#L47-L49 | |
yyzybb537/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | third_party/boost.context/tools/build/src/build/project.py | python | ProjectRegistry.find_jamfile | (self, dir, parent_root=0, no_errors=0) | Find the Jamfile at the given location. This returns the
exact names of all the Jamfiles in the given directory. The optional
parent-root argument causes this to search not the given directory
but the ones above it up to the directory given in it. | Find the Jamfile at the given location. This returns the
exact names of all the Jamfiles in the given directory. The optional
parent-root argument causes this to search not the given directory
but the ones above it up to the directory given in it. | [
"Find",
"the",
"Jamfile",
"at",
"the",
"given",
"location",
".",
"This",
"returns",
"the",
"exact",
"names",
"of",
"all",
"the",
"Jamfiles",
"in",
"the",
"given",
"directory",
".",
"The",
"optional",
"parent",
"-",
"root",
"argument",
"causes",
"this",
"to",
"search",
"not",
"the",
"given",
"directory",
"but",
"the",
"ones",
"above",
"it",
"up",
"to",
"the",
"directory",
"given",
"in",
"it",
"."
] | def find_jamfile (self, dir, parent_root=0, no_errors=0):
"""Find the Jamfile at the given location. This returns the
exact names of all the Jamfiles in the given directory. The optional
parent-root argument causes this to search not the given directory
but the ones above it up to the directory given in it."""
assert isinstance(dir, basestring)
assert isinstance(parent_root, (int, bool))
assert isinstance(no_errors, (int, bool))
# Glob for all the possible Jamfiles according to the match pattern.
#
jamfile_glob = None
if parent_root:
parent = self.dir2parent_jamfile.get(dir)
if not parent:
parent = b2.util.path.glob_in_parents(dir,
self.JAMFILE)
self.dir2parent_jamfile[dir] = parent
jamfile_glob = parent
else:
jamfile = self.dir2jamfile.get(dir)
if not jamfile:
jamfile = b2.util.path.glob([dir], self.JAMFILE)
self.dir2jamfile[dir] = jamfile
jamfile_glob = jamfile
if len(jamfile_glob) > 1:
# Multiple Jamfiles found in the same place. Warn about this.
# And ensure we use only one of them.
# As a temporary convenience measure, if there's Jamfile.v2 amount
# found files, suppress the warning and use it.
#
pattern = "(.*[Jj]amfile\\.v2)|(.*[Bb]uild\\.jam)"
v2_jamfiles = [x for x in jamfile_glob if re.match(pattern, x)]
if len(v2_jamfiles) == 1:
jamfile_glob = v2_jamfiles
else:
print """warning: Found multiple Jamfiles at '%s'!""" % (dir)
for j in jamfile_glob:
print " -", j
print "Loading the first one"
# Could not find it, error.
if not no_errors and not jamfile_glob:
self.manager.errors()(
"""Unable to load Jamfile.
Could not find a Jamfile in directory '%s'
Attempted to find it with pattern '%s'.
Please consult the documentation at 'http://boost.org/boost-build2'."""
% (dir, string.join(self.JAMFILE)))
if jamfile_glob:
return jamfile_glob[0] | [
"def",
"find_jamfile",
"(",
"self",
",",
"dir",
",",
"parent_root",
"=",
"0",
",",
"no_errors",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"dir",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"parent_root",
",",
"(",
"int",
",",
"bool",
")",
")",
"assert",
"isinstance",
"(",
"no_errors",
",",
"(",
"int",
",",
"bool",
")",
")",
"# Glob for all the possible Jamfiles according to the match pattern.",
"#",
"jamfile_glob",
"=",
"None",
"if",
"parent_root",
":",
"parent",
"=",
"self",
".",
"dir2parent_jamfile",
".",
"get",
"(",
"dir",
")",
"if",
"not",
"parent",
":",
"parent",
"=",
"b2",
".",
"util",
".",
"path",
".",
"glob_in_parents",
"(",
"dir",
",",
"self",
".",
"JAMFILE",
")",
"self",
".",
"dir2parent_jamfile",
"[",
"dir",
"]",
"=",
"parent",
"jamfile_glob",
"=",
"parent",
"else",
":",
"jamfile",
"=",
"self",
".",
"dir2jamfile",
".",
"get",
"(",
"dir",
")",
"if",
"not",
"jamfile",
":",
"jamfile",
"=",
"b2",
".",
"util",
".",
"path",
".",
"glob",
"(",
"[",
"dir",
"]",
",",
"self",
".",
"JAMFILE",
")",
"self",
".",
"dir2jamfile",
"[",
"dir",
"]",
"=",
"jamfile",
"jamfile_glob",
"=",
"jamfile",
"if",
"len",
"(",
"jamfile_glob",
")",
">",
"1",
":",
"# Multiple Jamfiles found in the same place. Warn about this.",
"# And ensure we use only one of them.",
"# As a temporary convenience measure, if there's Jamfile.v2 amount",
"# found files, suppress the warning and use it.",
"#",
"pattern",
"=",
"\"(.*[Jj]amfile\\\\.v2)|(.*[Bb]uild\\\\.jam)\"",
"v2_jamfiles",
"=",
"[",
"x",
"for",
"x",
"in",
"jamfile_glob",
"if",
"re",
".",
"match",
"(",
"pattern",
",",
"x",
")",
"]",
"if",
"len",
"(",
"v2_jamfiles",
")",
"==",
"1",
":",
"jamfile_glob",
"=",
"v2_jamfiles",
"else",
":",
"print",
"\"\"\"warning: Found multiple Jamfiles at '%s'!\"\"\"",
"%",
"(",
"dir",
")",
"for",
"j",
"in",
"jamfile_glob",
":",
"print",
"\" -\"",
",",
"j",
"print",
"\"Loading the first one\"",
"# Could not find it, error.",
"if",
"not",
"no_errors",
"and",
"not",
"jamfile_glob",
":",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"\"\"\"Unable to load Jamfile.\nCould not find a Jamfile in directory '%s'\nAttempted to find it with pattern '%s'.\nPlease consult the documentation at 'http://boost.org/boost-build2'.\"\"\"",
"%",
"(",
"dir",
",",
"string",
".",
"join",
"(",
"self",
".",
"JAMFILE",
")",
")",
")",
"if",
"jamfile_glob",
":",
"return",
"jamfile_glob",
"[",
"0",
"]"
] | https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/project.py#L237-L289 | ||
s9xie/hed | 94fb22f10cbfec8d84fbc0642b224022014b6bd6 | scripts/cpp_lint.py | python | _CppLintState.SetFilters | (self, filters) | Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" | Sets the error-message filters. | [
"Sets",
"the",
"error",
"-",
"message",
"filters",
"."
] | def SetFilters(self, filters):
"""Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
"""
# Default filters always have less priority than the flag ones.
self.filters = _DEFAULT_FILTERS[:]
for filt in filters.split(','):
clean_filt = filt.strip()
if clean_filt:
self.filters.append(clean_filt)
for filt in self.filters:
if not (filt.startswith('+') or filt.startswith('-')):
raise ValueError('Every filter in --filters must start with + or -'
' (%s does not)' % filt) | [
"def",
"SetFilters",
"(",
"self",
",",
"filters",
")",
":",
"# Default filters always have less priority than the flag ones.",
"self",
".",
"filters",
"=",
"_DEFAULT_FILTERS",
"[",
":",
"]",
"for",
"filt",
"in",
"filters",
".",
"split",
"(",
"','",
")",
":",
"clean_filt",
"=",
"filt",
".",
"strip",
"(",
")",
"if",
"clean_filt",
":",
"self",
".",
"filters",
".",
"append",
"(",
"clean_filt",
")",
"for",
"filt",
"in",
"self",
".",
"filters",
":",
"if",
"not",
"(",
"filt",
".",
"startswith",
"(",
"'+'",
")",
"or",
"filt",
".",
"startswith",
"(",
"'-'",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Every filter in --filters must start with + or -'",
"' (%s does not)'",
"%",
"filt",
")"
] | https://github.com/s9xie/hed/blob/94fb22f10cbfec8d84fbc0642b224022014b6bd6/scripts/cpp_lint.py#L717-L740 | ||
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/fluka.py | python | UsrbinTally.__init__ | (self, fh) | Creates a UsrbinTally object by reading through the file
Parameters
----------
fh : filehandle
An open usrbin file | Creates a UsrbinTally object by reading through the file | [
"Creates",
"a",
"UsrbinTally",
"object",
"by",
"reading",
"through",
"the",
"file"
] | def __init__(self, fh):
"""Creates a UsrbinTally object by reading through the file
Parameters
----------
fh : filehandle
An open usrbin file
"""
if not HAVE_PYMOAB:
raise RuntimeError("PyMOAB is not available, "
"unable to create Meshtal.")
part_data = []
error_data = []
line = fh.readline()
# Read the header for the tally.
# Information obtained: coordinate system used, user-defined tally
# name, particle, and x, y, and z dimension information.
[self.coord_sys, self.name, self.particle] = line.split('"')
self.name = self.name.strip()
self.coord_sys = self.coord_sys.split()[0]
self.particle = self.particle.split()[-1]
if self.coord_sys != 'Cartesian':
raise ValueError(
"Only cartesian coordinate system currently supported")
[x_info, y_info, z_info] = self._read_usrbin_head(fh)
# Advance to start of tally data skipping blank and/or text lines.
line = fh.readline()
line = fh.readline()
if "accurate deposition" in line:
line = fh.readline()
if "track-length binning" in line:
line = fh.readline()
# Read the track-length binning data (part_data) and percentage error
# data (error_data).
num_volume_element = x_info[2]*y_info[2]*z_info[2]
part_data += [float(x) for x in line.split()]
while (len(part_data) < num_volume_element):
line = fh.readline()
part_data += [float(x) for x in line.split()]
for count in range(0, 3):
line = fh.readline()
while (len(error_data) < num_volume_element):
line = fh.readline()
error_data += [float(x) for x in line.split()]
# create mesh object
self.x_bounds = self._generate_bounds(x_info)
self.y_bounds = self._generate_bounds(y_info)
self.z_bounds = self._generate_bounds(z_info)
self._create_mesh(part_data, error_data) | [
"def",
"__init__",
"(",
"self",
",",
"fh",
")",
":",
"if",
"not",
"HAVE_PYMOAB",
":",
"raise",
"RuntimeError",
"(",
"\"PyMOAB is not available, \"",
"\"unable to create Meshtal.\"",
")",
"part_data",
"=",
"[",
"]",
"error_data",
"=",
"[",
"]",
"line",
"=",
"fh",
".",
"readline",
"(",
")",
"# Read the header for the tally.",
"# Information obtained: coordinate system used, user-defined tally",
"# name, particle, and x, y, and z dimension information.",
"[",
"self",
".",
"coord_sys",
",",
"self",
".",
"name",
",",
"self",
".",
"particle",
"]",
"=",
"line",
".",
"split",
"(",
"'\"'",
")",
"self",
".",
"name",
"=",
"self",
".",
"name",
".",
"strip",
"(",
")",
"self",
".",
"coord_sys",
"=",
"self",
".",
"coord_sys",
".",
"split",
"(",
")",
"[",
"0",
"]",
"self",
".",
"particle",
"=",
"self",
".",
"particle",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
"if",
"self",
".",
"coord_sys",
"!=",
"'Cartesian'",
":",
"raise",
"ValueError",
"(",
"\"Only cartesian coordinate system currently supported\"",
")",
"[",
"x_info",
",",
"y_info",
",",
"z_info",
"]",
"=",
"self",
".",
"_read_usrbin_head",
"(",
"fh",
")",
"# Advance to start of tally data skipping blank and/or text lines.",
"line",
"=",
"fh",
".",
"readline",
"(",
")",
"line",
"=",
"fh",
".",
"readline",
"(",
")",
"if",
"\"accurate deposition\"",
"in",
"line",
":",
"line",
"=",
"fh",
".",
"readline",
"(",
")",
"if",
"\"track-length binning\"",
"in",
"line",
":",
"line",
"=",
"fh",
".",
"readline",
"(",
")",
"# Read the track-length binning data (part_data) and percentage error",
"# data (error_data).",
"num_volume_element",
"=",
"x_info",
"[",
"2",
"]",
"*",
"y_info",
"[",
"2",
"]",
"*",
"z_info",
"[",
"2",
"]",
"part_data",
"+=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"line",
".",
"split",
"(",
")",
"]",
"while",
"(",
"len",
"(",
"part_data",
")",
"<",
"num_volume_element",
")",
":",
"line",
"=",
"fh",
".",
"readline",
"(",
")",
"part_data",
"+=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"line",
".",
"split",
"(",
")",
"]",
"for",
"count",
"in",
"range",
"(",
"0",
",",
"3",
")",
":",
"line",
"=",
"fh",
".",
"readline",
"(",
")",
"while",
"(",
"len",
"(",
"error_data",
")",
"<",
"num_volume_element",
")",
":",
"line",
"=",
"fh",
".",
"readline",
"(",
")",
"error_data",
"+=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"line",
".",
"split",
"(",
")",
"]",
"# create mesh object",
"self",
".",
"x_bounds",
"=",
"self",
".",
"_generate_bounds",
"(",
"x_info",
")",
"self",
".",
"y_bounds",
"=",
"self",
".",
"_generate_bounds",
"(",
"y_info",
")",
"self",
".",
"z_bounds",
"=",
"self",
".",
"_generate_bounds",
"(",
"z_info",
")",
"self",
".",
"_create_mesh",
"(",
"part_data",
",",
"error_data",
")"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/fluka.py#L101-L158 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/extras/codelite.py | python | codelite_generator.get_solution_node | (self) | return self.solution_node | The solution filename is required when writing the .vcproj files
return self.solution_node and if it does not exist, make one | The solution filename is required when writing the .vcproj files
return self.solution_node and if it does not exist, make one | [
"The",
"solution",
"filename",
"is",
"required",
"when",
"writing",
"the",
".",
"vcproj",
"files",
"return",
"self",
".",
"solution_node",
"and",
"if",
"it",
"does",
"not",
"exist",
"make",
"one"
] | def get_solution_node(self):
"""
The solution filename is required when writing the .vcproj files
return self.solution_node and if it does not exist, make one
"""
try:
return self.solution_node
except:
pass
codelite_solution_name = getattr(self, 'codelite_solution_name', None)
if not codelite_solution_name:
codelite_solution_name = getattr(Context.g_module, Context.APPNAME, 'project') + '.workspace'
setattr(self, 'codelite_solution_name', codelite_solution_name)
if os.path.isabs(codelite_solution_name):
self.solution_node = self.root.make_node(codelite_solution_name)
else:
self.solution_node = self.srcnode.make_node(codelite_solution_name)
return self.solution_node | [
"def",
"get_solution_node",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"solution_node",
"except",
":",
"pass",
"codelite_solution_name",
"=",
"getattr",
"(",
"self",
",",
"'codelite_solution_name'",
",",
"None",
")",
"if",
"not",
"codelite_solution_name",
":",
"codelite_solution_name",
"=",
"getattr",
"(",
"Context",
".",
"g_module",
",",
"Context",
".",
"APPNAME",
",",
"'project'",
")",
"+",
"'.workspace'",
"setattr",
"(",
"self",
",",
"'codelite_solution_name'",
",",
"codelite_solution_name",
")",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"codelite_solution_name",
")",
":",
"self",
".",
"solution_node",
"=",
"self",
".",
"root",
".",
"make_node",
"(",
"codelite_solution_name",
")",
"else",
":",
"self",
".",
"solution_node",
"=",
"self",
".",
"srcnode",
".",
"make_node",
"(",
"codelite_solution_name",
")",
"return",
"self",
".",
"solution_node"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/codelite.py#L766-L784 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/affine/binary_operators.py | python | DivExpression.is_incr | (self, idx) | Is the composition non-decreasing in argument idx? | Is the composition non-decreasing in argument idx? | [
"Is",
"the",
"composition",
"non",
"-",
"decreasing",
"in",
"argument",
"idx?"
] | def is_incr(self, idx) -> bool:
"""Is the composition non-decreasing in argument idx?
"""
if idx == 0:
return self.args[1].is_nonneg()
else:
return self.args[0].is_nonpos() | [
"def",
"is_incr",
"(",
"self",
",",
"idx",
")",
"->",
"bool",
":",
"if",
"idx",
"==",
"0",
":",
"return",
"self",
".",
"args",
"[",
"1",
"]",
".",
"is_nonneg",
"(",
")",
"else",
":",
"return",
"self",
".",
"args",
"[",
"0",
"]",
".",
"is_nonpos",
"(",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/affine/binary_operators.py#L380-L386 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/plotting/_matplotlib/converter.py | python | TimeSeries_DateFormatter._set_default_format | (self, vmin, vmax) | return self.formatdict | Returns the default ticks spacing. | Returns the default ticks spacing. | [
"Returns",
"the",
"default",
"ticks",
"spacing",
"."
] | def _set_default_format(self, vmin, vmax):
"Returns the default ticks spacing."
if self.plot_obj.date_axis_info is None:
self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq)
info = self.plot_obj.date_axis_info
if self.isminor:
format = np.compress(info["min"] & np.logical_not(info["maj"]), info)
else:
format = np.compress(info["maj"], info)
self.formatdict = {x: f for (x, _, _, f) in format}
return self.formatdict | [
"def",
"_set_default_format",
"(",
"self",
",",
"vmin",
",",
"vmax",
")",
":",
"if",
"self",
".",
"plot_obj",
".",
"date_axis_info",
"is",
"None",
":",
"self",
".",
"plot_obj",
".",
"date_axis_info",
"=",
"self",
".",
"finder",
"(",
"vmin",
",",
"vmax",
",",
"self",
".",
"freq",
")",
"info",
"=",
"self",
".",
"plot_obj",
".",
"date_axis_info",
"if",
"self",
".",
"isminor",
":",
"format",
"=",
"np",
".",
"compress",
"(",
"info",
"[",
"\"min\"",
"]",
"&",
"np",
".",
"logical_not",
"(",
"info",
"[",
"\"maj\"",
"]",
")",
",",
"info",
")",
"else",
":",
"format",
"=",
"np",
".",
"compress",
"(",
"info",
"[",
"\"maj\"",
"]",
",",
"info",
")",
"self",
".",
"formatdict",
"=",
"{",
"x",
":",
"f",
"for",
"(",
"x",
",",
"_",
",",
"_",
",",
"f",
")",
"in",
"format",
"}",
"return",
"self",
".",
"formatdict"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/plotting/_matplotlib/converter.py#L1065-L1077 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | xmlDoc.schemaValidateDoc | (self, ctxt) | return ret | Validate a document tree in memory. | Validate a document tree in memory. | [
"Validate",
"a",
"document",
"tree",
"in",
"memory",
"."
] | def schemaValidateDoc(self, ctxt):
"""Validate a document tree in memory. """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.xmlSchemaValidateDoc(ctxt__o, self._o)
return ret | [
"def",
"schemaValidateDoc",
"(",
"self",
",",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlSchemaValidateDoc",
"(",
"ctxt__o",
",",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L4072-L4077 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | BookCtrlBase.SetPageText | (*args, **kwargs) | return _core_.BookCtrlBase_SetPageText(*args, **kwargs) | SetPageText(self, size_t n, String strText) -> bool | SetPageText(self, size_t n, String strText) -> bool | [
"SetPageText",
"(",
"self",
"size_t",
"n",
"String",
"strText",
")",
"-",
">",
"bool"
] | def SetPageText(*args, **kwargs):
"""SetPageText(self, size_t n, String strText) -> bool"""
return _core_.BookCtrlBase_SetPageText(*args, **kwargs) | [
"def",
"SetPageText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"BookCtrlBase_SetPageText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13554-L13556 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py2/jinja2/utils.py | python | open_if_exists | (filename, mode="rb") | return open(filename, mode) | Returns a file descriptor for the filename if that file exists,
otherwise ``None``. | Returns a file descriptor for the filename if that file exists,
otherwise ``None``. | [
"Returns",
"a",
"file",
"descriptor",
"for",
"the",
"filename",
"if",
"that",
"file",
"exists",
"otherwise",
"None",
"."
] | def open_if_exists(filename, mode="rb"):
"""Returns a file descriptor for the filename if that file exists,
otherwise ``None``.
"""
if not os.path.isfile(filename):
return None
return open(filename, mode) | [
"def",
"open_if_exists",
"(",
"filename",
",",
"mode",
"=",
"\"rb\"",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"return",
"None",
"return",
"open",
"(",
"filename",
",",
"mode",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/utils.py#L137-L144 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/data_structures/sgraph.py | python | SGraph.select_fields | (self, fields) | Return a new SGraph with only the selected fields. Other fields are
discarded, while fields that do not exist in the SGraph are ignored.
Parameters
----------
fields : string | list [string]
A single field name or a list of field names to select.
Returns
-------
out : SGraph
A new graph whose vertex and edge data are projected to the selected
fields.
See Also
--------
get_fields, get_vertex_fields, get_edge_fields
Examples
--------
>>> from turicreate import SGraph, Vertex
>>> verts = [Vertex(0, attr={'breed': 'labrador', 'age': 5}),
Vertex(1, attr={'breed': 'labrador', 'age': 3}),
Vertex(2, attr={'breed': 'vizsla', 'age': 8})]
>>> g = SGraph()
>>> g = g.add_vertices(verts)
>>> g2 = g.select_fields(fields=['breed']) | Return a new SGraph with only the selected fields. Other fields are
discarded, while fields that do not exist in the SGraph are ignored. | [
"Return",
"a",
"new",
"SGraph",
"with",
"only",
"the",
"selected",
"fields",
".",
"Other",
"fields",
"are",
"discarded",
"while",
"fields",
"that",
"do",
"not",
"exist",
"in",
"the",
"SGraph",
"are",
"ignored",
"."
] | def select_fields(self, fields):
"""
Return a new SGraph with only the selected fields. Other fields are
discarded, while fields that do not exist in the SGraph are ignored.
Parameters
----------
fields : string | list [string]
A single field name or a list of field names to select.
Returns
-------
out : SGraph
A new graph whose vertex and edge data are projected to the selected
fields.
See Also
--------
get_fields, get_vertex_fields, get_edge_fields
Examples
--------
>>> from turicreate import SGraph, Vertex
>>> verts = [Vertex(0, attr={'breed': 'labrador', 'age': 5}),
Vertex(1, attr={'breed': 'labrador', 'age': 3}),
Vertex(2, attr={'breed': 'vizsla', 'age': 8})]
>>> g = SGraph()
>>> g = g.add_vertices(verts)
>>> g2 = g.select_fields(fields=['breed'])
"""
if type(fields) is str:
fields = [fields]
if not isinstance(fields, list) or not all(type(x) is str for x in fields):
raise TypeError('"fields" must be a str or list[str]')
vfields = self.__proxy__.get_vertex_fields()
efields = self.__proxy__.get_edge_fields()
selected_vfields = []
selected_efields = []
for f in fields:
found = False
if f in vfields:
selected_vfields.append(f)
found = True
if f in efields:
selected_efields.append(f)
found = True
if not found:
raise ValueError("Field '%s' not in graph" % f)
with cython_context():
proxy = self.__proxy__
proxy = proxy.select_vertex_fields(selected_vfields)
proxy = proxy.select_edge_fields(selected_efields)
return SGraph(_proxy=proxy) | [
"def",
"select_fields",
"(",
"self",
",",
"fields",
")",
":",
"if",
"type",
"(",
"fields",
")",
"is",
"str",
":",
"fields",
"=",
"[",
"fields",
"]",
"if",
"not",
"isinstance",
"(",
"fields",
",",
"list",
")",
"or",
"not",
"all",
"(",
"type",
"(",
"x",
")",
"is",
"str",
"for",
"x",
"in",
"fields",
")",
":",
"raise",
"TypeError",
"(",
"'\"fields\" must be a str or list[str]'",
")",
"vfields",
"=",
"self",
".",
"__proxy__",
".",
"get_vertex_fields",
"(",
")",
"efields",
"=",
"self",
".",
"__proxy__",
".",
"get_edge_fields",
"(",
")",
"selected_vfields",
"=",
"[",
"]",
"selected_efields",
"=",
"[",
"]",
"for",
"f",
"in",
"fields",
":",
"found",
"=",
"False",
"if",
"f",
"in",
"vfields",
":",
"selected_vfields",
".",
"append",
"(",
"f",
")",
"found",
"=",
"True",
"if",
"f",
"in",
"efields",
":",
"selected_efields",
".",
"append",
"(",
"f",
")",
"found",
"=",
"True",
"if",
"not",
"found",
":",
"raise",
"ValueError",
"(",
"\"Field '%s' not in graph\"",
"%",
"f",
")",
"with",
"cython_context",
"(",
")",
":",
"proxy",
"=",
"self",
".",
"__proxy__",
"proxy",
"=",
"proxy",
".",
"select_vertex_fields",
"(",
"selected_vfields",
")",
"proxy",
"=",
"proxy",
".",
"select_edge_fields",
"(",
"selected_efields",
")",
"return",
"SGraph",
"(",
"_proxy",
"=",
"proxy",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sgraph.py#L843-L898 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/math_ops.py | python | real | (input, name=None) | Returns the real part of a complex number.
Given a tensor `input` of complex numbers, this operation returns a tensor of
type `float32` or `float64` that is the real part of each element in `input`.
All elements in `input` must be complex numbers of the form \\(a + bj\\),
where *a* is the real part returned by this operation and *b* is the
imaginary part.
For example:
```
# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]
tf.real(input) ==> [-2.25, 3.25]
```
Args:
input: A `Tensor`. Must be one of the following types: `complex64`,
`complex128`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `float32` or `float64`. | Returns the real part of a complex number. | [
"Returns",
"the",
"real",
"part",
"of",
"a",
"complex",
"number",
"."
] | def real(input, name=None):
"""Returns the real part of a complex number.
Given a tensor `input` of complex numbers, this operation returns a tensor of
type `float32` or `float64` that is the real part of each element in `input`.
All elements in `input` must be complex numbers of the form \\(a + bj\\),
where *a* is the real part returned by this operation and *b* is the
imaginary part.
For example:
```
# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]
tf.real(input) ==> [-2.25, 3.25]
```
Args:
input: A `Tensor`. Must be one of the following types: `complex64`,
`complex128`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `float32` or `float64`.
"""
with ops.op_scope([input], name, "Real") as name:
return gen_math_ops.real(input, Tout=input.dtype.real_dtype, name=name) | [
"def",
"real",
"(",
"input",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"input",
"]",
",",
"name",
",",
"\"Real\"",
")",
"as",
"name",
":",
"return",
"gen_math_ops",
".",
"real",
"(",
"input",
",",
"Tout",
"=",
"input",
".",
"dtype",
".",
"real_dtype",
",",
"name",
"=",
"name",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L508-L533 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/dynamodb/conditions.py | python | AttributeBase.begins_with | (self, value) | return BeginsWith(self, value) | Creates a condition where the attribute begins with the value.
:param value: The value that the attribute begins with. | Creates a condition where the attribute begins with the value. | [
"Creates",
"a",
"condition",
"where",
"the",
"attribute",
"begins",
"with",
"the",
"value",
"."
] | def begins_with(self, value):
"""Creates a condition where the attribute begins with the value.
:param value: The value that the attribute begins with.
"""
return BeginsWith(self, value) | [
"def",
"begins_with",
"(",
"self",
",",
"value",
")",
":",
"return",
"BeginsWith",
"(",
"self",
",",
"value",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/dynamodb/conditions.py#L111-L116 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/io/loader.py | python | save | (obj,type,fn) | General-purpose save of an arbitrary Klampt object to a file.
This also works with RobotModel, RigidObjectModel, and TerrainModel
(which don't work with load).
Args:
obj: a Klamp't object.
type (str): the Klampt type, 'json', or 'auto'
fn (str): a file name
Returns:
bool: True if successful. | General-purpose save of an arbitrary Klampt object to a file. | [
"General",
"-",
"purpose",
"save",
"of",
"an",
"arbitrary",
"Klampt",
"object",
"to",
"a",
"file",
"."
] | def save(obj,type,fn):
"""General-purpose save of an arbitrary Klampt object to a file.
This also works with RobotModel, RigidObjectModel, and TerrainModel
(which don't work with load).
Args:
obj: a Klamp't object.
type (str): the Klampt type, 'json', or 'auto'
fn (str): a file name
Returns:
bool: True if successful.
"""
global savers,writers
if hasattr(obj,'saveFile'):
return obj.saveFile(fn)
if type == 'auto':
savers_and_writers = savers.keys() + writers.keys()
type = autoType(obj,savers_and_writers)
if type is None:
raise ValueError("Can't determine a savable type for object of type "+obj.__class__.__name__)
elif type == 'json':
import json
with open(fn,'w') as f:
json.dump(toJson(obj),f)
return True
if type in savers:
return savers[type](obj,fn)
elif type in writers:
with open(fn,'w') as f:
f.write(writers[type](obj)+'\n')
return True
else:
raise ValueError("Saving of type "+type+" is not supported") | [
"def",
"save",
"(",
"obj",
",",
"type",
",",
"fn",
")",
":",
"global",
"savers",
",",
"writers",
"if",
"hasattr",
"(",
"obj",
",",
"'saveFile'",
")",
":",
"return",
"obj",
".",
"saveFile",
"(",
"fn",
")",
"if",
"type",
"==",
"'auto'",
":",
"savers_and_writers",
"=",
"savers",
".",
"keys",
"(",
")",
"+",
"writers",
".",
"keys",
"(",
")",
"type",
"=",
"autoType",
"(",
"obj",
",",
"savers_and_writers",
")",
"if",
"type",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Can't determine a savable type for object of type \"",
"+",
"obj",
".",
"__class__",
".",
"__name__",
")",
"elif",
"type",
"==",
"'json'",
":",
"import",
"json",
"with",
"open",
"(",
"fn",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"toJson",
"(",
"obj",
")",
",",
"f",
")",
"return",
"True",
"if",
"type",
"in",
"savers",
":",
"return",
"savers",
"[",
"type",
"]",
"(",
"obj",
",",
"fn",
")",
"elif",
"type",
"in",
"writers",
":",
"with",
"open",
"(",
"fn",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"writers",
"[",
"type",
"]",
"(",
"obj",
")",
"+",
"'\\n'",
")",
"return",
"True",
"else",
":",
"raise",
"ValueError",
"(",
"\"Saving of type \"",
"+",
"type",
"+",
"\" is not supported\"",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/io/loader.py#L607-L643 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_search.py | python | SearchController.SetQueryString | (self, query) | Sets the search query value
@param query: string to search for | Sets the search query value
@param query: string to search for | [
"Sets",
"the",
"search",
"query",
"value",
"@param",
"query",
":",
"string",
"to",
"search",
"for"
] | def SetQueryString(self, query):
"""Sets the search query value
@param query: string to search for
"""
self._data.SetFindString(query) | [
"def",
"SetQueryString",
"(",
"self",
",",
"query",
")",
":",
"self",
".",
"_data",
".",
"SetFindString",
"(",
"query",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_search.py#L821-L826 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/zoombar.py | python | ZoomBar.HitTest | (self, pos) | return wx.NOT_FOUND | HitTest method for :class:`ZoomBar`.
:param `pos`: the current mouse position.
:return: an index representing the button on which the mouse is hovering,
or ``wx.NOT_FOUND`` if no button has been hit. | HitTest method for :class:`ZoomBar`. | [
"HitTest",
"method",
"for",
":",
"class",
":",
"ZoomBar",
"."
] | def HitTest(self, pos):
"""
HitTest method for :class:`ZoomBar`.
:param `pos`: the current mouse position.
:return: an index representing the button on which the mouse is hovering,
or ``wx.NOT_FOUND`` if no button has been hit.
"""
for index, button in enumerate(self._buttons):
buttonPos = button.GetPosition()
if pos.x >= buttonPos.x and pos.x <= buttonPos.x + button._width:
return index
return wx.NOT_FOUND | [
"def",
"HitTest",
"(",
"self",
",",
"pos",
")",
":",
"for",
"index",
",",
"button",
"in",
"enumerate",
"(",
"self",
".",
"_buttons",
")",
":",
"buttonPos",
"=",
"button",
".",
"GetPosition",
"(",
")",
"if",
"pos",
".",
"x",
">=",
"buttonPos",
".",
"x",
"and",
"pos",
".",
"x",
"<=",
"buttonPos",
".",
"x",
"+",
"button",
".",
"_width",
":",
"return",
"index",
"return",
"wx",
".",
"NOT_FOUND"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/zoombar.py#L1300-L1315 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | ScrollHelper.GetTargetRect | (*args, **kwargs) | return _windows_.ScrollHelper_GetTargetRect(*args, **kwargs) | GetTargetRect(self) -> Rect | GetTargetRect(self) -> Rect | [
"GetTargetRect",
"(",
"self",
")",
"-",
">",
"Rect"
] | def GetTargetRect(*args, **kwargs):
"""GetTargetRect(self) -> Rect"""
return _windows_.ScrollHelper_GetTargetRect(*args, **kwargs) | [
"def",
"GetTargetRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"ScrollHelper_GetTargetRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L253-L255 | |
etotheipi/BitcoinArmory | 2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98 | armoryengine/ArmoryUtils.py | python | binaryBits_to_difficulty | (b) | return dDiff | Converts the 4-byte binary difficulty string to a float | Converts the 4-byte binary difficulty string to a float | [
"Converts",
"the",
"4",
"-",
"byte",
"binary",
"difficulty",
"string",
"to",
"a",
"float"
] | def binaryBits_to_difficulty(b):
""" Converts the 4-byte binary difficulty string to a float """
i = binary_to_int(b)
nShift = (i >> 24) & 0xff
dDiff = float(0x0000ffff) / float(i & 0x00ffffff)
while nShift < 29:
dDiff *= 256.0
nShift += 1
while nShift > 29:
dDiff /= 256.0
nShift -= 1
return dDiff | [
"def",
"binaryBits_to_difficulty",
"(",
"b",
")",
":",
"i",
"=",
"binary_to_int",
"(",
"b",
")",
"nShift",
"=",
"(",
"i",
">>",
"24",
")",
"&",
"0xff",
"dDiff",
"=",
"float",
"(",
"0x0000ffff",
")",
"/",
"float",
"(",
"i",
"&",
"0x00ffffff",
")",
"while",
"nShift",
"<",
"29",
":",
"dDiff",
"*=",
"256.0",
"nShift",
"+=",
"1",
"while",
"nShift",
">",
"29",
":",
"dDiff",
"/=",
"256.0",
"nShift",
"-=",
"1",
"return",
"dDiff"
] | https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/ArmoryUtils.py#L2381-L2392 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | Grid.DrawColLabel | (*args, **kwargs) | return _grid.Grid_DrawColLabel(*args, **kwargs) | DrawColLabel(self, DC dc, int col) | DrawColLabel(self, DC dc, int col) | [
"DrawColLabel",
"(",
"self",
"DC",
"dc",
"int",
"col",
")"
] | def DrawColLabel(*args, **kwargs):
"""DrawColLabel(self, DC dc, int col)"""
return _grid.Grid_DrawColLabel(*args, **kwargs) | [
"def",
"DrawColLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_DrawColLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L1314-L1316 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/adidas_utils/helpers/nonsymmetric/exploitability.py | python | qre_exploitability | (dist, payoff_tensor, temperature=0., aggregate=np.mean) | return aggregate(exp_i) | Compute Shannon regularized exploitability of dist for non-symmetric game.
Args:
dist: list of 1-d np.arrays, current estimate of nash distribution
payoff_tensor: (n x A1 x ... x An) np.array, payoffs for each joint action
assumed to be non-negative. can also be list of (A1 x ... x An) np.arrays
temperature: non-negative float
aggregate: function to reduce individual exp_is to scalar, e.g., mean or max
Returns:
exploitability (float): avg_i payoff_i of best response_i - payoff_i of dist | Compute Shannon regularized exploitability of dist for non-symmetric game. | [
"Compute",
"Shannon",
"regularized",
"exploitability",
"of",
"dist",
"for",
"non",
"-",
"symmetric",
"game",
"."
] | def qre_exploitability(dist, payoff_tensor, temperature=0., aggregate=np.mean):
"""Compute Shannon regularized exploitability of dist for non-symmetric game.
Args:
dist: list of 1-d np.arrays, current estimate of nash distribution
payoff_tensor: (n x A1 x ... x An) np.array, payoffs for each joint action
assumed to be non-negative. can also be list of (A1 x ... x An) np.arrays
temperature: non-negative float
aggregate: function to reduce individual exp_is to scalar, e.g., mean or max
Returns:
exploitability (float): avg_i payoff_i of best response_i - payoff_i of dist
"""
num_players = len(payoff_tensor)
exp_i = []
for i in range(num_players):
nabla_i = misc.pt_reduce(payoff_tensor[i], dist, [i])
dist_i = dist[i]
if temperature > 0:
br_i = special.softmax(nabla_i / temperature)
else:
br_i = np.zeros_like(dist_i)
maxima = (nabla_i == np.max(nabla_i))
br_i[maxima] = 1. / maxima.sum()
u_i_br = nabla_i.dot(br_i) + temperature * special.entr(br_i).sum()
u_i_dist = nabla_i.dot(dist_i) + temperature * special.entr(dist_i).sum()
exp_i.append(u_i_br - u_i_dist)
return aggregate(exp_i) | [
"def",
"qre_exploitability",
"(",
"dist",
",",
"payoff_tensor",
",",
"temperature",
"=",
"0.",
",",
"aggregate",
"=",
"np",
".",
"mean",
")",
":",
"num_players",
"=",
"len",
"(",
"payoff_tensor",
")",
"exp_i",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"num_players",
")",
":",
"nabla_i",
"=",
"misc",
".",
"pt_reduce",
"(",
"payoff_tensor",
"[",
"i",
"]",
",",
"dist",
",",
"[",
"i",
"]",
")",
"dist_i",
"=",
"dist",
"[",
"i",
"]",
"if",
"temperature",
">",
"0",
":",
"br_i",
"=",
"special",
".",
"softmax",
"(",
"nabla_i",
"/",
"temperature",
")",
"else",
":",
"br_i",
"=",
"np",
".",
"zeros_like",
"(",
"dist_i",
")",
"maxima",
"=",
"(",
"nabla_i",
"==",
"np",
".",
"max",
"(",
"nabla_i",
")",
")",
"br_i",
"[",
"maxima",
"]",
"=",
"1.",
"/",
"maxima",
".",
"sum",
"(",
")",
"u_i_br",
"=",
"nabla_i",
".",
"dot",
"(",
"br_i",
")",
"+",
"temperature",
"*",
"special",
".",
"entr",
"(",
"br_i",
")",
".",
"sum",
"(",
")",
"u_i_dist",
"=",
"nabla_i",
".",
"dot",
"(",
"dist_i",
")",
"+",
"temperature",
"*",
"special",
".",
"entr",
"(",
"dist_i",
")",
".",
"sum",
"(",
")",
"exp_i",
".",
"append",
"(",
"u_i_br",
"-",
"u_i_dist",
")",
"return",
"aggregate",
"(",
"exp_i",
")"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/helpers/nonsymmetric/exploitability.py#L87-L117 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | PointerArgument.WriteGetAddress | (self, file) | Overridden from Argument. | Overridden from Argument. | [
"Overridden",
"from",
"Argument",
"."
] | def WriteGetAddress(self, file):
"""Overridden from Argument."""
file.Write(
" %s %s = GetSharedMemoryAs<%s>(\n" %
(self.type, self.name, self.type))
file.Write(
" %s_shm_id, %s_shm_offset, %s_size);\n" %
(self.name, self.name, self.name)) | [
"def",
"WriteGetAddress",
"(",
"self",
",",
"file",
")",
":",
"file",
".",
"Write",
"(",
"\" %s %s = GetSharedMemoryAs<%s>(\\n\"",
"%",
"(",
"self",
".",
"type",
",",
"self",
".",
"name",
",",
"self",
".",
"type",
")",
")",
"file",
".",
"Write",
"(",
"\" %s_shm_id, %s_shm_offset, %s_size);\\n\"",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"name",
",",
"self",
".",
"name",
")",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L6187-L6194 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/logging_ops.py | python | merge_all_summaries | (key=ops.GraphKeys.SUMMARIES) | Merges all summaries collected in the default graph.
Args:
key: `GraphKey` used to collect the summaries. Defaults to
`GraphKeys.SUMMARIES`.
Returns:
If no summaries were collected, returns None. Otherwise returns a scalar
`Tensor` of type `string` containing the serialized `Summary` protocol
buffer resulting from the merging. | Merges all summaries collected in the default graph. | [
"Merges",
"all",
"summaries",
"collected",
"in",
"the",
"default",
"graph",
"."
] | def merge_all_summaries(key=ops.GraphKeys.SUMMARIES):
"""Merges all summaries collected in the default graph.
Args:
key: `GraphKey` used to collect the summaries. Defaults to
`GraphKeys.SUMMARIES`.
Returns:
If no summaries were collected, returns None. Otherwise returns a scalar
`Tensor` of type `string` containing the serialized `Summary` protocol
buffer resulting from the merging.
"""
summary_ops = ops.get_collection(key)
if not summary_ops:
return None
else:
return merge_summary(summary_ops) | [
"def",
"merge_all_summaries",
"(",
"key",
"=",
"ops",
".",
"GraphKeys",
".",
"SUMMARIES",
")",
":",
"summary_ops",
"=",
"ops",
".",
"get_collection",
"(",
"key",
")",
"if",
"not",
"summary_ops",
":",
"return",
"None",
"else",
":",
"return",
"merge_summary",
"(",
"summary_ops",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/logging_ops.py#L255-L271 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/configobj/configobj.py | python | Section.as_list | (self, key) | return [result] | A convenience method which fetches the specified value, guaranteeing
that it is a list.
>>> a = ConfigObj()
>>> a['a'] = 1
>>> a.as_list('a')
[1]
>>> a['a'] = (1,)
>>> a.as_list('a')
[1]
>>> a['a'] = [1]
>>> a.as_list('a')
[1] | A convenience method which fetches the specified value, guaranteeing
that it is a list.
>>> a = ConfigObj()
>>> a['a'] = 1
>>> a.as_list('a')
[1]
>>> a['a'] = (1,)
>>> a.as_list('a')
[1]
>>> a['a'] = [1]
>>> a.as_list('a')
[1] | [
"A",
"convenience",
"method",
"which",
"fetches",
"the",
"specified",
"value",
"guaranteeing",
"that",
"it",
"is",
"a",
"list",
".",
">>>",
"a",
"=",
"ConfigObj",
"()",
">>>",
"a",
"[",
"a",
"]",
"=",
"1",
">>>",
"a",
".",
"as_list",
"(",
"a",
")",
"[",
"1",
"]",
">>>",
"a",
"[",
"a",
"]",
"=",
"(",
"1",
")",
">>>",
"a",
".",
"as_list",
"(",
"a",
")",
"[",
"1",
"]",
">>>",
"a",
"[",
"a",
"]",
"=",
"[",
"1",
"]",
">>>",
"a",
".",
"as_list",
"(",
"a",
")",
"[",
"1",
"]"
] | def as_list(self, key):
"""
A convenience method which fetches the specified value, guaranteeing
that it is a list.
>>> a = ConfigObj()
>>> a['a'] = 1
>>> a.as_list('a')
[1]
>>> a['a'] = (1,)
>>> a.as_list('a')
[1]
>>> a['a'] = [1]
>>> a.as_list('a')
[1]
"""
result = self[key]
if isinstance(result, (tuple, list)):
return list(result)
return [result] | [
"def",
"as_list",
"(",
"self",
",",
"key",
")",
":",
"result",
"=",
"self",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"result",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"list",
"(",
"result",
")",
"return",
"[",
"result",
"]"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/configobj/configobj.py#L1029-L1048 | |
pristineio/webrtc-mirror | 7a5bcdffaab90a05bc1146b2b1ea71c004e54d71 | webrtc/rtc_tools/barcode_tools/barcode_decoder.py | python | ConvertYuvToPngFiles | (yuv_file_name, yuv_frame_width, yuv_frame_height,
output_directory, ffmpeg_path) | return True | Converts a YUV video file into PNG frames.
The function uses ffmpeg to convert the YUV file. The output of ffmpeg is in
the form frame_xxxx.png, where xxxx is the frame number, starting from 0001.
Args:
yuv_file_name(string): The name of the YUV file.
yuv_frame_width(int): The width of one YUV frame.
yuv_frame_height(int): The height of one YUV frame.
output_directory(string): The output directory where the PNG frames will be
stored.
ffmpeg_path(string): The path to the ffmpeg executable. If None, the PATH
will be searched for it.
Return:
(bool): True if the conversion was OK. | Converts a YUV video file into PNG frames. | [
"Converts",
"a",
"YUV",
"video",
"file",
"into",
"PNG",
"frames",
"."
] | def ConvertYuvToPngFiles(yuv_file_name, yuv_frame_width, yuv_frame_height,
output_directory, ffmpeg_path):
"""Converts a YUV video file into PNG frames.
The function uses ffmpeg to convert the YUV file. The output of ffmpeg is in
the form frame_xxxx.png, where xxxx is the frame number, starting from 0001.
Args:
yuv_file_name(string): The name of the YUV file.
yuv_frame_width(int): The width of one YUV frame.
yuv_frame_height(int): The height of one YUV frame.
output_directory(string): The output directory where the PNG frames will be
stored.
ffmpeg_path(string): The path to the ffmpeg executable. If None, the PATH
will be searched for it.
Return:
(bool): True if the conversion was OK.
"""
size_string = str(yuv_frame_width) + 'x' + str(yuv_frame_height)
output_files_pattern = os.path.join(output_directory, 'frame_%04d.png')
if not ffmpeg_path:
ffmpeg_path = 'ffmpeg.exe' if sys.platform == 'win32' else 'ffmpeg'
command = [ffmpeg_path, '-s', '%s' % size_string, '-i', '%s'
% yuv_file_name, '-f', 'image2', '-vcodec', 'png',
'%s' % output_files_pattern]
try:
print 'Converting YUV file to PNG images (may take a while)...'
print ' '.join(command)
helper_functions.RunShellCommand(
command, fail_msg='Error during YUV to PNG conversion')
except helper_functions.HelperError, err:
print 'Error executing command: %s. Error: %s' % (command, err)
return False
except OSError:
print 'Did not find %s. Have you installed it?' % ffmpeg_path
return False
return True | [
"def",
"ConvertYuvToPngFiles",
"(",
"yuv_file_name",
",",
"yuv_frame_width",
",",
"yuv_frame_height",
",",
"output_directory",
",",
"ffmpeg_path",
")",
":",
"size_string",
"=",
"str",
"(",
"yuv_frame_width",
")",
"+",
"'x'",
"+",
"str",
"(",
"yuv_frame_height",
")",
"output_files_pattern",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_directory",
",",
"'frame_%04d.png'",
")",
"if",
"not",
"ffmpeg_path",
":",
"ffmpeg_path",
"=",
"'ffmpeg.exe'",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
"else",
"'ffmpeg'",
"command",
"=",
"[",
"ffmpeg_path",
",",
"'-s'",
",",
"'%s'",
"%",
"size_string",
",",
"'-i'",
",",
"'%s'",
"%",
"yuv_file_name",
",",
"'-f'",
",",
"'image2'",
",",
"'-vcodec'",
",",
"'png'",
",",
"'%s'",
"%",
"output_files_pattern",
"]",
"try",
":",
"print",
"'Converting YUV file to PNG images (may take a while)...'",
"print",
"' '",
".",
"join",
"(",
"command",
")",
"helper_functions",
".",
"RunShellCommand",
"(",
"command",
",",
"fail_msg",
"=",
"'Error during YUV to PNG conversion'",
")",
"except",
"helper_functions",
".",
"HelperError",
",",
"err",
":",
"print",
"'Error executing command: %s. Error: %s'",
"%",
"(",
"command",
",",
"err",
")",
"return",
"False",
"except",
"OSError",
":",
"print",
"'Did not find %s. Have you installed it?'",
"%",
"ffmpeg_path",
"return",
"False",
"return",
"True"
] | https://github.com/pristineio/webrtc-mirror/blob/7a5bcdffaab90a05bc1146b2b1ea71c004e54d71/webrtc/rtc_tools/barcode_tools/barcode_decoder.py#L24-L61 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/computation/pytables.py | python | BinOp.kind | (self) | return getattr(self.queryables.get(self.lhs), "kind", None) | the kind of my field | the kind of my field | [
"the",
"kind",
"of",
"my",
"field"
] | def kind(self):
""" the kind of my field """
return getattr(self.queryables.get(self.lhs), "kind", None) | [
"def",
"kind",
"(",
"self",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"queryables",
".",
"get",
"(",
"self",
".",
"lhs",
")",
",",
"\"kind\"",
",",
"None",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/computation/pytables.py#L158-L160 | |
alibaba/graph-learn | 54cafee9db3054dc310a28b856be7f97c7d5aee9 | graphlearn/python/operator/knn_operator.py | python | KnnOperator.search | (self, node_type, inputs, k) | return np.reshape(ids, [batch_size, k]), \
np.reshape(distances, [batch_size, k]) | Get k nearest neighbors for inputs.
`inputs`(np.ndarray), with one or two dimensions. If one, it means the
batch size is 1, and the lengh of the array is vector size.
If two, it means the batch size is shape[0], and vector size is shape[1].
Return:
Two `np.ndarray` objects, `ids` and `distances`, shape=[`batch_size`] | Get k nearest neighbors for inputs. | [
"Get",
"k",
"nearest",
"neighbors",
"for",
"inputs",
"."
] | def search(self, node_type, inputs, k):
""" Get k nearest neighbors for inputs.
`inputs`(np.ndarray), with one or two dimensions. If one, it means the
batch size is 1, and the lengh of the array is vector size.
If two, it means the batch size is shape[0], and vector size is shape[1].
Return:
Two `np.ndarray` objects, `ids` and `distances`, shape=[`batch_size`]
"""
if not isinstance(inputs, np.ndarray):
raise ValueError("The knn inputs must be a np.ndarray")
batch_size = 1
dimension = -1
if len(inputs.shape) == 1:
dimension = inputs.shape[0]
elif len(inputs.shape) == 2:
batch_size = inputs.shape[0]
dimension = inputs.shape[1]
else:
raise ValueError("The knn inputs must be with 1 or 2 dimensions")
req = pywrap.new_knn_request(node_type, k)
res = pywrap.new_knn_response()
pywrap.set_knn_request(req, batch_size, dimension, inputs)
status = self._client.run_op(req, res)
if status.ok():
ids = pywrap.get_knn_ids(res)
distances = pywrap.get_knn_distances(res)
pywrap.del_op_response(res)
pywrap.del_op_request(req)
errors.raise_exception_on_not_ok_status(status)
return np.reshape(ids, [batch_size, k]), \
np.reshape(distances, [batch_size, k]) | [
"def",
"search",
"(",
"self",
",",
"node_type",
",",
"inputs",
",",
"k",
")",
":",
"if",
"not",
"isinstance",
"(",
"inputs",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"\"The knn inputs must be a np.ndarray\"",
")",
"batch_size",
"=",
"1",
"dimension",
"=",
"-",
"1",
"if",
"len",
"(",
"inputs",
".",
"shape",
")",
"==",
"1",
":",
"dimension",
"=",
"inputs",
".",
"shape",
"[",
"0",
"]",
"elif",
"len",
"(",
"inputs",
".",
"shape",
")",
"==",
"2",
":",
"batch_size",
"=",
"inputs",
".",
"shape",
"[",
"0",
"]",
"dimension",
"=",
"inputs",
".",
"shape",
"[",
"1",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"\"The knn inputs must be with 1 or 2 dimensions\"",
")",
"req",
"=",
"pywrap",
".",
"new_knn_request",
"(",
"node_type",
",",
"k",
")",
"res",
"=",
"pywrap",
".",
"new_knn_response",
"(",
")",
"pywrap",
".",
"set_knn_request",
"(",
"req",
",",
"batch_size",
",",
"dimension",
",",
"inputs",
")",
"status",
"=",
"self",
".",
"_client",
".",
"run_op",
"(",
"req",
",",
"res",
")",
"if",
"status",
".",
"ok",
"(",
")",
":",
"ids",
"=",
"pywrap",
".",
"get_knn_ids",
"(",
"res",
")",
"distances",
"=",
"pywrap",
".",
"get_knn_distances",
"(",
"res",
")",
"pywrap",
".",
"del_op_response",
"(",
"res",
")",
"pywrap",
".",
"del_op_request",
"(",
"req",
")",
"errors",
".",
"raise_exception_on_not_ok_status",
"(",
"status",
")",
"return",
"np",
".",
"reshape",
"(",
"ids",
",",
"[",
"batch_size",
",",
"k",
"]",
")",
",",
"np",
".",
"reshape",
"(",
"distances",
",",
"[",
"batch_size",
",",
"k",
"]",
")"
] | https://github.com/alibaba/graph-learn/blob/54cafee9db3054dc310a28b856be7f97c7d5aee9/graphlearn/python/operator/knn_operator.py#L34-L69 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/models/bug_label_patterns.py | python | GetBugLabelPatterns | () | return _Get().labels_to_patterns | Returns the dict of bug labels to test path patterns. | Returns the dict of bug labels to test path patterns. | [
"Returns",
"the",
"dict",
"of",
"bug",
"labels",
"to",
"test",
"path",
"patterns",
"."
] | def GetBugLabelPatterns():
"""Returns the dict of bug labels to test path patterns."""
return _Get().labels_to_patterns | [
"def",
"GetBugLabelPatterns",
"(",
")",
":",
"return",
"_Get",
"(",
")",
".",
"labels_to_patterns"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/models/bug_label_patterns.py#L40-L42 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/random-pick-index.py | python | Solution.pick | (self, target) | return reservoir | :type target: int
:rtype: int | :type target: int
:rtype: int | [
":",
"type",
"target",
":",
"int",
":",
"rtype",
":",
"int"
] | def pick(self, target):
"""
:type target: int
:rtype: int
"""
reservoir = -1
n = 0
for i in xrange(len(self.__nums)):
if self.__nums[i] != target:
continue
reservoir = i if randint(1, n+1) == 1 else reservoir
n += 1
return reservoir | [
"def",
"pick",
"(",
"self",
",",
"target",
")",
":",
"reservoir",
"=",
"-",
"1",
"n",
"=",
"0",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"__nums",
")",
")",
":",
"if",
"self",
".",
"__nums",
"[",
"i",
"]",
"!=",
"target",
":",
"continue",
"reservoir",
"=",
"i",
"if",
"randint",
"(",
"1",
",",
"n",
"+",
"1",
")",
"==",
"1",
"else",
"reservoir",
"n",
"+=",
"1",
"return",
"reservoir"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/random-pick-index.py#L16-L28 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Window.SetSizeWH | (*args, **kwargs) | return _core_.Window_SetSizeWH(*args, **kwargs) | SetSizeWH(self, int width, int height)
Sets the size of the window in pixels. | SetSizeWH(self, int width, int height) | [
"SetSizeWH",
"(",
"self",
"int",
"width",
"int",
"height",
")"
] | def SetSizeWH(*args, **kwargs):
"""
SetSizeWH(self, int width, int height)
Sets the size of the window in pixels.
"""
return _core_.Window_SetSizeWH(*args, **kwargs) | [
"def",
"SetSizeWH",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_SetSizeWH",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L9365-L9371 | |
vgc/vgc | 8bc17514dc75c99c1166f738d4440b3e0981ebe3 | third/fmt/support/docopt.py | python | docopt | (doc, argv=None, help=True, version=None, options_first=False) | Parse `argv` based on command-line interface described in `doc`.
`docopt` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, commands, which could be
[optional], (required), (mutually | exclusive) or repeated...
Parameters
----------
doc : str
Description of your command-line interface.
argv : list of str, optional
Argument vector to be parsed. sys.argv[1:] is used if not
provided.
help : bool (default: True)
Set to False to disable automatic help on -h or --help
options.
version : any object
If passed, the object will be printed if --version is in
`argv`.
options_first : bool (default: False)
Set to True to require options precede positional arguments,
i.e. to forbid options and positional arguments intermix.
Returns
-------
args : dict
A dictionary, where keys are names of command-line elements
such as e.g. "--verbose" and "<path>", and values are the
parsed values of those elements.
Example
-------
>>> from docopt import docopt
>>> doc = '''
... Usage:
... my_program tcp <host> <port> [--timeout=<seconds>]
... my_program serial <port> [--baud=<n>] [--timeout=<seconds>]
... my_program (-h | --help | --version)
...
... Options:
... -h, --help Show this screen and exit.
... --baud=<n> Baudrate [default: 9600]
... '''
>>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30']
>>> docopt(doc, argv)
{'--baud': '9600',
'--help': False,
'--timeout': '30',
'--version': False,
'<host>': '127.0.0.1',
'<port>': '80',
'serial': False,
'tcp': True}
See also
--------
* For video introduction see http://docopt.org
* Full documentation is available in README.rst as well as online
at https://github.com/docopt/docopt#readme | Parse `argv` based on command-line interface described in `doc`. | [
"Parse",
"argv",
"based",
"on",
"command",
"-",
"line",
"interface",
"described",
"in",
"doc",
"."
] | def docopt(doc, argv=None, help=True, version=None, options_first=False):
"""Parse `argv` based on command-line interface described in `doc`.
`docopt` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, commands, which could be
[optional], (required), (mutually | exclusive) or repeated...
Parameters
----------
doc : str
Description of your command-line interface.
argv : list of str, optional
Argument vector to be parsed. sys.argv[1:] is used if not
provided.
help : bool (default: True)
Set to False to disable automatic help on -h or --help
options.
version : any object
If passed, the object will be printed if --version is in
`argv`.
options_first : bool (default: False)
Set to True to require options precede positional arguments,
i.e. to forbid options and positional arguments intermix.
Returns
-------
args : dict
A dictionary, where keys are names of command-line elements
such as e.g. "--verbose" and "<path>", and values are the
parsed values of those elements.
Example
-------
>>> from docopt import docopt
>>> doc = '''
... Usage:
... my_program tcp <host> <port> [--timeout=<seconds>]
... my_program serial <port> [--baud=<n>] [--timeout=<seconds>]
... my_program (-h | --help | --version)
...
... Options:
... -h, --help Show this screen and exit.
... --baud=<n> Baudrate [default: 9600]
... '''
>>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30']
>>> docopt(doc, argv)
{'--baud': '9600',
'--help': False,
'--timeout': '30',
'--version': False,
'<host>': '127.0.0.1',
'<port>': '80',
'serial': False,
'tcp': True}
See also
--------
* For video introduction see http://docopt.org
* Full documentation is available in README.rst as well as online
at https://github.com/docopt/docopt#readme
"""
argv = sys.argv[1:] if argv is None else argv
usage_sections = parse_section('usage:', doc)
if len(usage_sections) == 0:
raise DocoptLanguageError('"usage:" (case-insensitive) not found.')
if len(usage_sections) > 1:
raise DocoptLanguageError('More than one "usage:" (case-insensitive).')
DocoptExit.usage = usage_sections[0]
options = parse_defaults(doc)
pattern = parse_pattern(formal_usage(DocoptExit.usage), options)
# [default] syntax for argument is disabled
#for a in pattern.flat(Argument):
# same_name = [d for d in arguments if d.name == a.name]
# if same_name:
# a.value = same_name[0].value
argv = parse_argv(Tokens(argv), list(options), options_first)
pattern_options = set(pattern.flat(Option))
for options_shortcut in pattern.flat(OptionsShortcut):
doc_options = parse_defaults(doc)
options_shortcut.children = list(set(doc_options) - pattern_options)
#if any_options:
# options_shortcut.children += [Option(o.short, o.long, o.argcount)
# for o in argv if type(o) is Option]
extras(help, version, argv, doc)
matched, left, collected = pattern.fix().match(argv)
if matched and left == []: # better error message if left?
return Dict((a.name, a.value) for a in (pattern.flat() + collected))
raise DocoptExit() | [
"def",
"docopt",
"(",
"doc",
",",
"argv",
"=",
"None",
",",
"help",
"=",
"True",
",",
"version",
"=",
"None",
",",
"options_first",
"=",
"False",
")",
":",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"if",
"argv",
"is",
"None",
"else",
"argv",
"usage_sections",
"=",
"parse_section",
"(",
"'usage:'",
",",
"doc",
")",
"if",
"len",
"(",
"usage_sections",
")",
"==",
"0",
":",
"raise",
"DocoptLanguageError",
"(",
"'\"usage:\" (case-insensitive) not found.'",
")",
"if",
"len",
"(",
"usage_sections",
")",
">",
"1",
":",
"raise",
"DocoptLanguageError",
"(",
"'More than one \"usage:\" (case-insensitive).'",
")",
"DocoptExit",
".",
"usage",
"=",
"usage_sections",
"[",
"0",
"]",
"options",
"=",
"parse_defaults",
"(",
"doc",
")",
"pattern",
"=",
"parse_pattern",
"(",
"formal_usage",
"(",
"DocoptExit",
".",
"usage",
")",
",",
"options",
")",
"# [default] syntax for argument is disabled",
"#for a in pattern.flat(Argument):",
"# same_name = [d for d in arguments if d.name == a.name]",
"# if same_name:",
"# a.value = same_name[0].value",
"argv",
"=",
"parse_argv",
"(",
"Tokens",
"(",
"argv",
")",
",",
"list",
"(",
"options",
")",
",",
"options_first",
")",
"pattern_options",
"=",
"set",
"(",
"pattern",
".",
"flat",
"(",
"Option",
")",
")",
"for",
"options_shortcut",
"in",
"pattern",
".",
"flat",
"(",
"OptionsShortcut",
")",
":",
"doc_options",
"=",
"parse_defaults",
"(",
"doc",
")",
"options_shortcut",
".",
"children",
"=",
"list",
"(",
"set",
"(",
"doc_options",
")",
"-",
"pattern_options",
")",
"#if any_options:",
"# options_shortcut.children += [Option(o.short, o.long, o.argcount)",
"# for o in argv if type(o) is Option]",
"extras",
"(",
"help",
",",
"version",
",",
"argv",
",",
"doc",
")",
"matched",
",",
"left",
",",
"collected",
"=",
"pattern",
".",
"fix",
"(",
")",
".",
"match",
"(",
"argv",
")",
"if",
"matched",
"and",
"left",
"==",
"[",
"]",
":",
"# better error message if left?",
"return",
"Dict",
"(",
"(",
"a",
".",
"name",
",",
"a",
".",
"value",
")",
"for",
"a",
"in",
"(",
"pattern",
".",
"flat",
"(",
")",
"+",
"collected",
")",
")",
"raise",
"DocoptExit",
"(",
")"
] | https://github.com/vgc/vgc/blob/8bc17514dc75c99c1166f738d4440b3e0981ebe3/third/fmt/support/docopt.py#L490-L581 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py | python | IMetadataProvider.metadata_listdir | (name) | List of metadata names in the directory (like ``os.listdir()``) | List of metadata names in the directory (like ``os.listdir()``) | [
"List",
"of",
"metadata",
"names",
"in",
"the",
"directory",
"(",
"like",
"os",
".",
"listdir",
"()",
")"
] | def metadata_listdir(name):
"""List of metadata names in the directory (like ``os.listdir()``)""" | [
"def",
"metadata_listdir",
"(",
"name",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L601-L602 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/environment.py | python | Environment.get_template | (self, name, parent=None, globals=None) | return self._load_template(name, self.make_globals(globals)) | Load a template from the loader. If a loader is configured this
method asks the loader for the template and returns a :class:`Template`.
If the `parent` parameter is not `None`, :meth:`join_path` is called
to get the real template name before loading.
The `globals` parameter can be used to provide template wide globals.
These variables are available in the context at render time.
If the template does not exist a :exc:`TemplateNotFound` exception is
raised.
.. versionchanged:: 2.4
If `name` is a :class:`Template` object it is returned from the
function unchanged. | Load a template from the loader. If a loader is configured this
method asks the loader for the template and returns a :class:`Template`.
If the `parent` parameter is not `None`, :meth:`join_path` is called
to get the real template name before loading. | [
"Load",
"a",
"template",
"from",
"the",
"loader",
".",
"If",
"a",
"loader",
"is",
"configured",
"this",
"method",
"asks",
"the",
"loader",
"for",
"the",
"template",
"and",
"returns",
"a",
":",
"class",
":",
"Template",
".",
"If",
"the",
"parent",
"parameter",
"is",
"not",
"None",
":",
"meth",
":",
"join_path",
"is",
"called",
"to",
"get",
"the",
"real",
"template",
"name",
"before",
"loading",
"."
] | def get_template(self, name, parent=None, globals=None):
"""Load a template from the loader. If a loader is configured this
method asks the loader for the template and returns a :class:`Template`.
If the `parent` parameter is not `None`, :meth:`join_path` is called
to get the real template name before loading.
The `globals` parameter can be used to provide template wide globals.
These variables are available in the context at render time.
If the template does not exist a :exc:`TemplateNotFound` exception is
raised.
.. versionchanged:: 2.4
If `name` is a :class:`Template` object it is returned from the
function unchanged.
"""
if isinstance(name, Template):
return name
if parent is not None:
name = self.join_path(name, parent)
return self._load_template(name, self.make_globals(globals)) | [
"def",
"get_template",
"(",
"self",
",",
"name",
",",
"parent",
"=",
"None",
",",
"globals",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"Template",
")",
":",
"return",
"name",
"if",
"parent",
"is",
"not",
"None",
":",
"name",
"=",
"self",
".",
"join_path",
"(",
"name",
",",
"parent",
")",
"return",
"self",
".",
"_load_template",
"(",
"name",
",",
"self",
".",
"make_globals",
"(",
"globals",
")",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/environment.py#L810-L830 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/all_reduce.py | python | _flatten_tensors | (tensors) | return tensors, shape | Check tensors for isomorphism and flatten.
Args:
tensors: list of T `tf.Tensor` which must all have the same shape.
Returns:
tensors: a list of T `tf.Tensor` which are flattened (1D) views of tensors
shape: the original shape of each element of input tensors
Raises:
ValueError: tensors are empty or non-isomorphic or have unknown shape. | Check tensors for isomorphism and flatten. | [
"Check",
"tensors",
"for",
"isomorphism",
"and",
"flatten",
"."
] | def _flatten_tensors(tensors):
"""Check tensors for isomorphism and flatten.
Args:
tensors: list of T `tf.Tensor` which must all have the same shape.
Returns:
tensors: a list of T `tf.Tensor` which are flattened (1D) views of tensors
shape: the original shape of each element of input tensors
Raises:
ValueError: tensors are empty or non-isomorphic or have unknown shape.
"""
if not tensors:
raise ValueError("tensors cannot be empty")
shape = tensors[0].shape
for tensor in tensors:
shape = shape.merge_with(tensor.shape)
if not shape.is_fully_defined():
raise ValueError("Tensors must have statically known shape.")
if len(shape) != 1:
reshaped = []
for t in tensors:
with ops.colocate_with(t):
reshaped.append(array_ops.reshape(t, [-1]))
tensors = reshaped
return tensors, shape | [
"def",
"_flatten_tensors",
"(",
"tensors",
")",
":",
"if",
"not",
"tensors",
":",
"raise",
"ValueError",
"(",
"\"tensors cannot be empty\"",
")",
"shape",
"=",
"tensors",
"[",
"0",
"]",
".",
"shape",
"for",
"tensor",
"in",
"tensors",
":",
"shape",
"=",
"shape",
".",
"merge_with",
"(",
"tensor",
".",
"shape",
")",
"if",
"not",
"shape",
".",
"is_fully_defined",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Tensors must have statically known shape.\"",
")",
"if",
"len",
"(",
"shape",
")",
"!=",
"1",
":",
"reshaped",
"=",
"[",
"]",
"for",
"t",
"in",
"tensors",
":",
"with",
"ops",
".",
"colocate_with",
"(",
"t",
")",
":",
"reshaped",
".",
"append",
"(",
"array_ops",
".",
"reshape",
"(",
"t",
",",
"[",
"-",
"1",
"]",
")",
")",
"tensors",
"=",
"reshaped",
"return",
"tensors",
",",
"shape"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/all_reduce.py#L31-L57 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/layers/python/layers/feature_column.py | python | _CrossedColumn.id_tensor | (self, input_tensor) | return input_tensor | Returns the id tensor from the given transformed input_tensor. | Returns the id tensor from the given transformed input_tensor. | [
"Returns",
"the",
"id",
"tensor",
"from",
"the",
"given",
"transformed",
"input_tensor",
"."
] | def id_tensor(self, input_tensor):
"""Returns the id tensor from the given transformed input_tensor."""
return input_tensor | [
"def",
"id_tensor",
"(",
"self",
",",
"input_tensor",
")",
":",
"return",
"input_tensor"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/layers/python/layers/feature_column.py#L2245-L2247 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.