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
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/__init__.py
python
_call_linker_cb
(env, callback, args, result = None)
return result
Returns the result of env['LINKCALLBACKS'][callback](*args) if env['LINKCALLBACKS'] is a dictionary and env['LINKCALLBACKS'][callback] is callable. If these conditions are not met, return the value provided as the *result* argument. This function is mainly used for generating library info such as versioned suffixes, symlink maps, sonames etc. by delegating the core job to callbacks configured by current linker tool
Returns the result of env['LINKCALLBACKS'][callback](*args) if env['LINKCALLBACKS'] is a dictionary and env['LINKCALLBACKS'][callback] is callable. If these conditions are not met, return the value provided as the *result* argument. This function is mainly used for generating library info such as versioned suffixes, symlink maps, sonames etc. by delegating the core job to callbacks configured by current linker tool
[ "Returns", "the", "result", "of", "env", "[", "LINKCALLBACKS", "]", "[", "callback", "]", "(", "*", "args", ")", "if", "env", "[", "LINKCALLBACKS", "]", "is", "a", "dictionary", "and", "env", "[", "LINKCALLBACKS", "]", "[", "callback", "]", "is", "callable", ".", "If", "these", "conditions", "are", "not", "met", "return", "the", "value", "provided", "as", "the", "*", "result", "*", "argument", ".", "This", "function", "is", "mainly", "used", "for", "generating", "library", "info", "such", "as", "versioned", "suffixes", "symlink", "maps", "sonames", "etc", ".", "by", "delegating", "the", "core", "job", "to", "callbacks", "configured", "by", "current", "linker", "tool" ]
def _call_linker_cb(env, callback, args, result = None): """Returns the result of env['LINKCALLBACKS'][callback](*args) if env['LINKCALLBACKS'] is a dictionary and env['LINKCALLBACKS'][callback] is callable. If these conditions are not met, return the value provided as the *result* argument. This function is mainly used for generating library info such as versioned suffixes, symlink maps, sonames etc. by delegating the core job to callbacks configured by current linker tool""" Verbose = False if Verbose: print '_call_linker_cb: args=%r' % args print '_call_linker_cb: callback=%r' % callback try: cbfun = env['LINKCALLBACKS'][callback] except (KeyError, TypeError): if Verbose: print '_call_linker_cb: env["LINKCALLBACKS"][%r] not found or can not be used' % callback pass else: if Verbose: print '_call_linker_cb: env["LINKCALLBACKS"][%r] found' % callback print '_call_linker_cb: env["LINKCALLBACKS"][%r]=%r' % (callback, cbfun) if(callable(cbfun)): if Verbose: print '_call_linker_cb: env["LINKCALLBACKS"][%r] is callable' % callback result = cbfun(env, *args) return result
[ "def", "_call_linker_cb", "(", "env", ",", "callback", ",", "args", ",", "result", "=", "None", ")", ":", "Verbose", "=", "False", "if", "Verbose", ":", "print", "'_call_linker_cb: args=%r'", "%", "args", "print", "'_call_linker_cb: callback=%r'", "%", "callback", "try", ":", "cbfun", "=", "env", "[", "'LINKCALLBACKS'", "]", "[", "callback", "]", "except", "(", "KeyError", ",", "TypeError", ")", ":", "if", "Verbose", ":", "print", "'_call_linker_cb: env[\"LINKCALLBACKS\"][%r] not found or can not be used'", "%", "callback", "pass", "else", ":", "if", "Verbose", ":", "print", "'_call_linker_cb: env[\"LINKCALLBACKS\"][%r] found'", "%", "callback", "print", "'_call_linker_cb: env[\"LINKCALLBACKS\"][%r]=%r'", "%", "(", "callback", ",", "cbfun", ")", "if", "(", "callable", "(", "cbfun", ")", ")", ":", "if", "Verbose", ":", "print", "'_call_linker_cb: env[\"LINKCALLBACKS\"][%r] is callable'", "%", "callback", "result", "=", "cbfun", "(", "env", ",", "*", "args", ")", "return", "result" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/__init__.py#L246-L274
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/statistics.py
python
pvariance
(data, mu=None)
return _convert(ss/n, T)
Return the population variance of ``data``. data should be an iterable of Real-valued numbers, with at least one value. The optional argument mu, if given, should be the mean of the data. If it is missing or None, the mean is automatically calculated. Use this function to calculate the variance from the entire population. To estimate the variance from a sample, the ``variance`` function is usually a better choice. Examples: >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25] >>> pvariance(data) 1.25 If you have already calculated the mean of the data, you can pass it as the optional second argument to avoid recalculating it: >>> mu = mean(data) >>> pvariance(data, mu) 1.25 This function does not check that ``mu`` is actually the mean of ``data``. Giving arbitrary values for ``mu`` may lead to invalid or impossible results. Decimals and Fractions are supported: >>> from decimal import Decimal as D >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")]) Decimal('24.815') >>> from fractions import Fraction as F >>> pvariance([F(1, 4), F(5, 4), F(1, 2)]) Fraction(13, 72)
Return the population variance of ``data``.
[ "Return", "the", "population", "variance", "of", "data", "." ]
def pvariance(data, mu=None): """Return the population variance of ``data``. data should be an iterable of Real-valued numbers, with at least one value. The optional argument mu, if given, should be the mean of the data. If it is missing or None, the mean is automatically calculated. Use this function to calculate the variance from the entire population. To estimate the variance from a sample, the ``variance`` function is usually a better choice. Examples: >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25] >>> pvariance(data) 1.25 If you have already calculated the mean of the data, you can pass it as the optional second argument to avoid recalculating it: >>> mu = mean(data) >>> pvariance(data, mu) 1.25 This function does not check that ``mu`` is actually the mean of ``data``. Giving arbitrary values for ``mu`` may lead to invalid or impossible results. Decimals and Fractions are supported: >>> from decimal import Decimal as D >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")]) Decimal('24.815') >>> from fractions import Fraction as F >>> pvariance([F(1, 4), F(5, 4), F(1, 2)]) Fraction(13, 72) """ if iter(data) is data: data = list(data) n = len(data) if n < 1: raise StatisticsError('pvariance requires at least one data point') T, ss = _ss(data, mu) return _convert(ss/n, T)
[ "def", "pvariance", "(", "data", ",", "mu", "=", "None", ")", ":", "if", "iter", "(", "data", ")", "is", "data", ":", "data", "=", "list", "(", "data", ")", "n", "=", "len", "(", "data", ")", "if", "n", "<", "1", ":", "raise", "StatisticsError", "(", "'pvariance requires at least one data point'", ")", "T", ",", "ss", "=", "_ss", "(", "data", ",", "mu", ")", "return", "_convert", "(", "ss", "/", "n", ",", "T", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/statistics.py#L592-L637
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Window.AddChild
(*args, **kwargs)
return _core_.Window_AddChild(*args, **kwargs)
AddChild(self, Window child) Adds a child window. This is called automatically by window creation functions so should not be required by the application programmer.
AddChild(self, Window child)
[ "AddChild", "(", "self", "Window", "child", ")" ]
def AddChild(*args, **kwargs): """ AddChild(self, Window child) Adds a child window. This is called automatically by window creation functions so should not be required by the application programmer. """ return _core_.Window_AddChild(*args, **kwargs)
[ "def", "AddChild", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_AddChild", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L10312-L10319
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/common/portable_globe.py
python
Globe.HasImagery
(self)
return self.has_imagery_
Returns whether glx has imagery.
Returns whether glx has imagery.
[ "Returns", "whether", "glx", "has", "imagery", "." ]
def HasImagery(self): """Returns whether glx has imagery.""" return self.has_imagery_
[ "def", "HasImagery", "(", "self", ")", ":", "return", "self", ".", "has_imagery_" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/common/portable_globe.py#L91-L93
DanielSWolf/rhubarb-lip-sync
5cface0af3b6e4e58c0b829c51561d784fb9f52f
rhubarb/lib/webrtc-8d2248ff/webrtc/tools/barcode_tools/barcode_decoder.py
python
decode_frames
(input_directory, zxing_path)
return helper_functions.perform_action_on_all_files( directory=input_directory, file_pattern='frame_', file_extension='png', start_number=1, action=_decode_barcode_in_file, command_line_decoder=zxing_path)
Decodes the barcodes overlaid in each frame. The function uses the Zxing command-line tool from the Zxing C++ distribution to decode the barcode in every PNG frame from the input directory. The frames should be named frame_xxxx.png, where xxxx is the frame number. The frame numbers should be consecutive and should start from 0001. The decoding results in a frame_xxxx.txt file for every successfully decoded barcode. This file contains the decoded barcode as 12-digit string (UPC-A format: 11 digits content + one check digit). Args: input_directory(string): The input directory from where the PNG frames are read. zxing_path(string): The path to the zxing binary. If specified as None, the PATH will be searched for it. Return: (bool): True if the decoding succeeded.
Decodes the barcodes overlaid in each frame.
[ "Decodes", "the", "barcodes", "overlaid", "in", "each", "frame", "." ]
def decode_frames(input_directory, zxing_path): """Decodes the barcodes overlaid in each frame. The function uses the Zxing command-line tool from the Zxing C++ distribution to decode the barcode in every PNG frame from the input directory. The frames should be named frame_xxxx.png, where xxxx is the frame number. The frame numbers should be consecutive and should start from 0001. The decoding results in a frame_xxxx.txt file for every successfully decoded barcode. This file contains the decoded barcode as 12-digit string (UPC-A format: 11 digits content + one check digit). Args: input_directory(string): The input directory from where the PNG frames are read. zxing_path(string): The path to the zxing binary. If specified as None, the PATH will be searched for it. Return: (bool): True if the decoding succeeded. """ if not zxing_path: zxing_path = 'zxing.exe' if sys.platform == 'win32' else 'zxing' print 'Decoding barcodes from PNG files with %s...' % zxing_path return helper_functions.perform_action_on_all_files( directory=input_directory, file_pattern='frame_', file_extension='png', start_number=1, action=_decode_barcode_in_file, command_line_decoder=zxing_path)
[ "def", "decode_frames", "(", "input_directory", ",", "zxing_path", ")", ":", "if", "not", "zxing_path", ":", "zxing_path", "=", "'zxing.exe'", "if", "sys", ".", "platform", "==", "'win32'", "else", "'zxing'", "print", "'Decoding barcodes from PNG files with %s...'", "%", "zxing_path", "return", "helper_functions", ".", "perform_action_on_all_files", "(", "directory", "=", "input_directory", ",", "file_pattern", "=", "'frame_'", ",", "file_extension", "=", "'png'", ",", "start_number", "=", "1", ",", "action", "=", "_decode_barcode_in_file", ",", "command_line_decoder", "=", "zxing_path", ")" ]
https://github.com/DanielSWolf/rhubarb-lip-sync/blob/5cface0af3b6e4e58c0b829c51561d784fb9f52f/rhubarb/lib/webrtc-8d2248ff/webrtc/tools/barcode_tools/barcode_decoder.py#L64-L89
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/utils/benchmark/tools/gbench/report.py
python
color_format
(use_color, fmt_str, *args, **kwargs)
return fmt_str.format(*args, **kwargs)
Return the result of 'fmt_str.format(*args, **kwargs)' after transforming 'args' and 'kwargs' according to the value of 'use_color'. If 'use_color' is False then all color codes in 'args' and 'kwargs' are replaced with the empty string.
Return the result of 'fmt_str.format(*args, **kwargs)' after transforming 'args' and 'kwargs' according to the value of 'use_color'. If 'use_color' is False then all color codes in 'args' and 'kwargs' are replaced with the empty string.
[ "Return", "the", "result", "of", "fmt_str", ".", "format", "(", "*", "args", "**", "kwargs", ")", "after", "transforming", "args", "and", "kwargs", "according", "to", "the", "value", "of", "use_color", ".", "If", "use_color", "is", "False", "then", "all", "color", "codes", "in", "args", "and", "kwargs", "are", "replaced", "with", "the", "empty", "string", "." ]
def color_format(use_color, fmt_str, *args, **kwargs): """ Return the result of 'fmt_str.format(*args, **kwargs)' after transforming 'args' and 'kwargs' according to the value of 'use_color'. If 'use_color' is False then all color codes in 'args' and 'kwargs' are replaced with the empty string. """ assert use_color is True or use_color is False if not use_color: args = [arg if not isinstance(arg, BenchmarkColor) else BC_NONE for arg in args] kwargs = {key: arg if not isinstance(arg, BenchmarkColor) else BC_NONE for key, arg in kwargs.items()} return fmt_str.format(*args, **kwargs)
[ "def", "color_format", "(", "use_color", ",", "fmt_str", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "use_color", "is", "True", "or", "use_color", "is", "False", "if", "not", "use_color", ":", "args", "=", "[", "arg", "if", "not", "isinstance", "(", "arg", ",", "BenchmarkColor", ")", "else", "BC_NONE", "for", "arg", "in", "args", "]", "kwargs", "=", "{", "key", ":", "arg", "if", "not", "isinstance", "(", "arg", ",", "BenchmarkColor", ")", "else", "BC_NONE", "for", "key", ",", "arg", "in", "kwargs", ".", "items", "(", ")", "}", "return", "fmt_str", ".", "format", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/utils/benchmark/tools/gbench/report.py#L32-L45
AutoRally/autorally
48bae14fe4b2d56e5ca11fd2fec3d7dfac7a0e75
autorally_gazebo/nodes/autorally_controller.py
python
AutoRallyCtrlr.spin
(self)
Control the vehicle.
Control the vehicle.
[ "Control", "the", "vehicle", "." ]
def spin(self): """Control the vehicle.""" last_time = rospy.get_time() while not rospy.is_shutdown(): t = rospy.get_time() delta_t = t - last_time last_time = t frontBrake = 0.0; speed = 0.0; chassisSt = chassisState() chassisSt.runstopMotionEnabled = self.getrunstop(); if (self._cmd_timeout > 0.0 and t - self._last_cmd_time > self._cmd_timeout): # Too much time has elapsed since the last command. Stop the # vehicle. steer_ang_changed, center_y = \ self._ctrl_steering(self._last_steer_ang, 0.0, 0.001) self._ctrl_axles(0.0, 0.0, 0.0, steer_ang_changed, center_y) elif delta_t > 0.0: with self.chassisCmdLock: foundSteering = False foundThrottle = False foundFrontBrake = False steer_ang = 0.0 steer_ang_vel = 0.0 foundSteering = False accel = 0.0 if not chassisSt.runstopMotionEnabled: chassisSt.throttle = 0.0; chassisSt.throttleCommander = 'runstop'; foundThrottle = True for cmd,priority in self.commandPriorities: #rospy.logwarn("looking for chassis commander %s with priority %d", cmd, priority) if cmd in self.chassisCmds: if abs(self.chassisCmds[cmd].steering) <= 1.0 and \ (rospy.Time.now()-self.chassisCmds[cmd].header.stamp) < \ rospy.Duration.from_sec(0.2) and\ not foundSteering: #rospy.loginfo("%s in control of steering", cmd); steer_ang = -math.radians(25)*self.chassisCmds[cmd].steering steer_ang_vel = 0.0 chassisSt.steering = self.chassisCmds[cmd].steering chassisSt.steeringCommander = self.chassisCmds[cmd].sender foundSteering = True if abs(self.chassisCmds[cmd].throttle) <= 1.0 and \ (rospy.Time.now()-self.chassisCmds[cmd].header.stamp) < \ rospy.Duration.from_sec(0.2) and\ not foundThrottle: #rospy.loginfo("%s in control of throttle", cmd); if self.chassisCmds[cmd].throttle >= 0.0: speed = self.rear_axle_max_effort*self.chassisCmds[cmd].throttle else: speed = self.rear_axle_brake_effort*self.chassisCmds[cmd].throttle accel = 0.0 chassisSt.throttle = self.chassisCmds[cmd].throttle chassisSt.throttleCommander = self.chassisCmds[cmd].sender foundThrottle = True if self.chassisCmds[cmd].frontBrake >= 0.0 and \ self.chassisCmds[cmd].frontBrake <= 1.0 and \ (rospy.Time.now()-self.chassisCmds[cmd].header.stamp) < \ rospy.Duration.from_sec(0.2) and\ not foundFrontBrake: #the brake acts to slow any movement frontBrake = numpy.sign(self.wheelSpeedFront)*(-self.front_axle_brake_effort*self.chassisCmds[cmd].frontBrake) chassisSt.frontBrake = self.chassisCmds[cmd].frontBrake chassisSt.frontBrakeCommander = self.chassisCmds[cmd].sender foundFrontBrake = True else: frontBrake = 0 steer_ang_changed, center_y = self._ctrl_steering(steer_ang, steer_ang_vel, delta_t) self._ctrl_axles(speed, accel, delta_t, steer_ang_changed, center_y) # Publish the steering and axle joint commands. chassisSt.header.stamp = rospy.Time.now() self.chassisStatePub.publish(chassisSt) self._left_steer_cmd_pub.publish(self._theta_left) self._right_steer_cmd_pub.publish(self._theta_right) if self._left_front_axle_cmd_pub: self._left_front_axle_cmd_pub.publish(frontBrake) if self._right_front_axle_cmd_pub: self._right_front_axle_cmd_pub.publish(frontBrake) if self._left_rear_axle_cmd_pub: self._left_rear_axle_cmd_pub.publish(speed) if self._right_rear_axle_cmd_pub: self._right_rear_axle_cmd_pub.publish(speed) try: self._sleep_timer.sleep() except rospy.exceptions.ROSTimeMovedBackwardsException: continue
[ "def", "spin", "(", "self", ")", ":", "last_time", "=", "rospy", ".", "get_time", "(", ")", "while", "not", "rospy", ".", "is_shutdown", "(", ")", ":", "t", "=", "rospy", ".", "get_time", "(", ")", "delta_t", "=", "t", "-", "last_time", "last_time", "=", "t", "frontBrake", "=", "0.0", "speed", "=", "0.0", "chassisSt", "=", "chassisState", "(", ")", "chassisSt", ".", "runstopMotionEnabled", "=", "self", ".", "getrunstop", "(", ")", "if", "(", "self", ".", "_cmd_timeout", ">", "0.0", "and", "t", "-", "self", ".", "_last_cmd_time", ">", "self", ".", "_cmd_timeout", ")", ":", "# Too much time has elapsed since the last command. Stop the", "# vehicle.", "steer_ang_changed", ",", "center_y", "=", "self", ".", "_ctrl_steering", "(", "self", ".", "_last_steer_ang", ",", "0.0", ",", "0.001", ")", "self", ".", "_ctrl_axles", "(", "0.0", ",", "0.0", ",", "0.0", ",", "steer_ang_changed", ",", "center_y", ")", "elif", "delta_t", ">", "0.0", ":", "with", "self", ".", "chassisCmdLock", ":", "foundSteering", "=", "False", "foundThrottle", "=", "False", "foundFrontBrake", "=", "False", "steer_ang", "=", "0.0", "steer_ang_vel", "=", "0.0", "foundSteering", "=", "False", "accel", "=", "0.0", "if", "not", "chassisSt", ".", "runstopMotionEnabled", ":", "chassisSt", ".", "throttle", "=", "0.0", "chassisSt", ".", "throttleCommander", "=", "'runstop'", "foundThrottle", "=", "True", "for", "cmd", ",", "priority", "in", "self", ".", "commandPriorities", ":", "#rospy.logwarn(\"looking for chassis commander %s with priority %d\", cmd, priority)", "if", "cmd", "in", "self", ".", "chassisCmds", ":", "if", "abs", "(", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "steering", ")", "<=", "1.0", "and", "(", "rospy", ".", "Time", ".", "now", "(", ")", "-", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "header", ".", "stamp", ")", "<", "rospy", ".", "Duration", ".", "from_sec", "(", "0.2", ")", "and", "not", "foundSteering", ":", "#rospy.loginfo(\"%s in control of steering\", cmd);", "steer_ang", "=", "-", "math", ".", "radians", "(", "25", ")", "*", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "steering", "steer_ang_vel", "=", "0.0", "chassisSt", ".", "steering", "=", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "steering", "chassisSt", ".", "steeringCommander", "=", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "sender", "foundSteering", "=", "True", "if", "abs", "(", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "throttle", ")", "<=", "1.0", "and", "(", "rospy", ".", "Time", ".", "now", "(", ")", "-", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "header", ".", "stamp", ")", "<", "rospy", ".", "Duration", ".", "from_sec", "(", "0.2", ")", "and", "not", "foundThrottle", ":", "#rospy.loginfo(\"%s in control of throttle\", cmd);", "if", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "throttle", ">=", "0.0", ":", "speed", "=", "self", ".", "rear_axle_max_effort", "*", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "throttle", "else", ":", "speed", "=", "self", ".", "rear_axle_brake_effort", "*", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "throttle", "accel", "=", "0.0", "chassisSt", ".", "throttle", "=", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "throttle", "chassisSt", ".", "throttleCommander", "=", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "sender", "foundThrottle", "=", "True", "if", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "frontBrake", ">=", "0.0", "and", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "frontBrake", "<=", "1.0", "and", "(", "rospy", ".", "Time", ".", "now", "(", ")", "-", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "header", ".", "stamp", ")", "<", "rospy", ".", "Duration", ".", "from_sec", "(", "0.2", ")", "and", "not", "foundFrontBrake", ":", "#the brake acts to slow any movement", "frontBrake", "=", "numpy", ".", "sign", "(", "self", ".", "wheelSpeedFront", ")", "*", "(", "-", "self", ".", "front_axle_brake_effort", "*", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "frontBrake", ")", "chassisSt", ".", "frontBrake", "=", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "frontBrake", "chassisSt", ".", "frontBrakeCommander", "=", "self", ".", "chassisCmds", "[", "cmd", "]", ".", "sender", "foundFrontBrake", "=", "True", "else", ":", "frontBrake", "=", "0", "steer_ang_changed", ",", "center_y", "=", "self", ".", "_ctrl_steering", "(", "steer_ang", ",", "steer_ang_vel", ",", "delta_t", ")", "self", ".", "_ctrl_axles", "(", "speed", ",", "accel", ",", "delta_t", ",", "steer_ang_changed", ",", "center_y", ")", "# Publish the steering and axle joint commands.", "chassisSt", ".", "header", ".", "stamp", "=", "rospy", ".", "Time", ".", "now", "(", ")", "self", ".", "chassisStatePub", ".", "publish", "(", "chassisSt", ")", "self", ".", "_left_steer_cmd_pub", ".", "publish", "(", "self", ".", "_theta_left", ")", "self", ".", "_right_steer_cmd_pub", ".", "publish", "(", "self", ".", "_theta_right", ")", "if", "self", ".", "_left_front_axle_cmd_pub", ":", "self", ".", "_left_front_axle_cmd_pub", ".", "publish", "(", "frontBrake", ")", "if", "self", ".", "_right_front_axle_cmd_pub", ":", "self", ".", "_right_front_axle_cmd_pub", ".", "publish", "(", "frontBrake", ")", "if", "self", ".", "_left_rear_axle_cmd_pub", ":", "self", ".", "_left_rear_axle_cmd_pub", ".", "publish", "(", "speed", ")", "if", "self", ".", "_right_rear_axle_cmd_pub", ":", "self", ".", "_right_rear_axle_cmd_pub", ".", "publish", "(", "speed", ")", "try", ":", "self", ".", "_sleep_timer", ".", "sleep", "(", ")", "except", "rospy", ".", "exceptions", ".", "ROSTimeMovedBackwardsException", ":", "continue" ]
https://github.com/AutoRally/autorally/blob/48bae14fe4b2d56e5ca11fd2fec3d7dfac7a0e75/autorally_gazebo/nodes/autorally_controller.py#L314-L417
MegaGlest/megaglest-source
e3af470288a3c9cc179f63b5a1eb414a669e3772
mk/linux/symbolstore.py
python
Dumper.GlobalInit
(cls, module=multiprocessing)
Initialize the class globals for the multiprocessing setup; must be called before any Dumper instances are created and used. Test cases may pass in a different module to supply Manager and Pool objects, usually multiprocessing.dummy.
Initialize the class globals for the multiprocessing setup; must be called before any Dumper instances are created and used. Test cases may pass in a different module to supply Manager and Pool objects, usually multiprocessing.dummy.
[ "Initialize", "the", "class", "globals", "for", "the", "multiprocessing", "setup", ";", "must", "be", "called", "before", "any", "Dumper", "instances", "are", "created", "and", "used", ".", "Test", "cases", "may", "pass", "in", "a", "different", "module", "to", "supply", "Manager", "and", "Pool", "objects", "usually", "multiprocessing", ".", "dummy", "." ]
def GlobalInit(cls, module=multiprocessing): """Initialize the class globals for the multiprocessing setup; must be called before any Dumper instances are created and used. Test cases may pass in a different module to supply Manager and Pool objects, usually multiprocessing.dummy.""" num_cpus = module.cpu_count() if num_cpus is None: # assume a dual core machine if we can't find out for some reason # probably better on single core anyway due to I/O constraints num_cpus = 2 # have to create any locks etc before the pool cls.manager = module.Manager() cls.jobs_condition = Dumper.manager.Condition() cls.lock = Dumper.manager.RLock() cls.pool = module.Pool(num_cpus, WorkerInitializer, (cls, cls.lock))
[ "def", "GlobalInit", "(", "cls", ",", "module", "=", "multiprocessing", ")", ":", "num_cpus", "=", "module", ".", "cpu_count", "(", ")", "if", "num_cpus", "is", "None", ":", "# assume a dual core machine if we can't find out for some reason", "# probably better on single core anyway due to I/O constraints", "num_cpus", "=", "2", "# have to create any locks etc before the pool", "cls", ".", "manager", "=", "module", ".", "Manager", "(", ")", "cls", ".", "jobs_condition", "=", "Dumper", ".", "manager", ".", "Condition", "(", ")", "cls", ".", "lock", "=", "Dumper", ".", "manager", ".", "RLock", "(", ")", "cls", ".", "pool", "=", "module", ".", "Pool", "(", "num_cpus", ",", "WorkerInitializer", ",", "(", "cls", ",", "cls", ".", "lock", ")", ")" ]
https://github.com/MegaGlest/megaglest-source/blob/e3af470288a3c9cc179f63b5a1eb414a669e3772/mk/linux/symbolstore.py#L369-L384
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py
python
Treeview.move
(self, item, parent, index)
Moves item to position index in parent's list of children. It is illegal to move an item under one of its descendants. If index is less than or equal to zero, item is moved to the beginning, if greater than or equal to the number of children, it is moved to the end. If item was detached it is reattached.
Moves item to position index in parent's list of children.
[ "Moves", "item", "to", "position", "index", "in", "parent", "s", "list", "of", "children", "." ]
def move(self, item, parent, index): """Moves item to position index in parent's list of children. It is illegal to move an item under one of its descendants. If index is less than or equal to zero, item is moved to the beginning, if greater than or equal to the number of children, it is moved to the end. If item was detached it is reattached.""" self.tk.call(self._w, "move", item, parent, index)
[ "def", "move", "(", "self", ",", "item", ",", "parent", ",", "index", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"move\"", ",", "item", ",", "parent", ",", "index", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py#L1352-L1359
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/command.py
python
FbCmd.do_help
(self, input)
Print out help
Print out help
[ "Print", "out", "help" ]
def do_help(self, input): """Print out help""" args = input.strip().split() if len(args) > 0: arg = args[0] try: func = self.ctx.lookup_helpfunction(arg) func() except AttributeError: pass try: func = getattr(self, 'help_' + arg.lower()) func() except AttributeError: pass else: cmds = self.get_shortcut_help() + self.get_help_lists(self.get_names(), self) cmdlist = {'title' : "Core Commands", 'commands' : cmds} self.io.print_cmd_list(cmdlist) if self.ctx.get_name() != self.defaultcontext.get_name(): cmds = self.get_help_lists(self.ctx.get_names(), self.ctx) cmdlist = {'title' : "%s Commands" %self.ctx.get_type(), 'commands' : cmds} self.io.print_cmd_list(cmdlist)
[ "def", "do_help", "(", "self", ",", "input", ")", ":", "args", "=", "input", ".", "strip", "(", ")", ".", "split", "(", ")", "if", "len", "(", "args", ")", ">", "0", ":", "arg", "=", "args", "[", "0", "]", "try", ":", "func", "=", "self", ".", "ctx", ".", "lookup_helpfunction", "(", "arg", ")", "func", "(", ")", "except", "AttributeError", ":", "pass", "try", ":", "func", "=", "getattr", "(", "self", ",", "'help_'", "+", "arg", ".", "lower", "(", ")", ")", "func", "(", ")", "except", "AttributeError", ":", "pass", "else", ":", "cmds", "=", "self", ".", "get_shortcut_help", "(", ")", "+", "self", ".", "get_help_lists", "(", "self", ".", "get_names", "(", ")", ",", "self", ")", "cmdlist", "=", "{", "'title'", ":", "\"Core Commands\"", ",", "'commands'", ":", "cmds", "}", "self", ".", "io", ".", "print_cmd_list", "(", "cmdlist", ")", "if", "self", ".", "ctx", ".", "get_name", "(", ")", "!=", "self", ".", "defaultcontext", ".", "get_name", "(", ")", ":", "cmds", "=", "self", ".", "get_help_lists", "(", "self", ".", "ctx", ".", "get_names", "(", ")", ",", "self", ".", "ctx", ")", "cmdlist", "=", "{", "'title'", ":", "\"%s Commands\"", "%", "self", ".", "ctx", ".", "get_type", "(", ")", ",", "'commands'", ":", "cmds", "}", "self", ".", "io", ".", "print_cmd_list", "(", "cmdlist", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/command.py#L371-L396
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/geodesy/utm.py
python
UTMPoint.toPoint
(self)
return pt
:returns: corresponding `geometry_msgs/Point`_ message. :todo: clamp message longitude to [-180..180]
:returns: corresponding `geometry_msgs/Point`_ message. :todo: clamp message longitude to [-180..180]
[ ":", "returns", ":", "corresponding", "geometry_msgs", "/", "Point", "_", "message", ".", ":", "todo", ":", "clamp", "message", "longitude", "to", "[", "-", "180", "..", "180", "]" ]
def toPoint(self): """:returns: corresponding `geometry_msgs/Point`_ message. :todo: clamp message longitude to [-180..180] """ if not self.valid(): raise ValueError('invalid UTM point: ' + str(self)) pt = Point(x = self.easting, y = self.northing) if not self.is2D(): pt.z = self.altitude return pt
[ "def", "toPoint", "(", "self", ")", ":", "if", "not", "self", ".", "valid", "(", ")", ":", "raise", "ValueError", "(", "'invalid UTM point: '", "+", "str", "(", "self", ")", ")", "pt", "=", "Point", "(", "x", "=", "self", ".", "easting", ",", "y", "=", "self", ".", "northing", ")", "if", "not", "self", ".", "is2D", "(", ")", ":", "pt", ".", "z", "=", "self", ".", "altitude", "return", "pt" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/geodesy/utm.py#L102-L111
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/datetimelike.py
python
AttributesMixin._check_compatible_with
( self, other: Union[Period, Timestamp, Timedelta, NaTType], setitem: bool = False )
Verify that `self` and `other` are compatible. * DatetimeArray verifies that the timezones (if any) match * PeriodArray verifies that the freq matches * Timedelta has no verification In each case, NaT is considered compatible. Parameters ---------- other setitem : bool, default False For __setitem__ we may have stricter compatiblity resrictions than for comparisons. Raises ------ Exception
Verify that `self` and `other` are compatible.
[ "Verify", "that", "self", "and", "other", "are", "compatible", "." ]
def _check_compatible_with( self, other: Union[Period, Timestamp, Timedelta, NaTType], setitem: bool = False ) -> None: """ Verify that `self` and `other` are compatible. * DatetimeArray verifies that the timezones (if any) match * PeriodArray verifies that the freq matches * Timedelta has no verification In each case, NaT is considered compatible. Parameters ---------- other setitem : bool, default False For __setitem__ we may have stricter compatiblity resrictions than for comparisons. Raises ------ Exception """ raise AbstractMethodError(self)
[ "def", "_check_compatible_with", "(", "self", ",", "other", ":", "Union", "[", "Period", ",", "Timestamp", ",", "Timedelta", ",", "NaTType", "]", ",", "setitem", ":", "bool", "=", "False", ")", "->", "None", ":", "raise", "AbstractMethodError", "(", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/datetimelike.py#L186-L209
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/runtime.py
python
Undefined._undefined_message
(self)
return ( f"{object_type_repr(self._undefined_obj)!r} has no" f" attribute {self._undefined_name!r}" )
Build a message about the undefined value based on how it was accessed.
Build a message about the undefined value based on how it was accessed.
[ "Build", "a", "message", "about", "the", "undefined", "value", "based", "on", "how", "it", "was", "accessed", "." ]
def _undefined_message(self) -> str: """Build a message about the undefined value based on how it was accessed. """ if self._undefined_hint: return self._undefined_hint if self._undefined_obj is missing: return f"{self._undefined_name!r} is undefined" if not isinstance(self._undefined_name, str): return ( f"{object_type_repr(self._undefined_obj)} has no" f" element {self._undefined_name!r}" ) return ( f"{object_type_repr(self._undefined_obj)!r} has no" f" attribute {self._undefined_name!r}" )
[ "def", "_undefined_message", "(", "self", ")", "->", "str", ":", "if", "self", ".", "_undefined_hint", ":", "return", "self", ".", "_undefined_hint", "if", "self", ".", "_undefined_obj", "is", "missing", ":", "return", "f\"{self._undefined_name!r} is undefined\"", "if", "not", "isinstance", "(", "self", ".", "_undefined_name", ",", "str", ")", ":", "return", "(", "f\"{object_type_repr(self._undefined_obj)} has no\"", "f\" element {self._undefined_name!r}\"", ")", "return", "(", "f\"{object_type_repr(self._undefined_obj)!r} has no\"", "f\" attribute {self._undefined_name!r}\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/runtime.py#L875-L894
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/datamodel/manager.py
python
DataModelManager.register
(self, fetypecls, handler)
Register the datamodel factory corresponding to a frontend-type class
Register the datamodel factory corresponding to a frontend-type class
[ "Register", "the", "datamodel", "factory", "corresponding", "to", "a", "frontend", "-", "type", "class" ]
def register(self, fetypecls, handler): """Register the datamodel factory corresponding to a frontend-type class """ assert issubclass(fetypecls, types.Type) self._handlers[fetypecls] = handler
[ "def", "register", "(", "self", ",", "fetypecls", ",", "handler", ")", ":", "assert", "issubclass", "(", "fetypecls", ",", "types", ".", "Type", ")", "self", ".", "_handlers", "[", "fetypecls", "]", "=", "handler" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/datamodel/manager.py#L18-L22
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/ert/ertScheme.py
python
DataSchemeBase.addInverse
(self, addInverse=False)
Add inverse value to create a full dataset.
Add inverse value to create a full dataset.
[ "Add", "inverse", "value", "to", "create", "a", "full", "dataset", "." ]
def addInverse(self, addInverse=False): """ Add inverse value to create a full dataset. """ self.addInverse_ = addInverse
[ "def", "addInverse", "(", "self", ",", "addInverse", "=", "False", ")", ":", "self", ".", "addInverse_", "=", "addInverse" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/ert/ertScheme.py#L310-L314
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/variable_scope.py
python
_PartitionInfo.single_slice_dim
(self, shape)
return slice_dim
Returns the slice dim when the variable is partitioned only in one dim. Args: shape: Tuple or list of `int` indicating the shape of one specific variable partition. Returns: `int` representing the dimension that the variable is partitioned in, or `None` if the variable doesn't seem to be partitioned at all. Raises: TypeError: If `shape` is not a sequence. ValueError: If `shape` is not the same length as `self.full_shape`. If the variable is partitioned in more than one dimension.
Returns the slice dim when the variable is partitioned only in one dim.
[ "Returns", "the", "slice", "dim", "when", "the", "variable", "is", "partitioned", "only", "in", "one", "dim", "." ]
def single_slice_dim(self, shape): """Returns the slice dim when the variable is partitioned only in one dim. Args: shape: Tuple or list of `int` indicating the shape of one specific variable partition. Returns: `int` representing the dimension that the variable is partitioned in, or `None` if the variable doesn't seem to be partitioned at all. Raises: TypeError: If `shape` is not a sequence. ValueError: If `shape` is not the same length as `self.full_shape`. If the variable is partitioned in more than one dimension. """ if not isinstance(shape, collections_lib.Sequence) or isinstance( shape, six.string_types): raise TypeError( "`shape` must be a sequence (like tuple or list) instead of " + type(shape).__name__) if len(shape) != len(self.full_shape): raise ValueError( "Expected equal length, but received shape={} of length {} while " "self.full_shape={} is of length {}.".format(shape, len( shape), self.full_shape, len(self.full_shape))) for i in xrange(len(shape)): if self.var_offset[i] + shape[i] > self.full_shape[i]: raise ValueError( "With self.var_offset={}, a partition of shape={} would exceed " "self.full_shape={} in dimension {}.".format( self.var_offset, shape, self.full_shape, i)) slice_dim = None for i in xrange(len(shape)): if shape[i] == self.full_shape[i]: continue if slice_dim is not None: raise ValueError( "Cannot use single_slice_dim() with shape={} and " "self.full_shape={} since slice dim could be either dimension {} " "or {}.".format(shape, self.full_shape, i, slice_dim)) slice_dim = i return slice_dim
[ "def", "single_slice_dim", "(", "self", ",", "shape", ")", ":", "if", "not", "isinstance", "(", "shape", ",", "collections_lib", ".", "Sequence", ")", "or", "isinstance", "(", "shape", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "\"`shape` must be a sequence (like tuple or list) instead of \"", "+", "type", "(", "shape", ")", ".", "__name__", ")", "if", "len", "(", "shape", ")", "!=", "len", "(", "self", ".", "full_shape", ")", ":", "raise", "ValueError", "(", "\"Expected equal length, but received shape={} of length {} while \"", "\"self.full_shape={} is of length {}.\"", ".", "format", "(", "shape", ",", "len", "(", "shape", ")", ",", "self", ".", "full_shape", ",", "len", "(", "self", ".", "full_shape", ")", ")", ")", "for", "i", "in", "xrange", "(", "len", "(", "shape", ")", ")", ":", "if", "self", ".", "var_offset", "[", "i", "]", "+", "shape", "[", "i", "]", ">", "self", ".", "full_shape", "[", "i", "]", ":", "raise", "ValueError", "(", "\"With self.var_offset={}, a partition of shape={} would exceed \"", "\"self.full_shape={} in dimension {}.\"", ".", "format", "(", "self", ".", "var_offset", ",", "shape", ",", "self", ".", "full_shape", ",", "i", ")", ")", "slice_dim", "=", "None", "for", "i", "in", "xrange", "(", "len", "(", "shape", ")", ")", ":", "if", "shape", "[", "i", "]", "==", "self", ".", "full_shape", "[", "i", "]", ":", "continue", "if", "slice_dim", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Cannot use single_slice_dim() with shape={} and \"", "\"self.full_shape={} since slice dim could be either dimension {} \"", "\"or {}.\"", ".", "format", "(", "shape", ",", "self", ".", "full_shape", ",", "i", ",", "slice_dim", ")", ")", "slice_dim", "=", "i", "return", "slice_dim" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/variable_scope.py#L126-L172
Illumina/hap.py
84011695b2ff2406c16a335106db6831fb67fdfe
src/python/Somatic/Strelka.py
python
extractStrelkaIndelFeatures
(vcfname, tag, avg_depth=None)
return df
Return a data frame with features collected from the given VCF, tagged by given type :param vcfname: name of the VCF file :param tag: type of variants :param avg_depth: average chromosome depths from BAM file
Return a data frame with features collected from the given VCF, tagged by given type :param vcfname: name of the VCF file :param tag: type of variants :param avg_depth: average chromosome depths from BAM file
[ "Return", "a", "data", "frame", "with", "features", "collected", "from", "the", "given", "VCF", "tagged", "by", "given", "type", ":", "param", "vcfname", ":", "name", "of", "the", "VCF", "file", ":", "param", "tag", ":", "type", "of", "variants", ":", "param", "avg_depth", ":", "average", "chromosome", "depths", "from", "BAM", "file" ]
def extractStrelkaIndelFeatures(vcfname, tag, avg_depth=None): """ Return a data frame with features collected from the given VCF, tagged by given type :param vcfname: name of the VCF file :param tag: type of variants :param avg_depth: average chromosome depths from BAM file """ features = ["CHROM", "POS", "REF", "ALT", "FILTER", "I.NT", "I.SOMATIC", "I.QSI_NT", "I.EVS", "I.EVSF", "I.SomaticEVS", "I.SGT", "I.RC", "I.RU", "I.IC", "I.IHP", "I.MQ", "I.MQ0", "S.1.DP", "S.2.DP", "S.1.TAR", "S.2.TAR", "S.1.TIR", "S.2.TIR", "S.1.TOR", "S.2.TOR", "S.1.BCN50", "S.2.BCN50", "S.1.FDP50", "S.2.FDP50", ] cols = ["CHROM", "POS", "REF", "ALT", "LENGTH", "INDELTYPE", "FILTER", "NT", "NT_REF", "EVS", "QSI_NT", "N_DP", "T_DP", "N_DP_RATE", "T_DP_RATE", "N_BCN", "T_BCN", "N_FDP", "T_FDP", "N_AF", "T_AF", "SGT", "RC", "RU", "RU_LEN", "IC", "IHP", "MQ", "MQ0", "tag"] records = [] vcfheaders = list(extractHeaders(vcfname)) evs_featurenames = {} for l in vcfheaders: if '##indel_scoring_features' in l: try: xl = str(l).split('=', 1) xl = xl[1].split(",") for i, n in enumerate(xl): evs_featurenames[i] = n cols.append("E." + n) logging.info("Scoring feature %i : %s" % (i, n)) except: logging.warn("Could not parse scoring feature names from Strelka output") if not avg_depth: avg_depth = {} for l in vcfheaders: x = str(l).lower() x = x.replace("##meandepth_", "##maxdepth_") x = x.replace("##depth_", "##maxdepth_") if '##maxdepth_' in x: p, _, l = l.partition("_") xl = str(l).split('=') xchr = xl[0] avg_depth[xchr] = float(xl[1]) logging.info("%s depth from VCF header is %f" % (xchr, avg_depth[xchr])) has_warned = {} for vr in vcfExtract(vcfname, features): rec = {} for i, ff in enumerate(features): rec[ff] = vr[i] rec["tag"] = tag if "I.SomaticEVS" in rec: try: rec["I.EVS"] = float(rec["I.SomaticEVS"]) except: rec["I.EVS"] = -1.0 else: try: rec["I.EVS"] = float(rec["I.EVS"]) except: rec["I.EVS"] = -1.0 # fix missing features for q in ["I.QSI_NT", "I.RC", "I.IC", "I.IHP", "S.1.DP", "S.2.DP", "S.1.BCN50", "S.2.BCN50", "S.1.FDP50", "S.2.FDP50"]: if q not in rec or rec[q] is None: rec[q] = 0 if not ("feat:" + q) in has_warned: logging.warn("Missing feature %s" % q) has_warned["feat:" + q] = True for q in ["S.1.TAR", "S.2.TAR", "S.1.TIR", "S.2.TIR", "S.1.TOR", "S.2.TOR"]: if q not in rec or rec[q] is None: rec[q] = [0, 0] if not ("feat:" + q) in has_warned: logging.warn("Missing feature %s" % q) has_warned["feat:" + q] = True NT = rec["I.NT"] NT_is_ref = int(NT == "ref") QSI_NT = int(rec["I.QSI_NT"]) n_DP = float(rec["S.1.DP"]) t_DP = float(rec["S.2.DP"]) in_del = 0 max_len = len(rec["REF"]) min_len = len(rec["REF"]) for a in rec["ALT"]: if len(a) > len(rec["REF"]): in_del |= 1 else: in_del |= 2 min_len = min(len(a), min_len) max_len = max(len(a), max_len) ilen = max_len - min_len n_DP_ratio = 0 t_DP_ratio = 0 if avg_depth: try: n_DP_ratio = n_DP / float(avg_depth[rec["CHROM"]]) t_DP_ratio = t_DP / float(avg_depth[rec["CHROM"]]) except: if not rec["CHROM"] in has_warned: logging.warn("Cannot normalize depths on %s" % rec["CHROM"]) has_warned[rec["CHROM"]] = True elif "DPnorm" not in has_warned: logging.warn("Cannot normalize depths.") has_warned["DPnorm"] = True # extract observed AF from strelka counts. TIR = ALT; TAR = REF try: n_af = float(rec["S.1.TIR"][0]) / (float(rec["S.1.TIR"][0]) + float(rec["S.1.TAR"][0])) except: n_af = 0 try: t_af = float(rec["S.2.TIR"][0]) / (float(rec["S.2.TIR"][0]) + float(rec["S.2.TAR"][0])) except: t_af = 0 # Gather the computed data into a dict qrec = { "CHROM": rec["CHROM"], "POS": int(rec["POS"]), "REF": rec["REF"], "ALT": ",".join(rec["ALT"]), "LENGTH": ilen, "INDELTYPE": in_del, "FILTER": ",".join(rec["FILTER"]), "NT": NT, "NT_REF": NT_is_ref, "QSI_NT": QSI_NT, "N_DP": n_DP, "T_DP": t_DP, "N_DP_RATE": n_DP_ratio, "T_DP_RATE": t_DP_ratio, "N_AF": n_af, "T_AF": t_af, "SGT": rec["I.SGT"], "tag": tag } # fields with defaults fields = [ {"n": "EVS", "s": "I.EVS", "def": 0, "t": float}, {"n": "VQSR", "s": "I.VQSR", "def": 0, "t": float}, {"n": "RC", "s": "I.RC", "def": 0, "t": int}, {"n": "RU", "s": "I.RU", "def": ""}, {"n": "RU_LEN", "s": "I.RU", "def": 0, "t": len}, {"n": "IC", "s": "I.IC", "def": 0, "t": int}, {"n": "IHP", "s": "I.IHP", "def": 0, "t": int}, {"n": "MQ", "s": "I.MQ", "def": 0.0, "t": float}, {"n": "MQ0", "s": "I.MQ0", "def": 0.0, "t": float}, {"n": "N_BCN", "s": "S.1.BCN50", "def": 0.0, "t": float}, {"n": "T_BCN", "s": "S.2.BCN50", "def": 0.0, "t": float}, {"n": "N_FDP", "s": "S.1.FDP50", "def": 0.0, "t": float}, {"n": "T_FDP", "s": "S.2.FDP50", "def": 0.0, "t": float}, ] for fd in fields: try: res = rec[fd["s"]] if "t" in fd: res = fd["t"](res) except: res = fd["def"] qrec[fd["n"]] = res # ESF features try: for i, v in enumerate(rec["I.EVSF"]): if i in evs_featurenames: try: qrec["E." + evs_featurenames[i]] = float(v) except: # failure to parse pass except: pass for k, v in evs_featurenames.iteritems(): if not "E." + v in qrec: qrec["E." + v] = 0 records.append(qrec) if records: df = pandas.DataFrame(records, columns=cols) else: df = pandas.DataFrame(columns=cols) return df
[ "def", "extractStrelkaIndelFeatures", "(", "vcfname", ",", "tag", ",", "avg_depth", "=", "None", ")", ":", "features", "=", "[", "\"CHROM\"", ",", "\"POS\"", ",", "\"REF\"", ",", "\"ALT\"", ",", "\"FILTER\"", ",", "\"I.NT\"", ",", "\"I.SOMATIC\"", ",", "\"I.QSI_NT\"", ",", "\"I.EVS\"", ",", "\"I.EVSF\"", ",", "\"I.SomaticEVS\"", ",", "\"I.SGT\"", ",", "\"I.RC\"", ",", "\"I.RU\"", ",", "\"I.IC\"", ",", "\"I.IHP\"", ",", "\"I.MQ\"", ",", "\"I.MQ0\"", ",", "\"S.1.DP\"", ",", "\"S.2.DP\"", ",", "\"S.1.TAR\"", ",", "\"S.2.TAR\"", ",", "\"S.1.TIR\"", ",", "\"S.2.TIR\"", ",", "\"S.1.TOR\"", ",", "\"S.2.TOR\"", ",", "\"S.1.BCN50\"", ",", "\"S.2.BCN50\"", ",", "\"S.1.FDP50\"", ",", "\"S.2.FDP50\"", ",", "]", "cols", "=", "[", "\"CHROM\"", ",", "\"POS\"", ",", "\"REF\"", ",", "\"ALT\"", ",", "\"LENGTH\"", ",", "\"INDELTYPE\"", ",", "\"FILTER\"", ",", "\"NT\"", ",", "\"NT_REF\"", ",", "\"EVS\"", ",", "\"QSI_NT\"", ",", "\"N_DP\"", ",", "\"T_DP\"", ",", "\"N_DP_RATE\"", ",", "\"T_DP_RATE\"", ",", "\"N_BCN\"", ",", "\"T_BCN\"", ",", "\"N_FDP\"", ",", "\"T_FDP\"", ",", "\"N_AF\"", ",", "\"T_AF\"", ",", "\"SGT\"", ",", "\"RC\"", ",", "\"RU\"", ",", "\"RU_LEN\"", ",", "\"IC\"", ",", "\"IHP\"", ",", "\"MQ\"", ",", "\"MQ0\"", ",", "\"tag\"", "]", "records", "=", "[", "]", "vcfheaders", "=", "list", "(", "extractHeaders", "(", "vcfname", ")", ")", "evs_featurenames", "=", "{", "}", "for", "l", "in", "vcfheaders", ":", "if", "'##indel_scoring_features'", "in", "l", ":", "try", ":", "xl", "=", "str", "(", "l", ")", ".", "split", "(", "'='", ",", "1", ")", "xl", "=", "xl", "[", "1", "]", ".", "split", "(", "\",\"", ")", "for", "i", ",", "n", "in", "enumerate", "(", "xl", ")", ":", "evs_featurenames", "[", "i", "]", "=", "n", "cols", ".", "append", "(", "\"E.\"", "+", "n", ")", "logging", ".", "info", "(", "\"Scoring feature %i : %s\"", "%", "(", "i", ",", "n", ")", ")", "except", ":", "logging", ".", "warn", "(", "\"Could not parse scoring feature names from Strelka output\"", ")", "if", "not", "avg_depth", ":", "avg_depth", "=", "{", "}", "for", "l", "in", "vcfheaders", ":", "x", "=", "str", "(", "l", ")", ".", "lower", "(", ")", "x", "=", "x", ".", "replace", "(", "\"##meandepth_\"", ",", "\"##maxdepth_\"", ")", "x", "=", "x", ".", "replace", "(", "\"##depth_\"", ",", "\"##maxdepth_\"", ")", "if", "'##maxdepth_'", "in", "x", ":", "p", ",", "_", ",", "l", "=", "l", ".", "partition", "(", "\"_\"", ")", "xl", "=", "str", "(", "l", ")", ".", "split", "(", "'='", ")", "xchr", "=", "xl", "[", "0", "]", "avg_depth", "[", "xchr", "]", "=", "float", "(", "xl", "[", "1", "]", ")", "logging", ".", "info", "(", "\"%s depth from VCF header is %f\"", "%", "(", "xchr", ",", "avg_depth", "[", "xchr", "]", ")", ")", "has_warned", "=", "{", "}", "for", "vr", "in", "vcfExtract", "(", "vcfname", ",", "features", ")", ":", "rec", "=", "{", "}", "for", "i", ",", "ff", "in", "enumerate", "(", "features", ")", ":", "rec", "[", "ff", "]", "=", "vr", "[", "i", "]", "rec", "[", "\"tag\"", "]", "=", "tag", "if", "\"I.SomaticEVS\"", "in", "rec", ":", "try", ":", "rec", "[", "\"I.EVS\"", "]", "=", "float", "(", "rec", "[", "\"I.SomaticEVS\"", "]", ")", "except", ":", "rec", "[", "\"I.EVS\"", "]", "=", "-", "1.0", "else", ":", "try", ":", "rec", "[", "\"I.EVS\"", "]", "=", "float", "(", "rec", "[", "\"I.EVS\"", "]", ")", "except", ":", "rec", "[", "\"I.EVS\"", "]", "=", "-", "1.0", "# fix missing features", "for", "q", "in", "[", "\"I.QSI_NT\"", ",", "\"I.RC\"", ",", "\"I.IC\"", ",", "\"I.IHP\"", ",", "\"S.1.DP\"", ",", "\"S.2.DP\"", ",", "\"S.1.BCN50\"", ",", "\"S.2.BCN50\"", ",", "\"S.1.FDP50\"", ",", "\"S.2.FDP50\"", "]", ":", "if", "q", "not", "in", "rec", "or", "rec", "[", "q", "]", "is", "None", ":", "rec", "[", "q", "]", "=", "0", "if", "not", "(", "\"feat:\"", "+", "q", ")", "in", "has_warned", ":", "logging", ".", "warn", "(", "\"Missing feature %s\"", "%", "q", ")", "has_warned", "[", "\"feat:\"", "+", "q", "]", "=", "True", "for", "q", "in", "[", "\"S.1.TAR\"", ",", "\"S.2.TAR\"", ",", "\"S.1.TIR\"", ",", "\"S.2.TIR\"", ",", "\"S.1.TOR\"", ",", "\"S.2.TOR\"", "]", ":", "if", "q", "not", "in", "rec", "or", "rec", "[", "q", "]", "is", "None", ":", "rec", "[", "q", "]", "=", "[", "0", ",", "0", "]", "if", "not", "(", "\"feat:\"", "+", "q", ")", "in", "has_warned", ":", "logging", ".", "warn", "(", "\"Missing feature %s\"", "%", "q", ")", "has_warned", "[", "\"feat:\"", "+", "q", "]", "=", "True", "NT", "=", "rec", "[", "\"I.NT\"", "]", "NT_is_ref", "=", "int", "(", "NT", "==", "\"ref\"", ")", "QSI_NT", "=", "int", "(", "rec", "[", "\"I.QSI_NT\"", "]", ")", "n_DP", "=", "float", "(", "rec", "[", "\"S.1.DP\"", "]", ")", "t_DP", "=", "float", "(", "rec", "[", "\"S.2.DP\"", "]", ")", "in_del", "=", "0", "max_len", "=", "len", "(", "rec", "[", "\"REF\"", "]", ")", "min_len", "=", "len", "(", "rec", "[", "\"REF\"", "]", ")", "for", "a", "in", "rec", "[", "\"ALT\"", "]", ":", "if", "len", "(", "a", ")", ">", "len", "(", "rec", "[", "\"REF\"", "]", ")", ":", "in_del", "|=", "1", "else", ":", "in_del", "|=", "2", "min_len", "=", "min", "(", "len", "(", "a", ")", ",", "min_len", ")", "max_len", "=", "max", "(", "len", "(", "a", ")", ",", "max_len", ")", "ilen", "=", "max_len", "-", "min_len", "n_DP_ratio", "=", "0", "t_DP_ratio", "=", "0", "if", "avg_depth", ":", "try", ":", "n_DP_ratio", "=", "n_DP", "/", "float", "(", "avg_depth", "[", "rec", "[", "\"CHROM\"", "]", "]", ")", "t_DP_ratio", "=", "t_DP", "/", "float", "(", "avg_depth", "[", "rec", "[", "\"CHROM\"", "]", "]", ")", "except", ":", "if", "not", "rec", "[", "\"CHROM\"", "]", "in", "has_warned", ":", "logging", ".", "warn", "(", "\"Cannot normalize depths on %s\"", "%", "rec", "[", "\"CHROM\"", "]", ")", "has_warned", "[", "rec", "[", "\"CHROM\"", "]", "]", "=", "True", "elif", "\"DPnorm\"", "not", "in", "has_warned", ":", "logging", ".", "warn", "(", "\"Cannot normalize depths.\"", ")", "has_warned", "[", "\"DPnorm\"", "]", "=", "True", "# extract observed AF from strelka counts. TIR = ALT; TAR = REF", "try", ":", "n_af", "=", "float", "(", "rec", "[", "\"S.1.TIR\"", "]", "[", "0", "]", ")", "/", "(", "float", "(", "rec", "[", "\"S.1.TIR\"", "]", "[", "0", "]", ")", "+", "float", "(", "rec", "[", "\"S.1.TAR\"", "]", "[", "0", "]", ")", ")", "except", ":", "n_af", "=", "0", "try", ":", "t_af", "=", "float", "(", "rec", "[", "\"S.2.TIR\"", "]", "[", "0", "]", ")", "/", "(", "float", "(", "rec", "[", "\"S.2.TIR\"", "]", "[", "0", "]", ")", "+", "float", "(", "rec", "[", "\"S.2.TAR\"", "]", "[", "0", "]", ")", ")", "except", ":", "t_af", "=", "0", "# Gather the computed data into a dict", "qrec", "=", "{", "\"CHROM\"", ":", "rec", "[", "\"CHROM\"", "]", ",", "\"POS\"", ":", "int", "(", "rec", "[", "\"POS\"", "]", ")", ",", "\"REF\"", ":", "rec", "[", "\"REF\"", "]", ",", "\"ALT\"", ":", "\",\"", ".", "join", "(", "rec", "[", "\"ALT\"", "]", ")", ",", "\"LENGTH\"", ":", "ilen", ",", "\"INDELTYPE\"", ":", "in_del", ",", "\"FILTER\"", ":", "\",\"", ".", "join", "(", "rec", "[", "\"FILTER\"", "]", ")", ",", "\"NT\"", ":", "NT", ",", "\"NT_REF\"", ":", "NT_is_ref", ",", "\"QSI_NT\"", ":", "QSI_NT", ",", "\"N_DP\"", ":", "n_DP", ",", "\"T_DP\"", ":", "t_DP", ",", "\"N_DP_RATE\"", ":", "n_DP_ratio", ",", "\"T_DP_RATE\"", ":", "t_DP_ratio", ",", "\"N_AF\"", ":", "n_af", ",", "\"T_AF\"", ":", "t_af", ",", "\"SGT\"", ":", "rec", "[", "\"I.SGT\"", "]", ",", "\"tag\"", ":", "tag", "}", "# fields with defaults", "fields", "=", "[", "{", "\"n\"", ":", "\"EVS\"", ",", "\"s\"", ":", "\"I.EVS\"", ",", "\"def\"", ":", "0", ",", "\"t\"", ":", "float", "}", ",", "{", "\"n\"", ":", "\"VQSR\"", ",", "\"s\"", ":", "\"I.VQSR\"", ",", "\"def\"", ":", "0", ",", "\"t\"", ":", "float", "}", ",", "{", "\"n\"", ":", "\"RC\"", ",", "\"s\"", ":", "\"I.RC\"", ",", "\"def\"", ":", "0", ",", "\"t\"", ":", "int", "}", ",", "{", "\"n\"", ":", "\"RU\"", ",", "\"s\"", ":", "\"I.RU\"", ",", "\"def\"", ":", "\"\"", "}", ",", "{", "\"n\"", ":", "\"RU_LEN\"", ",", "\"s\"", ":", "\"I.RU\"", ",", "\"def\"", ":", "0", ",", "\"t\"", ":", "len", "}", ",", "{", "\"n\"", ":", "\"IC\"", ",", "\"s\"", ":", "\"I.IC\"", ",", "\"def\"", ":", "0", ",", "\"t\"", ":", "int", "}", ",", "{", "\"n\"", ":", "\"IHP\"", ",", "\"s\"", ":", "\"I.IHP\"", ",", "\"def\"", ":", "0", ",", "\"t\"", ":", "int", "}", ",", "{", "\"n\"", ":", "\"MQ\"", ",", "\"s\"", ":", "\"I.MQ\"", ",", "\"def\"", ":", "0.0", ",", "\"t\"", ":", "float", "}", ",", "{", "\"n\"", ":", "\"MQ0\"", ",", "\"s\"", ":", "\"I.MQ0\"", ",", "\"def\"", ":", "0.0", ",", "\"t\"", ":", "float", "}", ",", "{", "\"n\"", ":", "\"N_BCN\"", ",", "\"s\"", ":", "\"S.1.BCN50\"", ",", "\"def\"", ":", "0.0", ",", "\"t\"", ":", "float", "}", ",", "{", "\"n\"", ":", "\"T_BCN\"", ",", "\"s\"", ":", "\"S.2.BCN50\"", ",", "\"def\"", ":", "0.0", ",", "\"t\"", ":", "float", "}", ",", "{", "\"n\"", ":", "\"N_FDP\"", ",", "\"s\"", ":", "\"S.1.FDP50\"", ",", "\"def\"", ":", "0.0", ",", "\"t\"", ":", "float", "}", ",", "{", "\"n\"", ":", "\"T_FDP\"", ",", "\"s\"", ":", "\"S.2.FDP50\"", ",", "\"def\"", ":", "0.0", ",", "\"t\"", ":", "float", "}", ",", "]", "for", "fd", "in", "fields", ":", "try", ":", "res", "=", "rec", "[", "fd", "[", "\"s\"", "]", "]", "if", "\"t\"", "in", "fd", ":", "res", "=", "fd", "[", "\"t\"", "]", "(", "res", ")", "except", ":", "res", "=", "fd", "[", "\"def\"", "]", "qrec", "[", "fd", "[", "\"n\"", "]", "]", "=", "res", "# ESF features", "try", ":", "for", "i", ",", "v", "in", "enumerate", "(", "rec", "[", "\"I.EVSF\"", "]", ")", ":", "if", "i", "in", "evs_featurenames", ":", "try", ":", "qrec", "[", "\"E.\"", "+", "evs_featurenames", "[", "i", "]", "]", "=", "float", "(", "v", ")", "except", ":", "# failure to parse", "pass", "except", ":", "pass", "for", "k", ",", "v", "in", "evs_featurenames", ".", "iteritems", "(", ")", ":", "if", "not", "\"E.\"", "+", "v", "in", "qrec", ":", "qrec", "[", "\"E.\"", "+", "v", "]", "=", "0", "records", ".", "append", "(", "qrec", ")", "if", "records", ":", "df", "=", "pandas", ".", "DataFrame", "(", "records", ",", "columns", "=", "cols", ")", "else", ":", "df", "=", "pandas", ".", "DataFrame", "(", "columns", "=", "cols", ")", "return", "df" ]
https://github.com/Illumina/hap.py/blob/84011695b2ff2406c16a335106db6831fb67fdfe/src/python/Somatic/Strelka.py#L267-L507
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pycc/platform.py
python
Toolchain.get_python_library_dirs
(self)
return list(self._py_lib_dirs) + self._math_info['library_dirs']
Get the library directories necessary to link with Python.
Get the library directories necessary to link with Python.
[ "Get", "the", "library", "directories", "necessary", "to", "link", "with", "Python", "." ]
def get_python_library_dirs(self): """ Get the library directories necessary to link with Python. """ return list(self._py_lib_dirs) + self._math_info['library_dirs']
[ "def", "get_python_library_dirs", "(", "self", ")", ":", "return", "list", "(", "self", ".", "_py_lib_dirs", ")", "+", "self", ".", "_math_info", "[", "'library_dirs'", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pycc/platform.py#L173-L177
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibook.py
python
AuiTabCtrl.OnEraseBackground
(self, event)
Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`AuiTabCtrl`. :param `event`: a :class:`EraseEvent` event to be processed. :note: This is intentionally empty, to reduce flicker.
Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`AuiTabCtrl`.
[ "Handles", "the", "wx", ".", "EVT_ERASE_BACKGROUND", "event", "for", ":", "class", ":", "AuiTabCtrl", "." ]
def OnEraseBackground(self, event): """ Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`AuiTabCtrl`. :param `event`: a :class:`EraseEvent` event to be processed. :note: This is intentionally empty, to reduce flicker. """ pass
[ "def", "OnEraseBackground", "(", "self", ",", "event", ")", ":", "pass" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L1851-L1860
facebook/proxygen
a9ca025af207787815cb01eee1971cd572c7a81e
build/fbcode_builder/shell_quoting.py
python
shell_quote
(s)
return ( s if isinstance(s, ShellQuoted) else ShellQuoted("'" + str(s).replace("'", "'\\''") + "'") )
Quotes a string if it is not already quoted
Quotes a string if it is not already quoted
[ "Quotes", "a", "string", "if", "it", "is", "not", "already", "quoted" ]
def shell_quote(s): "Quotes a string if it is not already quoted" return ( s if isinstance(s, ShellQuoted) else ShellQuoted("'" + str(s).replace("'", "'\\''") + "'") )
[ "def", "shell_quote", "(", "s", ")", ":", "return", "(", "s", "if", "isinstance", "(", "s", ",", "ShellQuoted", ")", "else", "ShellQuoted", "(", "\"'\"", "+", "str", "(", "s", ")", ".", "replace", "(", "\"'\"", ",", "\"'\\\\''\"", ")", "+", "\"'\"", ")", ")" ]
https://github.com/facebook/proxygen/blob/a9ca025af207787815cb01eee1971cd572c7a81e/build/fbcode_builder/shell_quoting.py#L68-L74
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintsbasisset.py
python
BasisSet.zero_ao_basis_set
()
return BasisSet()
Returns an empty basis set object. Returns a BasisSet object that actually has a single s-function at the origin with an exponent of 0.0 and contraction of 1.0. * @return A new empty BasisSet object.
Returns an empty basis set object. Returns a BasisSet object that actually has a single s-function at the origin with an exponent of 0.0 and contraction of 1.0. * @return A new empty BasisSet object.
[ "Returns", "an", "empty", "basis", "set", "object", ".", "Returns", "a", "BasisSet", "object", "that", "actually", "has", "a", "single", "s", "-", "function", "at", "the", "origin", "with", "an", "exponent", "of", "0", ".", "0", "and", "contraction", "of", "1", ".", "0", ".", "*", "@return", "A", "new", "empty", "BasisSet", "object", "." ]
def zero_ao_basis_set(): """Returns an empty basis set object. Returns a BasisSet object that actually has a single s-function at the origin with an exponent of 0.0 and contraction of 1.0. * @return A new empty BasisSet object. """ # In the new implementation, we simply call the default constructor return BasisSet()
[ "def", "zero_ao_basis_set", "(", ")", ":", "# In the new implementation, we simply call the default constructor", "return", "BasisSet", "(", ")" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintsbasisset.py#L494-L502
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/examples/python/crashlog.py
python
Interactive.do_quit
(self, line)
return True
Quit command
Quit command
[ "Quit", "command" ]
def do_quit(self, line): '''Quit command''' return True
[ "def", "do_quit", "(", "self", ",", "line", ")", ":", "return", "True" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/examples/python/crashlog.py#L582-L584
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/mixture/_bayesian_mixture.py
python
BayesianGaussianMixture._estimate_wishart_tied
(self, nk, xk, sk)
Estimate the tied Wishart distribution parameters. Parameters ---------- X : array-like, shape (n_samples, n_features) nk : array-like, shape (n_components,) xk : array-like, shape (n_components, n_features) sk : array-like, shape (n_features, n_features)
Estimate the tied Wishart distribution parameters.
[ "Estimate", "the", "tied", "Wishart", "distribution", "parameters", "." ]
def _estimate_wishart_tied(self, nk, xk, sk): """Estimate the tied Wishart distribution parameters. Parameters ---------- X : array-like, shape (n_samples, n_features) nk : array-like, shape (n_components,) xk : array-like, shape (n_components, n_features) sk : array-like, shape (n_features, n_features) """ _, n_features = xk.shape # Warning : in some Bishop book, there is a typo on the formula 10.63 # `degrees_of_freedom_k = degrees_of_freedom_0 + Nk` # is the correct formula self.degrees_of_freedom_ = ( self.degrees_of_freedom_prior_ + nk.sum() / self.n_components) diff = xk - self.mean_prior_ self.covariances_ = ( self.covariance_prior_ + sk * nk.sum() / self.n_components + self.mean_precision_prior_ / self.n_components * np.dot( (nk / self.mean_precision_) * diff.T, diff)) # Contrary to the original bishop book, we normalize the covariances self.covariances_ /= self.degrees_of_freedom_
[ "def", "_estimate_wishart_tied", "(", "self", ",", "nk", ",", "xk", ",", "sk", ")", ":", "_", ",", "n_features", "=", "xk", ".", "shape", "# Warning : in some Bishop book, there is a typo on the formula 10.63", "# `degrees_of_freedom_k = degrees_of_freedom_0 + Nk`", "# is the correct formula", "self", ".", "degrees_of_freedom_", "=", "(", "self", ".", "degrees_of_freedom_prior_", "+", "nk", ".", "sum", "(", ")", "/", "self", ".", "n_components", ")", "diff", "=", "xk", "-", "self", ".", "mean_prior_", "self", ".", "covariances_", "=", "(", "self", ".", "covariance_prior_", "+", "sk", "*", "nk", ".", "sum", "(", ")", "/", "self", ".", "n_components", "+", "self", ".", "mean_precision_prior_", "/", "self", ".", "n_components", "*", "np", ".", "dot", "(", "(", "nk", "/", "self", ".", "mean_precision_", ")", "*", "diff", ".", "T", ",", "diff", ")", ")", "# Contrary to the original bishop book, we normalize the covariances", "self", ".", "covariances_", "/=", "self", ".", "degrees_of_freedom_" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/mixture/_bayesian_mixture.py#L562-L590
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
MenuItem.GetFont
(*args, **kwargs)
return _core_.MenuItem_GetFont(*args, **kwargs)
GetFont(self) -> Font
GetFont(self) -> Font
[ "GetFont", "(", "self", ")", "-", ">", "Font" ]
def GetFont(*args, **kwargs): """GetFont(self) -> Font""" return _core_.MenuItem_GetFont(*args, **kwargs)
[ "def", "GetFont", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MenuItem_GetFont", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L12561-L12563
eclipse/omr
056e7c9ce9d503649190bc5bd9931fac30b4e4bc
jitbuilder/apigen/cppgen.py
python
CppGenerator.get_impl_class_name
(self, c)
return "TR::{}".format(self.get_class_name(c))
Returns the name of a given class in the JitBuilder implementation, prefixed with the name of all containing classes.
Returns the name of a given class in the JitBuilder implementation, prefixed with the name of all containing classes.
[ "Returns", "the", "name", "of", "a", "given", "class", "in", "the", "JitBuilder", "implementation", "prefixed", "with", "the", "name", "of", "all", "containing", "classes", "." ]
def get_impl_class_name(self, c): """ Returns the name of a given class in the JitBuilder implementation, prefixed with the name of all containing classes. """ return "TR::{}".format(self.get_class_name(c))
[ "def", "get_impl_class_name", "(", "self", ",", "c", ")", ":", "return", "\"TR::{}\"", ".", "format", "(", "self", ".", "get_class_name", "(", "c", ")", ")" ]
https://github.com/eclipse/omr/blob/056e7c9ce9d503649190bc5bd9931fac30b4e4bc/jitbuilder/apigen/cppgen.py#L140-L145
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pathlib2/pathlib2/__init__.py
python
Path.write_text
(self, data, encoding=None, errors=None)
Open the file in text mode, write to it, and close the file.
Open the file in text mode, write to it, and close the file.
[ "Open", "the", "file", "in", "text", "mode", "write", "to", "it", "and", "close", "the", "file", "." ]
def write_text(self, data, encoding=None, errors=None): """ Open the file in text mode, write to it, and close the file. """ if not isinstance(data, six.text_type): raise TypeError( 'data must be %s, not %s' % (six.text_type.__name__, data.__class__.__name__)) with self.open(mode='w', encoding=encoding, errors=errors) as f: return f.write(data)
[ "def", "write_text", "(", "self", ",", "data", ",", "encoding", "=", "None", ",", "errors", "=", "None", ")", ":", "if", "not", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", ":", "raise", "TypeError", "(", "'data must be %s, not %s'", "%", "(", "six", ".", "text_type", ".", "__name__", ",", "data", ".", "__class__", ".", "__name__", ")", ")", "with", "self", ".", "open", "(", "mode", "=", "'w'", ",", "encoding", "=", "encoding", ",", "errors", "=", "errors", ")", "as", "f", ":", "return", "f", ".", "write", "(", "data", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pathlib2/pathlib2/__init__.py#L1504-L1513
google-coral/edgetpu
5020de9386ff370dcc1f63291a2d0f98eeb98adb
edgetpu/learn/imprinting/engine.py
python
ImprintingEngine.__init__
(self, model_path, keep_classes=False)
Args: model_path (str): Path to the model you want to retrain. This model must be a ``.tflite`` file output by the ``join_tflite_models`` tool. For more information about how to create a compatible model, read `Retrain an image classification model on-device <https://coral.ai/docs/edgetpu/retrain-classification-ondevice/>`_. keep_classes (bool): If True, keep the existing classes from the pre-trained model (and use training to add additional classes). If False, drop the existing classes and train the model to include new classes only.
Args: model_path (str): Path to the model you want to retrain. This model must be a ``.tflite`` file output by the ``join_tflite_models`` tool. For more information about how to create a compatible model, read `Retrain an image classification model on-device <https://coral.ai/docs/edgetpu/retrain-classification-ondevice/>`_. keep_classes (bool): If True, keep the existing classes from the pre-trained model (and use training to add additional classes). If False, drop the existing classes and train the model to include new classes only.
[ "Args", ":", "model_path", "(", "str", ")", ":", "Path", "to", "the", "model", "you", "want", "to", "retrain", ".", "This", "model", "must", "be", "a", ".", "tflite", "file", "output", "by", "the", "join_tflite_models", "tool", ".", "For", "more", "information", "about", "how", "to", "create", "a", "compatible", "model", "read", "Retrain", "an", "image", "classification", "model", "on", "-", "device", "<https", ":", "//", "coral", ".", "ai", "/", "docs", "/", "edgetpu", "/", "retrain", "-", "classification", "-", "ondevice", "/", ">", "_", ".", "keep_classes", "(", "bool", ")", ":", "If", "True", "keep", "the", "existing", "classes", "from", "the", "pre", "-", "trained", "model", "(", "and", "use", "training", "to", "add", "additional", "classes", ")", ".", "If", "False", "drop", "the", "existing", "classes", "and", "train", "the", "model", "to", "include", "new", "classes", "only", "." ]
def __init__(self, model_path, keep_classes=False): """ Args: model_path (str): Path to the model you want to retrain. This model must be a ``.tflite`` file output by the ``join_tflite_models`` tool. For more information about how to create a compatible model, read `Retrain an image classification model on-device <https://coral.ai/docs/edgetpu/retrain-classification-ondevice/>`_. keep_classes (bool): If True, keep the existing classes from the pre-trained model (and use training to add additional classes). If False, drop the existing classes and train the model to include new classes only. """ self._engine = ImprintingEnginePythonWrapper.CreateFromFile( model_path, keep_classes) self._num_classes = 0 if keep_classes: tmp = BasicEngine(model_path) assert tmp.get_num_of_output_tensors() == 1 self._num_classes = tmp.total_output_array_size()
[ "def", "__init__", "(", "self", ",", "model_path", ",", "keep_classes", "=", "False", ")", ":", "self", ".", "_engine", "=", "ImprintingEnginePythonWrapper", ".", "CreateFromFile", "(", "model_path", ",", "keep_classes", ")", "self", ".", "_num_classes", "=", "0", "if", "keep_classes", ":", "tmp", "=", "BasicEngine", "(", "model_path", ")", "assert", "tmp", ".", "get_num_of_output_tensors", "(", ")", "==", "1", "self", ".", "_num_classes", "=", "tmp", ".", "total_output_array_size", "(", ")" ]
https://github.com/google-coral/edgetpu/blob/5020de9386ff370dcc1f63291a2d0f98eeb98adb/edgetpu/learn/imprinting/engine.py#L54-L71
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBDebugger.GetFormatForType
(self, *args)
return _lldb.SBDebugger_GetFormatForType(self, *args)
GetFormatForType(self, SBTypeNameSpecifier arg0) -> SBTypeFormat
GetFormatForType(self, SBTypeNameSpecifier arg0) -> SBTypeFormat
[ "GetFormatForType", "(", "self", "SBTypeNameSpecifier", "arg0", ")", "-", ">", "SBTypeFormat" ]
def GetFormatForType(self, *args): """GetFormatForType(self, SBTypeNameSpecifier arg0) -> SBTypeFormat""" return _lldb.SBDebugger_GetFormatForType(self, *args)
[ "def", "GetFormatForType", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBDebugger_GetFormatForType", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L3507-L3509
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/externals/_pep562.py
python
Pep562.__getattr__
(self, name)
Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present.
Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present.
[ "Attempt", "to", "retrieve", "the", "attribute", "from", "the", "module", "and", "if", "missing", "use", "the", "overridden", "function", "if", "present", "." ]
def __getattr__(self, name): """Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present.""" try: return getattr(self._module, name) except AttributeError: if self._get_attr: return self._get_attr(name) raise
[ "def", "__getattr__", "(", "self", ",", "name", ")", ":", "try", ":", "return", "getattr", "(", "self", ".", "_module", ",", "name", ")", "except", "AttributeError", ":", "if", "self", ".", "_get_attr", ":", "return", "self", ".", "_get_attr", "(", "name", ")", "raise" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/externals/_pep562.py#L50-L58
s9xie/hed
94fb22f10cbfec8d84fbc0642b224022014b6bd6
scripts/cpp_lint.py
python
_NestingState.InNamespaceBody
(self)
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise.
Check if we are currently one level inside a namespace body.
[ "Check", "if", "we", "are", "currently", "one", "level", "inside", "a", "namespace", "body", "." ]
def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
[ "def", "InNamespaceBody", "(", "self", ")", ":", "return", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_NamespaceInfo", ")" ]
https://github.com/s9xie/hed/blob/94fb22f10cbfec8d84fbc0642b224022014b6bd6/scripts/cpp_lint.py#L1940-L1946
deepmind/reverb
ef3c8f0be1b720a741d2dee335e15e44668c291a
reverb/trajectory_dataset.py
python
TrajectoryDataset.from_table_signature
(cls, server_address: str, table: str, max_in_flight_samples_per_worker: int, num_workers_per_iterator: int = -1, max_samples_per_stream: int = -1, rate_limiter_timeout_ms: int = -1, get_signature_timeout_secs: Optional[int] = None, max_samples: int = -1)
return cls( server_address=server_address, table=table, shapes=shapes, dtypes=dtypes, max_in_flight_samples_per_worker=max_in_flight_samples_per_worker, num_workers_per_iterator=num_workers_per_iterator, max_samples_per_stream=max_samples_per_stream, rate_limiter_timeout_ms=rate_limiter_timeout_ms, max_samples=max_samples)
Constructs a TrajectoryDataset using the table's signature to infer specs. Note: The target `Table` must specify a signature which represent the entire trajectory (as opposed to a single timestep). See `Table.__init__` (./server.py) for more details. Args: server_address: Address of gRPC ReverbService. table: Table to read the signature and sample from. max_in_flight_samples_per_worker: See __init__ for details. num_workers_per_iterator: See __init__ for details. max_samples_per_stream: See __init__ for details. rate_limiter_timeout_ms: See __init__ for details. get_signature_timeout_secs: Timeout in seconds to wait for server to respond when fetching the table signature. By default no timeout is set and the call will block indefinitely if the server does not respond. max_samples: See __init__ for details. Returns: TrajectoryDataset using the specs defined by the table signature to build `shapes` and `dtypes`. Raises: ValueError: If `table` does not exist on server at `server_address`. ValueError: If `table` does not have a signature. errors.DeadlineExceededError: If `get_signature_timeout_secs` provided and exceeded. ValueError: See __init__.
Constructs a TrajectoryDataset using the table's signature to infer specs.
[ "Constructs", "a", "TrajectoryDataset", "using", "the", "table", "s", "signature", "to", "infer", "specs", "." ]
def from_table_signature(cls, server_address: str, table: str, max_in_flight_samples_per_worker: int, num_workers_per_iterator: int = -1, max_samples_per_stream: int = -1, rate_limiter_timeout_ms: int = -1, get_signature_timeout_secs: Optional[int] = None, max_samples: int = -1): """Constructs a TrajectoryDataset using the table's signature to infer specs. Note: The target `Table` must specify a signature which represent the entire trajectory (as opposed to a single timestep). See `Table.__init__` (./server.py) for more details. Args: server_address: Address of gRPC ReverbService. table: Table to read the signature and sample from. max_in_flight_samples_per_worker: See __init__ for details. num_workers_per_iterator: See __init__ for details. max_samples_per_stream: See __init__ for details. rate_limiter_timeout_ms: See __init__ for details. get_signature_timeout_secs: Timeout in seconds to wait for server to respond when fetching the table signature. By default no timeout is set and the call will block indefinitely if the server does not respond. max_samples: See __init__ for details. Returns: TrajectoryDataset using the specs defined by the table signature to build `shapes` and `dtypes`. Raises: ValueError: If `table` does not exist on server at `server_address`. ValueError: If `table` does not have a signature. errors.DeadlineExceededError: If `get_signature_timeout_secs` provided and exceeded. ValueError: See __init__. """ client = reverb_client.Client(server_address) info = client.server_info(get_signature_timeout_secs) if table not in info: raise ValueError( f'Server at {server_address} does not contain any table named ' f'{table}. Found: {", ".join(sorted(info.keys()))}.') if not info[table].signature: raise ValueError( f'Table {table} at {server_address} does not have a signature.') shapes = tree.map_structure(lambda x: x.shape, info[table].signature) dtypes = tree.map_structure(lambda x: x.dtype, info[table].signature) return cls( server_address=server_address, table=table, shapes=shapes, dtypes=dtypes, max_in_flight_samples_per_worker=max_in_flight_samples_per_worker, num_workers_per_iterator=num_workers_per_iterator, max_samples_per_stream=max_samples_per_stream, rate_limiter_timeout_ms=rate_limiter_timeout_ms, max_samples=max_samples)
[ "def", "from_table_signature", "(", "cls", ",", "server_address", ":", "str", ",", "table", ":", "str", ",", "max_in_flight_samples_per_worker", ":", "int", ",", "num_workers_per_iterator", ":", "int", "=", "-", "1", ",", "max_samples_per_stream", ":", "int", "=", "-", "1", ",", "rate_limiter_timeout_ms", ":", "int", "=", "-", "1", ",", "get_signature_timeout_secs", ":", "Optional", "[", "int", "]", "=", "None", ",", "max_samples", ":", "int", "=", "-", "1", ")", ":", "client", "=", "reverb_client", ".", "Client", "(", "server_address", ")", "info", "=", "client", ".", "server_info", "(", "get_signature_timeout_secs", ")", "if", "table", "not", "in", "info", ":", "raise", "ValueError", "(", "f'Server at {server_address} does not contain any table named '", "f'{table}. Found: {\", \".join(sorted(info.keys()))}.'", ")", "if", "not", "info", "[", "table", "]", ".", "signature", ":", "raise", "ValueError", "(", "f'Table {table} at {server_address} does not have a signature.'", ")", "shapes", "=", "tree", ".", "map_structure", "(", "lambda", "x", ":", "x", ".", "shape", ",", "info", "[", "table", "]", ".", "signature", ")", "dtypes", "=", "tree", ".", "map_structure", "(", "lambda", "x", ":", "x", ".", "dtype", ",", "info", "[", "table", "]", ".", "signature", ")", "return", "cls", "(", "server_address", "=", "server_address", ",", "table", "=", "table", ",", "shapes", "=", "shapes", ",", "dtypes", "=", "dtypes", ",", "max_in_flight_samples_per_worker", "=", "max_in_flight_samples_per_worker", ",", "num_workers_per_iterator", "=", "num_workers_per_iterator", ",", "max_samples_per_stream", "=", "max_samples_per_stream", ",", "rate_limiter_timeout_ms", "=", "rate_limiter_timeout_ms", ",", "max_samples", "=", "max_samples", ")" ]
https://github.com/deepmind/reverb/blob/ef3c8f0be1b720a741d2dee335e15e44668c291a/reverb/trajectory_dataset.py#L149-L210
wujixiu/helmet-detection
8eff5c59ddfba5a29e0b76aeb48babcb49246178
old-version/ssd_vgg.py
python
CaffeDetection.detect
(self, image_file, conf_thresh=0.2, topn=20)
return result
SSD detection
SSD detection
[ "SSD", "detection" ]
def detect(self, image_file, conf_thresh=0.2, topn=20): ''' SSD detection ''' # set net to batch size of 1 # image_resize = 300 image = caffe.io.load_image(image_file) self.net.blobs['data'].reshape(1, 3, self.image_resize, self.image_resize) #Run the net and examine the top_k results transformed_image = self.transformer.preprocess('data', image) self.net.blobs['data'].data[...] = transformed_image # Forward pass. detections = self.net.forward()['detection_out'] # Parse the outputs. det_label = detections[0,0,:,1] det_conf = detections[0,0,:,2] det_xmin = detections[0,0,:,3] det_ymin = detections[0,0,:,4] det_xmax = detections[0,0,:,5] det_ymax = detections[0,0,:,6] # Get detections with confidence higher than 0.6. top_indices = [i for i, conf in enumerate(det_conf) if conf >= conf_thresh] top_conf = det_conf[top_indices] top_label_indices = det_label[top_indices].tolist() top_labels = get_labelname(self.labelmap, top_label_indices) top_xmin = det_xmin[top_indices] top_ymin = det_ymin[top_indices] top_xmax = det_xmax[top_indices] top_ymax = det_ymax[top_indices] result = [] for i in xrange(min(topn, top_conf.shape[0])): xmin = top_xmin[i] # xmin = int(round(top_xmin[i] * image.shape[1])) ymin = top_ymin[i] # ymin = int(round(top_ymin[i] * image.shape[0])) xmax = top_xmax[i] # xmax = int(round(top_xmax[i] * image.shape[1])) ymax = top_ymax[i] # ymax = int(round(top_ymax[i] * image.shape[0])) score = top_conf[i] label = int(top_label_indices[i]) label_name = top_labels[i] result.append([xmin, ymin, xmax, ymax, label, score, label_name]) return result
[ "def", "detect", "(", "self", ",", "image_file", ",", "conf_thresh", "=", "0.2", ",", "topn", "=", "20", ")", ":", "# set net to batch size of 1", "# image_resize = 300", "image", "=", "caffe", ".", "io", ".", "load_image", "(", "image_file", ")", "self", ".", "net", ".", "blobs", "[", "'data'", "]", ".", "reshape", "(", "1", ",", "3", ",", "self", ".", "image_resize", ",", "self", ".", "image_resize", ")", "#Run the net and examine the top_k results", "transformed_image", "=", "self", ".", "transformer", ".", "preprocess", "(", "'data'", ",", "image", ")", "self", ".", "net", ".", "blobs", "[", "'data'", "]", ".", "data", "[", "...", "]", "=", "transformed_image", "# Forward pass.", "detections", "=", "self", ".", "net", ".", "forward", "(", ")", "[", "'detection_out'", "]", "# Parse the outputs.", "det_label", "=", "detections", "[", "0", ",", "0", ",", ":", ",", "1", "]", "det_conf", "=", "detections", "[", "0", ",", "0", ",", ":", ",", "2", "]", "det_xmin", "=", "detections", "[", "0", ",", "0", ",", ":", ",", "3", "]", "det_ymin", "=", "detections", "[", "0", ",", "0", ",", ":", ",", "4", "]", "det_xmax", "=", "detections", "[", "0", ",", "0", ",", ":", ",", "5", "]", "det_ymax", "=", "detections", "[", "0", ",", "0", ",", ":", ",", "6", "]", "# Get detections with confidence higher than 0.6.", "top_indices", "=", "[", "i", "for", "i", ",", "conf", "in", "enumerate", "(", "det_conf", ")", "if", "conf", ">=", "conf_thresh", "]", "top_conf", "=", "det_conf", "[", "top_indices", "]", "top_label_indices", "=", "det_label", "[", "top_indices", "]", ".", "tolist", "(", ")", "top_labels", "=", "get_labelname", "(", "self", ".", "labelmap", ",", "top_label_indices", ")", "top_xmin", "=", "det_xmin", "[", "top_indices", "]", "top_ymin", "=", "det_ymin", "[", "top_indices", "]", "top_xmax", "=", "det_xmax", "[", "top_indices", "]", "top_ymax", "=", "det_ymax", "[", "top_indices", "]", "result", "=", "[", "]", "for", "i", "in", "xrange", "(", "min", "(", "topn", ",", "top_conf", ".", "shape", "[", "0", "]", ")", ")", ":", "xmin", "=", "top_xmin", "[", "i", "]", "# xmin = int(round(top_xmin[i] * image.shape[1]))", "ymin", "=", "top_ymin", "[", "i", "]", "# ymin = int(round(top_ymin[i] * image.shape[0]))", "xmax", "=", "top_xmax", "[", "i", "]", "# xmax = int(round(top_xmax[i] * image.shape[1]))", "ymax", "=", "top_ymax", "[", "i", "]", "# ymax = int(round(top_ymax[i] * image.shape[0]))", "score", "=", "top_conf", "[", "i", "]", "label", "=", "int", "(", "top_label_indices", "[", "i", "]", ")", "label_name", "=", "top_labels", "[", "i", "]", "result", ".", "append", "(", "[", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", ",", "label", ",", "score", ",", "label_name", "]", ")", "return", "result" ]
https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/old-version/ssd_vgg.py#L66-L112
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/eslint.py
python
_lint_files
(eslint, files)
return True
Lint a list of files with ESLint
Lint a list of files with ESLint
[ "Lint", "a", "list", "of", "files", "with", "ESLint" ]
def _lint_files(eslint, files): """Lint a list of files with ESLint """ eslint = ESLint(eslint, _get_build_dir()) lint_clean = parallel.parallel_process([os.path.abspath(f) for f in files], eslint.lint) if not lint_clean: print("ERROR: ESLint found errors. Run ESLint manually to see errors in "\ "files that were skipped") sys.exit(1) return True
[ "def", "_lint_files", "(", "eslint", ",", "files", ")", ":", "eslint", "=", "ESLint", "(", "eslint", ",", "_get_build_dir", "(", ")", ")", "lint_clean", "=", "parallel", ".", "parallel_process", "(", "[", "os", ".", "path", ".", "abspath", "(", "f", ")", "for", "f", "in", "files", "]", ",", "eslint", ".", "lint", ")", "if", "not", "lint_clean", ":", "print", "(", "\"ERROR: ESLint found errors. Run ESLint manually to see errors in \"", "\"files that were skipped\"", ")", "sys", ".", "exit", "(", "1", ")", "return", "True" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/eslint.py#L203-L215
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/multi.py
python
MultiIndex._is_memory_usage_qualified
(self)
return any(f(level) for level in self._inferred_type_levels)
return a boolean if we need a qualified .info display
return a boolean if we need a qualified .info display
[ "return", "a", "boolean", "if", "we", "need", "a", "qualified", ".", "info", "display" ]
def _is_memory_usage_qualified(self) -> bool: """return a boolean if we need a qualified .info display""" def f(level): return "mixed" in level or "string" in level or "unicode" in level return any(f(level) for level in self._inferred_type_levels)
[ "def", "_is_memory_usage_qualified", "(", "self", ")", "->", "bool", ":", "def", "f", "(", "level", ")", ":", "return", "\"mixed\"", "in", "level", "or", "\"string\"", "in", "level", "or", "\"unicode\"", "in", "level", "return", "any", "(", "f", "(", "level", ")", "for", "level", "in", "self", ".", "_inferred_type_levels", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/multi.py#L1228-L1234
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/syndata.py
python
SyntaxDataBase.GetProperties
(self)
return list()
Get the Properties List @return: list of tuples [('fold', '1'),]
Get the Properties List @return: list of tuples [('fold', '1'),]
[ "Get", "the", "Properties", "List", "@return", ":", "list", "of", "tuples", "[", "(", "fold", "1", ")", "]" ]
def GetProperties(self): """Get the Properties List @return: list of tuples [('fold', '1'),] """ return list()
[ "def", "GetProperties", "(", "self", ")", ":", "return", "list", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/syndata.py#L96-L101
may0324/DeepCompression-caffe
0aff6c1287bda4cfc7f378ed8a16524e1afabd8c
scripts/cpp_lint.py
python
_CppLintState.SetVerboseLevel
(self, level)
return last_verbose_level
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level
[ "def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level" ]
https://github.com/may0324/DeepCompression-caffe/blob/0aff6c1287bda4cfc7f378ed8a16524e1afabd8c/scripts/cpp_lint.py#L707-L711
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/layer/normalization.py
python
_BatchNorm.__init__
(self, num_features, eps=1e-5, momentum=0.9, affine=True, gamma_init='ones', beta_init='zeros', moving_mean_init='zeros', moving_var_init='ones', use_batch_statistics=None, device_num_each_group=1, process_groups=0, input_dims='2d', data_format='NCHW')
Initialize _BatchNorm.
Initialize _BatchNorm.
[ "Initialize", "_BatchNorm", "." ]
def __init__(self, num_features, eps=1e-5, momentum=0.9, affine=True, gamma_init='ones', beta_init='zeros', moving_mean_init='zeros', moving_var_init='ones', use_batch_statistics=None, device_num_each_group=1, process_groups=0, input_dims='2d', data_format='NCHW'): """Initialize _BatchNorm.""" super(_BatchNorm, self).__init__() validator.check_value_type('num_features', num_features, [int], self.cls_name) if num_features < 1: raise ValueError(f"For '{self.cls_name}', the 'num_features' must be at least 1, but got {num_features}.") if momentum < 0 or momentum > 1: raise ValueError(f"For '{self.cls_name}', the 'momentum' should be a number in range [0, 1], " f"but got {momentum}.") self.input_dims = input_dims self.format = validator.check_string(data_format, ['NCHW', 'NHWC'], 'format', self.cls_name) if context.get_context("device_target") != "GPU" and self.format == "NHWC": raise ValueError(f"For '{self.cls_name}', the 'NHWC' format only support in GPU target, but got device " f"target {context.get_context('device_target')}.") self.use_batch_statistics = use_batch_statistics if self.use_batch_statistics is not None and not isinstance(self.use_batch_statistics, bool): raise ValueError(f"For '{self.cls_name}', the 'use_batch_statistics' should be a boolean value or None," f" but got {use_batch_statistics}.") self.num_features = num_features self.eps = eps self.moving_mean = Parameter(initializer( moving_mean_init, num_features), name="mean", requires_grad=False) self.moving_variance = Parameter(initializer( moving_var_init, num_features), name="variance", requires_grad=False) self.gamma = Parameter(initializer( gamma_init, num_features), name="gamma", requires_grad=affine) self.beta = Parameter(initializer( beta_init, num_features), name="beta", requires_grad=affine) self.group_device_num = validator.check_positive_int(device_num_each_group, "device_num_each_group", self.cls_name) self.process_groups = process_groups self.is_global = False self.parallel_mode = context.get_auto_parallel_context("parallel_mode") global SYNC_BN_GROUP_NAME # for GlobalBatchNorm if self.group_device_num != 1: self.rank_id = get_rank() self.rank_size = get_group_size() self.device_list = [i for i in range(0, self.rank_size)] self.rank_list = self.list_group(self.device_list, self.group_device_num) self.rank_list_idx = len(self.rank_list) self._create_global_groups() # for SyncBatchNorm if self.process_groups != 0: self.rank_id = get_rank() self.rank_size = get_group_size() if self.process_groups is not None: validator.check_isinstance("process_groups", self.process_groups, list) self._check_rank_ids(self.process_groups, self.rank_size) self._create_sync_groups() elif self.rank_size > 1: self.is_global = True self.group_device_num = self.rank_size self.device_list = [i for i in range(0, self.rank_size)] if context.get_context("device_target") == "Ascend": if SYNC_BN_GROUP_NAME == "": SYNC_BN_GROUP_NAME = "sync_bn_group0" management.create_group(SYNC_BN_GROUP_NAME, self.device_list) elif context.get_context("device_target") == "GPU": if SYNC_BN_GROUP_NAME == "": SYNC_BN_GROUP_NAME = "nccl_world_group" self.shape = P.Shape() self.reduce_mean = P.ReduceMean(keep_dims=True) self.square = P.Square() self.sqrt = P.Sqrt() self.cast = P.Cast() self.dtype = P.DType() self.reshape = P.Reshape() self._target = context.get_context("device_target") self.is_graph_mode = context.get_context("mode") == context.GRAPH_MODE self.momentum = 1.0 - momentum if context.get_context("enable_ge"): self.is_ge_backend = True else: self.is_ge_backend = False self.bn_train = P.BatchNorm(is_training=True, epsilon=self.eps, momentum=self.momentum, data_format=self.format) if self.is_global: self.bn_train = inner.SyncBatchNorm(epsilon=self.eps, momentum=self.momentum, group=SYNC_BN_GROUP_NAME, device_num=self.group_device_num) self.bn_infer = P.BatchNorm(is_training=False, epsilon=self.eps, data_format=self.format) if _is_in_auto_parallel_mode(): data_parallel_strategy = ((1,), (1,)) data_parallel_strategy_one = ((1,), ()) else: data_parallel_strategy = None data_parallel_strategy_one = None self.sub_mean = P.Sub().shard(data_parallel_strategy) self.sub_var = P.Sub().shard(data_parallel_strategy) self.mul_mean = P.Mul().shard(data_parallel_strategy_one) self.mul_var = P.Mul().shard(data_parallel_strategy_one) self.assign_sub_mean = P.AssignSub().shard(data_parallel_strategy) self.assign_sub_var = P.AssignSub().shard(data_parallel_strategy)
[ "def", "__init__", "(", "self", ",", "num_features", ",", "eps", "=", "1e-5", ",", "momentum", "=", "0.9", ",", "affine", "=", "True", ",", "gamma_init", "=", "'ones'", ",", "beta_init", "=", "'zeros'", ",", "moving_mean_init", "=", "'zeros'", ",", "moving_var_init", "=", "'ones'", ",", "use_batch_statistics", "=", "None", ",", "device_num_each_group", "=", "1", ",", "process_groups", "=", "0", ",", "input_dims", "=", "'2d'", ",", "data_format", "=", "'NCHW'", ")", ":", "super", "(", "_BatchNorm", ",", "self", ")", ".", "__init__", "(", ")", "validator", ".", "check_value_type", "(", "'num_features'", ",", "num_features", ",", "[", "int", "]", ",", "self", ".", "cls_name", ")", "if", "num_features", "<", "1", ":", "raise", "ValueError", "(", "f\"For '{self.cls_name}', the 'num_features' must be at least 1, but got {num_features}.\"", ")", "if", "momentum", "<", "0", "or", "momentum", ">", "1", ":", "raise", "ValueError", "(", "f\"For '{self.cls_name}', the 'momentum' should be a number in range [0, 1], \"", "f\"but got {momentum}.\"", ")", "self", ".", "input_dims", "=", "input_dims", "self", ".", "format", "=", "validator", ".", "check_string", "(", "data_format", ",", "[", "'NCHW'", ",", "'NHWC'", "]", ",", "'format'", ",", "self", ".", "cls_name", ")", "if", "context", ".", "get_context", "(", "\"device_target\"", ")", "!=", "\"GPU\"", "and", "self", ".", "format", "==", "\"NHWC\"", ":", "raise", "ValueError", "(", "f\"For '{self.cls_name}', the 'NHWC' format only support in GPU target, but got device \"", "f\"target {context.get_context('device_target')}.\"", ")", "self", ".", "use_batch_statistics", "=", "use_batch_statistics", "if", "self", ".", "use_batch_statistics", "is", "not", "None", "and", "not", "isinstance", "(", "self", ".", "use_batch_statistics", ",", "bool", ")", ":", "raise", "ValueError", "(", "f\"For '{self.cls_name}', the 'use_batch_statistics' should be a boolean value or None,\"", "f\" but got {use_batch_statistics}.\"", ")", "self", ".", "num_features", "=", "num_features", "self", ".", "eps", "=", "eps", "self", ".", "moving_mean", "=", "Parameter", "(", "initializer", "(", "moving_mean_init", ",", "num_features", ")", ",", "name", "=", "\"mean\"", ",", "requires_grad", "=", "False", ")", "self", ".", "moving_variance", "=", "Parameter", "(", "initializer", "(", "moving_var_init", ",", "num_features", ")", ",", "name", "=", "\"variance\"", ",", "requires_grad", "=", "False", ")", "self", ".", "gamma", "=", "Parameter", "(", "initializer", "(", "gamma_init", ",", "num_features", ")", ",", "name", "=", "\"gamma\"", ",", "requires_grad", "=", "affine", ")", "self", ".", "beta", "=", "Parameter", "(", "initializer", "(", "beta_init", ",", "num_features", ")", ",", "name", "=", "\"beta\"", ",", "requires_grad", "=", "affine", ")", "self", ".", "group_device_num", "=", "validator", ".", "check_positive_int", "(", "device_num_each_group", ",", "\"device_num_each_group\"", ",", "self", ".", "cls_name", ")", "self", ".", "process_groups", "=", "process_groups", "self", ".", "is_global", "=", "False", "self", ".", "parallel_mode", "=", "context", ".", "get_auto_parallel_context", "(", "\"parallel_mode\"", ")", "global", "SYNC_BN_GROUP_NAME", "# for GlobalBatchNorm", "if", "self", ".", "group_device_num", "!=", "1", ":", "self", ".", "rank_id", "=", "get_rank", "(", ")", "self", ".", "rank_size", "=", "get_group_size", "(", ")", "self", ".", "device_list", "=", "[", "i", "for", "i", "in", "range", "(", "0", ",", "self", ".", "rank_size", ")", "]", "self", ".", "rank_list", "=", "self", ".", "list_group", "(", "self", ".", "device_list", ",", "self", ".", "group_device_num", ")", "self", ".", "rank_list_idx", "=", "len", "(", "self", ".", "rank_list", ")", "self", ".", "_create_global_groups", "(", ")", "# for SyncBatchNorm", "if", "self", ".", "process_groups", "!=", "0", ":", "self", ".", "rank_id", "=", "get_rank", "(", ")", "self", ".", "rank_size", "=", "get_group_size", "(", ")", "if", "self", ".", "process_groups", "is", "not", "None", ":", "validator", ".", "check_isinstance", "(", "\"process_groups\"", ",", "self", ".", "process_groups", ",", "list", ")", "self", ".", "_check_rank_ids", "(", "self", ".", "process_groups", ",", "self", ".", "rank_size", ")", "self", ".", "_create_sync_groups", "(", ")", "elif", "self", ".", "rank_size", ">", "1", ":", "self", ".", "is_global", "=", "True", "self", ".", "group_device_num", "=", "self", ".", "rank_size", "self", ".", "device_list", "=", "[", "i", "for", "i", "in", "range", "(", "0", ",", "self", ".", "rank_size", ")", "]", "if", "context", ".", "get_context", "(", "\"device_target\"", ")", "==", "\"Ascend\"", ":", "if", "SYNC_BN_GROUP_NAME", "==", "\"\"", ":", "SYNC_BN_GROUP_NAME", "=", "\"sync_bn_group0\"", "management", ".", "create_group", "(", "SYNC_BN_GROUP_NAME", ",", "self", ".", "device_list", ")", "elif", "context", ".", "get_context", "(", "\"device_target\"", ")", "==", "\"GPU\"", ":", "if", "SYNC_BN_GROUP_NAME", "==", "\"\"", ":", "SYNC_BN_GROUP_NAME", "=", "\"nccl_world_group\"", "self", ".", "shape", "=", "P", ".", "Shape", "(", ")", "self", ".", "reduce_mean", "=", "P", ".", "ReduceMean", "(", "keep_dims", "=", "True", ")", "self", ".", "square", "=", "P", ".", "Square", "(", ")", "self", ".", "sqrt", "=", "P", ".", "Sqrt", "(", ")", "self", ".", "cast", "=", "P", ".", "Cast", "(", ")", "self", ".", "dtype", "=", "P", ".", "DType", "(", ")", "self", ".", "reshape", "=", "P", ".", "Reshape", "(", ")", "self", ".", "_target", "=", "context", ".", "get_context", "(", "\"device_target\"", ")", "self", ".", "is_graph_mode", "=", "context", ".", "get_context", "(", "\"mode\"", ")", "==", "context", ".", "GRAPH_MODE", "self", ".", "momentum", "=", "1.0", "-", "momentum", "if", "context", ".", "get_context", "(", "\"enable_ge\"", ")", ":", "self", ".", "is_ge_backend", "=", "True", "else", ":", "self", ".", "is_ge_backend", "=", "False", "self", ".", "bn_train", "=", "P", ".", "BatchNorm", "(", "is_training", "=", "True", ",", "epsilon", "=", "self", ".", "eps", ",", "momentum", "=", "self", ".", "momentum", ",", "data_format", "=", "self", ".", "format", ")", "if", "self", ".", "is_global", ":", "self", ".", "bn_train", "=", "inner", ".", "SyncBatchNorm", "(", "epsilon", "=", "self", ".", "eps", ",", "momentum", "=", "self", ".", "momentum", ",", "group", "=", "SYNC_BN_GROUP_NAME", ",", "device_num", "=", "self", ".", "group_device_num", ")", "self", ".", "bn_infer", "=", "P", ".", "BatchNorm", "(", "is_training", "=", "False", ",", "epsilon", "=", "self", ".", "eps", ",", "data_format", "=", "self", ".", "format", ")", "if", "_is_in_auto_parallel_mode", "(", ")", ":", "data_parallel_strategy", "=", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ")", "data_parallel_strategy_one", "=", "(", "(", "1", ",", ")", ",", "(", ")", ")", "else", ":", "data_parallel_strategy", "=", "None", "data_parallel_strategy_one", "=", "None", "self", ".", "sub_mean", "=", "P", ".", "Sub", "(", ")", ".", "shard", "(", "data_parallel_strategy", ")", "self", ".", "sub_var", "=", "P", ".", "Sub", "(", ")", ".", "shard", "(", "data_parallel_strategy", ")", "self", ".", "mul_mean", "=", "P", ".", "Mul", "(", ")", ".", "shard", "(", "data_parallel_strategy_one", ")", "self", ".", "mul_var", "=", "P", ".", "Mul", "(", ")", ".", "shard", "(", "data_parallel_strategy_one", ")", "self", ".", "assign_sub_mean", "=", "P", ".", "AssignSub", "(", ")", ".", "shard", "(", "data_parallel_strategy", ")", "self", ".", "assign_sub_var", "=", "P", ".", "AssignSub", "(", ")", ".", "shard", "(", "data_parallel_strategy", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/normalization.py#L47-L160
Tencent/TNN
7acca99f54c55747b415a4c57677403eebc7b706
third_party/flatbuffers/python/flatbuffers/builder.py
python
Builder.Place
(self, x, flags)
Place prepends a value specified by `flags` to the Builder, without checking for available space.
Place prepends a value specified by `flags` to the Builder, without checking for available space.
[ "Place", "prepends", "a", "value", "specified", "by", "flags", "to", "the", "Builder", "without", "checking", "for", "available", "space", "." ]
def Place(self, x, flags): """ Place prepends a value specified by `flags` to the Builder, without checking for available space. """ N.enforce_number(x, flags) self.head = self.head - flags.bytewidth encode.Write(flags.packer_type, self.Bytes, self.Head(), x)
[ "def", "Place", "(", "self", ",", "x", ",", "flags", ")", ":", "N", ".", "enforce_number", "(", "x", ",", "flags", ")", "self", ".", "head", "=", "self", ".", "head", "-", "flags", ".", "bytewidth", "encode", ".", "Write", "(", "flags", ".", "packer_type", ",", "self", ".", "Bytes", ",", "self", ".", "Head", "(", ")", ",", "x", ")" ]
https://github.com/Tencent/TNN/blob/7acca99f54c55747b415a4c57677403eebc7b706/third_party/flatbuffers/python/flatbuffers/builder.py#L720-L728
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/mozbuild/mozbuild/makeutil.py
python
Rule.dump
(self, fh)
Dump the rule to the given file handle.
Dump the rule to the given file handle.
[ "Dump", "the", "rule", "to", "the", "given", "file", "handle", "." ]
def dump(self, fh): ''' Dump the rule to the given file handle. ''' if not self._targets: return fh.write('%s:' % ' '.join(self._targets)) if self._dependencies: fh.write(' %s' % ' '.join(self.dependencies())) fh.write('\n') for cmd in self._commands: fh.write('\t%s\n' % cmd)
[ "def", "dump", "(", "self", ",", "fh", ")", ":", "if", "not", "self", ".", "_targets", ":", "return", "fh", ".", "write", "(", "'%s:'", "%", "' '", ".", "join", "(", "self", ".", "_targets", ")", ")", "if", "self", ".", "_dependencies", ":", "fh", ".", "write", "(", "' %s'", "%", "' '", ".", "join", "(", "self", ".", "dependencies", "(", ")", ")", ")", "fh", ".", "write", "(", "'\\n'", ")", "for", "cmd", "in", "self", ".", "_commands", ":", "fh", ".", "write", "(", "'\\t%s\\n'", "%", "cmd", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozbuild/makeutil.py#L134-L145
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py
python
TurtleScreenBase._drawimage
(self, item, (x, y), image)
Configure image item as to draw image object at position (x,y) on canvas)
Configure image item as to draw image object at position (x,y) on canvas)
[ "Configure", "image", "item", "as", "to", "draw", "image", "object", "at", "position", "(", "x", "y", ")", "on", "canvas", ")" ]
def _drawimage(self, item, (x, y), image): """Configure image item as to draw image object at position (x,y) on canvas) """ self.cv.coords(item, (x * self.xscale, -y * self.yscale)) self.cv.itemconfig(item, image=image)
[ "def", "_drawimage", "(", "self", ",", "item", ",", "(", "x", ",", "y", ")", ",", "image", ")", ":", "self", ".", "cv", ".", "coords", "(", "item", ",", "(", "x", "*", "self", ".", "xscale", ",", "-", "y", "*", "self", ".", "yscale", ")", ")", "self", ".", "cv", ".", "itemconfig", "(", "item", ",", "image", "=", "image", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py#L731-L736
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/frontend/context.py
python
SourcePath.translated
(self)
return mozpath.normpath(ret)
Returns the corresponding path in the objdir. Ideally, we wouldn't need this function, but the fact that both source path under topsrcdir and the external source dir end up mixed in the objdir (aka pseudo-rework), this is needed.
Returns the corresponding path in the objdir.
[ "Returns", "the", "corresponding", "path", "in", "the", "objdir", "." ]
def translated(self): """Returns the corresponding path in the objdir. Ideally, we wouldn't need this function, but the fact that both source path under topsrcdir and the external source dir end up mixed in the objdir (aka pseudo-rework), this is needed. """ if self.value.startswith('/'): ret = mozpath.join(self.context.config.topobjdir, self.value[1:]) else: ret = mozpath.join(self.context.objdir, self.value) return mozpath.normpath(ret)
[ "def", "translated", "(", "self", ")", ":", "if", "self", ".", "value", ".", "startswith", "(", "'/'", ")", ":", "ret", "=", "mozpath", ".", "join", "(", "self", ".", "context", ".", "config", ".", "topobjdir", ",", "self", ".", "value", "[", "1", ":", "]", ")", "else", ":", "ret", "=", "mozpath", ".", "join", "(", "self", ".", "context", ".", "objdir", ",", "self", ".", "value", ")", "return", "mozpath", ".", "normpath", "(", "ret", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/frontend/context.py#L329-L340
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/SANSUtility.py
python
CummulativeTimeSeriesPropertyAdder.extract_sample_logs_from_workspace
(self, lhs, rhs)
When adding specific logs, we need to make sure that the values are added correctly. :param lhs: the lhs workspace :param rhs: the rhs workspace
When adding specific logs, we need to make sure that the values are added correctly. :param lhs: the lhs workspace :param rhs: the rhs workspace
[ "When", "adding", "specific", "logs", "we", "need", "to", "make", "sure", "that", "the", "values", "are", "added", "correctly", ".", ":", "param", "lhs", ":", "the", "lhs", "workspace", ":", "param", "rhs", ":", "the", "rhs", "workspace" ]
def extract_sample_logs_from_workspace(self, lhs, rhs): """ When adding specific logs, we need to make sure that the values are added correctly. :param lhs: the lhs workspace :param rhs: the rhs workspace """ run_lhs = lhs.getRun() run_rhs = rhs.getRun() # Get the cumulative time s for element in self._time_series: if (run_lhs.hasProperty(element) and run_rhs.hasProperty(element)): # Get values for lhs property_lhs = run_lhs.getProperty(element) self._original_times_lhs[element] = property_lhs.times self._original_values_lhs[element] = property_lhs.value # Get values for rhs property_rhs = run_rhs.getProperty(element) self._original_times_rhs[element] = property_rhs.times self._original_values_rhs[element] = property_rhs.value for element in self._single_valued: if (run_lhs.hasProperty(element) and run_rhs.hasProperty(element)): # Get the values for lhs property_lhs = run_lhs.getProperty(element) self._original_single_valued_lhs[element] = property_lhs.value # Get the values for rhs property_rhs = run_rhs.getProperty(element) self._original_single_valued_rhs[element] = property_rhs.value log_name_start_time = "start_time" if (run_lhs.hasProperty(log_name_start_time) and run_rhs.hasProperty(log_name_start_time)): def convert_to_date(val): return DateAndTime(val) if isinstance(val, str) else val self._start_time_lhs = convert_to_date(run_lhs.getProperty(log_name_start_time).value) self._start_time_rhs = convert_to_date(run_rhs.getProperty(log_name_start_time).value)
[ "def", "extract_sample_logs_from_workspace", "(", "self", ",", "lhs", ",", "rhs", ")", ":", "run_lhs", "=", "lhs", ".", "getRun", "(", ")", "run_rhs", "=", "rhs", ".", "getRun", "(", ")", "# Get the cumulative time s", "for", "element", "in", "self", ".", "_time_series", ":", "if", "(", "run_lhs", ".", "hasProperty", "(", "element", ")", "and", "run_rhs", ".", "hasProperty", "(", "element", ")", ")", ":", "# Get values for lhs", "property_lhs", "=", "run_lhs", ".", "getProperty", "(", "element", ")", "self", ".", "_original_times_lhs", "[", "element", "]", "=", "property_lhs", ".", "times", "self", ".", "_original_values_lhs", "[", "element", "]", "=", "property_lhs", ".", "value", "# Get values for rhs", "property_rhs", "=", "run_rhs", ".", "getProperty", "(", "element", ")", "self", ".", "_original_times_rhs", "[", "element", "]", "=", "property_rhs", ".", "times", "self", ".", "_original_values_rhs", "[", "element", "]", "=", "property_rhs", ".", "value", "for", "element", "in", "self", ".", "_single_valued", ":", "if", "(", "run_lhs", ".", "hasProperty", "(", "element", ")", "and", "run_rhs", ".", "hasProperty", "(", "element", ")", ")", ":", "# Get the values for lhs", "property_lhs", "=", "run_lhs", ".", "getProperty", "(", "element", ")", "self", ".", "_original_single_valued_lhs", "[", "element", "]", "=", "property_lhs", ".", "value", "# Get the values for rhs", "property_rhs", "=", "run_rhs", ".", "getProperty", "(", "element", ")", "self", ".", "_original_single_valued_rhs", "[", "element", "]", "=", "property_rhs", ".", "value", "log_name_start_time", "=", "\"start_time\"", "if", "(", "run_lhs", ".", "hasProperty", "(", "log_name_start_time", ")", "and", "run_rhs", ".", "hasProperty", "(", "log_name_start_time", ")", ")", ":", "def", "convert_to_date", "(", "val", ")", ":", "return", "DateAndTime", "(", "val", ")", "if", "isinstance", "(", "val", ",", "str", ")", "else", "val", "self", ".", "_start_time_lhs", "=", "convert_to_date", "(", "run_lhs", ".", "getProperty", "(", "log_name_start_time", ")", ".", "value", ")", "self", ".", "_start_time_rhs", "=", "convert_to_date", "(", "run_rhs", ".", "getProperty", "(", "log_name_start_time", ")", ".", "value", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/SANSUtility.py#L1287-L1326
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py
python
IRBuilder.block
(self)
return self._block
The current basic block.
The current basic block.
[ "The", "current", "basic", "block", "." ]
def block(self): """ The current basic block. """ return self._block
[ "def", "block", "(", "self", ")", ":", "return", "self", ".", "_block" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py#L176-L180
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/json_schema_compiler/idl_schema.py
python
Main
()
Dump a json serialization of parse result for the IDL files whose names were passed in on the command line.
Dump a json serialization of parse result for the IDL files whose names were passed in on the command line.
[ "Dump", "a", "json", "serialization", "of", "parse", "result", "for", "the", "IDL", "files", "whose", "names", "were", "passed", "in", "on", "the", "command", "line", "." ]
def Main(): ''' Dump a json serialization of parse result for the IDL files whose names were passed in on the command line. ''' if len(sys.argv) > 1: for filename in sys.argv[1:]: schema = Load(filename) print json.dumps(schema, indent=2) else: contents = sys.stdin.read() idl = idl_parser.IDLParser().ParseData(contents, '<stdin>') schema = IDLSchema(idl).process() print json.dumps(schema, indent=2)
[ "def", "Main", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", ">", "1", ":", "for", "filename", "in", "sys", ".", "argv", "[", "1", ":", "]", ":", "schema", "=", "Load", "(", "filename", ")", "print", "json", ".", "dumps", "(", "schema", ",", "indent", "=", "2", ")", "else", ":", "contents", "=", "sys", ".", "stdin", ".", "read", "(", ")", "idl", "=", "idl_parser", ".", "IDLParser", "(", ")", ".", "ParseData", "(", "contents", ",", "'<stdin>'", ")", "schema", "=", "IDLSchema", "(", "idl", ")", ".", "process", "(", ")", "print", "json", ".", "dumps", "(", "schema", ",", "indent", "=", "2", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_schema_compiler/idl_schema.py#L543-L556
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/support/layer1.py
python
SupportConnection.describe_trusted_advisor_check_summaries
(self, check_ids)
return self.make_request(action='DescribeTrustedAdvisorCheckSummaries', body=json.dumps(params))
Returns the summaries of the results of the Trusted Advisor checks that have the specified check IDs. Check IDs can be obtained by calling DescribeTrustedAdvisorChecks. The response contains an array of TrustedAdvisorCheckSummary objects. :type check_ids: list :param check_ids: The IDs of the Trusted Advisor checks.
Returns the summaries of the results of the Trusted Advisor checks that have the specified check IDs. Check IDs can be obtained by calling DescribeTrustedAdvisorChecks.
[ "Returns", "the", "summaries", "of", "the", "results", "of", "the", "Trusted", "Advisor", "checks", "that", "have", "the", "specified", "check", "IDs", ".", "Check", "IDs", "can", "be", "obtained", "by", "calling", "DescribeTrustedAdvisorChecks", "." ]
def describe_trusted_advisor_check_summaries(self, check_ids): """ Returns the summaries of the results of the Trusted Advisor checks that have the specified check IDs. Check IDs can be obtained by calling DescribeTrustedAdvisorChecks. The response contains an array of TrustedAdvisorCheckSummary objects. :type check_ids: list :param check_ids: The IDs of the Trusted Advisor checks. """ params = {'checkIds': check_ids, } return self.make_request(action='DescribeTrustedAdvisorCheckSummaries', body=json.dumps(params))
[ "def", "describe_trusted_advisor_check_summaries", "(", "self", ",", "check_ids", ")", ":", "params", "=", "{", "'checkIds'", ":", "check_ids", ",", "}", "return", "self", ".", "make_request", "(", "action", "=", "'DescribeTrustedAdvisorCheckSummaries'", ",", "body", "=", "json", ".", "dumps", "(", "params", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/support/layer1.py#L574-L589
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/dev/riscv/HiFive.py
python
HiFive.attachPlic
(self)
Count number of PLIC interrupt sources
Count number of PLIC interrupt sources
[ "Count", "number", "of", "PLIC", "interrupt", "sources" ]
def attachPlic(self): """Count number of PLIC interrupt sources """ plic_srcs = [self.uart_int_id] for device in self._off_chip_devices(): if hasattr(device, "interrupt_id"): plic_srcs.append(device.interrupt_id) self.plic.n_src = max(plic_srcs) + 1
[ "def", "attachPlic", "(", "self", ")", ":", "plic_srcs", "=", "[", "self", ".", "uart_int_id", "]", "for", "device", "in", "self", ".", "_off_chip_devices", "(", ")", ":", "if", "hasattr", "(", "device", ",", "\"interrupt_id\"", ")", ":", "plic_srcs", ".", "append", "(", "device", ".", "interrupt_id", ")", "self", ".", "plic", ".", "n_src", "=", "max", "(", "plic_srcs", ")", "+", "1" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/dev/riscv/HiFive.py#L151-L158
seqan/seqan
f5f658343c366c9c3d44ba358ffc9317e78a09ed
util/py_lib/pyratemp.py
python
escape
(s, format=HTML)
return unicode(s)
Replace special characters by their escape sequence. :Parameters: - `s`: string or unicode-string to escape - `format`: - `NONE`: nothing is replaced - `HTML`: replace &<>'" by &...; - `LATEX`: replace \#$%&_{} (TODO! - this is very incomplete!) :Returns: the escaped string in unicode :Exceptions: - `ValueError`: if `format` is invalid. :TODO: complete LaTeX-escaping, optimize speed
Replace special characters by their escape sequence.
[ "Replace", "special", "characters", "by", "their", "escape", "sequence", "." ]
def escape(s, format=HTML): """Replace special characters by their escape sequence. :Parameters: - `s`: string or unicode-string to escape - `format`: - `NONE`: nothing is replaced - `HTML`: replace &<>'" by &...; - `LATEX`: replace \#$%&_{} (TODO! - this is very incomplete!) :Returns: the escaped string in unicode :Exceptions: - `ValueError`: if `format` is invalid. :TODO: complete LaTeX-escaping, optimize speed """ #Note: If you have to make sure that every character gets replaced # only once (and if you cannot achieve this with the following code), # use something like u"".join([replacedict.get(c,c) for c in s]) # which is about 2-3 times slower (but maybe needs less memory). #Note: This is one of the most time-consuming parts of the template. # So maybe speed this up. if format is None or format == NONE: pass elif format == HTML: s = s.replace(u"&", u"&amp;") # must be done first! s = s.replace(u"<", u"&lt;") s = s.replace(u">", u"&gt;") s = s.replace(u'"', u"&quot;") s = s.replace(u"'", u"&#39;") elif format == LATEX: #TODO: which are the "reserved" characters for LaTeX? # are there more than these? s = s.replace("\\", u"\\backslash{}") #must be done first! s = s.replace("#", u"\\#") s = s.replace("$", u"\\$") s = s.replace("%", u"\\%") s = s.replace("&", u"\\&") s = s.replace("_", u"\\_") s = s.replace("{", u"\\{") s = s.replace("}", u"\\}") else: raise ValueError('Invalid format (only None, HTML and LATEX are supported).') return unicode(s)
[ "def", "escape", "(", "s", ",", "format", "=", "HTML", ")", ":", "#Note: If you have to make sure that every character gets replaced", "# only once (and if you cannot achieve this with the following code),", "# use something like u\"\".join([replacedict.get(c,c) for c in s])", "# which is about 2-3 times slower (but maybe needs less memory).", "#Note: This is one of the most time-consuming parts of the template.", "# So maybe speed this up.", "if", "format", "is", "None", "or", "format", "==", "NONE", ":", "pass", "elif", "format", "==", "HTML", ":", "s", "=", "s", ".", "replace", "(", "u\"&\"", ",", "u\"&amp;\"", ")", "# must be done first!", "s", "=", "s", ".", "replace", "(", "u\"<\"", ",", "u\"&lt;\"", ")", "s", "=", "s", ".", "replace", "(", "u\">\"", ",", "u\"&gt;\"", ")", "s", "=", "s", ".", "replace", "(", "u'\"'", ",", "u\"&quot;\"", ")", "s", "=", "s", ".", "replace", "(", "u\"'\"", ",", "u\"&#39;\"", ")", "elif", "format", "==", "LATEX", ":", "#TODO: which are the \"reserved\" characters for LaTeX?", "# are there more than these?", "s", "=", "s", ".", "replace", "(", "\"\\\\\"", ",", "u\"\\\\backslash{}\"", ")", "#must be done first!", "s", "=", "s", ".", "replace", "(", "\"#\"", ",", "u\"\\\\#\"", ")", "s", "=", "s", ".", "replace", "(", "\"$\"", ",", "u\"\\\\$\"", ")", "s", "=", "s", ".", "replace", "(", "\"%\"", ",", "u\"\\\\%\"", ")", "s", "=", "s", ".", "replace", "(", "\"&\"", ",", "u\"\\\\&\"", ")", "s", "=", "s", ".", "replace", "(", "\"_\"", ",", "u\"\\\\_\"", ")", "s", "=", "s", ".", "replace", "(", "\"{\"", ",", "u\"\\\\{\"", ")", "s", "=", "s", ".", "replace", "(", "\"}\"", ",", "u\"\\\\}\"", ")", "else", ":", "raise", "ValueError", "(", "'Invalid format (only None, HTML and LATEX are supported).'", ")", "return", "unicode", "(", "s", ")" ]
https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/pyratemp.py#L253-L298
ideawu/ssdb
f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4
deps/cpy/antlr3/streams.py
python
CharStream.getCharPositionInLine
(self)
The index of the character relative to the beginning of the line 0..n-1
The index of the character relative to the beginning of the line 0..n-1
[ "The", "index", "of", "the", "character", "relative", "to", "the", "beginning", "of", "the", "line", "0", "..", "n", "-", "1" ]
def getCharPositionInLine(self): """ The index of the character relative to the beginning of the line 0..n-1 """ raise NotImplementedError
[ "def", "getCharPositionInLine", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/streams.py#L231-L236
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Window.ConvertDialogSizeToPixels
(*args, **kwargs)
return _core_.Window_ConvertDialogSizeToPixels(*args, **kwargs)
ConvertDialogSizeToPixels(self, Size sz) -> Size Converts a point or size from dialog units to pixels. Dialog units are used for maintaining a dialog's proportions even if the font changes. For the x dimension, the dialog units are multiplied by the average character width and then divided by 4. For the y dimension, the dialog units are multiplied by the average character height and then divided by 8.
ConvertDialogSizeToPixels(self, Size sz) -> Size
[ "ConvertDialogSizeToPixels", "(", "self", "Size", "sz", ")", "-", ">", "Size" ]
def ConvertDialogSizeToPixels(*args, **kwargs): """ ConvertDialogSizeToPixels(self, Size sz) -> Size Converts a point or size from dialog units to pixels. Dialog units are used for maintaining a dialog's proportions even if the font changes. For the x dimension, the dialog units are multiplied by the average character width and then divided by 4. For the y dimension, the dialog units are multiplied by the average character height and then divided by 8. """ return _core_.Window_ConvertDialogSizeToPixels(*args, **kwargs)
[ "def", "ConvertDialogSizeToPixels", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_ConvertDialogSizeToPixels", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L10561-L10572
lballabio/quantlib-old
136336947ed4fea9ecc1da6edad188700e821739
gensrc/gensrc/addins/c.py
python
CAddin.generateHeader
(self, func, suffix)
return CAddin.BUFFER_FUNCDEC % { 'func_name' : func.name(), 'func_dec' : functionDeclaration, 'func_ret' : self.functionReturnType_.apply(func.returnValue()), 'suffix' : suffix }
Generate source for prototype of given function.
Generate source for prototype of given function.
[ "Generate", "source", "for", "prototype", "of", "given", "function", "." ]
def generateHeader(self, func, suffix): """Generate source for prototype of given function.""" functionDeclaration = func.parameterList().generate(self.functionDeclaration_) if functionDeclaration: functionDeclaration += ',' return CAddin.BUFFER_FUNCDEC % { 'func_name' : func.name(), 'func_dec' : functionDeclaration, 'func_ret' : self.functionReturnType_.apply(func.returnValue()), 'suffix' : suffix }
[ "def", "generateHeader", "(", "self", ",", "func", ",", "suffix", ")", ":", "functionDeclaration", "=", "func", ".", "parameterList", "(", ")", ".", "generate", "(", "self", ".", "functionDeclaration_", ")", "if", "functionDeclaration", ":", "functionDeclaration", "+=", "','", "return", "CAddin", ".", "BUFFER_FUNCDEC", "%", "{", "'func_name'", ":", "func", ".", "name", "(", ")", ",", "'func_dec'", ":", "functionDeclaration", ",", "'func_ret'", ":", "self", ".", "functionReturnType_", ".", "apply", "(", "func", ".", "returnValue", "(", ")", ")", ",", "'suffix'", ":", "suffix", "}" ]
https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/addins/c.py#L71-L79
HKUST-Aerial-Robotics/Teach-Repeat-Replan
98505a7f74b13c8b501176ff838a38423dbef536
utils/quadrotor_msgs/src/quadrotor_msgs/msg/_Serial.py
python
Serial.serialize
(self, buff)
serialize message into buffer :param buff: buffer, ``StringIO``
serialize message into buffer :param buff: buffer, ``StringIO``
[ "serialize", "message", "into", "buffer", ":", "param", "buff", ":", "buffer", "StringIO" ]
def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) if python3: buff.write(struct.pack('<I%sB'%length, length, *_x)) else: buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self buff.write(_struct_2B.pack(_x.channel, _x.type)) _x = self.data length = len(_x) # - if encoded as a list instead, serialize as bytes instead of string if type(_x) in [list, tuple]: buff.write(struct.pack('<I%sB'%length, length, *_x)) else: buff.write(struct.pack('<I%ss'%length, length, _x)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x)))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
[ "def", "serialize", "(", "self", ",", "buff", ")", ":", "try", ":", "_x", "=", "self", "buff", ".", "write", "(", "_struct_3I", ".", "pack", "(", "_x", ".", "header", ".", "seq", ",", "_x", ".", "header", ".", "stamp", ".", "secs", ",", "_x", ".", "header", ".", "stamp", ".", "nsecs", ")", ")", "_x", "=", "self", ".", "header", ".", "frame_id", "length", "=", "len", "(", "_x", ")", "if", "python3", "or", "type", "(", "_x", ")", "==", "unicode", ":", "_x", "=", "_x", ".", "encode", "(", "'utf-8'", ")", "length", "=", "len", "(", "_x", ")", "if", "python3", ":", "buff", ".", "write", "(", "struct", ".", "pack", "(", "'<I%sB'", "%", "length", ",", "length", ",", "*", "_x", ")", ")", "else", ":", "buff", ".", "write", "(", "struct", ".", "pack", "(", "'<I%ss'", "%", "length", ",", "length", ",", "_x", ")", ")", "_x", "=", "self", "buff", ".", "write", "(", "_struct_2B", ".", "pack", "(", "_x", ".", "channel", ",", "_x", ".", "type", ")", ")", "_x", "=", "self", ".", "data", "length", "=", "len", "(", "_x", ")", "# - if encoded as a list instead, serialize as bytes instead of string", "if", "type", "(", "_x", ")", "in", "[", "list", ",", "tuple", "]", ":", "buff", ".", "write", "(", "struct", ".", "pack", "(", "'<I%sB'", "%", "length", ",", "length", ",", "*", "_x", ")", ")", "else", ":", "buff", ".", "write", "(", "struct", ".", "pack", "(", "'<I%ss'", "%", "length", ",", "length", ",", "_x", ")", ")", "except", "struct", ".", "error", "as", "se", ":", "self", ".", "_check_types", "(", "struct", ".", "error", "(", "\"%s: '%s' when writing '%s'\"", "%", "(", "type", "(", "se", ")", ",", "str", "(", "se", ")", ",", "str", "(", "_x", ")", ")", ")", ")", "except", "TypeError", "as", "te", ":", "self", ".", "_check_types", "(", "ValueError", "(", "\"%s: '%s' when writing '%s'\"", "%", "(", "type", "(", "te", ")", ",", "str", "(", "te", ")", ",", "str", "(", "_x", ")", ")", ")", ")" ]
https://github.com/HKUST-Aerial-Robotics/Teach-Repeat-Replan/blob/98505a7f74b13c8b501176ff838a38423dbef536/utils/quadrotor_msgs/src/quadrotor_msgs/msg/_Serial.py#L94-L121
zerollzeng/tiny-tensorrt
e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2
third_party/pybind11/tools/clang/cindex.py
python
Type.get_ref_qualifier
(self)
return RefQualifierKind.from_id( conf.lib.clang_Type_getCXXRefQualifier(self))
Retrieve the ref-qualifier of the type.
Retrieve the ref-qualifier of the type.
[ "Retrieve", "the", "ref", "-", "qualifier", "of", "the", "type", "." ]
def get_ref_qualifier(self): """ Retrieve the ref-qualifier of the type. """ return RefQualifierKind.from_id( conf.lib.clang_Type_getCXXRefQualifier(self))
[ "def", "get_ref_qualifier", "(", "self", ")", ":", "return", "RefQualifierKind", ".", "from_id", "(", "conf", ".", "lib", ".", "clang_Type_getCXXRefQualifier", "(", "self", ")", ")" ]
https://github.com/zerollzeng/tiny-tensorrt/blob/e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2/third_party/pybind11/tools/clang/cindex.py#L2101-L2106
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
armoryengine/PyBtcWallet.py
python
PyBtcWallet.detectHighestUsedIndex
(self, startFrom=0, writeResultToWallet=False, fullscan=False)
return highestIndex
This method is used to find the highestUsedChainIndex value of the wallet WITHIN its address pool. It will NOT extend its address pool in this search, because it is assumed that the wallet couldn't have used any addresses it had not calculated yet. If you have a wallet IMPORT, though, or a wallet that has been used before but does not have this information stored with it, then you should be using the next method: self.freshImportFindHighestIndex() which will actually extend the address pool as necessary to find the highest address used.
This method is used to find the highestUsedChainIndex value of the wallet WITHIN its address pool. It will NOT extend its address pool in this search, because it is assumed that the wallet couldn't have used any addresses it had not calculated yet.
[ "This", "method", "is", "used", "to", "find", "the", "highestUsedChainIndex", "value", "of", "the", "wallet", "WITHIN", "its", "address", "pool", ".", "It", "will", "NOT", "extend", "its", "address", "pool", "in", "this", "search", "because", "it", "is", "assumed", "that", "the", "wallet", "couldn", "t", "have", "used", "any", "addresses", "it", "had", "not", "calculated", "yet", "." ]
def detectHighestUsedIndex(self, startFrom=0, writeResultToWallet=False, fullscan=False): """ This method is used to find the highestUsedChainIndex value of the wallet WITHIN its address pool. It will NOT extend its address pool in this search, because it is assumed that the wallet couldn't have used any addresses it had not calculated yet. If you have a wallet IMPORT, though, or a wallet that has been used before but does not have this information stored with it, then you should be using the next method: self.freshImportFindHighestIndex() which will actually extend the address pool as necessary to find the highest address used. """ if fullscan: startFrom = 0 highestIndex = max(self.highestUsedChainIndex, 0) for a160 in self.linearAddr160List[startFrom:]: addr = self.addrMap[a160] scrAddr = Hash160ToScrAddr(a160) if self.cppWallet.getAddrTotalTxnCount(scrAddr) > 0: highestIndex = max(highestIndex, addr.chainIndex) if writeResultToWallet: self.highestUsedChainIndex = highestIndex self.walletFileSafeUpdate( [[WLT_UPDATE_MODIFY, self.offsetTopUsed, \ int_to_binary(highestIndex, widthBytes=8)]]) return highestIndex
[ "def", "detectHighestUsedIndex", "(", "self", ",", "startFrom", "=", "0", ",", "writeResultToWallet", "=", "False", ",", "fullscan", "=", "False", ")", ":", "if", "fullscan", ":", "startFrom", "=", "0", "highestIndex", "=", "max", "(", "self", ".", "highestUsedChainIndex", ",", "0", ")", "for", "a160", "in", "self", ".", "linearAddr160List", "[", "startFrom", ":", "]", ":", "addr", "=", "self", ".", "addrMap", "[", "a160", "]", "scrAddr", "=", "Hash160ToScrAddr", "(", "a160", ")", "if", "self", ".", "cppWallet", ".", "getAddrTotalTxnCount", "(", "scrAddr", ")", ">", "0", ":", "highestIndex", "=", "max", "(", "highestIndex", ",", "addr", ".", "chainIndex", ")", "if", "writeResultToWallet", ":", "self", ".", "highestUsedChainIndex", "=", "highestIndex", "self", ".", "walletFileSafeUpdate", "(", "[", "[", "WLT_UPDATE_MODIFY", ",", "self", ".", "offsetTopUsed", ",", "int_to_binary", "(", "highestIndex", ",", "widthBytes", "=", "8", ")", "]", "]", ")", "return", "highestIndex" ]
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/PyBtcWallet.py#L1074-L1107
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
v8_4_5/build/landmine_utils.py
python
memoize
(default=None)
return memoizer
This decorator caches the return value of a parameterless pure function
This decorator caches the return value of a parameterless pure function
[ "This", "decorator", "caches", "the", "return", "value", "of", "a", "parameterless", "pure", "function" ]
def memoize(default=None): """This decorator caches the return value of a parameterless pure function""" def memoizer(func): val = [] @functools.wraps(func) def inner(): if not val: ret = func() val.append(ret if ret is not None else default) if logging.getLogger().isEnabledFor(logging.INFO): print '%s -> %r' % (func.__name__, val[0]) return val[0] return inner return memoizer
[ "def", "memoize", "(", "default", "=", "None", ")", ":", "def", "memoizer", "(", "func", ")", ":", "val", "=", "[", "]", "@", "functools", ".", "wraps", "(", "func", ")", "def", "inner", "(", ")", ":", "if", "not", "val", ":", "ret", "=", "func", "(", ")", "val", ".", "append", "(", "ret", "if", "ret", "is", "not", "None", "else", "default", ")", "if", "logging", ".", "getLogger", "(", ")", ".", "isEnabledFor", "(", "logging", ".", "INFO", ")", ":", "print", "'%s -> %r'", "%", "(", "func", ".", "__name__", ",", "val", "[", "0", "]", ")", "return", "val", "[", "0", "]", "return", "inner", "return", "memoizer" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/v8_4_5/build/landmine_utils.py#L13-L26
Project-OSRM/osrm-backend
f2e284623e25b5570dd2a5e6985abcb3790fd348
third_party/flatbuffers/python/flatbuffers/builder.py
python
Builder.PlaceUOffsetT
(self, x)
PlaceUOffsetT prepends a UOffsetT to the Builder, without checking for space.
PlaceUOffsetT prepends a UOffsetT to the Builder, without checking for space.
[ "PlaceUOffsetT", "prepends", "a", "UOffsetT", "to", "the", "Builder", "without", "checking", "for", "space", "." ]
def PlaceUOffsetT(self, x): """PlaceUOffsetT prepends a UOffsetT to the Builder, without checking for space. """ N.enforce_number(x, N.UOffsetTFlags) self.head = self.head - N.UOffsetTFlags.bytewidth encode.Write(packer.uoffset, self.Bytes, self.Head(), x)
[ "def", "PlaceUOffsetT", "(", "self", ",", "x", ")", ":", "N", ".", "enforce_number", "(", "x", ",", "N", ".", "UOffsetTFlags", ")", "self", ".", "head", "=", "self", ".", "head", "-", "N", ".", "UOffsetTFlags", ".", "bytewidth", "encode", ".", "Write", "(", "packer", ".", "uoffset", ",", "self", ".", "Bytes", ",", "self", ".", "Head", "(", ")", ",", "x", ")" ]
https://github.com/Project-OSRM/osrm-backend/blob/f2e284623e25b5570dd2a5e6985abcb3790fd348/third_party/flatbuffers/python/flatbuffers/builder.py#L725-L731
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/llvm/bindings/python/llvm/disassembler.py
python
Disassembler.get_instructions
(self, source, pc=0)
Obtain multiple instructions from an input source. This is like get_instruction() except it is a generator for all instructions within the source. It starts at the beginning of the source and reads instructions until no more can be read. This generator returns 3-tuple of: long address of instruction. long size of instruction, in bytes. str representation of instruction.
Obtain multiple instructions from an input source.
[ "Obtain", "multiple", "instructions", "from", "an", "input", "source", "." ]
def get_instructions(self, source, pc=0): """Obtain multiple instructions from an input source. This is like get_instruction() except it is a generator for all instructions within the source. It starts at the beginning of the source and reads instructions until no more can be read. This generator returns 3-tuple of: long address of instruction. long size of instruction, in bytes. str representation of instruction. """ source_bytes = c_char_p(source) out_str = cast((c_byte * 255)(), c_char_p) # This could probably be written cleaner. But, it does work. buf = cast(source_bytes, POINTER(c_ubyte * len(source))).contents offset = 0 address = pc end_address = pc + len(source) while address < end_address: b = cast(addressof(buf) + offset, POINTER(c_ubyte)) result = lib.LLVMDisasmInstruction(self, b, c_uint64(len(source) - offset), c_uint64(address), out_str, 255) if result == 0: break yield (address, result, out_str.value) address += result offset += result
[ "def", "get_instructions", "(", "self", ",", "source", ",", "pc", "=", "0", ")", ":", "source_bytes", "=", "c_char_p", "(", "source", ")", "out_str", "=", "cast", "(", "(", "c_byte", "*", "255", ")", "(", ")", ",", "c_char_p", ")", "# This could probably be written cleaner. But, it does work.", "buf", "=", "cast", "(", "source_bytes", ",", "POINTER", "(", "c_ubyte", "*", "len", "(", "source", ")", ")", ")", ".", "contents", "offset", "=", "0", "address", "=", "pc", "end_address", "=", "pc", "+", "len", "(", "source", ")", "while", "address", "<", "end_address", ":", "b", "=", "cast", "(", "addressof", "(", "buf", ")", "+", "offset", ",", "POINTER", "(", "c_ubyte", ")", ")", "result", "=", "lib", ".", "LLVMDisasmInstruction", "(", "self", ",", "b", ",", "c_uint64", "(", "len", "(", "source", ")", "-", "offset", ")", ",", "c_uint64", "(", "address", ")", ",", "out_str", ",", "255", ")", "if", "result", "==", "0", ":", "break", "yield", "(", "address", ",", "result", ",", "out_str", ".", "value", ")", "address", "+=", "result", "offset", "+=", "result" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/llvm/bindings/python/llvm/disassembler.py#L109-L142
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
is_bv_value
(a)
return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
Return `True` if `a` is a Z3 bit-vector numeral value. >>> b = BitVec('b', 32) >>> is_bv_value(b) False >>> b = BitVecVal(10, 32) >>> b 10 >>> is_bv_value(b) True
Return `True` if `a` is a Z3 bit-vector numeral value.
[ "Return", "True", "if", "a", "is", "a", "Z3", "bit", "-", "vector", "numeral", "value", "." ]
def is_bv_value(a): """Return `True` if `a` is a Z3 bit-vector numeral value. >>> b = BitVec('b', 32) >>> is_bv_value(b) False >>> b = BitVecVal(10, 32) >>> b 10 >>> is_bv_value(b) True """ return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
[ "def", "is_bv_value", "(", "a", ")", ":", "return", "is_bv", "(", "a", ")", "and", "_is_numeral", "(", "a", ".", "ctx", ",", "a", ".", "as_ast", "(", ")", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L3923-L3935
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/util/cloudpickle.py
python
CloudPickler.save_inst
(self, obj)
Inner logic to save instance. Based off pickle.save_inst Supports __transient__
Inner logic to save instance. Based off pickle.save_inst Supports __transient__
[ "Inner", "logic", "to", "save", "instance", ".", "Based", "off", "pickle", ".", "save_inst", "Supports", "__transient__" ]
def save_inst(self, obj): """Inner logic to save instance. Based off pickle.save_inst Supports __transient__""" cls = obj.__class__ memo = self.memo write = self.write save = self.save if hasattr(obj, '__getinitargs__'): args = obj.__getinitargs__() len(args) # XXX Assert it's a sequence pickle._keep_alive(args, memo) else: args = () write(pickle.MARK) if self.bin: save(cls) for arg in args: save(arg) write(pickle.OBJ) else: for arg in args: save(arg) write(pickle.INST + cls.__module__ + '\n' + cls.__name__ + '\n') self.memoize(obj) try: getstate = obj.__getstate__ except AttributeError: stuff = obj.__dict__ #remove items if transient if hasattr(obj, '__transient__'): transient = obj.__transient__ stuff = stuff.copy() for k in list(stuff.keys()): if k in transient: del stuff[k] else: stuff = getstate() pickle._keep_alive(stuff, memo) save(stuff) write(pickle.BUILD)
[ "def", "save_inst", "(", "self", ",", "obj", ")", ":", "cls", "=", "obj", ".", "__class__", "memo", "=", "self", ".", "memo", "write", "=", "self", ".", "write", "save", "=", "self", ".", "save", "if", "hasattr", "(", "obj", ",", "'__getinitargs__'", ")", ":", "args", "=", "obj", ".", "__getinitargs__", "(", ")", "len", "(", "args", ")", "# XXX Assert it's a sequence", "pickle", ".", "_keep_alive", "(", "args", ",", "memo", ")", "else", ":", "args", "=", "(", ")", "write", "(", "pickle", ".", "MARK", ")", "if", "self", ".", "bin", ":", "save", "(", "cls", ")", "for", "arg", "in", "args", ":", "save", "(", "arg", ")", "write", "(", "pickle", ".", "OBJ", ")", "else", ":", "for", "arg", "in", "args", ":", "save", "(", "arg", ")", "write", "(", "pickle", ".", "INST", "+", "cls", ".", "__module__", "+", "'\\n'", "+", "cls", ".", "__name__", "+", "'\\n'", ")", "self", ".", "memoize", "(", "obj", ")", "try", ":", "getstate", "=", "obj", ".", "__getstate__", "except", "AttributeError", ":", "stuff", "=", "obj", ".", "__dict__", "#remove items if transient", "if", "hasattr", "(", "obj", ",", "'__transient__'", ")", ":", "transient", "=", "obj", ".", "__transient__", "stuff", "=", "stuff", ".", "copy", "(", ")", "for", "k", "in", "list", "(", "stuff", ".", "keys", "(", ")", ")", ":", "if", "k", "in", "transient", ":", "del", "stuff", "[", "k", "]", "else", ":", "stuff", "=", "getstate", "(", ")", "pickle", ".", "_keep_alive", "(", "stuff", ",", "memo", ")", "save", "(", "stuff", ")", "write", "(", "pickle", ".", "BUILD", ")" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/util/cloudpickle.py#L394-L439
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/decoder.py
python
_SkipFixed64
(buffer, pos, end)
return pos
Skip a fixed64 value. Returns the new position.
Skip a fixed64 value. Returns the new position.
[ "Skip", "a", "fixed64", "value", ".", "Returns", "the", "new", "position", "." ]
def _SkipFixed64(buffer, pos, end): """Skip a fixed64 value. Returns the new position.""" pos += 8 if pos > end: raise _DecodeError('Truncated message.') return pos
[ "def", "_SkipFixed64", "(", "buffer", ",", "pos", ",", "end", ")", ":", "pos", "+=", "8", "if", "pos", ">", "end", ":", "raise", "_DecodeError", "(", "'Truncated message.'", ")", "return", "pos" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/decoder.py#L563-L569
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
orttraining/orttraining/python/training/_utils.py
python
state_dict_original_dimension_key
()
return 'original_dim'
Returns the original dimension key name in the state dictionary
Returns the original dimension key name in the state dictionary
[ "Returns", "the", "original", "dimension", "key", "name", "in", "the", "state", "dictionary" ]
def state_dict_original_dimension_key(): """Returns the original dimension key name in the state dictionary""" return 'original_dim'
[ "def", "state_dict_original_dimension_key", "(", ")", ":", "return", "'original_dim'" ]
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/_utils.py#L241-L244
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py
python
easy_install.expand_dirs
(self)
Calls `os.path.expanduser` on install dirs.
Calls `os.path.expanduser` on install dirs.
[ "Calls", "os", ".", "path", ".", "expanduser", "on", "install", "dirs", "." ]
def expand_dirs(self): """Calls `os.path.expanduser` on install dirs.""" dirs = [ 'install_purelib', 'install_platlib', 'install_lib', 'install_headers', 'install_scripts', 'install_data', ] self._expand_attrs(dirs)
[ "def", "expand_dirs", "(", "self", ")", ":", "dirs", "=", "[", "'install_purelib'", ",", "'install_platlib'", ",", "'install_lib'", ",", "'install_headers'", ",", "'install_scripts'", ",", "'install_data'", ",", "]", "self", ".", "_expand_attrs", "(", "dirs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py#L395-L405
rootm0s/Protectors
5b3f4d11687a5955caf9c3af30666c4bfc2c19ab
OWASP-ZSC/module/readline_windows/pyreadline/lineeditor/history.py
python
LineHistory.next_history
(self, current)
Move forward through the history list, fetching the next command.
Move forward through the history list, fetching the next command.
[ "Move", "forward", "through", "the", "history", "list", "fetching", "the", "next", "command", "." ]
def next_history(self, current): # (C-n) '''Move forward through the history list, fetching the next command. ''' if self.history_cursor < len(self.history) - 1: self.history_cursor += 1 current.set_line(self.history[self.history_cursor].get_line_text())
[ "def", "next_history", "(", "self", ",", "current", ")", ":", "# (C-n)", "if", "self", ".", "history_cursor", "<", "len", "(", "self", ".", "history", ")", "-", "1", ":", "self", ".", "history_cursor", "+=", "1", "current", ".", "set_line", "(", "self", ".", "history", "[", "self", ".", "history_cursor", "]", ".", "get_line_text", "(", ")", ")" ]
https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/lineeditor/history.py#L129-L133
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/BASIC/basparse.py
python
p_number
(p)
number : INTEGER | FLOAT
number : INTEGER | FLOAT
[ "number", ":", "INTEGER", "|", "FLOAT" ]
def p_number(p): '''number : INTEGER | FLOAT''' p[0] = eval(p[1])
[ "def", "p_number", "(", "p", ")", ":", "p", "[", "0", "]", "=", "eval", "(", "p", "[", "1", "]", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/BASIC/basparse.py#L358-L361
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/array_ops.py
python
zeros
(shape, dtype=dtypes.float32, name=None)
return output
Creates a tensor with all elements set to zero. This operation returns a tensor of type `dtype` with shape `shape` and all elements set to zero. For example: ```python tf.zeros([3, 4], int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ``` Args: shape: Either a list of integers, or a 1-D `Tensor` of type `int32`. dtype: The type of an element in the resulting `Tensor`. name: A name for the operation (optional). Returns: A `Tensor` with all elements set to zero.
Creates a tensor with all elements set to zero.
[ "Creates", "a", "tensor", "with", "all", "elements", "set", "to", "zero", "." ]
def zeros(shape, dtype=dtypes.float32, name=None): """Creates a tensor with all elements set to zero. This operation returns a tensor of type `dtype` with shape `shape` and all elements set to zero. For example: ```python tf.zeros([3, 4], int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ``` Args: shape: Either a list of integers, or a 1-D `Tensor` of type `int32`. dtype: The type of an element in the resulting `Tensor`. name: A name for the operation (optional). Returns: A `Tensor` with all elements set to zero. """ with ops.op_scope([shape], name, "zeros") as name: try: shape = tensor_shape.as_shape(shape) output = constant(0, shape=shape, dtype=dtype, name=name) except (TypeError, ValueError): shape = ops.convert_to_tensor(shape, dtype=dtypes.int32, name="shape") output = fill(shape, constant(0, dtype=dtype), name=name) assert output.dtype.base_dtype == dtypes.as_dtype(dtype).base_dtype return output
[ "def", "zeros", "(", "shape", ",", "dtype", "=", "dtypes", ".", "float32", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "shape", "]", ",", "name", ",", "\"zeros\"", ")", "as", "name", ":", "try", ":", "shape", "=", "tensor_shape", ".", "as_shape", "(", "shape", ")", "output", "=", "constant", "(", "0", ",", "shape", "=", "shape", ",", "dtype", "=", "dtype", ",", "name", "=", "name", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "shape", "=", "ops", ".", "convert_to_tensor", "(", "shape", ",", "dtype", "=", "dtypes", ".", "int32", ",", "name", "=", "\"shape\"", ")", "output", "=", "fill", "(", "shape", ",", "constant", "(", "0", ",", "dtype", "=", "dtype", ")", ",", "name", "=", "name", ")", "assert", "output", ".", "dtype", ".", "base_dtype", "==", "dtypes", ".", "as_dtype", "(", "dtype", ")", ".", "base_dtype", "return", "output" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L1046-L1074
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Image.Copy
(*args, **kwargs)
return _core_.Image_Copy(*args, **kwargs)
Copy(self) -> Image Returns an identical copy of the image.
Copy(self) -> Image
[ "Copy", "(", "self", ")", "-", ">", "Image" ]
def Copy(*args, **kwargs): """ Copy(self) -> Image Returns an identical copy of the image. """ return _core_.Image_Copy(*args, **kwargs)
[ "def", "Copy", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_Copy", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L3340-L3346
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/interpolate/fitpack2.py
python
UnivariateSpline.get_coeffs
(self)
return data[9][:n-k-1]
Return spline coefficients.
Return spline coefficients.
[ "Return", "spline", "coefficients", "." ]
def get_coeffs(self): """Return spline coefficients.""" data = self._data k, n = data[5], data[7] return data[9][:n-k-1]
[ "def", "get_coeffs", "(", "self", ")", ":", "data", "=", "self", ".", "_data", "k", ",", "n", "=", "data", "[", "5", "]", ",", "data", "[", "7", "]", "return", "data", "[", "9", "]", "[", ":", "n", "-", "k", "-", "1", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/interpolate/fitpack2.py#L323-L327
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextBuffer.SetStyleSheet
(*args, **kwargs)
return _richtext.RichTextBuffer_SetStyleSheet(*args, **kwargs)
SetStyleSheet(self, wxRichTextStyleSheet styleSheet)
SetStyleSheet(self, wxRichTextStyleSheet styleSheet)
[ "SetStyleSheet", "(", "self", "wxRichTextStyleSheet", "styleSheet", ")" ]
def SetStyleSheet(*args, **kwargs): """SetStyleSheet(self, wxRichTextStyleSheet styleSheet)""" return _richtext.RichTextBuffer_SetStyleSheet(*args, **kwargs)
[ "def", "SetStyleSheet", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_SetStyleSheet", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2213-L2215
MtnViewJohn/context-free
757d7bde9742f201cec61bd195dda98093edd1e8
src-scintilla/scripts/FileGenerator.py
python
GenerateFile
(inpath, outpath, commentPrefix, retainDefs, *lists)
Generate 'outpath' from 'inpath'.
Generate 'outpath' from 'inpath'.
[ "Generate", "outpath", "from", "inpath", "." ]
def GenerateFile(inpath, outpath, commentPrefix, retainDefs, *lists): """Generate 'outpath' from 'inpath'. """ try: with codecs.open(inpath, "r", "UTF-8") as infile: original = infile.read() updated = CopyWithInsertion(original, commentPrefix, retainDefs, lists) UpdateFile(outpath, updated) except IOError: print("Can not open %s" % inpath)
[ "def", "GenerateFile", "(", "inpath", ",", "outpath", ",", "commentPrefix", ",", "retainDefs", ",", "*", "lists", ")", ":", "try", ":", "with", "codecs", ".", "open", "(", "inpath", ",", "\"r\"", ",", "\"UTF-8\"", ")", "as", "infile", ":", "original", "=", "infile", ".", "read", "(", ")", "updated", "=", "CopyWithInsertion", "(", "original", ",", "commentPrefix", ",", "retainDefs", ",", "lists", ")", "UpdateFile", "(", "outpath", ",", "updated", ")", "except", "IOError", ":", "print", "(", "\"Can not open %s\"", "%", "inpath", ")" ]
https://github.com/MtnViewJohn/context-free/blob/757d7bde9742f201cec61bd195dda98093edd1e8/src-scintilla/scripts/FileGenerator.py#L117-L128
esa/pagmo
80281d549c8f1b470e1489a5d37c8f06b2e429c0
PyGMO/topology/__init__.py
python
_to_networkx
(self)
return retval
Export topology as a networkx DiGraph.
Export topology as a networkx DiGraph.
[ "Export", "topology", "as", "a", "networkx", "DiGraph", "." ]
def _to_networkx(self): """ Export topology as a networkx DiGraph. """ try: import networkx as nx except ImportError: raise ImportError('Could not import the networkx module.') retval = nx.DiGraph() for i in range(self.number_of_vertices): if self.get_num_adjacent_vertices(i): retval.add_edges_from([(i, n) for n in self.get_adjacent_vertices(i)]) else: retval.add_node(i) return retval
[ "def", "_to_networkx", "(", "self", ")", ":", "try", ":", "import", "networkx", "as", "nx", "except", "ImportError", ":", "raise", "ImportError", "(", "'Could not import the networkx module.'", ")", "retval", "=", "nx", ".", "DiGraph", "(", ")", "for", "i", "in", "range", "(", "self", ".", "number_of_vertices", ")", ":", "if", "self", ".", "get_num_adjacent_vertices", "(", "i", ")", ":", "retval", ".", "add_edges_from", "(", "[", "(", "i", ",", "n", ")", "for", "n", "in", "self", ".", "get_adjacent_vertices", "(", "i", ")", "]", ")", "else", ":", "retval", ".", "add_node", "(", "i", ")", "return", "retval" ]
https://github.com/esa/pagmo/blob/80281d549c8f1b470e1489a5d37c8f06b2e429c0/PyGMO/topology/__init__.py#L6-L21
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/Conv.py
python
TransposedConv3D.filter_size
(self)
return self._internal.get_filter_height(), self._internal.get_filter_width(), self._internal.get_filter_depth()
Gets the filter size.
Gets the filter size.
[ "Gets", "the", "filter", "size", "." ]
def filter_size(self): """Gets the filter size. """ return self._internal.get_filter_height(), self._internal.get_filter_width(), self._internal.get_filter_depth()
[ "def", "filter_size", "(", "self", ")", ":", "return", "self", ".", "_internal", ".", "get_filter_height", "(", ")", ",", "self", ".", "_internal", ".", "get_filter_width", "(", ")", ",", "self", ".", "_internal", ".", "get_filter_depth", "(", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Conv.py#L502-L505
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py
python
SpawnBase.expect_list
(self, pattern_list, timeout=-1, searchwindowsize=-1, async_=False, **kw)
This takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT(which are not compiled regular expressions). This method is similar to the expect() method except that expect_list() does not recompile the pattern list on every call. This may help if you are trying to optimize for speed, otherwise just use the expect() method. This is called by expect(). Like :meth:`expect`, passing ``async_=True`` will make this return an asyncio coroutine.
This takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT(which are not compiled regular expressions). This method is similar to the expect() method except that expect_list() does not recompile the pattern list on every call. This may help if you are trying to optimize for speed, otherwise just use the expect() method. This is called by expect().
[ "This", "takes", "a", "list", "of", "compiled", "regular", "expressions", "and", "returns", "the", "index", "into", "the", "pattern_list", "that", "matched", "the", "child", "output", ".", "The", "list", "may", "also", "contain", "EOF", "or", "TIMEOUT", "(", "which", "are", "not", "compiled", "regular", "expressions", ")", ".", "This", "method", "is", "similar", "to", "the", "expect", "()", "method", "except", "that", "expect_list", "()", "does", "not", "recompile", "the", "pattern", "list", "on", "every", "call", ".", "This", "may", "help", "if", "you", "are", "trying", "to", "optimize", "for", "speed", "otherwise", "just", "use", "the", "expect", "()", "method", ".", "This", "is", "called", "by", "expect", "()", "." ]
def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1, async_=False, **kw): '''This takes a list of compiled regular expressions and returns the index into the pattern_list that matched the child output. The list may also contain EOF or TIMEOUT(which are not compiled regular expressions). This method is similar to the expect() method except that expect_list() does not recompile the pattern list on every call. This may help if you are trying to optimize for speed, otherwise just use the expect() method. This is called by expect(). Like :meth:`expect`, passing ``async_=True`` will make this return an asyncio coroutine. ''' if timeout == -1: timeout = self.timeout if 'async' in kw: async_ = kw.pop('async') if kw: raise TypeError("Unknown keyword arguments: {}".format(kw)) exp = Expecter(self, searcher_re(pattern_list), searchwindowsize) if async_: from ._async import expect_async return expect_async(exp, timeout) else: return exp.expect_loop(timeout)
[ "def", "expect_list", "(", "self", ",", "pattern_list", ",", "timeout", "=", "-", "1", ",", "searchwindowsize", "=", "-", "1", ",", "async_", "=", "False", ",", "*", "*", "kw", ")", ":", "if", "timeout", "==", "-", "1", ":", "timeout", "=", "self", ".", "timeout", "if", "'async'", "in", "kw", ":", "async_", "=", "kw", ".", "pop", "(", "'async'", ")", "if", "kw", ":", "raise", "TypeError", "(", "\"Unknown keyword arguments: {}\"", ".", "format", "(", "kw", ")", ")", "exp", "=", "Expecter", "(", "self", ",", "searcher_re", "(", "pattern_list", ")", ",", "searchwindowsize", ")", "if", "async_", ":", "from", ".", "_async", "import", "expect_async", "return", "expect_async", "(", "exp", ",", "timeout", ")", "else", ":", "return", "exp", ".", "expect_loop", "(", "timeout", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py#L343-L369
HKUST-Aerial-Robotics/Teach-Repeat-Replan
98505a7f74b13c8b501176ff838a38423dbef536
utils/quadrotor_msgs/src/quadrotor_msgs/msg/_AuxCommand.py
python
AuxCommand.serialize_numpy
(self, buff, numpy)
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
[ "serialize", "message", "with", "numpy", "array", "types", "into", "buffer", ":", "param", "buff", ":", "buffer", "StringIO", ":", "param", "numpy", ":", "numpy", "python", "module" ]
def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self buff.write(_struct_2d.pack(_x.current_yaw, _x.kf_correction)) buff.write(self.angle_corrections.tostring()) _x = self buff.write(_struct_2B.pack(_x.enable_motors, _x.use_external_yaw)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x)))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
[ "def", "serialize_numpy", "(", "self", ",", "buff", ",", "numpy", ")", ":", "try", ":", "_x", "=", "self", "buff", ".", "write", "(", "_struct_2d", ".", "pack", "(", "_x", ".", "current_yaw", ",", "_x", ".", "kf_correction", ")", ")", "buff", ".", "write", "(", "self", ".", "angle_corrections", ".", "tostring", "(", ")", ")", "_x", "=", "self", "buff", ".", "write", "(", "_struct_2B", ".", "pack", "(", "_x", ".", "enable_motors", ",", "_x", ".", "use_external_yaw", ")", ")", "except", "struct", ".", "error", "as", "se", ":", "self", ".", "_check_types", "(", "struct", ".", "error", "(", "\"%s: '%s' when writing '%s'\"", "%", "(", "type", "(", "se", ")", ",", "str", "(", "se", ")", ",", "str", "(", "_x", ")", ")", ")", ")", "except", "TypeError", "as", "te", ":", "self", ".", "_check_types", "(", "ValueError", "(", "\"%s: '%s' when writing '%s'\"", "%", "(", "type", "(", "te", ")", ",", "str", "(", "te", ")", ",", "str", "(", "_x", ")", ")", ")", ")" ]
https://github.com/HKUST-Aerial-Robotics/Teach-Repeat-Replan/blob/98505a7f74b13c8b501176ff838a38423dbef536/utils/quadrotor_msgs/src/quadrotor_msgs/msg/_AuxCommand.py#L101-L114
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/distributions/python/ops/binomial.py
python
Binomial.logits
(self)
return self._logits
Log-odds of drawing a `1`.
Log-odds of drawing a `1`.
[ "Log", "-", "odds", "of", "drawing", "a", "1", "." ]
def logits(self): """Log-odds of drawing a `1`.""" return self._logits
[ "def", "logits", "(", "self", ")", ":", "return", "self", ".", "_logits" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/distributions/python/ops/binomial.py#L193-L195
ARM-software/armnn
5e9965cae1cc6162649910f423ebd86001fc1931
python/pyarmnn/examples/speech_recognition/preprocess.py
python
MFCC.mel_scale
(self, freq, use_htk_method)
return mel
Gets the mel scale for a particular sample frequency. Args: freq: The sampling frequency. use_htk_method: Boolean to set whether to use HTK method or not. Returns: the mel scale
Gets the mel scale for a particular sample frequency.
[ "Gets", "the", "mel", "scale", "for", "a", "particular", "sample", "frequency", "." ]
def mel_scale(self, freq, use_htk_method): """ Gets the mel scale for a particular sample frequency. Args: freq: The sampling frequency. use_htk_method: Boolean to set whether to use HTK method or not. Returns: the mel scale """ if use_htk_method: return 1127.0 * np.log(1.0 + freq / 700.0) else: mel = freq / self.FREQ_STEP if freq >= self.MIN_LOG_HZ: mel = self.MIN_LOG_MEL + np.log(freq / self.MIN_LOG_HZ) / self.LOG_STEP return mel
[ "def", "mel_scale", "(", "self", ",", "freq", ",", "use_htk_method", ")", ":", "if", "use_htk_method", ":", "return", "1127.0", "*", "np", ".", "log", "(", "1.0", "+", "freq", "/", "700.0", ")", "else", ":", "mel", "=", "freq", "/", "self", ".", "FREQ_STEP", "if", "freq", ">=", "self", ".", "MIN_LOG_HZ", ":", "mel", "=", "self", ".", "MIN_LOG_MEL", "+", "np", ".", "log", "(", "freq", "/", "self", ".", "MIN_LOG_HZ", ")", "/", "self", ".", "LOG_STEP", "return", "mel" ]
https://github.com/ARM-software/armnn/blob/5e9965cae1cc6162649910f423ebd86001fc1931/python/pyarmnn/examples/speech_recognition/preprocess.py#L47-L65
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
ParseResults.append
( self, item )
Add single element to end of ParseResults list of elements. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to compute the sum of the parsed integers, and add it to the end def append_sum(tokens): tokens.append(sum(map(int, tokens))) print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
Add single element to end of ParseResults list of elements.
[ "Add", "single", "element", "to", "end", "of", "ParseResults", "list", "of", "elements", "." ]
def append( self, item ): """ Add single element to end of ParseResults list of elements. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to compute the sum of the parsed integers, and add it to the end def append_sum(tokens): tokens.append(sum(map(int, tokens))) print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444] """ self.__toklist.append(item)
[ "def", "append", "(", "self", ",", "item", ")", ":", "self", ".", "__toklist", ".", "append", "(", "item", ")" ]
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#L605-L617
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/encoders.py
python
encode_quopri
(msg)
Encode the message's payload in quoted-printable. Also, add an appropriate Content-Transfer-Encoding header.
Encode the message's payload in quoted-printable.
[ "Encode", "the", "message", "s", "payload", "in", "quoted", "-", "printable", "." ]
def encode_quopri(msg): """Encode the message's payload in quoted-printable. Also, add an appropriate Content-Transfer-Encoding header. """ orig = msg.get_payload(decode=True) encdata = _qencode(orig) msg.set_payload(encdata) msg['Content-Transfer-Encoding'] = 'quoted-printable'
[ "def", "encode_quopri", "(", "msg", ")", ":", "orig", "=", "msg", ".", "get_payload", "(", "decode", "=", "True", ")", "encdata", "=", "_qencode", "(", "orig", ")", "msg", ".", "set_payload", "(", "encdata", ")", "msg", "[", "'Content-Transfer-Encoding'", "]", "=", "'quoted-printable'" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/encoders.py#L38-L46
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pymcuprog/nvmspi.py
python
NvmAccessProviderCmsisDapSpi.write
(self, memory_info, offset, data)
Write the memory with data :param memory_info: dictionary for the memory as provided by the DeviceMemoryInfo class :param offset: relative offset within the memory type :param data: the data to program :return: None
Write the memory with data
[ "Write", "the", "memory", "with", "data" ]
def write(self, memory_info, offset, data): """ Write the memory with data :param memory_info: dictionary for the memory as provided by the DeviceMemoryInfo class :param offset: relative offset within the memory type :param data: the data to program :return: None """ # Make sure the data is aligned to a memory page data_aligned, offset_aligned = utils.pagealign(data, offset, memory_info[DeviceMemoryInfoKeys.PAGE_SIZE], memory_info[DeviceMemoryInfoKeys.WRITE_SIZE]) if memory_info[DeviceMemoryInfoKeys.NAME] != MemoryNames.FLASH: raise PymcuprogNotSupportedError("Currently only Flash memory is supported by write for SPI/ISP") write_chunk_size = memory_info[DeviceMemoryInfoKeys.PAGE_SIZE] n_chunk = math.ceil(len(data_aligned)/write_chunk_size) bar = progress_bar.ProgressBar(n_chunk, hide=n_chunk == 1) while data_aligned: bar.step() if len(data_aligned) < write_chunk_size: write_chunk_size = len(data_aligned) chunk = data_aligned[0:write_chunk_size] self.logger.debug("Writing %d bytes to address 0x%06X", write_chunk_size, offset_aligned) self.isp.write_flash_page(offset_aligned, chunk) offset_aligned += write_chunk_size data_aligned = data_aligned[write_chunk_size:]
[ "def", "write", "(", "self", ",", "memory_info", ",", "offset", ",", "data", ")", ":", "# Make sure the data is aligned to a memory page", "data_aligned", ",", "offset_aligned", "=", "utils", ".", "pagealign", "(", "data", ",", "offset", ",", "memory_info", "[", "DeviceMemoryInfoKeys", ".", "PAGE_SIZE", "]", ",", "memory_info", "[", "DeviceMemoryInfoKeys", ".", "WRITE_SIZE", "]", ")", "if", "memory_info", "[", "DeviceMemoryInfoKeys", ".", "NAME", "]", "!=", "MemoryNames", ".", "FLASH", ":", "raise", "PymcuprogNotSupportedError", "(", "\"Currently only Flash memory is supported by write for SPI/ISP\"", ")", "write_chunk_size", "=", "memory_info", "[", "DeviceMemoryInfoKeys", ".", "PAGE_SIZE", "]", "n_chunk", "=", "math", ".", "ceil", "(", "len", "(", "data_aligned", ")", "/", "write_chunk_size", ")", "bar", "=", "progress_bar", ".", "ProgressBar", "(", "n_chunk", ",", "hide", "=", "n_chunk", "==", "1", ")", "while", "data_aligned", ":", "bar", ".", "step", "(", ")", "if", "len", "(", "data_aligned", ")", "<", "write_chunk_size", ":", "write_chunk_size", "=", "len", "(", "data_aligned", ")", "chunk", "=", "data_aligned", "[", "0", ":", "write_chunk_size", "]", "self", ".", "logger", ".", "debug", "(", "\"Writing %d bytes to address 0x%06X\"", ",", "write_chunk_size", ",", "offset_aligned", ")", "self", ".", "isp", ".", "write_flash_page", "(", "offset_aligned", ",", "chunk", ")", "offset_aligned", "+=", "write_chunk_size", "data_aligned", "=", "data_aligned", "[", "write_chunk_size", ":", "]" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/nvmspi.py#L55-L84
vslavik/poedit
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
deps/boost/tools/build/src/build/feature.py
python
subfeature
(feature_name, value_string, subfeature, subvalues, attributes = [])
Declares a subfeature. feature_name: Root feature that is not a subfeature. value_string: An optional value-string specifying which feature or subfeature values this subfeature is specific to, if any. subfeature: The name of the subfeature being declared. subvalues: The allowed values of this subfeature. attributes: The attributes of the subfeature.
Declares a subfeature. feature_name: Root feature that is not a subfeature. value_string: An optional value-string specifying which feature or subfeature values this subfeature is specific to, if any. subfeature: The name of the subfeature being declared. subvalues: The allowed values of this subfeature. attributes: The attributes of the subfeature.
[ "Declares", "a", "subfeature", ".", "feature_name", ":", "Root", "feature", "that", "is", "not", "a", "subfeature", ".", "value_string", ":", "An", "optional", "value", "-", "string", "specifying", "which", "feature", "or", "subfeature", "values", "this", "subfeature", "is", "specific", "to", "if", "any", ".", "subfeature", ":", "The", "name", "of", "the", "subfeature", "being", "declared", ".", "subvalues", ":", "The", "allowed", "values", "of", "this", "subfeature", ".", "attributes", ":", "The", "attributes", "of", "the", "subfeature", "." ]
def subfeature (feature_name, value_string, subfeature, subvalues, attributes = []): """ Declares a subfeature. feature_name: Root feature that is not a subfeature. value_string: An optional value-string specifying which feature or subfeature values this subfeature is specific to, if any. subfeature: The name of the subfeature being declared. subvalues: The allowed values of this subfeature. attributes: The attributes of the subfeature. """ parent_feature = validate_feature (feature_name) # Add grist to the subfeature name if a value-string was supplied subfeature_name = __get_subfeature_name (subfeature, value_string) if subfeature_name in __all_features[feature_name].subfeatures: message = "'%s' already declared as a subfeature of '%s'" % (subfeature, feature_name) message += " specific to '%s'" % value_string raise BaseException (message) # First declare the subfeature as a feature in its own right f = feature (feature_name + '-' + subfeature_name, subvalues, attributes + ['subfeature']) f.set_parent(parent_feature, value_string) parent_feature.add_subfeature(f) # Now make sure the subfeature values are known. extend_subfeature (feature_name, value_string, subfeature, subvalues)
[ "def", "subfeature", "(", "feature_name", ",", "value_string", ",", "subfeature", ",", "subvalues", ",", "attributes", "=", "[", "]", ")", ":", "parent_feature", "=", "validate_feature", "(", "feature_name", ")", "# Add grist to the subfeature name if a value-string was supplied", "subfeature_name", "=", "__get_subfeature_name", "(", "subfeature", ",", "value_string", ")", "if", "subfeature_name", "in", "__all_features", "[", "feature_name", "]", ".", "subfeatures", ":", "message", "=", "\"'%s' already declared as a subfeature of '%s'\"", "%", "(", "subfeature", ",", "feature_name", ")", "message", "+=", "\" specific to '%s'\"", "%", "value_string", "raise", "BaseException", "(", "message", ")", "# First declare the subfeature as a feature in its own right", "f", "=", "feature", "(", "feature_name", "+", "'-'", "+", "subfeature_name", ",", "subvalues", ",", "attributes", "+", "[", "'subfeature'", "]", ")", "f", ".", "set_parent", "(", "parent_feature", ",", "value_string", ")", "parent_feature", ".", "add_subfeature", "(", "f", ")", "# Now make sure the subfeature values are known.", "extend_subfeature", "(", "feature_name", ",", "value_string", ",", "subfeature", ",", "subvalues", ")" ]
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/feature.py#L482-L509
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/index/package_finder.py
python
CandidateEvaluator.sort_best_candidate
( self, candidates, # type: List[InstallationCandidate] )
return best_candidate
Return the best candidate per the instance's sort order, or None if no candidate is acceptable.
Return the best candidate per the instance's sort order, or None if no candidate is acceptable.
[ "Return", "the", "best", "candidate", "per", "the", "instance", "s", "sort", "order", "or", "None", "if", "no", "candidate", "is", "acceptable", "." ]
def sort_best_candidate( self, candidates, # type: List[InstallationCandidate] ): # type: (...) -> Optional[InstallationCandidate] """ Return the best candidate per the instance's sort order, or None if no candidate is acceptable. """ if not candidates: return None best_candidate = max(candidates, key=self._sort_key) return best_candidate
[ "def", "sort_best_candidate", "(", "self", ",", "candidates", ",", "# type: List[InstallationCandidate]", ")", ":", "# type: (...) -> Optional[InstallationCandidate]", "if", "not", "candidates", ":", "return", "None", "best_candidate", "=", "max", "(", "candidates", ",", "key", "=", "self", ".", "_sort_key", ")", "return", "best_candidate" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/index/package_finder.py#L542-L554
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/packages/six.py
python
_SixMetaPathImporter.get_code
(self, fullname)
return None
Return None Required, if is_package is implemented
Return None
[ "Return", "None" ]
def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None
[ "def", "get_code", "(", "self", ",", "fullname", ")", ":", "self", ".", "__get_module", "(", "fullname", ")", "# eventually raises ImportError", "return", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/packages/six.py#L218-L223
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/io/idl.py
python
_read_int64
(f)
return np.int64(struct.unpack('>q', f.read(8))[0])
Read a signed 64-bit integer
Read a signed 64-bit integer
[ "Read", "a", "signed", "64", "-", "bit", "integer" ]
def _read_int64(f): '''Read a signed 64-bit integer''' return np.int64(struct.unpack('>q', f.read(8))[0])
[ "def", "_read_int64", "(", "f", ")", ":", "return", "np", ".", "int64", "(", "struct", ".", "unpack", "(", "'>q'", ",", "f", ".", "read", "(", "8", ")", ")", "[", "0", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/io/idl.py#L116-L118
epiqc/ScaffCC
66a79944ee4cd116b27bc1a69137276885461db8
clang/tools/scan-build-py/libscanbuild/arguments.py
python
create_intercept_parser
()
return parser
Creates a parser for command-line arguments to 'intercept'.
Creates a parser for command-line arguments to 'intercept'.
[ "Creates", "a", "parser", "for", "command", "-", "line", "arguments", "to", "intercept", "." ]
def create_intercept_parser(): """ Creates a parser for command-line arguments to 'intercept'. """ parser = create_default_parser() parser_add_cdb(parser) parser_add_prefer_wrapper(parser) parser_add_compilers(parser) advanced = parser.add_argument_group('advanced options') group = advanced.add_mutually_exclusive_group() group.add_argument( '--append', action='store_true', help="""Extend existing compilation database with new entries. Duplicate entries are detected and not present in the final output. The output is not continuously updated, it's done when the build command finished. """) parser.add_argument( dest='build', nargs=argparse.REMAINDER, help="""Command to run.""") return parser
[ "def", "create_intercept_parser", "(", ")", ":", "parser", "=", "create_default_parser", "(", ")", "parser_add_cdb", "(", "parser", ")", "parser_add_prefer_wrapper", "(", "parser", ")", "parser_add_compilers", "(", "parser", ")", "advanced", "=", "parser", ".", "add_argument_group", "(", "'advanced options'", ")", "group", "=", "advanced", ".", "add_mutually_exclusive_group", "(", ")", "group", ".", "add_argument", "(", "'--append'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"\"\"Extend existing compilation database with new entries.\n Duplicate entries are detected and not present in the final output.\n The output is not continuously updated, it's done when the build\n command finished. \"\"\"", ")", "parser", ".", "add_argument", "(", "dest", "=", "'build'", ",", "nargs", "=", "argparse", ".", "REMAINDER", ",", "help", "=", "\"\"\"Command to run.\"\"\"", ")", "return", "parser" ]
https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/tools/scan-build-py/libscanbuild/arguments.py#L143-L164
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetCompilerPdbName
(self, config, expand_special)
return pdbname
Get the pdb file name that should be used for compiler invocations, or None if there's no explicit name specified.
Get the pdb file name that should be used for compiler invocations, or None if there's no explicit name specified.
[ "Get", "the", "pdb", "file", "name", "that", "should", "be", "used", "for", "compiler", "invocations", "or", "None", "if", "there", "s", "no", "explicit", "name", "specified", "." ]
def GetCompilerPdbName(self, config, expand_special): """Get the pdb file name that should be used for compiler invocations, or None if there's no explicit name specified.""" config = self._TargetConfig(config) pdbname = self._Setting( ('VCCLCompilerTool', 'ProgramDataBaseFileName'), config) if pdbname: pdbname = expand_special(self.ConvertVSMacros(pdbname)) return pdbname
[ "def", "GetCompilerPdbName", "(", "self", ",", "config", ",", "expand_special", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "pdbname", "=", "self", ".", "_Setting", "(", "(", "'VCCLCompilerTool'", ",", "'ProgramDataBaseFileName'", ")", ",", "config", ")", "if", "pdbname", ":", "pdbname", "=", "expand_special", "(", "self", ".", "ConvertVSMacros", "(", "pdbname", ")", ")", "return", "pdbname" ]
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/msvs_emulation.py#L363-L371
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/formats/latex.py
python
RowStringConverter._compose_cline
(self, i: int, icol: int)
return "".join(lst)
Create clines after multirow-blocks are finished.
Create clines after multirow-blocks are finished.
[ "Create", "clines", "after", "multirow", "-", "blocks", "are", "finished", "." ]
def _compose_cline(self, i: int, icol: int) -> str: """ Create clines after multirow-blocks are finished. """ lst = [] for cl in self.clinebuf: if cl[0] == i: lst.append(f"\n\\cline{{{cl[1]:d}-{icol:d}}}") # remove entries that have been written to buffer self.clinebuf = [x for x in self.clinebuf if x[0] != i] return "".join(lst)
[ "def", "_compose_cline", "(", "self", ",", "i", ":", "int", ",", "icol", ":", "int", ")", "->", "str", ":", "lst", "=", "[", "]", "for", "cl", "in", "self", ".", "clinebuf", ":", "if", "cl", "[", "0", "]", "==", "i", ":", "lst", ".", "append", "(", "f\"\\n\\\\cline{{{cl[1]:d}-{icol:d}}}\"", ")", "# remove entries that have been written to buffer", "self", ".", "clinebuf", "=", "[", "x", "for", "x", "in", "self", ".", "clinebuf", "if", "x", "[", "0", "]", "!=", "i", "]", "return", "\"\"", ".", "join", "(", "lst", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/latex.py#L263-L273
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/gluon/utils.py
python
_brief_print_list
(lst, limit=7)
return ', '.join(["'%s'"%str(i) for i in lst])
Print at most `limit` elements of list.
Print at most `limit` elements of list.
[ "Print", "at", "most", "limit", "elements", "of", "list", "." ]
def _brief_print_list(lst, limit=7): """Print at most `limit` elements of list.""" lst = list(lst) if len(lst) > limit: return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \ _brief_print_list(lst[-limit//2:], limit) return ', '.join(["'%s'"%str(i) for i in lst])
[ "def", "_brief_print_list", "(", "lst", ",", "limit", "=", "7", ")", ":", "lst", "=", "list", "(", "lst", ")", "if", "len", "(", "lst", ")", ">", "limit", ":", "return", "_brief_print_list", "(", "lst", "[", ":", "limit", "//", "2", "]", ",", "limit", ")", "+", "', ..., '", "+", "_brief_print_list", "(", "lst", "[", "-", "limit", "//", "2", ":", "]", ",", "limit", ")", "return", "', '", ".", "join", "(", "[", "\"'%s'\"", "%", "str", "(", "i", ")", "for", "i", "in", "lst", "]", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/utils.py#L389-L395
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
PyApp_GetMacAboutMenuItemId
(*args)
return _core_.PyApp_GetMacAboutMenuItemId(*args)
PyApp_GetMacAboutMenuItemId() -> long
PyApp_GetMacAboutMenuItemId() -> long
[ "PyApp_GetMacAboutMenuItemId", "()", "-", ">", "long" ]
def PyApp_GetMacAboutMenuItemId(*args): """PyApp_GetMacAboutMenuItemId() -> long""" return _core_.PyApp_GetMacAboutMenuItemId(*args)
[ "def", "PyApp_GetMacAboutMenuItemId", "(", "*", "args", ")", ":", "return", "_core_", ".", "PyApp_GetMacAboutMenuItemId", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L8278-L8280
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
panreas_hnn/hed-globalweight/scripts/cpp_lint.py
python
_SetOutputFormat
(output_format)
Sets the module's output format.
Sets the module's output format.
[ "Sets", "the", "module", "s", "output", "format", "." ]
def _SetOutputFormat(output_format): """Sets the module's output format.""" _cpplint_state.SetOutputFormat(output_format)
[ "def", "_SetOutputFormat", "(", "output_format", ")", ":", "_cpplint_state", ".", "SetOutputFormat", "(", "output_format", ")" ]
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/panreas_hnn/hed-globalweight/scripts/cpp_lint.py#L772-L774
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/toasterbox.py
python
ToasterBox.GetUseFocus
(self)
return self._usefocus
Returns whether :class:`ToasterBox` will steal the focus from the parent application.
Returns whether :class:`ToasterBox` will steal the focus from the parent application.
[ "Returns", "whether", ":", "class", ":", "ToasterBox", "will", "steal", "the", "focus", "from", "the", "parent", "application", "." ]
def GetUseFocus(self): """ Returns whether :class:`ToasterBox` will steal the focus from the parent application. """ return self._usefocus
[ "def", "GetUseFocus", "(", "self", ")", ":", "return", "self", ".", "_usefocus" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/toasterbox.py#L597-L600
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PropertyGridInterface.GetSelectedProperties
(*args, **kwargs)
return _propgrid.PropertyGridInterface_GetSelectedProperties(*args, **kwargs)
GetSelectedProperties(self) -> wxArrayPGProperty
GetSelectedProperties(self) -> wxArrayPGProperty
[ "GetSelectedProperties", "(", "self", ")", "-", ">", "wxArrayPGProperty" ]
def GetSelectedProperties(*args, **kwargs): """GetSelectedProperties(self) -> wxArrayPGProperty""" return _propgrid.PropertyGridInterface_GetSelectedProperties(*args, **kwargs)
[ "def", "GetSelectedProperties", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_GetSelectedProperties", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L1280-L1282
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/sparse_ops.py
python
_convert_to_sparse_tensor
(sp_input)
return sp_input
Convert `sp_input` to `SparseTensor` and return it. Args: sp_input: `SparseTensor` or `SparseTensorValue`. Returns: `sp_input` converted to `SparseTensor`. Raises: ValueError: if `sp_input` is neither `SparseTensor` nor `SparseTensorValue`.
Convert `sp_input` to `SparseTensor` and return it.
[ "Convert", "sp_input", "to", "SparseTensor", "and", "return", "it", "." ]
def _convert_to_sparse_tensor(sp_input): """Convert `sp_input` to `SparseTensor` and return it. Args: sp_input: `SparseTensor` or `SparseTensorValue`. Returns: `sp_input` converted to `SparseTensor`. Raises: ValueError: if `sp_input` is neither `SparseTensor` nor `SparseTensorValue`. """ if isinstance(sp_input, sparse_tensor.SparseTensorValue): return sparse_tensor.SparseTensor.from_value(sp_input) if not isinstance(sp_input, sparse_tensor.SparseTensor): raise TypeError("Input must be a SparseTensor.") return sp_input
[ "def", "_convert_to_sparse_tensor", "(", "sp_input", ")", ":", "if", "isinstance", "(", "sp_input", ",", "sparse_tensor", ".", "SparseTensorValue", ")", ":", "return", "sparse_tensor", ".", "SparseTensor", ".", "from_value", "(", "sp_input", ")", "if", "not", "isinstance", "(", "sp_input", ",", "sparse_tensor", ".", "SparseTensor", ")", ":", "raise", "TypeError", "(", "\"Input must be a SparseTensor.\"", ")", "return", "sp_input" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/sparse_ops.py#L52-L68
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/python/google/httpd_utils.py
python
ApacheHttpd.__init__
(self, start_command, stop_command, port_list, cygserver_path=None)
Args: start_command: command list to call to start the httpd stop_command: command list to call to stop the httpd if one has been started. May kill all httpd processes running on the machine. port_list: list of ports expected to respond on the local machine when the server has been successfully started. cygserver_path: Path to cygserver.exe. If specified, exe will be started with server as well as stopped when server is stopped.
Args: start_command: command list to call to start the httpd stop_command: command list to call to stop the httpd if one has been started. May kill all httpd processes running on the machine. port_list: list of ports expected to respond on the local machine when the server has been successfully started. cygserver_path: Path to cygserver.exe. If specified, exe will be started with server as well as stopped when server is stopped.
[ "Args", ":", "start_command", ":", "command", "list", "to", "call", "to", "start", "the", "httpd", "stop_command", ":", "command", "list", "to", "call", "to", "stop", "the", "httpd", "if", "one", "has", "been", "started", ".", "May", "kill", "all", "httpd", "processes", "running", "on", "the", "machine", ".", "port_list", ":", "list", "of", "ports", "expected", "to", "respond", "on", "the", "local", "machine", "when", "the", "server", "has", "been", "successfully", "started", ".", "cygserver_path", ":", "Path", "to", "cygserver", ".", "exe", ".", "If", "specified", "exe", "will", "be", "started", "with", "server", "as", "well", "as", "stopped", "when", "server", "is", "stopped", "." ]
def __init__(self, start_command, stop_command, port_list, cygserver_path=None): """Args: start_command: command list to call to start the httpd stop_command: command list to call to stop the httpd if one has been started. May kill all httpd processes running on the machine. port_list: list of ports expected to respond on the local machine when the server has been successfully started. cygserver_path: Path to cygserver.exe. If specified, exe will be started with server as well as stopped when server is stopped. """ self._http_server_proc = None self._start_command = start_command self._stop_command = stop_command self._port_list = port_list self._cygserver_path = cygserver_path
[ "def", "__init__", "(", "self", ",", "start_command", ",", "stop_command", ",", "port_list", ",", "cygserver_path", "=", "None", ")", ":", "self", ".", "_http_server_proc", "=", "None", "self", ".", "_start_command", "=", "start_command", "self", ".", "_stop_command", "=", "stop_command", "self", ".", "_port_list", "=", "port_list", "self", ".", "_cygserver_path", "=", "cygserver_path" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/python/google/httpd_utils.py#L118-L133
continental/ecal
204dab80a24fe01abca62541133b311bf0c09608
lang/python/core/ecal/core/core.py
python
subscriber.set_qos_reliability
(self, qpolicy)
return sub_set_qos_reliability(self.thandle, qpolicy)
set quality of service reliability mode :param qpolicy: 0 = best_effort_reliability_qos, 1 = reliable_reliability_qos :type qpolicy: int
set quality of service reliability mode
[ "set", "quality", "of", "service", "reliability", "mode" ]
def set_qos_reliability(self, qpolicy): """ set quality of service reliability mode :param qpolicy: 0 = best_effort_reliability_qos, 1 = reliable_reliability_qos :type qpolicy: int """ return sub_set_qos_reliability(self.thandle, qpolicy)
[ "def", "set_qos_reliability", "(", "self", ",", "qpolicy", ")", ":", "return", "sub_set_qos_reliability", "(", "self", ".", "thandle", ",", "qpolicy", ")" ]
https://github.com/continental/ecal/blob/204dab80a24fe01abca62541133b311bf0c09608/lang/python/core/ecal/core/core.py#L672-L680
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/base64.py
python
encodestring
(s)
return "".join(pieces)
Encode a string into multiple lines of base-64 data.
Encode a string into multiple lines of base-64 data.
[ "Encode", "a", "string", "into", "multiple", "lines", "of", "base", "-", "64", "data", "." ]
def encodestring(s): """Encode a string into multiple lines of base-64 data.""" pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i : i + MAXBINSIZE] pieces.append(binascii.b2a_base64(chunk)) return "".join(pieces)
[ "def", "encodestring", "(", "s", ")", ":", "pieces", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "s", ")", ",", "MAXBINSIZE", ")", ":", "chunk", "=", "s", "[", "i", ":", "i", "+", "MAXBINSIZE", "]", "pieces", ".", "append", "(", "binascii", ".", "b2a_base64", "(", "chunk", ")", ")", "return", "\"\"", ".", "join", "(", "pieces", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/base64.py#L310-L316
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/models/image/cifar10/cifar10_input.py
python
read_cifar10
(filename_queue)
return result
Reads and parses examples from CIFAR10 data files. Recommendation: if you want N-way read parallelism, call this function N times. This will give you N independent Readers reading different files & positions within those files, which will give better mixing of examples. Args: filename_queue: A queue of strings with the filenames to read from. Returns: An object representing a single example, with the following fields: height: number of rows in the result (32) width: number of columns in the result (32) depth: number of color channels in the result (3) key: a scalar string Tensor describing the filename & record number for this example. label: an int32 Tensor with the label in the range 0..9. uint8image: a [height, width, depth] uint8 Tensor with the image data
Reads and parses examples from CIFAR10 data files.
[ "Reads", "and", "parses", "examples", "from", "CIFAR10", "data", "files", "." ]
def read_cifar10(filename_queue): """Reads and parses examples from CIFAR10 data files. Recommendation: if you want N-way read parallelism, call this function N times. This will give you N independent Readers reading different files & positions within those files, which will give better mixing of examples. Args: filename_queue: A queue of strings with the filenames to read from. Returns: An object representing a single example, with the following fields: height: number of rows in the result (32) width: number of columns in the result (32) depth: number of color channels in the result (3) key: a scalar string Tensor describing the filename & record number for this example. label: an int32 Tensor with the label in the range 0..9. uint8image: a [height, width, depth] uint8 Tensor with the image data """ class CIFAR10Record(object): pass result = CIFAR10Record() # Dimensions of the images in the CIFAR-10 dataset. # See http://www.cs.toronto.edu/~kriz/cifar.html for a description of the # input format. label_bytes = 1 # 2 for CIFAR-100 result.height = 32 result.width = 32 result.depth = 3 image_bytes = result.height * result.width * result.depth # Every record consists of a label followed by the image, with a # fixed number of bytes for each. record_bytes = label_bytes + image_bytes # Read a record, getting filenames from the filename_queue. No # header or footer in the CIFAR-10 format, so we leave header_bytes # and footer_bytes at their default of 0. reader = tf.FixedLengthRecordReader(record_bytes=record_bytes) result.key, value = reader.read(filename_queue) # Convert from a string to a vector of uint8 that is record_bytes long. record_bytes = tf.decode_raw(value, tf.uint8) # The first bytes represent the label, which we convert from uint8->int32. result.label = tf.cast( tf.slice(record_bytes, [0], [label_bytes]), tf.int32) # The remaining bytes after the label represent the image, which we reshape # from [depth * height * width] to [depth, height, width]. depth_major = tf.reshape(tf.slice(record_bytes, [label_bytes], [image_bytes]), [result.depth, result.height, result.width]) # Convert from [depth, height, width] to [height, width, depth]. result.uint8image = tf.transpose(depth_major, [1, 2, 0]) return result
[ "def", "read_cifar10", "(", "filename_queue", ")", ":", "class", "CIFAR10Record", "(", "object", ")", ":", "pass", "result", "=", "CIFAR10Record", "(", ")", "# Dimensions of the images in the CIFAR-10 dataset.", "# See http://www.cs.toronto.edu/~kriz/cifar.html for a description of the", "# input format.", "label_bytes", "=", "1", "# 2 for CIFAR-100", "result", ".", "height", "=", "32", "result", ".", "width", "=", "32", "result", ".", "depth", "=", "3", "image_bytes", "=", "result", ".", "height", "*", "result", ".", "width", "*", "result", ".", "depth", "# Every record consists of a label followed by the image, with a", "# fixed number of bytes for each.", "record_bytes", "=", "label_bytes", "+", "image_bytes", "# Read a record, getting filenames from the filename_queue. No", "# header or footer in the CIFAR-10 format, so we leave header_bytes", "# and footer_bytes at their default of 0.", "reader", "=", "tf", ".", "FixedLengthRecordReader", "(", "record_bytes", "=", "record_bytes", ")", "result", ".", "key", ",", "value", "=", "reader", ".", "read", "(", "filename_queue", ")", "# Convert from a string to a vector of uint8 that is record_bytes long.", "record_bytes", "=", "tf", ".", "decode_raw", "(", "value", ",", "tf", ".", "uint8", ")", "# The first bytes represent the label, which we convert from uint8->int32.", "result", ".", "label", "=", "tf", ".", "cast", "(", "tf", ".", "slice", "(", "record_bytes", ",", "[", "0", "]", ",", "[", "label_bytes", "]", ")", ",", "tf", ".", "int32", ")", "# The remaining bytes after the label represent the image, which we reshape", "# from [depth * height * width] to [depth, height, width].", "depth_major", "=", "tf", ".", "reshape", "(", "tf", ".", "slice", "(", "record_bytes", ",", "[", "label_bytes", "]", ",", "[", "image_bytes", "]", ")", ",", "[", "result", ".", "depth", ",", "result", ".", "height", ",", "result", ".", "width", "]", ")", "# Convert from [depth, height, width] to [height, width, depth].", "result", ".", "uint8image", "=", "tf", ".", "transpose", "(", "depth_major", ",", "[", "1", ",", "2", ",", "0", "]", ")", "return", "result" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/models/image/cifar10/cifar10_input.py#L38-L96
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/reduction_gui/reduction/diffraction/diffraction_adv_setup_script.py
python
AdvancedSetupScript.to_script
(self)
return script
'Public' method to save the current GUI to string via str() and general class ReductionScript
'Public' method to save the current GUI to string via str() and general class ReductionScript
[ "Public", "method", "to", "save", "the", "current", "GUI", "to", "string", "via", "str", "()", "and", "general", "class", "ReductionScript" ]
def to_script(self): """ 'Public' method to save the current GUI to string via str() and general class ReductionScript """ # 1. Form (partial) script parnamevaluedict = self.buildParameterDict() script = "" for parname in self.parnamelist: parvalue = parnamevaluedict[parname] if parvalue != "" and parname != "Instrument" and parname != "Facility": if str(parvalue) == "True": parvalue = "1" elif str(parvalue) == "False": parvalue = "0" if not isinstance(parvalue, dict): script += "%-10s = \"%s\",\n" % (parname, parvalue) else: script += "%-10s = %s,\n" % (parname, parvalue) #ENDFOR return script
[ "def", "to_script", "(", "self", ")", ":", "# 1. Form (partial) script", "parnamevaluedict", "=", "self", ".", "buildParameterDict", "(", ")", "script", "=", "\"\"", "for", "parname", "in", "self", ".", "parnamelist", ":", "parvalue", "=", "parnamevaluedict", "[", "parname", "]", "if", "parvalue", "!=", "\"\"", "and", "parname", "!=", "\"Instrument\"", "and", "parname", "!=", "\"Facility\"", ":", "if", "str", "(", "parvalue", ")", "==", "\"True\"", ":", "parvalue", "=", "\"1\"", "elif", "str", "(", "parvalue", ")", "==", "\"False\"", ":", "parvalue", "=", "\"0\"", "if", "not", "isinstance", "(", "parvalue", ",", "dict", ")", ":", "script", "+=", "\"%-10s = \\\"%s\\\",\\n\"", "%", "(", "parname", ",", "parvalue", ")", "else", ":", "script", "+=", "\"%-10s = %s,\\n\"", "%", "(", "parname", ",", "parvalue", ")", "#ENDFOR", "return", "script" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_gui/reduction/diffraction/diffraction_adv_setup_script.py#L138-L157
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/configdialog.py
python
VarTrace.clear
(self)
Clear lists (for tests).
Clear lists (for tests).
[ "Clear", "lists", "(", "for", "tests", ")", "." ]
def clear(self): "Clear lists (for tests)." # Call after all tests in a module to avoid memory leaks. self.untraced.clear() self.traced.clear()
[ "def", "clear", "(", "self", ")", ":", "# Call after all tests in a module to avoid memory leaks.", "self", ".", "untraced", ".", "clear", "(", ")", "self", ".", "traced", ".", "clear", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/configdialog.py#L2212-L2216
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/importIFClegacy.py
python
IfcSchema.readTypes
(self)
return types
Parse all the possible types from the schema, returns a dictionary Name -> Type
Parse all the possible types from the schema, returns a dictionary Name -> Type
[ "Parse", "all", "the", "possible", "types", "from", "the", "schema", "returns", "a", "dictionary", "Name", "-", ">", "Type" ]
def readTypes(self): """ Parse all the possible types from the schema, returns a dictionary Name -> Type """ types = {} for m in re.finditer("TYPE (.*) = (.*);", self.data): typename, typetype = m.groups() if typetype in self.SIMPLETYPES: types[typename] = typetype else: types[typename] = "#" + typetype return types
[ "def", "readTypes", "(", "self", ")", ":", "types", "=", "{", "}", "for", "m", "in", "re", ".", "finditer", "(", "\"TYPE (.*) = (.*);\"", ",", "self", ".", "data", ")", ":", "typename", ",", "typetype", "=", "m", ".", "groups", "(", ")", "if", "typetype", "in", "self", ".", "SIMPLETYPES", ":", "types", "[", "typename", "]", "=", "typetype", "else", ":", "types", "[", "typename", "]", "=", "\"#\"", "+", "typetype", "return", "types" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/importIFClegacy.py#L1423-L1436
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/dos/load_euphonic.py
python
euphonic_calculate_modes
(filename: str, cutoff: float = 20., gamma: bool = True, acoustic_sum_rule: Optional[str] = 'reciprocal')
return modes
Read force constants file with Euphonic and sample frequencies/modes :param filename: Input data :param cutoff: Sampling density of Brillouin-zone. Specified as real-space length cutoff in Angstrom. :param gamma: Shift sampling grid to include the Gamma-point. :param acoustic_sum_rule: Apply acoustic sum rule correction to force constants: options are 'realspace' and 'reciprocal', specifying different implementations of the correction. If None, no correction is applied. This option is referred to as "asr" in the Euphonic python API and command-line tools. :returns: euphonic.QpointPhononModes
Read force constants file with Euphonic and sample frequencies/modes
[ "Read", "force", "constants", "file", "with", "Euphonic", "and", "sample", "frequencies", "/", "modes" ]
def euphonic_calculate_modes(filename: str, cutoff: float = 20., gamma: bool = True, acoustic_sum_rule: Optional[str] = 'reciprocal'): """ Read force constants file with Euphonic and sample frequencies/modes :param filename: Input data :param cutoff: Sampling density of Brillouin-zone. Specified as real-space length cutoff in Angstrom. :param gamma: Shift sampling grid to include the Gamma-point. :param acoustic_sum_rule: Apply acoustic sum rule correction to force constants: options are 'realspace' and 'reciprocal', specifying different implementations of the correction. If None, no correction is applied. This option is referred to as "asr" in the Euphonic python API and command-line tools. :returns: euphonic.QpointPhononModes """ from math import ceil from euphonic.cli.utils import force_constants_from_file from euphonic.util import mp_grid fc = force_constants_from_file(filename) recip_lattice_lengths = np.linalg.norm( fc.crystal.reciprocal_cell().to('1/angstrom').magnitude, axis=1) mp_sampling = [ceil(x) for x in (cutoff * recip_lattice_lengths / (2 * np.pi))] qpts = mp_grid(mp_sampling) if gamma: mp_sampling = np.array(mp_sampling, dtype=int) # Shift directions with even number of samples by half the grid spacing offsets = ((mp_sampling + 1) % 2) * (0.5 / mp_sampling) qpts += offsets logger.notice('Calculating phonon modes on {} grid'.format( 'x'.join(map(str, mp_sampling)))) modes = fc.calculate_qpoint_phonon_modes(qpts, asr=acoustic_sum_rule) return modes
[ "def", "euphonic_calculate_modes", "(", "filename", ":", "str", ",", "cutoff", ":", "float", "=", "20.", ",", "gamma", ":", "bool", "=", "True", ",", "acoustic_sum_rule", ":", "Optional", "[", "str", "]", "=", "'reciprocal'", ")", ":", "from", "math", "import", "ceil", "from", "euphonic", ".", "cli", ".", "utils", "import", "force_constants_from_file", "from", "euphonic", ".", "util", "import", "mp_grid", "fc", "=", "force_constants_from_file", "(", "filename", ")", "recip_lattice_lengths", "=", "np", ".", "linalg", ".", "norm", "(", "fc", ".", "crystal", ".", "reciprocal_cell", "(", ")", ".", "to", "(", "'1/angstrom'", ")", ".", "magnitude", ",", "axis", "=", "1", ")", "mp_sampling", "=", "[", "ceil", "(", "x", ")", "for", "x", "in", "(", "cutoff", "*", "recip_lattice_lengths", "/", "(", "2", "*", "np", ".", "pi", ")", ")", "]", "qpts", "=", "mp_grid", "(", "mp_sampling", ")", "if", "gamma", ":", "mp_sampling", "=", "np", ".", "array", "(", "mp_sampling", ",", "dtype", "=", "int", ")", "# Shift directions with even number of samples by half the grid spacing", "offsets", "=", "(", "(", "mp_sampling", "+", "1", ")", "%", "2", ")", "*", "(", "0.5", "/", "mp_sampling", ")", "qpts", "+=", "offsets", "logger", ".", "notice", "(", "'Calculating phonon modes on {} grid'", ".", "format", "(", "'x'", ".", "join", "(", "map", "(", "str", ",", "mp_sampling", ")", ")", ")", ")", "modes", "=", "fc", ".", "calculate_qpoint_phonon_modes", "(", "qpts", ",", "asr", "=", "acoustic_sum_rule", ")", "return", "modes" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/dos/load_euphonic.py#L28-L71
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/xrc.py
python
XmlNode.AddPropertyName
(*args, **kwargs)
return _xrc.XmlNode_AddPropertyName(*args, **kwargs)
AddPropertyName(self, String name, String value)
AddPropertyName(self, String name, String value)
[ "AddPropertyName", "(", "self", "String", "name", "String", "value", ")" ]
def AddPropertyName(*args, **kwargs): """AddPropertyName(self, String name, String value)""" return _xrc.XmlNode_AddPropertyName(*args, **kwargs)
[ "def", "AddPropertyName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_xrc", ".", "XmlNode_AddPropertyName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/xrc.py#L378-L380
ArduPilot/ardupilot
6e684b3496122b8158ac412b609d00004b7ac306
libraries/AP_HAL_ChibiOS/hwdef/scripts/chibios_hwdef.py
python
write_ROMFS
(outdir)
create ROMFS embedded header
create ROMFS embedded header
[ "create", "ROMFS", "embedded", "header" ]
def write_ROMFS(outdir): '''create ROMFS embedded header''' romfs_list = [] for k in romfs.keys(): romfs_list.append((k, romfs[k])) env_vars['ROMFS_FILES'] = romfs_list
[ "def", "write_ROMFS", "(", "outdir", ")", ":", "romfs_list", "=", "[", "]", "for", "k", "in", "romfs", ".", "keys", "(", ")", ":", "romfs_list", ".", "append", "(", "(", "k", ",", "romfs", "[", "k", "]", ")", ")", "env_vars", "[", "'ROMFS_FILES'", "]", "=", "romfs_list" ]
https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/libraries/AP_HAL_ChibiOS/hwdef/scripts/chibios_hwdef.py#L2083-L2088