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
Qihoo360/mongosync
55b647e81c072ebe91daaa3b9dc1a953c3c22e19
dep/mongo-cxx-driver/site_scons/buildscripts/cpplint.py
python
CheckBraces
(filename, clean_lines, linenum, error)
Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Looks for misplaced braces (e.g. at the end of line).
[ "Looks", "for", "misplaced", "braces", "(", "e", ".", "g", ".", "at", "the", "end", "of", "line", ")", "." ]
def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone # is using braces in a block to explicitly create a new scope, # which is commonly used to control the lifetime of # stack-allocated variables. We don't detect this perfectly: we # just don't complain if the last non-whitespace character on the # previous non-blank line is ';', ':', '{', or '}'. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if not Search(r'[;:}{]\s*$', prevline): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\s*', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) if endline[endpos:].find('{') == -1: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') else: # common case: else not followed by a multi-line if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Braces shouldn't be followed by a ; unless they're defining a struct # or initializing an array. # We can't tell in general, but we can for some common cases. prevlinenum = linenum while True: (prevline, prevlinenum) = GetPreviousNonBlankLine(clean_lines, prevlinenum) if Match(r'\s+{.*}\s*;', line) and not prevline.count(';'): line = prevline + line else: break if (Search(r'{.*}\s*;', line) and line.count('{') == line.count('}') and not Search(r'struct|class|enum|\s*=\s*{', line)): error(filename, linenum, 'readability/braces', 4, "You don't need a ; after a }")
[ "def", "CheckBraces", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "if", "Match", "(", "r'\\s*{\\s*$'", ",", "line", ")", ":", "# We allow an open brace to start a line in the case where someone", "# is using braces in a block to explicitly create a new scope,", "# which is commonly used to control the lifetime of", "# stack-allocated variables. We don't detect this perfectly: we", "# just don't complain if the last non-whitespace character on the", "# previous non-blank line is ';', ':', '{', or '}'.", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "not", "Search", "(", "r'[;:}{]\\s*$'", ",", "prevline", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "4", ",", "'{ should almost always be at the end of the previous line'", ")", "# An else clause should be on the same line as the preceding closing brace.", "if", "Match", "(", "r'\\s*else\\s*'", ",", "line", ")", ":", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "Match", "(", "r'\\s*}\\s*$'", ",", "prevline", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'An else should appear on the same line as the preceding }'", ")", "# If braces come on one side of an else, they should be on both.", "# However, we have to worry about \"else if\" that spans multiple lines!", "if", "Search", "(", "r'}\\s*else[^{]*$'", ",", "line", ")", "or", "Match", "(", "r'[^}]*else\\s*{'", ",", "line", ")", ":", "if", "Search", "(", "r'}\\s*else if([^{]*)$'", ",", "line", ")", ":", "# could be multi-line if", "# find the ( after the if", "pos", "=", "line", ".", "find", "(", "'else if'", ")", "pos", "=", "line", ".", "find", "(", "'('", ",", "pos", ")", "if", "pos", ">", "0", ":", "(", "endline", ",", "_", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", "if", "endline", "[", "endpos", ":", "]", ".", "find", "(", "'{'", ")", "==", "-", "1", ":", "# must be brace after if", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "5", ",", "'If an else has a brace on one side, it should have it on both'", ")", "else", ":", "# common case: else not followed by a multi-line if", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "5", ",", "'If an else has a brace on one side, it should have it on both'", ")", "# Likewise, an else should never have the else clause on the same line", "if", "Search", "(", "r'\\belse [^\\s{]'", ",", "line", ")", "and", "not", "Search", "(", "r'\\belse if\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'Else clause should never be on same line as else (use 2 lines)'", ")", "# In the same way, a do/while should never be on one line", "if", "Match", "(", "r'\\s*do [^\\s{]'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "4", ",", "'do/while clauses should not be on a single line'", ")", "# Braces shouldn't be followed by a ; unless they're defining a struct", "# or initializing an array.", "# We can't tell in general, but we can for some common cases.", "prevlinenum", "=", "linenum", "while", "True", ":", "(", "prevline", ",", "prevlinenum", ")", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "prevlinenum", ")", "if", "Match", "(", "r'\\s+{.*}\\s*;'", ",", "line", ")", "and", "not", "prevline", ".", "count", "(", "';'", ")", ":", "line", "=", "prevline", "+", "line", "else", ":", "break", "if", "(", "Search", "(", "r'{.*}\\s*;'", ",", "line", ")", "and", "line", ".", "count", "(", "'{'", ")", "==", "line", ".", "count", "(", "'}'", ")", "and", "not", "Search", "(", "r'struct|class|enum|\\s*=\\s*{'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/braces'", ",", "4", ",", "\"You don't need a ; after a }\"", ")" ]
https://github.com/Qihoo360/mongosync/blob/55b647e81c072ebe91daaa3b9dc1a953c3c22e19/dep/mongo-cxx-driver/site_scons/buildscripts/cpplint.py#L1993-L2064
sigmaai/self-driving-golf-cart
8d891600af3d851add27a10ae45cf3c2108bb87c
ros/src/ros_carla_bridge/carla_ackermann_control/src/carla_ackermann_control/carla_ackermann_control_node.py
python
CarlaAckermannControl.reconfigure_pid_parameters
(self, ego_vehicle_control_parameter, _level)
return ego_vehicle_control_parameter
Callback for dynamic reconfigure call to set the PID parameters :param ego_vehicle_control_parameter: :type ego_vehicle_control_parameter: \ carla_ackermann_control.cfg.EgoVehicleControlParameterConfig
Callback for dynamic reconfigure call to set the PID parameters
[ "Callback", "for", "dynamic", "reconfigure", "call", "to", "set", "the", "PID", "parameters" ]
def reconfigure_pid_parameters(self, ego_vehicle_control_parameter, _level): """ Callback for dynamic reconfigure call to set the PID parameters :param ego_vehicle_control_parameter: :type ego_vehicle_control_parameter: \ carla_ackermann_control.cfg.EgoVehicleControlParameterConfig """ rospy.loginfo("Reconfigure Request: " "speed ({speed_Kp}, {speed_Ki}, {speed_Kd})," "accel ({accel_Kp}, {accel_Ki}, {accel_Kd})," "".format(**ego_vehicle_control_parameter)) self.speed_controller.tunings = ( ego_vehicle_control_parameter['speed_Kp'], ego_vehicle_control_parameter['speed_Ki'], ego_vehicle_control_parameter['speed_Kd'] ) self.accel_controller.tunings = ( ego_vehicle_control_parameter['accel_Kp'], ego_vehicle_control_parameter['accel_Ki'], ego_vehicle_control_parameter['accel_Kd'] ) return ego_vehicle_control_parameter
[ "def", "reconfigure_pid_parameters", "(", "self", ",", "ego_vehicle_control_parameter", ",", "_level", ")", ":", "rospy", ".", "loginfo", "(", "\"Reconfigure Request: \"", "\"speed ({speed_Kp}, {speed_Ki}, {speed_Kd}),\"", "\"accel ({accel_Kp}, {accel_Ki}, {accel_Kd}),\"", "\"\"", ".", "format", "(", "*", "*", "ego_vehicle_control_parameter", ")", ")", "self", ".", "speed_controller", ".", "tunings", "=", "(", "ego_vehicle_control_parameter", "[", "'speed_Kp'", "]", ",", "ego_vehicle_control_parameter", "[", "'speed_Ki'", "]", ",", "ego_vehicle_control_parameter", "[", "'speed_Kd'", "]", ")", "self", ".", "accel_controller", ".", "tunings", "=", "(", "ego_vehicle_control_parameter", "[", "'accel_Kp'", "]", ",", "ego_vehicle_control_parameter", "[", "'accel_Ki'", "]", ",", "ego_vehicle_control_parameter", "[", "'accel_Kd'", "]", ")", "return", "ego_vehicle_control_parameter" ]
https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/carla_ackermann_control/src/carla_ackermann_control/carla_ackermann_control_node.py#L154-L177
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
external_tools/ply_info/example/ansic/cparse.py
python
p_and_expression_2
(t)
and_expression : and_expression AND equality_expression
and_expression : and_expression AND equality_expression
[ "and_expression", ":", "and_expression", "AND", "equality_expression" ]
def p_and_expression_2(t): 'and_expression : and_expression AND equality_expression' pass
[ "def", "p_and_expression_2", "(", "t", ")", ":", "pass" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/cparse.py#L661-L663
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_root.py
python
_root_broyden1_doc
()
Options ------- nit : int, optional Number of iterations to make. If omitted (default), make as many as required to meet tolerances. disp : bool, optional Print status to stdout on every iteration. maxiter : int, optional Maximum number of iterations to make. If more are needed to meet convergence, `NoConvergence` is raised. ftol : float, optional Relative tolerance for the residual. If omitted, not used. fatol : float, optional Absolute tolerance (in max-norm) for the residual. If omitted, default is 6e-6. xtol : float, optional Relative minimum step size. If omitted, not used. xatol : float, optional Absolute minimum step size, as determined from the Jacobian approximation. If the step size is smaller than this, optimization is terminated as successful. If omitted, not used. tol_norm : function(vector) -> scalar, optional Norm to use in convergence check. Default is the maximum norm. line_search : {None, 'armijo' (default), 'wolfe'}, optional Which type of a line search to use to determine the step size in the direction given by the Jacobian approximation. Defaults to 'armijo'. jac_options : dict, optional Options for the respective Jacobian approximation. alpha : float, optional Initial guess for the Jacobian is (-1/alpha). reduction_method : str or tuple, optional Method used in ensuring that the rank of the Broyden matrix stays low. Can either be a string giving the name of the method, or a tuple of the form ``(method, param1, param2, ...)`` that gives the name of the method and values for additional parameters. Methods available: - ``restart``: drop all matrix columns. Has no extra parameters. - ``simple``: drop oldest matrix column. Has no extra parameters. - ``svd``: keep only the most significant SVD components. Extra parameters: - ``to_retain``: number of SVD components to retain when rank reduction is done. Default is ``max_rank - 2``. max_rank : int, optional Maximum rank for the Broyden matrix. Default is infinity (ie., no rank reduction).
Options ------- nit : int, optional Number of iterations to make. If omitted (default), make as many as required to meet tolerances. disp : bool, optional Print status to stdout on every iteration. maxiter : int, optional Maximum number of iterations to make. If more are needed to meet convergence, `NoConvergence` is raised. ftol : float, optional Relative tolerance for the residual. If omitted, not used. fatol : float, optional Absolute tolerance (in max-norm) for the residual. If omitted, default is 6e-6. xtol : float, optional Relative minimum step size. If omitted, not used. xatol : float, optional Absolute minimum step size, as determined from the Jacobian approximation. If the step size is smaller than this, optimization is terminated as successful. If omitted, not used. tol_norm : function(vector) -> scalar, optional Norm to use in convergence check. Default is the maximum norm. line_search : {None, 'armijo' (default), 'wolfe'}, optional Which type of a line search to use to determine the step size in the direction given by the Jacobian approximation. Defaults to 'armijo'. jac_options : dict, optional Options for the respective Jacobian approximation. alpha : float, optional Initial guess for the Jacobian is (-1/alpha). reduction_method : str or tuple, optional Method used in ensuring that the rank of the Broyden matrix stays low. Can either be a string giving the name of the method, or a tuple of the form ``(method, param1, param2, ...)`` that gives the name of the method and values for additional parameters.
[ "Options", "-------", "nit", ":", "int", "optional", "Number", "of", "iterations", "to", "make", ".", "If", "omitted", "(", "default", ")", "make", "as", "many", "as", "required", "to", "meet", "tolerances", ".", "disp", ":", "bool", "optional", "Print", "status", "to", "stdout", "on", "every", "iteration", ".", "maxiter", ":", "int", "optional", "Maximum", "number", "of", "iterations", "to", "make", ".", "If", "more", "are", "needed", "to", "meet", "convergence", "NoConvergence", "is", "raised", ".", "ftol", ":", "float", "optional", "Relative", "tolerance", "for", "the", "residual", ".", "If", "omitted", "not", "used", ".", "fatol", ":", "float", "optional", "Absolute", "tolerance", "(", "in", "max", "-", "norm", ")", "for", "the", "residual", ".", "If", "omitted", "default", "is", "6e", "-", "6", ".", "xtol", ":", "float", "optional", "Relative", "minimum", "step", "size", ".", "If", "omitted", "not", "used", ".", "xatol", ":", "float", "optional", "Absolute", "minimum", "step", "size", "as", "determined", "from", "the", "Jacobian", "approximation", ".", "If", "the", "step", "size", "is", "smaller", "than", "this", "optimization", "is", "terminated", "as", "successful", ".", "If", "omitted", "not", "used", ".", "tol_norm", ":", "function", "(", "vector", ")", "-", ">", "scalar", "optional", "Norm", "to", "use", "in", "convergence", "check", ".", "Default", "is", "the", "maximum", "norm", ".", "line_search", ":", "{", "None", "armijo", "(", "default", ")", "wolfe", "}", "optional", "Which", "type", "of", "a", "line", "search", "to", "use", "to", "determine", "the", "step", "size", "in", "the", "direction", "given", "by", "the", "Jacobian", "approximation", ".", "Defaults", "to", "armijo", ".", "jac_options", ":", "dict", "optional", "Options", "for", "the", "respective", "Jacobian", "approximation", ".", "alpha", ":", "float", "optional", "Initial", "guess", "for", "the", "Jacobian", "is", "(", "-", "1", "/", "alpha", ")", ".", "reduction_method", ":", "str", "or", "tuple", "optional", "Method", "used", "in", "ensuring", "that", "the", "rank", "of", "the", "Broyden", "matrix", "stays", "low", ".", "Can", "either", "be", "a", "string", "giving", "the", "name", "of", "the", "method", "or", "a", "tuple", "of", "the", "form", "(", "method", "param1", "param2", "...", ")", "that", "gives", "the", "name", "of", "the", "method", "and", "values", "for", "additional", "parameters", "." ]
def _root_broyden1_doc(): """ Options ------- nit : int, optional Number of iterations to make. If omitted (default), make as many as required to meet tolerances. disp : bool, optional Print status to stdout on every iteration. maxiter : int, optional Maximum number of iterations to make. If more are needed to meet convergence, `NoConvergence` is raised. ftol : float, optional Relative tolerance for the residual. If omitted, not used. fatol : float, optional Absolute tolerance (in max-norm) for the residual. If omitted, default is 6e-6. xtol : float, optional Relative minimum step size. If omitted, not used. xatol : float, optional Absolute minimum step size, as determined from the Jacobian approximation. If the step size is smaller than this, optimization is terminated as successful. If omitted, not used. tol_norm : function(vector) -> scalar, optional Norm to use in convergence check. Default is the maximum norm. line_search : {None, 'armijo' (default), 'wolfe'}, optional Which type of a line search to use to determine the step size in the direction given by the Jacobian approximation. Defaults to 'armijo'. jac_options : dict, optional Options for the respective Jacobian approximation. alpha : float, optional Initial guess for the Jacobian is (-1/alpha). reduction_method : str or tuple, optional Method used in ensuring that the rank of the Broyden matrix stays low. Can either be a string giving the name of the method, or a tuple of the form ``(method, param1, param2, ...)`` that gives the name of the method and values for additional parameters. Methods available: - ``restart``: drop all matrix columns. Has no extra parameters. - ``simple``: drop oldest matrix column. Has no extra parameters. - ``svd``: keep only the most significant SVD components. Extra parameters: - ``to_retain``: number of SVD components to retain when rank reduction is done. Default is ``max_rank - 2``. max_rank : int, optional Maximum rank for the Broyden matrix. Default is infinity (ie., no rank reduction). """ pass
[ "def", "_root_broyden1_doc", "(", ")", ":", "pass" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_root.py#L307-L362
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/display.py
python
DisplayObject.__init__
(self, data=None, url=None, filename=None)
Create a display object given raw data. When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for 'image/png' data. If the data is a URL, the data will first be downloaded and then displayed. If Parameters ---------- data : unicode, str or bytes The raw data or a URL or file to load the data from url : unicode A URL to download the data from. filename : unicode Path to a local file to load the data from.
Create a display object given raw data.
[ "Create", "a", "display", "object", "given", "raw", "data", "." ]
def __init__(self, data=None, url=None, filename=None): """Create a display object given raw data. When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for 'image/png' data. If the data is a URL, the data will first be downloaded and then displayed. If Parameters ---------- data : unicode, str or bytes The raw data or a URL or file to load the data from url : unicode A URL to download the data from. filename : unicode Path to a local file to load the data from. """ if data is not None and isinstance(data, string_types): if data.startswith('http') and url is None: url = data filename = None data = None elif _safe_exists(data) and filename is None: url = None filename = data data = None self.data = data self.url = url self.filename = None if filename is None else unicode_type(filename) self.reload() self._check_data()
[ "def", "__init__", "(", "self", ",", "data", "=", "None", ",", "url", "=", "None", ",", "filename", "=", "None", ")", ":", "if", "data", "is", "not", "None", "and", "isinstance", "(", "data", ",", "string_types", ")", ":", "if", "data", ".", "startswith", "(", "'http'", ")", "and", "url", "is", "None", ":", "url", "=", "data", "filename", "=", "None", "data", "=", "None", "elif", "_safe_exists", "(", "data", ")", "and", "filename", "is", "None", ":", "url", "=", "None", "filename", "=", "data", "data", "=", "None", "self", ".", "data", "=", "data", "self", ".", "url", "=", "url", "self", ".", "filename", "=", "None", "if", "filename", "is", "None", "else", "unicode_type", "(", "filename", ")", "self", ".", "reload", "(", ")", "self", ".", "_check_data", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/display.py#L585-L619
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
clang/bindings/python/clang/cindex.py
python
Cursor.is_abstract_record
(self)
return conf.lib.clang_CXXRecord_isAbstract(self)
Returns True if the cursor refers to a C++ record declaration that has pure virtual member functions.
Returns True if the cursor refers to a C++ record declaration that has pure virtual member functions.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "C", "++", "record", "declaration", "that", "has", "pure", "virtual", "member", "functions", "." ]
def is_abstract_record(self): """Returns True if the cursor refers to a C++ record declaration that has pure virtual member functions. """ return conf.lib.clang_CXXRecord_isAbstract(self)
[ "def", "is_abstract_record", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CXXRecord_isAbstract", "(", "self", ")" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/bindings/python/clang/cindex.py#L1500-L1504
facebook/openr
ed38bdfd6bf290084bfab4821b59f83e7b59315d
openr/py/openr/cli/commands/kvstore.py
python
KvNodesCmd.get_connected_nodes
( self, adj_keys: kvstore_types.Publication, node_id: str )
return nx.node_connected_component(graph, node_id)
Build graph of adjacencies and return list of connected node from current node-id
Build graph of adjacencies and return list of connected node from current node-id
[ "Build", "graph", "of", "adjacencies", "and", "return", "list", "of", "connected", "node", "from", "current", "node", "-", "id" ]
def get_connected_nodes( self, adj_keys: kvstore_types.Publication, node_id: str ) -> Set[str]: """ Build graph of adjacencies and return list of connected node from current node-id """ import networkx as nx edges = set() graph = nx.Graph() for adj_value in adj_keys.keyVals.values(): adj_db = serializer.deserialize_thrift_object( adj_value.value, openr_types.AdjacencyDatabase ) graph.add_node(adj_db.thisNodeName) for adj in adj_db.adjacencies: # Add edge only when we see the reverse side of it. if (adj.otherNodeName, adj_db.thisNodeName, adj.otherIfName) in edges: graph.add_edge(adj.otherNodeName, adj_db.thisNodeName) continue edges.add((adj_db.thisNodeName, adj.otherNodeName, adj.ifName)) # pyre-ignore[16] return nx.node_connected_component(graph, node_id)
[ "def", "get_connected_nodes", "(", "self", ",", "adj_keys", ":", "kvstore_types", ".", "Publication", ",", "node_id", ":", "str", ")", "->", "Set", "[", "str", "]", ":", "import", "networkx", "as", "nx", "edges", "=", "set", "(", ")", "graph", "=", "nx", ".", "Graph", "(", ")", "for", "adj_value", "in", "adj_keys", ".", "keyVals", ".", "values", "(", ")", ":", "adj_db", "=", "serializer", ".", "deserialize_thrift_object", "(", "adj_value", ".", "value", ",", "openr_types", ".", "AdjacencyDatabase", ")", "graph", ".", "add_node", "(", "adj_db", ".", "thisNodeName", ")", "for", "adj", "in", "adj_db", ".", "adjacencies", ":", "# Add edge only when we see the reverse side of it.", "if", "(", "adj", ".", "otherNodeName", ",", "adj_db", ".", "thisNodeName", ",", "adj", ".", "otherIfName", ")", "in", "edges", ":", "graph", ".", "add_edge", "(", "adj", ".", "otherNodeName", ",", "adj_db", ".", "thisNodeName", ")", "continue", "edges", ".", "add", "(", "(", "adj_db", ".", "thisNodeName", ",", "adj", ".", "otherNodeName", ",", "adj", ".", "ifName", ")", ")", "# pyre-ignore[16]", "return", "nx", ".", "node_connected_component", "(", "graph", ",", "node_id", ")" ]
https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/commands/kvstore.py#L437-L460
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/telemetry/core/gpu_info.py
python
GPUInfo.feature_status
(self)
return self._feature_status
Returns an optional dictionary of graphics features and their status.
Returns an optional dictionary of graphics features and their status.
[ "Returns", "an", "optional", "dictionary", "of", "graphics", "features", "and", "their", "status", "." ]
def feature_status(self): """Returns an optional dictionary of graphics features and their status.""" return self._feature_status
[ "def", "feature_status", "(", "self", ")", ":", "return", "self", ".", "_feature_status" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/core/gpu_info.py#L59-L61
jiaxiang-wu/quantized-cnn
4d020e17026df90e40111d219e3eb74e0afb1588
cpplint.py
python
CheckForNewlineAtEOF
(filename, lines, error)
Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found.
Logs an error if there is no newline char at the end of the file.
[ "Logs", "an", "error", "if", "there", "is", "no", "newline", "char", "at", "the", "end", "of", "the", "file", "." ]
def CheckForNewlineAtEOF(filename, lines, error): """Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # The array lines() was created by adding two newlines to the # original file (go figure), then splitting on \n. # To verify that the file ends in \n, we just have to make sure the # last-but-two element of lines() exists and is empty. if len(lines) < 3 or lines[-2]: error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, 'Could not find a newline character at the end of the file.')
[ "def", "CheckForNewlineAtEOF", "(", "filename", ",", "lines", ",", "error", ")", ":", "# The array lines() was created by adding two newlines to the", "# original file (go figure), then splitting on \\n.", "# To verify that the file ends in \\n, we just have to make sure the", "# last-but-two element of lines() exists and is empty.", "if", "len", "(", "lines", ")", "<", "3", "or", "lines", "[", "-", "2", "]", ":", "error", "(", "filename", ",", "len", "(", "lines", ")", "-", "2", ",", "'whitespace/ending_newline'", ",", "5", ",", "'Could not find a newline character at the end of the file.'", ")" ]
https://github.com/jiaxiang-wu/quantized-cnn/blob/4d020e17026df90e40111d219e3eb74e0afb1588/cpplint.py#L1825-L1840
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/glcanvas.py
python
GLCanvas.SetCurrent
(*args)
return _glcanvas.GLCanvas_SetCurrent(*args)
SetCurrent(self, GLContext context) -> bool SetCurrent(self)
SetCurrent(self, GLContext context) -> bool SetCurrent(self)
[ "SetCurrent", "(", "self", "GLContext", "context", ")", "-", ">", "bool", "SetCurrent", "(", "self", ")" ]
def SetCurrent(*args): """ SetCurrent(self, GLContext context) -> bool SetCurrent(self) """ return _glcanvas.GLCanvas_SetCurrent(*args)
[ "def", "SetCurrent", "(", "*", "args", ")", ":", "return", "_glcanvas", ".", "GLCanvas_SetCurrent", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/glcanvas.py#L135-L140
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
modules/tools/control_info/control_info.py
python
ControlInfo.longitudinal
(self)
Showing Longitudinal
Showing Longitudinal
[ "Showing", "Longitudinal" ]
def longitudinal(self): """ Showing Longitudinal """ for loc, ax in numpy.ndenumerate(self.ax): ax.clear() self.ax[0, 0].plot( self.canbustime, self.throttlefbk, label='Throttle Feedback') self.ax[0, 0].plot( self.controltime, self.throttlecmd, label='Throttle Command') self.ax[0, 0].plot( self.canbustime, self.brakefbk, label='Brake Feedback') self.ax[0, 0].plot( self.controltime, self.brakecmd, label='Brake Command') self.ax[0, 0].legend(fontsize='medium') self.ax[0, 0].grid(True) self.ax[0, 0].set_title('Throttle Brake Info') self.ax[0, 0].set_xlabel('Time') self.ax[0, 1].plot( self.speed_lookup, self.acceleration_lookup, label='Table Lookup') self.ax[0, 1].plot( self.target_speed, self.target_acceleration, label='Target') self.ax[0, 1].legend(fontsize='medium') self.ax[0, 1].grid(True) self.ax[0, 1].set_title('Calibration Lookup') self.ax[0, 1].set_xlabel('Speed') self.ax[0, 1].set_ylabel('Acceleration') self.ax[1, 0].plot(self.canbustime, self.speed, label='Vehicle Speed') self.ax[1, 0].plot( self.target_time, self.target_speed, label='Target Speed') self.ax[1, 0].plot( self.target_time, self.target_acceleration, label='Target Acc') self.ax[1, 0].plot( self.localizationtime, self.imuforward, label='IMU Forward') self.ax[1, 0].legend(fontsize='medium') self.ax[1, 0].grid(True) self.ax[1, 0].set_title('Speed Info') self.ax[1, 0].set_xlabel('Time') self.ax[1, 1].plot( self.controltime, self.acceleration_lookup, label='Lookup Acc') self.ax[1, 1].plot(self.controltime, self.acc_open, label='Acc Open') self.ax[1, 1].plot(self.controltime, self.acc_close, label='Acc Close') self.ax[1, 1].plot( self.controltime, self.station_error, label='station_error') self.ax[1, 1].plot( self.controltime, self.speed_error, label='speed_error') self.ax[1, 1].legend(fontsize='medium') self.ax[1, 1].grid(True) self.ax[1, 1].set_title('IMU Info') self.ax[1, 1].set_xlabel('Time') if len(self.mode_time) % 2 == 1: self.mode_time.append(self.controltime[-1]) for i in range(0, len(self.mode_time), 2): self.ax[0, 0].axvspan( self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1) self.ax[1, 0].axvspan( self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1) self.ax[1, 1].axvspan( self.mode_time[i], self.mode_time[i + 1], fc='0.1', alpha=0.1) plt.draw()
[ "def", "longitudinal", "(", "self", ")", ":", "for", "loc", ",", "ax", "in", "numpy", ".", "ndenumerate", "(", "self", ".", "ax", ")", ":", "ax", ".", "clear", "(", ")", "self", ".", "ax", "[", "0", ",", "0", "]", ".", "plot", "(", "self", ".", "canbustime", ",", "self", ".", "throttlefbk", ",", "label", "=", "'Throttle Feedback'", ")", "self", ".", "ax", "[", "0", ",", "0", "]", ".", "plot", "(", "self", ".", "controltime", ",", "self", ".", "throttlecmd", ",", "label", "=", "'Throttle Command'", ")", "self", ".", "ax", "[", "0", ",", "0", "]", ".", "plot", "(", "self", ".", "canbustime", ",", "self", ".", "brakefbk", ",", "label", "=", "'Brake Feedback'", ")", "self", ".", "ax", "[", "0", ",", "0", "]", ".", "plot", "(", "self", ".", "controltime", ",", "self", ".", "brakecmd", ",", "label", "=", "'Brake Command'", ")", "self", ".", "ax", "[", "0", ",", "0", "]", ".", "legend", "(", "fontsize", "=", "'medium'", ")", "self", ".", "ax", "[", "0", ",", "0", "]", ".", "grid", "(", "True", ")", "self", ".", "ax", "[", "0", ",", "0", "]", ".", "set_title", "(", "'Throttle Brake Info'", ")", "self", ".", "ax", "[", "0", ",", "0", "]", ".", "set_xlabel", "(", "'Time'", ")", "self", ".", "ax", "[", "0", ",", "1", "]", ".", "plot", "(", "self", ".", "speed_lookup", ",", "self", ".", "acceleration_lookup", ",", "label", "=", "'Table Lookup'", ")", "self", ".", "ax", "[", "0", ",", "1", "]", ".", "plot", "(", "self", ".", "target_speed", ",", "self", ".", "target_acceleration", ",", "label", "=", "'Target'", ")", "self", ".", "ax", "[", "0", ",", "1", "]", ".", "legend", "(", "fontsize", "=", "'medium'", ")", "self", ".", "ax", "[", "0", ",", "1", "]", ".", "grid", "(", "True", ")", "self", ".", "ax", "[", "0", ",", "1", "]", ".", "set_title", "(", "'Calibration Lookup'", ")", "self", ".", "ax", "[", "0", ",", "1", "]", ".", "set_xlabel", "(", "'Speed'", ")", "self", ".", "ax", "[", "0", ",", "1", "]", ".", "set_ylabel", "(", "'Acceleration'", ")", "self", ".", "ax", "[", "1", ",", "0", "]", ".", "plot", "(", "self", ".", "canbustime", ",", "self", ".", "speed", ",", "label", "=", "'Vehicle Speed'", ")", "self", ".", "ax", "[", "1", ",", "0", "]", ".", "plot", "(", "self", ".", "target_time", ",", "self", ".", "target_speed", ",", "label", "=", "'Target Speed'", ")", "self", ".", "ax", "[", "1", ",", "0", "]", ".", "plot", "(", "self", ".", "target_time", ",", "self", ".", "target_acceleration", ",", "label", "=", "'Target Acc'", ")", "self", ".", "ax", "[", "1", ",", "0", "]", ".", "plot", "(", "self", ".", "localizationtime", ",", "self", ".", "imuforward", ",", "label", "=", "'IMU Forward'", ")", "self", ".", "ax", "[", "1", ",", "0", "]", ".", "legend", "(", "fontsize", "=", "'medium'", ")", "self", ".", "ax", "[", "1", ",", "0", "]", ".", "grid", "(", "True", ")", "self", ".", "ax", "[", "1", ",", "0", "]", ".", "set_title", "(", "'Speed Info'", ")", "self", ".", "ax", "[", "1", ",", "0", "]", ".", "set_xlabel", "(", "'Time'", ")", "self", ".", "ax", "[", "1", ",", "1", "]", ".", "plot", "(", "self", ".", "controltime", ",", "self", ".", "acceleration_lookup", ",", "label", "=", "'Lookup Acc'", ")", "self", ".", "ax", "[", "1", ",", "1", "]", ".", "plot", "(", "self", ".", "controltime", ",", "self", ".", "acc_open", ",", "label", "=", "'Acc Open'", ")", "self", ".", "ax", "[", "1", ",", "1", "]", ".", "plot", "(", "self", ".", "controltime", ",", "self", ".", "acc_close", ",", "label", "=", "'Acc Close'", ")", "self", ".", "ax", "[", "1", ",", "1", "]", ".", "plot", "(", "self", ".", "controltime", ",", "self", ".", "station_error", ",", "label", "=", "'station_error'", ")", "self", ".", "ax", "[", "1", ",", "1", "]", ".", "plot", "(", "self", ".", "controltime", ",", "self", ".", "speed_error", ",", "label", "=", "'speed_error'", ")", "self", ".", "ax", "[", "1", ",", "1", "]", ".", "legend", "(", "fontsize", "=", "'medium'", ")", "self", ".", "ax", "[", "1", ",", "1", "]", ".", "grid", "(", "True", ")", "self", ".", "ax", "[", "1", ",", "1", "]", ".", "set_title", "(", "'IMU Info'", ")", "self", ".", "ax", "[", "1", ",", "1", "]", ".", "set_xlabel", "(", "'Time'", ")", "if", "len", "(", "self", ".", "mode_time", ")", "%", "2", "==", "1", ":", "self", ".", "mode_time", ".", "append", "(", "self", ".", "controltime", "[", "-", "1", "]", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "mode_time", ")", ",", "2", ")", ":", "self", ".", "ax", "[", "0", ",", "0", "]", ".", "axvspan", "(", "self", ".", "mode_time", "[", "i", "]", ",", "self", ".", "mode_time", "[", "i", "+", "1", "]", ",", "fc", "=", "'0.1'", ",", "alpha", "=", "0.1", ")", "self", ".", "ax", "[", "1", ",", "0", "]", ".", "axvspan", "(", "self", ".", "mode_time", "[", "i", "]", ",", "self", ".", "mode_time", "[", "i", "+", "1", "]", ",", "fc", "=", "'0.1'", ",", "alpha", "=", "0.1", ")", "self", ".", "ax", "[", "1", ",", "1", "]", ".", "axvspan", "(", "self", ".", "mode_time", "[", "i", "]", ",", "self", ".", "mode_time", "[", "i", "+", "1", "]", ",", "fc", "=", "'0.1'", ",", "alpha", "=", "0.1", ")", "plt", ".", "draw", "(", ")" ]
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/control_info/control_info.py#L193-L256
rsummers11/CADLab
976ed959a0b5208bb4173127a7ef732ac73a9b6f
panreas_hnn/hed-globalweight/python/caffe/draw.py
python
choose_color_by_layertype
(layertype)
return color
Define colors for nodes based on the layer type.
Define colors for nodes based on the layer type.
[ "Define", "colors", "for", "nodes", "based", "on", "the", "layer", "type", "." ]
def choose_color_by_layertype(layertype): """Define colors for nodes based on the layer type. """ color = '#6495ED' # Default if layertype == 'Convolution' or layertype == 'Deconvolution': color = '#FF5050' elif layertype == 'Pooling': color = '#FF9900' elif layertype == 'InnerProduct': color = '#CC33FF' return color
[ "def", "choose_color_by_layertype", "(", "layertype", ")", ":", "color", "=", "'#6495ED'", "# Default", "if", "layertype", "==", "'Convolution'", "or", "layertype", "==", "'Deconvolution'", ":", "color", "=", "'#FF5050'", "elif", "layertype", "==", "'Pooling'", ":", "color", "=", "'#FF9900'", "elif", "layertype", "==", "'InnerProduct'", ":", "color", "=", "'#CC33FF'", "return", "color" ]
https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/panreas_hnn/hed-globalweight/python/caffe/draw.py#L108-L118
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py
python
_check_config_keys
(config, expected_keys)
Checks that a config has all expected_keys.
Checks that a config has all expected_keys.
[ "Checks", "that", "a", "config", "has", "all", "expected_keys", "." ]
def _check_config_keys(config, expected_keys): """Checks that a config has all expected_keys.""" if set(config.keys()) != set(expected_keys): raise ValueError('Invalid config: {}, expected keys: {}'.format( config, expected_keys))
[ "def", "_check_config_keys", "(", "config", ",", "expected_keys", ")", ":", "if", "set", "(", "config", ".", "keys", "(", ")", ")", "!=", "set", "(", "expected_keys", ")", ":", "raise", "ValueError", "(", "'Invalid config: {}, expected keys: {}'", ".", "format", "(", "config", ",", "expected_keys", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py#L4597-L4601
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/function.py
python
_DefinedFunction._create_definition_if_needed
(self)
Creates the function definition if it's not created yet.
Creates the function definition if it's not created yet.
[ "Creates", "the", "function", "definition", "if", "it", "s", "not", "created", "yet", "." ]
def _create_definition_if_needed(self): """Creates the function definition if it's not created yet.""" with context.graph_mode(): self._create_definition_if_needed_impl()
[ "def", "_create_definition_if_needed", "(", "self", ")", ":", "with", "context", ".", "graph_mode", "(", ")", ":", "self", ".", "_create_definition_if_needed_impl", "(", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/function.py#L374-L377
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/boost/boost_1_68_0/tools/build/src/build/type.py
python
all_bases
(type)
return result
Returns type and all of its bases, in the order of their distance from type.
Returns type and all of its bases, in the order of their distance from type.
[ "Returns", "type", "and", "all", "of", "its", "bases", "in", "the", "order", "of", "their", "distance", "from", "type", "." ]
def all_bases (type): """ Returns type and all of its bases, in the order of their distance from type. """ assert isinstance(type, basestring) result = [] while type: result.append (type) type = __types [type]['base'] return result
[ "def", "all_bases", "(", "type", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "result", "=", "[", "]", "while", "type", ":", "result", ".", "append", "(", "type", ")", "type", "=", "__types", "[", "type", "]", "[", "'base'", "]", "return", "result" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/build/type.py#L181-L190
PrincetonUniversity/athena-public-version
9c266692b9423743d8e23509b3ab266a232a92d2
tst/style/cpplint.py
python
Error
(filename, linenum, category, confidence, message)
Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message.
Logs the fact we've found a lint error.
[ "Logs", "the", "fact", "we", "ve", "found", "a", "lint", "error", "." ]
def Error(filename, linenum, category, confidence, message): """Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message. """ if _ShouldPrintError(category, confidence, linenum): _cpplint_state.IncrementErrorCount(category) if _cpplint_state.output_format == 'vs7': _cpplint_state.PrintError('%s(%s): error cpplint: [%s] %s [%d]\n' % ( filename, linenum, category, message, confidence)) elif _cpplint_state.output_format == 'eclipse': sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'junit': _cpplint_state.AddJUnitFailure(filename, linenum, message, category, confidence) else: final_message = '%s:%s: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence) sys.stderr.write(final_message)
[ "def", "Error", "(", "filename", ",", "linenum", ",", "category", ",", "confidence", ",", "message", ")", ":", "if", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "_cpplint_state", ".", "IncrementErrorCount", "(", "category", ")", "if", "_cpplint_state", ".", "output_format", "==", "'vs7'", ":", "_cpplint_state", ".", "PrintError", "(", "'%s(%s): error cpplint: [%s] %s [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "category", ",", "message", ",", "confidence", ")", ")", "elif", "_cpplint_state", ".", "output_format", "==", "'eclipse'", ":", "sys", ".", "stderr", ".", "write", "(", "'%s:%s: warning: %s [%s] [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", ")", "elif", "_cpplint_state", ".", "output_format", "==", "'junit'", ":", "_cpplint_state", ".", "AddJUnitFailure", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", "else", ":", "final_message", "=", "'%s:%s: %s [%s] [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", "sys", ".", "stderr", ".", "write", "(", "final_message", ")" ]
https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/tst/style/cpplint.py#L1443-L1479
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/vision/models/resnet.py
python
resnet152
(pretrained=False, **kwargs)
return _resnet('resnet152', BottleneckBlock, 152, pretrained, **kwargs)
ResNet 152-layer model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet Examples: .. code-block:: python import paddle from paddle.vision.models import resnet152 # build model model = resnet152() # build model and load imagenet pretrained weight # model = resnet152(pretrained=True) x = paddle.rand([1, 3, 224, 224]) out = model(x) print(out.shape)
ResNet 152-layer model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
[ "ResNet", "152", "-", "layer", "model", "from", "Deep", "Residual", "Learning", "for", "Image", "Recognition", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1512", ".", "03385", ".", "pdf", ">", "_" ]
def resnet152(pretrained=False, **kwargs): """ResNet 152-layer model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet Examples: .. code-block:: python import paddle from paddle.vision.models import resnet152 # build model model = resnet152() # build model and load imagenet pretrained weight # model = resnet152(pretrained=True) x = paddle.rand([1, 3, 224, 224]) out = model(x) print(out.shape) """ return _resnet('resnet152', BottleneckBlock, 152, pretrained, **kwargs)
[ "def", "resnet152", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "_resnet", "(", "'resnet152'", ",", "BottleneckBlock", ",", "152", ",", "pretrained", ",", "*", "*", "kwargs", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/vision/models/resnet.py#L406-L430
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/ConfigParser.py
python
ConfigParser.items
(self, section, raw=False, vars=None)
Return a list of tuples with (name, value) for each option in the section. All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument `raw' is true. Additional substitutions may be provided using the `vars' argument, which must be a dictionary whose contents overrides any pre-existing defaults. The section DEFAULT is special.
Return a list of tuples with (name, value) for each option in the section.
[ "Return", "a", "list", "of", "tuples", "with", "(", "name", "value", ")", "for", "each", "option", "in", "the", "section", "." ]
def items(self, section, raw=False, vars=None): """Return a list of tuples with (name, value) for each option in the section. All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument `raw' is true. Additional substitutions may be provided using the `vars' argument, which must be a dictionary whose contents overrides any pre-existing defaults. The section DEFAULT is special. """ d = self._defaults.copy() try: d.update(self._sections[section]) except KeyError: if section != DEFAULTSECT: raise NoSectionError(section) # Update with the entry specific variables if vars: for key, value in vars.items(): d[self.optionxform(key)] = value options = d.keys() if "__name__" in options: options.remove("__name__") if raw: return [(option, d[option]) for option in options] else: return [(option, self._interpolate(section, option, d[option], d)) for option in options]
[ "def", "items", "(", "self", ",", "section", ",", "raw", "=", "False", ",", "vars", "=", "None", ")", ":", "d", "=", "self", ".", "_defaults", ".", "copy", "(", ")", "try", ":", "d", ".", "update", "(", "self", ".", "_sections", "[", "section", "]", ")", "except", "KeyError", ":", "if", "section", "!=", "DEFAULTSECT", ":", "raise", "NoSectionError", "(", "section", ")", "# Update with the entry specific variables", "if", "vars", ":", "for", "key", ",", "value", "in", "vars", ".", "items", "(", ")", ":", "d", "[", "self", ".", "optionxform", "(", "key", ")", "]", "=", "value", "options", "=", "d", ".", "keys", "(", ")", "if", "\"__name__\"", "in", "options", ":", "options", ".", "remove", "(", "\"__name__\"", ")", "if", "raw", ":", "return", "[", "(", "option", ",", "d", "[", "option", "]", ")", "for", "option", "in", "options", "]", "else", ":", "return", "[", "(", "option", ",", "self", ".", "_interpolate", "(", "section", ",", "option", ",", "d", "[", "option", "]", ",", "d", ")", ")", "for", "option", "in", "options", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/ConfigParser.py#L625-L655
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/framework/op_def_library.py
python
OpDefLibrary.add_op
(self, op_def)
Register an OpDef. May call apply_op with the name afterwards.
Register an OpDef. May call apply_op with the name afterwards.
[ "Register", "an", "OpDef", ".", "May", "call", "apply_op", "with", "the", "name", "afterwards", "." ]
def add_op(self, op_def): """Register an OpDef. May call apply_op with the name afterwards.""" if not isinstance(op_def, op_def_pb2.OpDef): raise TypeError("%s is %s, not an op_def_pb2.OpDef" % (op_def, type(op_def))) if not op_def.name: raise ValueError("%s missing name." % op_def) if op_def.name in self._ops: raise RuntimeError("Op name %s registered twice." % op_def.name) self._ops[op_def.name] = _OpInfo(op_def)
[ "def", "add_op", "(", "self", ",", "op_def", ")", ":", "if", "not", "isinstance", "(", "op_def", ",", "op_def_pb2", ".", "OpDef", ")", ":", "raise", "TypeError", "(", "\"%s is %s, not an op_def_pb2.OpDef\"", "%", "(", "op_def", ",", "type", "(", "op_def", ")", ")", ")", "if", "not", "op_def", ".", "name", ":", "raise", "ValueError", "(", "\"%s missing name.\"", "%", "op_def", ")", "if", "op_def", ".", "name", "in", "self", ".", "_ops", ":", "raise", "RuntimeError", "(", "\"Op name %s registered twice.\"", "%", "op_def", ".", "name", ")", "self", ".", "_ops", "[", "op_def", ".", "name", "]", "=", "_OpInfo", "(", "op_def", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/op_def_library.py#L269-L278
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/procrouting/proc.py
python
select_adc2
(name, **kwargs)
Function selecting the algorithm for ADC(2) excited state energy call and directing to specified or best-performance default modules.
Function selecting the algorithm for ADC(2) excited state energy call and directing to specified or best-performance default modules.
[ "Function", "selecting", "the", "algorithm", "for", "ADC", "(", "2", ")", "excited", "state", "energy", "call", "and", "directing", "to", "specified", "or", "best", "-", "performance", "default", "modules", "." ]
def select_adc2(name, **kwargs): """Function selecting the algorithm for ADC(2) excited state energy call and directing to specified or best-performance default modules. """ reference = core.get_option('SCF', 'REFERENCE') mtd_type = core.get_global_option('MP_TYPE') module = core.get_global_option('QC_MODULE') # Considering only adcc/adc # TODO Actually one should do selection on a couple of other options here # as well, e.g. adcc supports frozen-core and frozen-virtual, # spin-specific states or spin-flip methods. # But as far as I (mfherbst) know the BUILTIN ADC routine only supports # singlet states and without freezing some core or some virtual orbitals. func = None if reference == 'RHF': if mtd_type == 'CONV': if module in {'ADCC', ''} and extras.addons("adcc"): func = run_adcc elif module in {'BUILTIN', ''}: func = run_adc if reference == 'UHF': if mtd_type == 'CONV': if module in ['ADCC', ''] and extras.addons("adcc"): func = run_adcc # Note: ROHF is theoretically available in adcc, but are not fully tested # ... so will be added later. if func is None: raise ManagedMethodError(['select_adc2', name, 'MP_TYPE', mtd_type, reference, module]) if kwargs.pop('probe', False): return else: return func(name, **kwargs)
[ "def", "select_adc2", "(", "name", ",", "*", "*", "kwargs", ")", ":", "reference", "=", "core", ".", "get_option", "(", "'SCF'", ",", "'REFERENCE'", ")", "mtd_type", "=", "core", ".", "get_global_option", "(", "'MP_TYPE'", ")", "module", "=", "core", ".", "get_global_option", "(", "'QC_MODULE'", ")", "# Considering only adcc/adc", "# TODO Actually one should do selection on a couple of other options here", "# as well, e.g. adcc supports frozen-core and frozen-virtual,", "# spin-specific states or spin-flip methods.", "# But as far as I (mfherbst) know the BUILTIN ADC routine only supports", "# singlet states and without freezing some core or some virtual orbitals.", "func", "=", "None", "if", "reference", "==", "'RHF'", ":", "if", "mtd_type", "==", "'CONV'", ":", "if", "module", "in", "{", "'ADCC'", ",", "''", "}", "and", "extras", ".", "addons", "(", "\"adcc\"", ")", ":", "func", "=", "run_adcc", "elif", "module", "in", "{", "'BUILTIN'", ",", "''", "}", ":", "func", "=", "run_adc", "if", "reference", "==", "'UHF'", ":", "if", "mtd_type", "==", "'CONV'", ":", "if", "module", "in", "[", "'ADCC'", ",", "''", "]", "and", "extras", ".", "addons", "(", "\"adcc\"", ")", ":", "func", "=", "run_adcc", "# Note: ROHF is theoretically available in adcc, but are not fully tested", "# ... so will be added later.", "if", "func", "is", "None", ":", "raise", "ManagedMethodError", "(", "[", "'select_adc2'", ",", "name", ",", "'MP_TYPE'", ",", "mtd_type", ",", "reference", ",", "module", "]", ")", "if", "kwargs", ".", "pop", "(", "'probe'", ",", "False", ")", ":", "return", "else", ":", "return", "func", "(", "name", ",", "*", "*", "kwargs", ")" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/procrouting/proc.py#L1095-L1133
mavlink/mavros
a32232d57a5e91abf6737e454d4199cae29b369c
mavros/mavros/cmd/safety.py
python
safety
(client)
Tool to send safety commands to MAVLink device.
Tool to send safety commands to MAVLink device.
[ "Tool", "to", "send", "safety", "commands", "to", "MAVLink", "device", "." ]
def safety(client): """Tool to send safety commands to MAVLink device."""
[ "def", "safety", "(", "client", ")", ":" ]
https://github.com/mavlink/mavros/blob/a32232d57a5e91abf6737e454d4199cae29b369c/mavros/mavros/cmd/safety.py#L25-L26
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
example/caffe/caffe_net.py
python
get_lenet
()
return lenet
LeCun, Yann, Leon Bottou, Yoshua Bengio, and Patrick Haffner. "Gradient-based learning applied to document recognition." Proceedings of the IEEE (1998)
LeCun, Yann, Leon Bottou, Yoshua Bengio, and Patrick Haffner. "Gradient-based learning applied to document recognition." Proceedings of the IEEE (1998)
[ "LeCun", "Yann", "Leon", "Bottou", "Yoshua", "Bengio", "and", "Patrick", "Haffner", ".", "Gradient", "-", "based", "learning", "applied", "to", "document", "recognition", ".", "Proceedings", "of", "the", "IEEE", "(", "1998", ")" ]
def get_lenet(): """ LeCun, Yann, Leon Bottou, Yoshua Bengio, and Patrick Haffner. "Gradient-based learning applied to document recognition." Proceedings of the IEEE (1998) """ data = mx.symbol.Variable('data') # first conv conv1 = mx.symbol.CaffeOp(data_0=data, num_weight=2, prototxt="layer{type:\"Convolution\" convolution_param { num_output: 20 kernel_size: 5 stride: 1} }") act1 = mx.symbol.CaffeOp(data_0=conv1, prototxt="layer{type:\"TanH\"}") pool1 = mx.symbol.CaffeOp(data_0=act1, prototxt="layer{type:\"Pooling\" pooling_param { pool: MAX kernel_size: 2 stride: 2}}") # second conv conv2 = mx.symbol.CaffeOp(data_0=pool1, num_weight=2, prototxt="layer{type:\"Convolution\" convolution_param { num_output: 50 kernel_size: 5 stride: 1} }") act2 = mx.symbol.CaffeOp(data_0=conv2, prototxt="layer{type:\"TanH\"}") pool2 = mx.symbol.CaffeOp(data_0=act2, prototxt="layer{type:\"Pooling\" pooling_param { pool: MAX kernel_size: 2 stride: 2}}") fc1 = mx.symbol.CaffeOp(data_0=pool2, num_weight=2, prototxt="layer{type:\"InnerProduct\" inner_product_param{num_output: 500} }") act3 = mx.symbol.CaffeOp(data_0=fc1, prototxt="layer{type:\"TanH\"}") # second fullc fc2 = mx.symbol.CaffeOp(data_0=act3, num_weight=2, prototxt="layer{type:\"InnerProduct\"inner_product_param{num_output: 10} }") if use_caffe_loss: label = mx.symbol.Variable('softmax_label') lenet = mx.symbol.CaffeLoss(data=fc2, label=label, grad_scale=1, name='softmax', prototxt="layer{type:\"SoftmaxWithLoss\"}") else: lenet = mx.symbol.SoftmaxOutput(data=fc2, name='softmax') return lenet
[ "def", "get_lenet", "(", ")", ":", "data", "=", "mx", ".", "symbol", ".", "Variable", "(", "'data'", ")", "# first conv", "conv1", "=", "mx", ".", "symbol", ".", "CaffeOp", "(", "data_0", "=", "data", ",", "num_weight", "=", "2", ",", "prototxt", "=", "\"layer{type:\\\"Convolution\\\" convolution_param { num_output: 20 kernel_size: 5 stride: 1} }\"", ")", "act1", "=", "mx", ".", "symbol", ".", "CaffeOp", "(", "data_0", "=", "conv1", ",", "prototxt", "=", "\"layer{type:\\\"TanH\\\"}\"", ")", "pool1", "=", "mx", ".", "symbol", ".", "CaffeOp", "(", "data_0", "=", "act1", ",", "prototxt", "=", "\"layer{type:\\\"Pooling\\\" pooling_param { pool: MAX kernel_size: 2 stride: 2}}\"", ")", "# second conv", "conv2", "=", "mx", ".", "symbol", ".", "CaffeOp", "(", "data_0", "=", "pool1", ",", "num_weight", "=", "2", ",", "prototxt", "=", "\"layer{type:\\\"Convolution\\\" convolution_param { num_output: 50 kernel_size: 5 stride: 1} }\"", ")", "act2", "=", "mx", ".", "symbol", ".", "CaffeOp", "(", "data_0", "=", "conv2", ",", "prototxt", "=", "\"layer{type:\\\"TanH\\\"}\"", ")", "pool2", "=", "mx", ".", "symbol", ".", "CaffeOp", "(", "data_0", "=", "act2", ",", "prototxt", "=", "\"layer{type:\\\"Pooling\\\" pooling_param { pool: MAX kernel_size: 2 stride: 2}}\"", ")", "fc1", "=", "mx", ".", "symbol", ".", "CaffeOp", "(", "data_0", "=", "pool2", ",", "num_weight", "=", "2", ",", "prototxt", "=", "\"layer{type:\\\"InnerProduct\\\" inner_product_param{num_output: 500} }\"", ")", "act3", "=", "mx", ".", "symbol", ".", "CaffeOp", "(", "data_0", "=", "fc1", ",", "prototxt", "=", "\"layer{type:\\\"TanH\\\"}\"", ")", "# second fullc", "fc2", "=", "mx", ".", "symbol", ".", "CaffeOp", "(", "data_0", "=", "act3", ",", "num_weight", "=", "2", ",", "prototxt", "=", "\"layer{type:\\\"InnerProduct\\\"inner_product_param{num_output: 10} }\"", ")", "if", "use_caffe_loss", ":", "label", "=", "mx", ".", "symbol", ".", "Variable", "(", "'softmax_label'", ")", "lenet", "=", "mx", ".", "symbol", ".", "CaffeLoss", "(", "data", "=", "fc2", ",", "label", "=", "label", ",", "grad_scale", "=", "1", ",", "name", "=", "'softmax'", ",", "prototxt", "=", "\"layer{type:\\\"SoftmaxWithLoss\\\"}\"", ")", "else", ":", "lenet", "=", "mx", ".", "symbol", ".", "SoftmaxOutput", "(", "data", "=", "fc2", ",", "name", "=", "'softmax'", ")", "return", "lenet" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/caffe/caffe_net.py#L40-L68
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/backend.py
python
update_add
(x, increment)
return state_ops.assign_add(x, increment)
Update the value of `x` by adding `increment`. Arguments: x: A Variable. increment: A tensor of same shape as `x`. Returns: The variable `x` updated.
Update the value of `x` by adding `increment`.
[ "Update", "the", "value", "of", "x", "by", "adding", "increment", "." ]
def update_add(x, increment): """Update the value of `x` by adding `increment`. Arguments: x: A Variable. increment: A tensor of same shape as `x`. Returns: The variable `x` updated. """ return state_ops.assign_add(x, increment)
[ "def", "update_add", "(", "x", ",", "increment", ")", ":", "return", "state_ops", ".", "assign_add", "(", "x", ",", "increment", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L1099-L1109
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/graph_kernel/model/model.py
python
Tensor.get_size
(self)
return size
Get size
Get size
[ "Get", "size" ]
def get_size(self): """Get size""" size = PrimLib.dtype_bytes(self.dtype) for i in self.shape: size *= i return size
[ "def", "get_size", "(", "self", ")", ":", "size", "=", "PrimLib", ".", "dtype_bytes", "(", "self", ".", "dtype", ")", "for", "i", "in", "self", ".", "shape", ":", "size", "*=", "i", "return", "size" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/graph_kernel/model/model.py#L326-L331
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/interactiveshell.py
python
InteractiveShell.getoutput
(self, cmd, split=True, depth=0)
return out
Get output (possibly including stderr) from a subprocess. Parameters ---------- cmd : str Command to execute (can not end in '&', as background processes are not supported. split : bool, optional If True, split the output into an IPython SList. Otherwise, an IPython LSString is returned. These are objects similar to normal lists and strings, with a few convenience attributes for easier manipulation of line-based output. You can use '?' on them for details. depth : int, optional How many frames above the caller are the local variables which should be expanded in the command string? The default (0) assumes that the expansion variables are in the stack frame calling this function.
Get output (possibly including stderr) from a subprocess.
[ "Get", "output", "(", "possibly", "including", "stderr", ")", "from", "a", "subprocess", "." ]
def getoutput(self, cmd, split=True, depth=0): """Get output (possibly including stderr) from a subprocess. Parameters ---------- cmd : str Command to execute (can not end in '&', as background processes are not supported. split : bool, optional If True, split the output into an IPython SList. Otherwise, an IPython LSString is returned. These are objects similar to normal lists and strings, with a few convenience attributes for easier manipulation of line-based output. You can use '?' on them for details. depth : int, optional How many frames above the caller are the local variables which should be expanded in the command string? The default (0) assumes that the expansion variables are in the stack frame calling this function. """ if cmd.rstrip().endswith('&'): # this is *far* from a rigorous test raise OSError("Background processes not supported.") out = getoutput(self.var_expand(cmd, depth=depth+1)) if split: out = SList(out.splitlines()) else: out = LSString(out) return out
[ "def", "getoutput", "(", "self", ",", "cmd", ",", "split", "=", "True", ",", "depth", "=", "0", ")", ":", "if", "cmd", ".", "rstrip", "(", ")", ".", "endswith", "(", "'&'", ")", ":", "# this is *far* from a rigorous test", "raise", "OSError", "(", "\"Background processes not supported.\"", ")", "out", "=", "getoutput", "(", "self", ".", "var_expand", "(", "cmd", ",", "depth", "=", "depth", "+", "1", ")", ")", "if", "split", ":", "out", "=", "SList", "(", "out", ".", "splitlines", "(", ")", ")", "else", ":", "out", "=", "LSString", "(", "out", ")", "return", "out" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/interactiveshell.py#L2267-L2294
Kitware/VTK
5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8
Wrapping/Python/vtkmodules/wx/wxVTKRenderWindow.py
python
wxVTKRenderWindow.OnButtonUp
(self, event)
Overridable event.
Overridable event.
[ "Overridable", "event", "." ]
def OnButtonUp(self, event): """Overridable event. """ if event.LeftUp(): self.OnLeftUp(event) elif event.RightUp(): self.OnRightUp(event) elif event.MiddleUp(): self.OnMiddleUp(event) # if not interacting, then do nothing more if self._Mode: if self._CurrentRenderer: self.Render() self._Mode = None
[ "def", "OnButtonUp", "(", "self", ",", "event", ")", ":", "if", "event", ".", "LeftUp", "(", ")", ":", "self", ".", "OnLeftUp", "(", "event", ")", "elif", "event", ".", "RightUp", "(", ")", ":", "self", ".", "OnRightUp", "(", "event", ")", "elif", "event", ".", "MiddleUp", "(", ")", ":", "self", ".", "OnMiddleUp", "(", "event", ")", "# if not interacting, then do nothing more", "if", "self", ".", "_Mode", ":", "if", "self", ".", "_CurrentRenderer", ":", "self", ".", "Render", "(", ")", "self", ".", "_Mode", "=", "None" ]
https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/wx/wxVTKRenderWindow.py#L415-L430
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/tracer/function.py
python
functionTracer.process
(self, data, t_range=[])
test_performanc-19925 [003] .... 110337.353720: _fun_9351538_entry: (0xffff8553b0d8)
test_performanc-19925 [003] .... 110337.353720: _fun_9351538_entry: (0xffff8553b0d8)
[ "test_performanc", "-", "19925", "[", "003", "]", "....", "110337", ".", "353720", ":", "_fun_9351538_entry", ":", "(", "0xffff8553b0d8", ")" ]
def process(self, data, t_range=[]): """"test_performanc-19925 [003] .... 110337.353720: _fun_9351538_entry: (0xffff8553b0d8)""" data = [l for l in data.get('ftrace', {}).get( self.name) if not l.startswith('#')] data_out = [] for l in data: ftraceSym = l.strip().split()[4].rsplit('_', 1)[0] data_out.append(l.replace(ftraceSym, self.ftraceSymMap[ftraceSym])) # for k in self.ftraceSymMap.keys(): # if l.find(k) > 0: # data_out.append(l.replace(k, self.ftraceSymMap[k])) self.data = data_out
[ "def", "process", "(", "self", ",", "data", ",", "t_range", "=", "[", "]", ")", ":", "data", "=", "[", "l", "for", "l", "in", "data", ".", "get", "(", "'ftrace'", ",", "{", "}", ")", ".", "get", "(", "self", ".", "name", ")", "if", "not", "l", ".", "startswith", "(", "'#'", ")", "]", "data_out", "=", "[", "]", "for", "l", "in", "data", ":", "ftraceSym", "=", "l", ".", "strip", "(", ")", ".", "split", "(", ")", "[", "4", "]", ".", "rsplit", "(", "'_'", ",", "1", ")", "[", "0", "]", "data_out", ".", "append", "(", "l", ".", "replace", "(", "ftraceSym", ",", "self", ".", "ftraceSymMap", "[", "ftraceSym", "]", ")", ")", "# for k in self.ftraceSymMap.keys():", "# if l.find(k) > 0:", "# data_out.append(l.replace(k, self.ftraceSymMap[k]))", "self", ".", "data", "=", "data_out" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/tracer/function.py#L389-L400
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/_pyio.py
python
FileIO.closefd
(self)
return self._closefd
True if the file descriptor will be closed by close().
True if the file descriptor will be closed by close().
[ "True", "if", "the", "file", "descriptor", "will", "be", "closed", "by", "close", "()", "." ]
def closefd(self): """True if the file descriptor will be closed by close().""" return self._closefd
[ "def", "closefd", "(", "self", ")", ":", "return", "self", ".", "_closefd" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pyio.py#L1744-L1746
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/tlslite/tlslite/utils/keyfactory.py
python
generateRSAKey
(bits, implementations=["openssl", "python"])
Generate an RSA key with the specified bit length. @type bits: int @param bits: Desired bit length of the new key's modulus. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: A new RSA private key.
Generate an RSA key with the specified bit length.
[ "Generate", "an", "RSA", "key", "with", "the", "specified", "bit", "length", "." ]
def generateRSAKey(bits, implementations=["openssl", "python"]): """Generate an RSA key with the specified bit length. @type bits: int @param bits: Desired bit length of the new key's modulus. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: A new RSA private key. """ for implementation in implementations: if implementation == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_RSAKey.generate(bits) elif implementation == "python": return Python_RSAKey.generate(bits) raise ValueError("No acceptable implementations")
[ "def", "generateRSAKey", "(", "bits", ",", "implementations", "=", "[", "\"openssl\"", ",", "\"python\"", "]", ")", ":", "for", "implementation", "in", "implementations", ":", "if", "implementation", "==", "\"openssl\"", "and", "cryptomath", ".", "m2cryptoLoaded", ":", "return", "OpenSSL_RSAKey", ".", "generate", "(", "bits", ")", "elif", "implementation", "==", "\"python\"", ":", "return", "Python_RSAKey", ".", "generate", "(", "bits", ")", "raise", "ValueError", "(", "\"No acceptable implementations\"", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/tlslite/tlslite/utils/keyfactory.py#L22-L36
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/layer1.py
python
CloudSearchConnection.define_index_field
(self, domain_name, index_field)
return self._make_request( action='DefineIndexField', verb='POST', path='/', params=params)
Configures an `IndexField` for the search domain. Used to create new fields and modify existing ones. You must specify the name of the domain you are configuring and an index field configuration. The index field configuration specifies a unique name, the index field type, and the options you want to configure for the field. The options you can specify depend on the `IndexFieldType`. If the field exists, the new configuration replaces the old one. For more information, see `Configuring Index Fields`_ in the Amazon CloudSearch Developer Guide . :type domain_name: string :param domain_name: A string that represents the name of a domain. Domain names are unique across the domains owned by an account within an AWS region. Domain names start with a letter or number and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen). :type index_field: dict :param index_field: The index field and field options you want to configure.
Configures an `IndexField` for the search domain. Used to create new fields and modify existing ones. You must specify the name of the domain you are configuring and an index field configuration. The index field configuration specifies a unique name, the index field type, and the options you want to configure for the field. The options you can specify depend on the `IndexFieldType`. If the field exists, the new configuration replaces the old one. For more information, see `Configuring Index Fields`_ in the Amazon CloudSearch Developer Guide .
[ "Configures", "an", "IndexField", "for", "the", "search", "domain", ".", "Used", "to", "create", "new", "fields", "and", "modify", "existing", "ones", ".", "You", "must", "specify", "the", "name", "of", "the", "domain", "you", "are", "configuring", "and", "an", "index", "field", "configuration", ".", "The", "index", "field", "configuration", "specifies", "a", "unique", "name", "the", "index", "field", "type", "and", "the", "options", "you", "want", "to", "configure", "for", "the", "field", ".", "The", "options", "you", "can", "specify", "depend", "on", "the", "IndexFieldType", ".", "If", "the", "field", "exists", "the", "new", "configuration", "replaces", "the", "old", "one", ".", "For", "more", "information", "see", "Configuring", "Index", "Fields", "_", "in", "the", "Amazon", "CloudSearch", "Developer", "Guide", "." ]
def define_index_field(self, domain_name, index_field): """ Configures an `IndexField` for the search domain. Used to create new fields and modify existing ones. You must specify the name of the domain you are configuring and an index field configuration. The index field configuration specifies a unique name, the index field type, and the options you want to configure for the field. The options you can specify depend on the `IndexFieldType`. If the field exists, the new configuration replaces the old one. For more information, see `Configuring Index Fields`_ in the Amazon CloudSearch Developer Guide . :type domain_name: string :param domain_name: A string that represents the name of a domain. Domain names are unique across the domains owned by an account within an AWS region. Domain names start with a letter or number and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen). :type index_field: dict :param index_field: The index field and field options you want to configure. """ params = {'DomainName': domain_name, } self.build_complex_param(params, 'IndexField', index_field) return self._make_request( action='DefineIndexField', verb='POST', path='/', params=params)
[ "def", "define_index_field", "(", "self", ",", "domain_name", ",", "index_field", ")", ":", "params", "=", "{", "'DomainName'", ":", "domain_name", ",", "}", "self", ".", "build_complex_param", "(", "params", ",", "'IndexField'", ",", "index_field", ")", "return", "self", ".", "_make_request", "(", "action", "=", "'DefineIndexField'", ",", "verb", "=", "'POST'", ",", "path", "=", "'/'", ",", "params", "=", "params", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/layer1.py#L173-L204
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/bucket.py
python
Bucket.validate_kwarg_names
(self, kwargs, names)
Checks that all named arguments are in the specified list of names. :type kwargs: dict :param kwargs: Dictionary of kwargs to validate. :type names: list :param names: List of possible named arguments.
Checks that all named arguments are in the specified list of names.
[ "Checks", "that", "all", "named", "arguments", "are", "in", "the", "specified", "list", "of", "names", "." ]
def validate_kwarg_names(self, kwargs, names): """ Checks that all named arguments are in the specified list of names. :type kwargs: dict :param kwargs: Dictionary of kwargs to validate. :type names: list :param names: List of possible named arguments. """ for kwarg in kwargs: if kwarg not in names: raise TypeError('Invalid argument "%s"!' % kwarg)
[ "def", "validate_kwarg_names", "(", "self", ",", "kwargs", ",", "names", ")", ":", "for", "kwarg", "in", "kwargs", ":", "if", "kwarg", "not", "in", "names", ":", "raise", "TypeError", "(", "'Invalid argument \"%s\"!'", "%", "kwarg", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/bucket.py#L412-L424
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/crywaflib/compile_rules_linux_x64_linux_x64_clang.py
python
load_release_linux_x64_linux_x64_clang_settings
(conf)
Setup all compiler and linker settings shared over all linux_x64_linux_x64_clang configurations for the 'release' configuration
Setup all compiler and linker settings shared over all linux_x64_linux_x64_clang configurations for the 'release' configuration
[ "Setup", "all", "compiler", "and", "linker", "settings", "shared", "over", "all", "linux_x64_linux_x64_clang", "configurations", "for", "the", "release", "configuration" ]
def load_release_linux_x64_linux_x64_clang_settings(conf): """ Setup all compiler and linker settings shared over all linux_x64_linux_x64_clang configurations for the 'release' configuration """ v = conf.env conf.load_linux_x64_linux_x64_clang_common_settings() # Load addional shared settings conf.load_release_cryengine_settings() conf.load_release_clang_settings() conf.load_release_linux_settings() conf.load_release_linux_x64_settings()
[ "def", "load_release_linux_x64_linux_x64_clang_settings", "(", "conf", ")", ":", "v", "=", "conf", ".", "env", "conf", ".", "load_linux_x64_linux_x64_clang_common_settings", "(", ")", "# Load addional shared settings", "conf", ".", "load_release_cryengine_settings", "(", ")", "conf", ".", "load_release_clang_settings", "(", ")", "conf", ".", "load_release_linux_settings", "(", ")", "conf", ".", "load_release_linux_x64_settings", "(", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/compile_rules_linux_x64_linux_x64_clang.py#L75-L87
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/universe_generation/galaxy.py
python
DSet.bind_parent
(self, parent)
Bind to parent.
Bind to parent.
[ "Bind", "to", "parent", "." ]
def bind_parent(self, parent): """Bind to parent.""" assert self is not parent self.parent = parent
[ "def", "bind_parent", "(", "self", ",", "parent", ")", ":", "assert", "self", "is", "not", "parent", "self", ".", "parent", "=", "parent" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/universe_generation/galaxy.py#L115-L118
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/swift_build_support/swift_build_support/products/swiftinspect.py
python
SwiftInspect.test
(self, host_target)
Just run a single instance of the command for both .debug and .release.
Just run a single instance of the command for both .debug and .release.
[ "Just", "run", "a", "single", "instance", "of", "the", "command", "for", "both", ".", "debug", "and", ".", "release", "." ]
def test(self, host_target): """Just run a single instance of the command for both .debug and .release. """ pass
[ "def", "test", "(", "self", ",", "host_target", ")", ":", "pass" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/swift_build_support/swift_build_support/products/swiftinspect.py#L54-L58
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/CGIHTTPServer.py
python
CGIHTTPRequestHandler.send_head
(self)
Version of send_head that support CGI scripts
Version of send_head that support CGI scripts
[ "Version", "of", "send_head", "that", "support", "CGI", "scripts" ]
def send_head(self): """Version of send_head that support CGI scripts""" if self.is_cgi(): return self.run_cgi() else: return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)
[ "def", "send_head", "(", "self", ")", ":", "if", "self", ".", "is_cgi", "(", ")", ":", "return", "self", ".", "run_cgi", "(", ")", "else", ":", "return", "SimpleHTTPServer", ".", "SimpleHTTPRequestHandler", ".", "send_head", "(", "self", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/CGIHTTPServer.py#L66-L71
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
GridCellAttr.GetTextColour
(*args, **kwargs)
return _grid.GridCellAttr_GetTextColour(*args, **kwargs)
GetTextColour(self) -> Colour
GetTextColour(self) -> Colour
[ "GetTextColour", "(", "self", ")", "-", ">", "Colour" ]
def GetTextColour(*args, **kwargs): """GetTextColour(self) -> Colour""" return _grid.GridCellAttr_GetTextColour(*args, **kwargs)
[ "def", "GetTextColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridCellAttr_GetTextColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L615-L617
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
ThirdParty/cinemasci/paraview/tpl/cinemasci/cis/colormap.py
python
colormap.add_point
(self, point)
return
Add a point, a tuple of (x,o,r,g,b) to points.
Add a point, a tuple of (x,o,r,g,b) to points.
[ "Add", "a", "point", "a", "tuple", "of", "(", "x", "o", "r", "g", "b", ")", "to", "points", "." ]
def add_point(self, point): """ Add a point, a tuple of (x,o,r,g,b) to points. """ self.edited = True self.points.append(point) self.points.sort() #to do, if x value of point already exists, replace or return error? return
[ "def", "add_point", "(", "self", ",", "point", ")", ":", "self", ".", "edited", "=", "True", "self", ".", "points", ".", "append", "(", "point", ")", "self", ".", "points", ".", "sort", "(", ")", "#to do, if x value of point already exists, replace or return error?", "return" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinemasci/paraview/tpl/cinemasci/cis/colormap.py#L66-L72
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distribution/dirichlet.py
python
Dirichlet.sample
(self, shape=())
return _dirichlet(self.concentration.expand(self._extend_shape(shape)))
Sample from dirichlet distribution. Args: shape (Sequence[int], optional): Sample shape. Defaults to empty tuple.
Sample from dirichlet distribution.
[ "Sample", "from", "dirichlet", "distribution", "." ]
def sample(self, shape=()): """Sample from dirichlet distribution. Args: shape (Sequence[int], optional): Sample shape. Defaults to empty tuple. """ shape = shape if isinstance(shape, tuple) else tuple(shape) return _dirichlet(self.concentration.expand(self._extend_shape(shape)))
[ "def", "sample", "(", "self", ",", "shape", "=", "(", ")", ")", ":", "shape", "=", "shape", "if", "isinstance", "(", "shape", ",", "tuple", ")", "else", "tuple", "(", "shape", ")", "return", "_dirichlet", "(", "self", ".", "concentration", ".", "expand", "(", "self", ".", "_extend_shape", "(", "shape", ")", ")", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distribution/dirichlet.py#L103-L110
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
PseudoDC.DrawRectanglePointSize
(*args, **kwargs)
return _gdi_.PseudoDC_DrawRectanglePointSize(*args, **kwargs)
DrawRectanglePointSize(self, Point pt, Size sz) Draws a rectangle with the given top left corner, and with the given size. The current pen is used for the outline and the current brush for filling the shape.
DrawRectanglePointSize(self, Point pt, Size sz)
[ "DrawRectanglePointSize", "(", "self", "Point", "pt", "Size", "sz", ")" ]
def DrawRectanglePointSize(*args, **kwargs): """ DrawRectanglePointSize(self, Point pt, Size sz) Draws a rectangle with the given top left corner, and with the given size. The current pen is used for the outline and the current brush for filling the shape. """ return _gdi_.PseudoDC_DrawRectanglePointSize(*args, **kwargs)
[ "def", "DrawRectanglePointSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "PseudoDC_DrawRectanglePointSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L7932-L7940
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/debug/debug_utils.py
python
add_debug_tensor_watch
(run_options, node_name, output_slot=0, debug_ops="DebugIdentity", debug_urls=None)
Add debug tensor watch option to RunOptions. Args: run_options: An instance of tensorflow.core.protobuf.config_pb2.RunOptions node_name: Name of the node to watch. output_slot: Output slot index of the tensor from the watched node. debug_ops: Name(s) of the debug op(s). Default: "DebugIdentity". Can be a list of strings or a single string. The latter case is equivalent to a list of string with only one element. debug_urls: URLs to send debug signals to: a non-empty list of strings or a string, or None. The case of a string is equivalent to a list of string with only one element.
Add debug tensor watch option to RunOptions.
[ "Add", "debug", "tensor", "watch", "option", "to", "RunOptions", "." ]
def add_debug_tensor_watch(run_options, node_name, output_slot=0, debug_ops="DebugIdentity", debug_urls=None): """Add debug tensor watch option to RunOptions. Args: run_options: An instance of tensorflow.core.protobuf.config_pb2.RunOptions node_name: Name of the node to watch. output_slot: Output slot index of the tensor from the watched node. debug_ops: Name(s) of the debug op(s). Default: "DebugIdentity". Can be a list of strings or a single string. The latter case is equivalent to a list of string with only one element. debug_urls: URLs to send debug signals to: a non-empty list of strings or a string, or None. The case of a string is equivalent to a list of string with only one element. """ watch_opts = run_options.debug_tensor_watch_opts watch = watch_opts.add() watch.node_name = node_name watch.output_slot = output_slot if isinstance(debug_ops, str): debug_ops = [debug_ops] watch.debug_ops.extend(debug_ops) if debug_urls: if isinstance(debug_urls, str): debug_urls = [debug_urls] watch.debug_urls.extend(debug_urls)
[ "def", "add_debug_tensor_watch", "(", "run_options", ",", "node_name", ",", "output_slot", "=", "0", ",", "debug_ops", "=", "\"DebugIdentity\"", ",", "debug_urls", "=", "None", ")", ":", "watch_opts", "=", "run_options", ".", "debug_tensor_watch_opts", "watch", "=", "watch_opts", ".", "add", "(", ")", "watch", ".", "node_name", "=", "node_name", "watch", ".", "output_slot", "=", "output_slot", "if", "isinstance", "(", "debug_ops", ",", "str", ")", ":", "debug_ops", "=", "[", "debug_ops", "]", "watch", ".", "debug_ops", ".", "extend", "(", "debug_ops", ")", "if", "debug_urls", ":", "if", "isinstance", "(", "debug_urls", ",", "str", ")", ":", "debug_urls", "=", "[", "debug_urls", "]", "watch", ".", "debug_urls", ".", "extend", "(", "debug_urls", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/debug/debug_utils.py#L25-L59
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/constraint_solver/samples/vrp_initial_routes.py
python
main
()
Solve the CVRP problem.
Solve the CVRP problem.
[ "Solve", "the", "CVRP", "problem", "." ]
def main(): """Solve the CVRP problem.""" # Instantiate the data problem. # [START data] data = create_data_model() # [END data] # Create the routing index manager. # [START index_manager] manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']), data['num_vehicles'], data['depot']) # [END index_manager] # Create Routing Model. # [START routing_model] routing = pywrapcp.RoutingModel(manager) # [END routing_model] # Create and register a transit callback. # [START transit_callback] def distance_callback(from_index, to_index): """Returns the distance between the two nodes.""" # Convert from routing variable Index to distance matrix NodeIndex. from_node = manager.IndexToNode(from_index) to_node = manager.IndexToNode(to_index) return data['distance_matrix'][from_node][to_node] transit_callback_index = routing.RegisterTransitCallback(distance_callback) # [END transit_callback] # Define cost of each arc. # [START arc_cost] routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index) # [END arc_cost] # Add Distance constraint. # [START distance_constraint] dimension_name = 'Distance' routing.AddDimension( transit_callback_index, 0, # no slack 3000, # vehicle maximum travel distance True, # start cumul to zero dimension_name) distance_dimension = routing.GetDimensionOrDie(dimension_name) distance_dimension.SetGlobalSpanCostCoefficient(100) # [END distance_constraint] # [START print_initial_solution] initial_solution = routing.ReadAssignmentFromRoutes(data['initial_routes'], True) print('Initial solution:') print_solution(data, manager, routing, initial_solution) # [END print_initial_solution] # Set default search parameters. # [START parameters] search_parameters = pywrapcp.DefaultRoutingSearchParameters() # [END parameters] # Solve the problem. # [START solve] solution = routing.SolveFromAssignmentWithParameters( initial_solution, search_parameters) # [END solve] # Print solution on console. # [START print_solution] if solution: print('Solution after search:') print_solution(data, manager, routing, solution)
[ "def", "main", "(", ")", ":", "# Instantiate the data problem.", "# [START data]", "data", "=", "create_data_model", "(", ")", "# [END data]", "# Create the routing index manager.", "# [START index_manager]", "manager", "=", "pywrapcp", ".", "RoutingIndexManager", "(", "len", "(", "data", "[", "'distance_matrix'", "]", ")", ",", "data", "[", "'num_vehicles'", "]", ",", "data", "[", "'depot'", "]", ")", "# [END index_manager]", "# Create Routing Model.", "# [START routing_model]", "routing", "=", "pywrapcp", ".", "RoutingModel", "(", "manager", ")", "# [END routing_model]", "# Create and register a transit callback.", "# [START transit_callback]", "def", "distance_callback", "(", "from_index", ",", "to_index", ")", ":", "\"\"\"Returns the distance between the two nodes.\"\"\"", "# Convert from routing variable Index to distance matrix NodeIndex.", "from_node", "=", "manager", ".", "IndexToNode", "(", "from_index", ")", "to_node", "=", "manager", ".", "IndexToNode", "(", "to_index", ")", "return", "data", "[", "'distance_matrix'", "]", "[", "from_node", "]", "[", "to_node", "]", "transit_callback_index", "=", "routing", ".", "RegisterTransitCallback", "(", "distance_callback", ")", "# [END transit_callback]", "# Define cost of each arc.", "# [START arc_cost]", "routing", ".", "SetArcCostEvaluatorOfAllVehicles", "(", "transit_callback_index", ")", "# [END arc_cost]", "# Add Distance constraint.", "# [START distance_constraint]", "dimension_name", "=", "'Distance'", "routing", ".", "AddDimension", "(", "transit_callback_index", ",", "0", ",", "# no slack", "3000", ",", "# vehicle maximum travel distance", "True", ",", "# start cumul to zero", "dimension_name", ")", "distance_dimension", "=", "routing", ".", "GetDimensionOrDie", "(", "dimension_name", ")", "distance_dimension", ".", "SetGlobalSpanCostCoefficient", "(", "100", ")", "# [END distance_constraint]", "# [START print_initial_solution]", "initial_solution", "=", "routing", ".", "ReadAssignmentFromRoutes", "(", "data", "[", "'initial_routes'", "]", ",", "True", ")", "print", "(", "'Initial solution:'", ")", "print_solution", "(", "data", ",", "manager", ",", "routing", ",", "initial_solution", ")", "# [END print_initial_solution]", "# Set default search parameters.", "# [START parameters]", "search_parameters", "=", "pywrapcp", ".", "DefaultRoutingSearchParameters", "(", ")", "# [END parameters]", "# Solve the problem.", "# [START solve]", "solution", "=", "routing", ".", "SolveFromAssignmentWithParameters", "(", "initial_solution", ",", "search_parameters", ")", "# [END solve]", "# Print solution on console.", "# [START print_solution]", "if", "solution", ":", "print", "(", "'Solution after search:'", ")", "print_solution", "(", "data", ",", "manager", ",", "routing", ",", "solution", ")" ]
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/constraint_solver/samples/vrp_initial_routes.py#L134-L205
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/Blast/houdini/python2.7libs/blastExport/slice.py
python
Slice.translate
(self)
return self.__translate
:return: str
:return: str
[ ":", "return", ":", "str" ]
def translate(self): """ :return: str """ return self.__translate
[ "def", "translate", "(", "self", ")", ":", "return", "self", ".", "__translate" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/houdini/python2.7libs/blastExport/slice.py#L293-L297
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/py/editor.py
python
EditorFrame.bufferSaveAs
(self)
return cancel
Save buffer to a new filename.
Save buffer to a new filename.
[ "Save", "buffer", "to", "a", "new", "filename", "." ]
def bufferSaveAs(self): """Save buffer to a new filename.""" if self.bufferHasChanged() and self.buffer.doc.filepath: cancel = self.bufferSuggestSave() if cancel: return cancel filedir = '' if self.buffer and self.buffer.doc.filedir: filedir = self.buffer.doc.filedir result = saveSingle(directory=filedir) if result.path: self.buffer.saveAs(result.path) cancel = False else: cancel = True return cancel
[ "def", "bufferSaveAs", "(", "self", ")", ":", "if", "self", ".", "bufferHasChanged", "(", ")", "and", "self", ".", "buffer", ".", "doc", ".", "filepath", ":", "cancel", "=", "self", ".", "bufferSuggestSave", "(", ")", "if", "cancel", ":", "return", "cancel", "filedir", "=", "''", "if", "self", ".", "buffer", "and", "self", ".", "buffer", ".", "doc", ".", "filedir", ":", "filedir", "=", "self", ".", "buffer", ".", "doc", ".", "filedir", "result", "=", "saveSingle", "(", "directory", "=", "filedir", ")", "if", "result", ".", "path", ":", "self", ".", "buffer", ".", "saveAs", "(", "result", ".", "path", ")", "cancel", "=", "False", "else", ":", "cancel", "=", "True", "return", "cancel" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/editor.py#L215-L230
RobotLocomotion/drake
0e18a34604c45ed65bc9018a54f7610f91cdad5b
bindings/pydrake/systems/planar_scenegraph_visualizer.py
python
PlanarSceneGraphVisualizer._build_body_patches
(self, use_random_colors, substitute_collocated_mesh_files, inspector)
Generates body patches. self._patch_Blist stores a list of patches for each body (starting at body id 1). A body patch is a list of all 3D vertices of a piece of visual geometry.
Generates body patches. self._patch_Blist stores a list of patches for each body (starting at body id 1). A body patch is a list of all 3D vertices of a piece of visual geometry.
[ "Generates", "body", "patches", ".", "self", ".", "_patch_Blist", "stores", "a", "list", "of", "patches", "for", "each", "body", "(", "starting", "at", "body", "id", "1", ")", ".", "A", "body", "patch", "is", "a", "list", "of", "all", "3D", "vertices", "of", "a", "piece", "of", "visual", "geometry", "." ]
def _build_body_patches(self, use_random_colors, substitute_collocated_mesh_files, inspector): """ Generates body patches. self._patch_Blist stores a list of patches for each body (starting at body id 1). A body patch is a list of all 3D vertices of a piece of visual geometry. """ self._patch_Blist = {} self._patch_Blist_colors = {} for frame_id in inspector.GetAllFrameIds(): count = inspector.NumGeometriesForFrameWithRole(frame_id, Role.kIllustration) if count == 0: continue frame_name = self.frame_name(frame_id, inspector) this_body_patches = [] this_body_colors = [] for g_id in inspector.GetGeometries(frame_id, Role.kIllustration): X_BG = inspector.GetPoseInFrame(g_id) shape = inspector.GetShape(g_id) if isinstance(shape, Box): # Draw a bounding box. patch_G = np.vstack(( shape.width()/2.*np.array( [-1, -1, 1, 1, -1, -1, 1, 1]), shape.depth()/2.*np.array( [-1, 1, -1, 1, -1, 1, -1, 1]), shape.height()/2.*np.array( [-1, -1, -1, -1, 1, 1, 1, 1]))) elif isinstance(shape, Sphere): # Sphere is the only shape that allows a zero-measure. A # zero-radius sphere is a point, and we skip it. if shape.radius() == 0: continue lati, longi = np.meshgrid(np.arange(0., 2.*math.pi, 0.5), np.arange(0., 2.*math.pi, 0.5)) lati = lati.ravel() longi = longi.ravel() patch_G = np.vstack([ np.sin(lati)*np.cos(longi), np.sin(lati)*np.sin(longi), np.cos(lati)]) patch_G *= shape.radius() elif isinstance(shape, Cylinder): radius = shape.radius() length = shape.length() # In the lcm geometry, cylinders are along +z # https://github.com/RobotLocomotion/drake/blob/last_sha_with_original_matlab/drake/matlab/systems/plants/RigidBodyCylinder.m # Two circles: one at bottom, one at top. sample_pts = np.arange(0., 2.*math.pi, 0.25) patch_G = np.hstack( [np.array([ [radius*math.cos(pt), radius*math.sin(pt), -length/2.], [radius*math.cos(pt), radius*math.sin(pt), length/2.]]).T for pt in sample_pts]) elif isinstance(shape, (Mesh, Convex)): filename = shape.filename() base, ext = os.path.splitext(filename) if (ext.lower() != ".obj" and substitute_collocated_mesh_files): # Check for a co-located .obj file (case insensitive). for f in glob.glob(base + '.*'): if f[-4:].lower() == '.obj': filename = f break if filename[-4:].lower() != '.obj': raise RuntimeError( f"The given file {filename} is not " f"supported and no alternate {base}" ".obj could be found.") if not os.path.exists(filename): raise FileNotFoundError(errno.ENOENT, os.strerror( errno.ENOENT), filename) # Get mesh scaling. scale = shape.scale() mesh = ReadObjToTriangleSurfaceMesh(filename, scale) patch_G = np.vstack(mesh.vertices()) # Only store the vertices of the (3D) convex hull of the # mesh, as any interior vertices will still be interior # vertices after projection, and will therefore be removed # in _update_body_fill_verts(). hull = spatial.ConvexHull(patch_G) patch_G = np.vstack( [patch_G[v, :] for v in hull.vertices]).T elif isinstance(shape, HalfSpace): # For a half space, we'll simply create a large box with # the top face at z = 0, the bottom face at z = -1 and the # far corners at +/- 50 in the x- and y- directions. x = 50 y = 50 z = -1 patch_G = np.vstack(( x * np.array([-1, -1, 1, 1, -1, -1, 1, 1]), y * np.array([-1, 1, -1, 1, -1, 1, -1, 1]), z * np.array([-1, -1, -1, -1, 0, 0, 0, 0]))) # TODO(SeanCurtis-TRI): Provide support for capsule and # ellipsoid. else: print("UNSUPPORTED GEOMETRY TYPE {} IGNORED".format( type(shape))) continue # Compute pose in body. patch_B = X_BG @ patch_G # Close path if not closed. if (patch_B[:, -1] != patch_B[:, 0]).any(): patch_B = np.hstack((patch_B, patch_B[:, 0][np.newaxis].T)) this_body_patches.append(patch_B) if not use_random_colors: # If we need to use random colors, we apply them after the # fact. See below. props = inspector.GetIllustrationProperties(g_id) assert props is not None rgba = props.GetPropertyOrDefault( "phong", "diffuse", Rgba(0.9, 0.9, 0.9, 1.0)) color = np.array((rgba.r(), rgba.g(), rgba.b(), rgba.a())) this_body_colors.append(color) self._patch_Blist[frame_name] = this_body_patches self._patch_Blist_colors[frame_name] = this_body_colors # Spawn a random color generator. Each body will be given a unique # color when using this random generator, with each visual element of # the body colored the same. if use_random_colors: color = iter(plt.cm.rainbow( np.linspace(0, 1, len(self._patch_Blist_colors)))) for name in self._patch_Blist_colors.keys(): this_color = next(color) patch_count = len(self._patch_Blist[name]) self._patch_Blist_colors[name] = [this_color] * patch_count
[ "def", "_build_body_patches", "(", "self", ",", "use_random_colors", ",", "substitute_collocated_mesh_files", ",", "inspector", ")", ":", "self", ".", "_patch_Blist", "=", "{", "}", "self", ".", "_patch_Blist_colors", "=", "{", "}", "for", "frame_id", "in", "inspector", ".", "GetAllFrameIds", "(", ")", ":", "count", "=", "inspector", ".", "NumGeometriesForFrameWithRole", "(", "frame_id", ",", "Role", ".", "kIllustration", ")", "if", "count", "==", "0", ":", "continue", "frame_name", "=", "self", ".", "frame_name", "(", "frame_id", ",", "inspector", ")", "this_body_patches", "=", "[", "]", "this_body_colors", "=", "[", "]", "for", "g_id", "in", "inspector", ".", "GetGeometries", "(", "frame_id", ",", "Role", ".", "kIllustration", ")", ":", "X_BG", "=", "inspector", ".", "GetPoseInFrame", "(", "g_id", ")", "shape", "=", "inspector", ".", "GetShape", "(", "g_id", ")", "if", "isinstance", "(", "shape", ",", "Box", ")", ":", "# Draw a bounding box.", "patch_G", "=", "np", ".", "vstack", "(", "(", "shape", ".", "width", "(", ")", "/", "2.", "*", "np", ".", "array", "(", "[", "-", "1", ",", "-", "1", ",", "1", ",", "1", ",", "-", "1", ",", "-", "1", ",", "1", ",", "1", "]", ")", ",", "shape", ".", "depth", "(", ")", "/", "2.", "*", "np", ".", "array", "(", "[", "-", "1", ",", "1", ",", "-", "1", ",", "1", ",", "-", "1", ",", "1", ",", "-", "1", ",", "1", "]", ")", ",", "shape", ".", "height", "(", ")", "/", "2.", "*", "np", ".", "array", "(", "[", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "1", ",", "1", ",", "1", ",", "1", "]", ")", ")", ")", "elif", "isinstance", "(", "shape", ",", "Sphere", ")", ":", "# Sphere is the only shape that allows a zero-measure. A", "# zero-radius sphere is a point, and we skip it.", "if", "shape", ".", "radius", "(", ")", "==", "0", ":", "continue", "lati", ",", "longi", "=", "np", ".", "meshgrid", "(", "np", ".", "arange", "(", "0.", ",", "2.", "*", "math", ".", "pi", ",", "0.5", ")", ",", "np", ".", "arange", "(", "0.", ",", "2.", "*", "math", ".", "pi", ",", "0.5", ")", ")", "lati", "=", "lati", ".", "ravel", "(", ")", "longi", "=", "longi", ".", "ravel", "(", ")", "patch_G", "=", "np", ".", "vstack", "(", "[", "np", ".", "sin", "(", "lati", ")", "*", "np", ".", "cos", "(", "longi", ")", ",", "np", ".", "sin", "(", "lati", ")", "*", "np", ".", "sin", "(", "longi", ")", ",", "np", ".", "cos", "(", "lati", ")", "]", ")", "patch_G", "*=", "shape", ".", "radius", "(", ")", "elif", "isinstance", "(", "shape", ",", "Cylinder", ")", ":", "radius", "=", "shape", ".", "radius", "(", ")", "length", "=", "shape", ".", "length", "(", ")", "# In the lcm geometry, cylinders are along +z", "# https://github.com/RobotLocomotion/drake/blob/last_sha_with_original_matlab/drake/matlab/systems/plants/RigidBodyCylinder.m", "# Two circles: one at bottom, one at top.", "sample_pts", "=", "np", ".", "arange", "(", "0.", ",", "2.", "*", "math", ".", "pi", ",", "0.25", ")", "patch_G", "=", "np", ".", "hstack", "(", "[", "np", ".", "array", "(", "[", "[", "radius", "*", "math", ".", "cos", "(", "pt", ")", ",", "radius", "*", "math", ".", "sin", "(", "pt", ")", ",", "-", "length", "/", "2.", "]", ",", "[", "radius", "*", "math", ".", "cos", "(", "pt", ")", ",", "radius", "*", "math", ".", "sin", "(", "pt", ")", ",", "length", "/", "2.", "]", "]", ")", ".", "T", "for", "pt", "in", "sample_pts", "]", ")", "elif", "isinstance", "(", "shape", ",", "(", "Mesh", ",", "Convex", ")", ")", ":", "filename", "=", "shape", ".", "filename", "(", ")", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "(", "ext", ".", "lower", "(", ")", "!=", "\".obj\"", "and", "substitute_collocated_mesh_files", ")", ":", "# Check for a co-located .obj file (case insensitive).", "for", "f", "in", "glob", ".", "glob", "(", "base", "+", "'.*'", ")", ":", "if", "f", "[", "-", "4", ":", "]", ".", "lower", "(", ")", "==", "'.obj'", ":", "filename", "=", "f", "break", "if", "filename", "[", "-", "4", ":", "]", ".", "lower", "(", ")", "!=", "'.obj'", ":", "raise", "RuntimeError", "(", "f\"The given file {filename} is not \"", "f\"supported and no alternate {base}\"", "\".obj could be found.\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "FileNotFoundError", "(", "errno", ".", "ENOENT", ",", "os", ".", "strerror", "(", "errno", ".", "ENOENT", ")", ",", "filename", ")", "# Get mesh scaling.", "scale", "=", "shape", ".", "scale", "(", ")", "mesh", "=", "ReadObjToTriangleSurfaceMesh", "(", "filename", ",", "scale", ")", "patch_G", "=", "np", ".", "vstack", "(", "mesh", ".", "vertices", "(", ")", ")", "# Only store the vertices of the (3D) convex hull of the", "# mesh, as any interior vertices will still be interior", "# vertices after projection, and will therefore be removed", "# in _update_body_fill_verts().", "hull", "=", "spatial", ".", "ConvexHull", "(", "patch_G", ")", "patch_G", "=", "np", ".", "vstack", "(", "[", "patch_G", "[", "v", ",", ":", "]", "for", "v", "in", "hull", ".", "vertices", "]", ")", ".", "T", "elif", "isinstance", "(", "shape", ",", "HalfSpace", ")", ":", "# For a half space, we'll simply create a large box with", "# the top face at z = 0, the bottom face at z = -1 and the", "# far corners at +/- 50 in the x- and y- directions.", "x", "=", "50", "y", "=", "50", "z", "=", "-", "1", "patch_G", "=", "np", ".", "vstack", "(", "(", "x", "*", "np", ".", "array", "(", "[", "-", "1", ",", "-", "1", ",", "1", ",", "1", ",", "-", "1", ",", "-", "1", ",", "1", ",", "1", "]", ")", ",", "y", "*", "np", ".", "array", "(", "[", "-", "1", ",", "1", ",", "-", "1", ",", "1", ",", "-", "1", ",", "1", ",", "-", "1", ",", "1", "]", ")", ",", "z", "*", "np", ".", "array", "(", "[", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "0", ",", "0", ",", "0", ",", "0", "]", ")", ")", ")", "# TODO(SeanCurtis-TRI): Provide support for capsule and", "# ellipsoid.", "else", ":", "print", "(", "\"UNSUPPORTED GEOMETRY TYPE {} IGNORED\"", ".", "format", "(", "type", "(", "shape", ")", ")", ")", "continue", "# Compute pose in body.", "patch_B", "=", "X_BG", "@", "patch_G", "# Close path if not closed.", "if", "(", "patch_B", "[", ":", ",", "-", "1", "]", "!=", "patch_B", "[", ":", ",", "0", "]", ")", ".", "any", "(", ")", ":", "patch_B", "=", "np", ".", "hstack", "(", "(", "patch_B", ",", "patch_B", "[", ":", ",", "0", "]", "[", "np", ".", "newaxis", "]", ".", "T", ")", ")", "this_body_patches", ".", "append", "(", "patch_B", ")", "if", "not", "use_random_colors", ":", "# If we need to use random colors, we apply them after the", "# fact. See below.", "props", "=", "inspector", ".", "GetIllustrationProperties", "(", "g_id", ")", "assert", "props", "is", "not", "None", "rgba", "=", "props", ".", "GetPropertyOrDefault", "(", "\"phong\"", ",", "\"diffuse\"", ",", "Rgba", "(", "0.9", ",", "0.9", ",", "0.9", ",", "1.0", ")", ")", "color", "=", "np", ".", "array", "(", "(", "rgba", ".", "r", "(", ")", ",", "rgba", ".", "g", "(", ")", ",", "rgba", ".", "b", "(", ")", ",", "rgba", ".", "a", "(", ")", ")", ")", "this_body_colors", ".", "append", "(", "color", ")", "self", ".", "_patch_Blist", "[", "frame_name", "]", "=", "this_body_patches", "self", ".", "_patch_Blist_colors", "[", "frame_name", "]", "=", "this_body_colors", "# Spawn a random color generator. Each body will be given a unique", "# color when using this random generator, with each visual element of", "# the body colored the same.", "if", "use_random_colors", ":", "color", "=", "iter", "(", "plt", ".", "cm", ".", "rainbow", "(", "np", ".", "linspace", "(", "0", ",", "1", ",", "len", "(", "self", ".", "_patch_Blist_colors", ")", ")", ")", ")", "for", "name", "in", "self", ".", "_patch_Blist_colors", ".", "keys", "(", ")", ":", "this_color", "=", "next", "(", "color", ")", "patch_count", "=", "len", "(", "self", ".", "_patch_Blist", "[", "name", "]", ")", "self", ".", "_patch_Blist_colors", "[", "name", "]", "=", "[", "this_color", "]", "*", "patch_count" ]
https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/bindings/pydrake/systems/planar_scenegraph_visualizer.py#L183-L331
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/signaltools.py
python
resample_poly
(x, up, down, axis=0, window=('kaiser', 5.0))
return y[tuple(keep)]
Resample `x` along the given axis using polyphase filtering. The signal `x` is upsampled by the factor `up`, a zero-phase low-pass FIR filter is applied, and then it is downsampled by the factor `down`. The resulting sample rate is ``up / down`` times the original sample rate. Values beyond the boundary of the signal are assumed to be zero during the filtering step. Parameters ---------- x : array_like The data to be resampled. up : int The upsampling factor. down : int The downsampling factor. axis : int, optional The axis of `x` that is resampled. Default is 0. window : string, tuple, or array_like, optional Desired window to use to design the low-pass filter, or the FIR filter coefficients to employ. See below for details. Returns ------- resampled_x : array The resampled array. See Also -------- decimate : Downsample the signal after applying an FIR or IIR filter. resample : Resample up or down using the FFT method. Notes ----- This polyphase method will likely be faster than the Fourier method in `scipy.signal.resample` when the number of samples is large and prime, or when the number of samples is large and `up` and `down` share a large greatest common denominator. The length of the FIR filter used will depend on ``max(up, down) // gcd(up, down)``, and the number of operations during polyphase filtering will depend on the filter length and `down` (see `scipy.signal.upfirdn` for details). The argument `window` specifies the FIR low-pass filter design. If `window` is an array_like it is assumed to be the FIR filter coefficients. Note that the FIR filter is applied after the upsampling step, so it should be designed to operate on a signal at a sampling frequency higher than the original by a factor of `up//gcd(up, down)`. This function's output will be centered with respect to this array, so it is best to pass a symmetric filter with an odd number of samples if, as is usually the case, a zero-phase filter is desired. For any other type of `window`, the functions `scipy.signal.get_window` and `scipy.signal.firwin` are called to generate the appropriate filter coefficients. The first sample of the returned vector is the same as the first sample of the input vector. The spacing between samples is changed from ``dx`` to ``dx * down / float(up)``. Examples -------- Note that the end of the resampled data rises to meet the first sample of the next cycle for the FFT method, and gets closer to zero for the polyphase method: >>> from scipy import signal >>> x = np.linspace(0, 10, 20, endpoint=False) >>> y = np.cos(-x**2/6.0) >>> f_fft = signal.resample(y, 100) >>> f_poly = signal.resample_poly(y, 100, 20) >>> xnew = np.linspace(0, 10, 100, endpoint=False) >>> import matplotlib.pyplot as plt >>> plt.plot(xnew, f_fft, 'b.-', xnew, f_poly, 'r.-') >>> plt.plot(x, y, 'ko-') >>> plt.plot(10, y[0], 'bo', 10, 0., 'ro') # boundaries >>> plt.legend(['resample', 'resamp_poly', 'data'], loc='best') >>> plt.show()
Resample `x` along the given axis using polyphase filtering.
[ "Resample", "x", "along", "the", "given", "axis", "using", "polyphase", "filtering", "." ]
def resample_poly(x, up, down, axis=0, window=('kaiser', 5.0)): """ Resample `x` along the given axis using polyphase filtering. The signal `x` is upsampled by the factor `up`, a zero-phase low-pass FIR filter is applied, and then it is downsampled by the factor `down`. The resulting sample rate is ``up / down`` times the original sample rate. Values beyond the boundary of the signal are assumed to be zero during the filtering step. Parameters ---------- x : array_like The data to be resampled. up : int The upsampling factor. down : int The downsampling factor. axis : int, optional The axis of `x` that is resampled. Default is 0. window : string, tuple, or array_like, optional Desired window to use to design the low-pass filter, or the FIR filter coefficients to employ. See below for details. Returns ------- resampled_x : array The resampled array. See Also -------- decimate : Downsample the signal after applying an FIR or IIR filter. resample : Resample up or down using the FFT method. Notes ----- This polyphase method will likely be faster than the Fourier method in `scipy.signal.resample` when the number of samples is large and prime, or when the number of samples is large and `up` and `down` share a large greatest common denominator. The length of the FIR filter used will depend on ``max(up, down) // gcd(up, down)``, and the number of operations during polyphase filtering will depend on the filter length and `down` (see `scipy.signal.upfirdn` for details). The argument `window` specifies the FIR low-pass filter design. If `window` is an array_like it is assumed to be the FIR filter coefficients. Note that the FIR filter is applied after the upsampling step, so it should be designed to operate on a signal at a sampling frequency higher than the original by a factor of `up//gcd(up, down)`. This function's output will be centered with respect to this array, so it is best to pass a symmetric filter with an odd number of samples if, as is usually the case, a zero-phase filter is desired. For any other type of `window`, the functions `scipy.signal.get_window` and `scipy.signal.firwin` are called to generate the appropriate filter coefficients. The first sample of the returned vector is the same as the first sample of the input vector. The spacing between samples is changed from ``dx`` to ``dx * down / float(up)``. Examples -------- Note that the end of the resampled data rises to meet the first sample of the next cycle for the FFT method, and gets closer to zero for the polyphase method: >>> from scipy import signal >>> x = np.linspace(0, 10, 20, endpoint=False) >>> y = np.cos(-x**2/6.0) >>> f_fft = signal.resample(y, 100) >>> f_poly = signal.resample_poly(y, 100, 20) >>> xnew = np.linspace(0, 10, 100, endpoint=False) >>> import matplotlib.pyplot as plt >>> plt.plot(xnew, f_fft, 'b.-', xnew, f_poly, 'r.-') >>> plt.plot(x, y, 'ko-') >>> plt.plot(10, y[0], 'bo', 10, 0., 'ro') # boundaries >>> plt.legend(['resample', 'resamp_poly', 'data'], loc='best') >>> plt.show() """ x = asarray(x) if up != int(up): raise ValueError("up must be an integer") if down != int(down): raise ValueError("down must be an integer") up = int(up) down = int(down) if up < 1 or down < 1: raise ValueError('up and down must be >= 1') # Determine our up and down factors # Use a rational approximation to save computation time on really long # signals g_ = gcd(up, down) up //= g_ down //= g_ if up == down == 1: return x.copy() n_out = x.shape[axis] * up n_out = n_out // down + bool(n_out % down) if isinstance(window, (list, np.ndarray)): window = array(window) # use array to force a copy (we modify it) if window.ndim > 1: raise ValueError('window must be 1-D') half_len = (window.size - 1) // 2 h = window else: # Design a linear-phase low-pass FIR filter max_rate = max(up, down) f_c = 1. / max_rate # cutoff of FIR filter (rel. to Nyquist) half_len = 10 * max_rate # reasonable cutoff for our sinc-like function h = firwin(2 * half_len + 1, f_c, window=window) h *= up # Zero-pad our filter to put the output samples at the center n_pre_pad = (down - half_len % down) n_post_pad = 0 n_pre_remove = (half_len + n_pre_pad) // down # We should rarely need to do this given our filter lengths... while _output_len(len(h) + n_pre_pad + n_post_pad, x.shape[axis], up, down) < n_out + n_pre_remove: n_post_pad += 1 h = np.concatenate((np.zeros(n_pre_pad, dtype=h.dtype), h, np.zeros(n_post_pad, dtype=h.dtype))) n_pre_remove_end = n_pre_remove + n_out # filter then remove excess y = upfirdn(h, x, up, down, axis=axis) keep = [slice(None), ]*x.ndim keep[axis] = slice(n_pre_remove, n_pre_remove_end) return y[tuple(keep)]
[ "def", "resample_poly", "(", "x", ",", "up", ",", "down", ",", "axis", "=", "0", ",", "window", "=", "(", "'kaiser'", ",", "5.0", ")", ")", ":", "x", "=", "asarray", "(", "x", ")", "if", "up", "!=", "int", "(", "up", ")", ":", "raise", "ValueError", "(", "\"up must be an integer\"", ")", "if", "down", "!=", "int", "(", "down", ")", ":", "raise", "ValueError", "(", "\"down must be an integer\"", ")", "up", "=", "int", "(", "up", ")", "down", "=", "int", "(", "down", ")", "if", "up", "<", "1", "or", "down", "<", "1", ":", "raise", "ValueError", "(", "'up and down must be >= 1'", ")", "# Determine our up and down factors", "# Use a rational approximation to save computation time on really long", "# signals", "g_", "=", "gcd", "(", "up", ",", "down", ")", "up", "//=", "g_", "down", "//=", "g_", "if", "up", "==", "down", "==", "1", ":", "return", "x", ".", "copy", "(", ")", "n_out", "=", "x", ".", "shape", "[", "axis", "]", "*", "up", "n_out", "=", "n_out", "//", "down", "+", "bool", "(", "n_out", "%", "down", ")", "if", "isinstance", "(", "window", ",", "(", "list", ",", "np", ".", "ndarray", ")", ")", ":", "window", "=", "array", "(", "window", ")", "# use array to force a copy (we modify it)", "if", "window", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "'window must be 1-D'", ")", "half_len", "=", "(", "window", ".", "size", "-", "1", ")", "//", "2", "h", "=", "window", "else", ":", "# Design a linear-phase low-pass FIR filter", "max_rate", "=", "max", "(", "up", ",", "down", ")", "f_c", "=", "1.", "/", "max_rate", "# cutoff of FIR filter (rel. to Nyquist)", "half_len", "=", "10", "*", "max_rate", "# reasonable cutoff for our sinc-like function", "h", "=", "firwin", "(", "2", "*", "half_len", "+", "1", ",", "f_c", ",", "window", "=", "window", ")", "h", "*=", "up", "# Zero-pad our filter to put the output samples at the center", "n_pre_pad", "=", "(", "down", "-", "half_len", "%", "down", ")", "n_post_pad", "=", "0", "n_pre_remove", "=", "(", "half_len", "+", "n_pre_pad", ")", "//", "down", "# We should rarely need to do this given our filter lengths...", "while", "_output_len", "(", "len", "(", "h", ")", "+", "n_pre_pad", "+", "n_post_pad", ",", "x", ".", "shape", "[", "axis", "]", ",", "up", ",", "down", ")", "<", "n_out", "+", "n_pre_remove", ":", "n_post_pad", "+=", "1", "h", "=", "np", ".", "concatenate", "(", "(", "np", ".", "zeros", "(", "n_pre_pad", ",", "dtype", "=", "h", ".", "dtype", ")", ",", "h", ",", "np", ".", "zeros", "(", "n_post_pad", ",", "dtype", "=", "h", ".", "dtype", ")", ")", ")", "n_pre_remove_end", "=", "n_pre_remove", "+", "n_out", "# filter then remove excess", "y", "=", "upfirdn", "(", "h", ",", "x", ",", "up", ",", "down", ",", "axis", "=", "axis", ")", "keep", "=", "[", "slice", "(", "None", ")", ",", "]", "*", "x", ".", "ndim", "keep", "[", "axis", "]", "=", "slice", "(", "n_pre_remove", ",", "n_pre_remove_end", ")", "return", "y", "[", "tuple", "(", "keep", ")", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/signaltools.py#L2287-L2421
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/mailbox.py
python
Maildir.remove
(self, key)
Remove the keyed message; raise KeyError if it doesn't exist.
Remove the keyed message; raise KeyError if it doesn't exist.
[ "Remove", "the", "keyed", "message", ";", "raise", "KeyError", "if", "it", "doesn", "t", "exist", "." ]
def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" os.remove(os.path.join(self._path, self._lookup(key)))
[ "def", "remove", "(", "self", ",", "key", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "self", ".", "_lookup", "(", "key", ")", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/mailbox.py#L331-L333
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/models.py
python
RequestHooksMixin.deregister_hook
(self, event, hook)
Deregister a previously registered hook. Returns True if the hook existed, False if not.
Deregister a previously registered hook. Returns True if the hook existed, False if not.
[ "Deregister", "a", "previously", "registered", "hook", ".", "Returns", "True", "if", "the", "hook", "existed", "False", "if", "not", "." ]
def deregister_hook(self, event, hook): """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False
[ "def", "deregister_hook", "(", "self", ",", "event", ",", "hook", ")", ":", "try", ":", "self", ".", "hooks", "[", "event", "]", ".", "remove", "(", "hook", ")", "return", "True", "except", "ValueError", ":", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/models.py#L186-L195
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/core/tensor.py
python
Tensor.__rdiv__
(self, other)
return output
Calculate y / x. Parameters ---------- other : Tensor The y. Returns ------- Tensor The output tensor.
Calculate y / x.
[ "Calculate", "y", "/", "x", "." ]
def __rdiv__(self, other): """Calculate y / x. Parameters ---------- other : Tensor The y. Returns ------- Tensor The output tensor. """ if not isinstance(other, Tensor): if not isinstance(other, np.ndarray): if not isinstance(other, list): other = [other] other = np.array(other, dtype=np.float32) tensor = Tensor(GetTensorName()) ws.FeedTensor(tensor, other) other = tensor output = self.CreateOperator(inputs=[other, self], nout=1, op_type='RDiv') if self.shape is not None: output.shape = self.shape[:] return output
[ "def", "__rdiv__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Tensor", ")", ":", "if", "not", "isinstance", "(", "other", ",", "np", ".", "ndarray", ")", ":", "if", "not", "isinstance", "(", "other", ",", "list", ")", ":", "other", "=", "[", "other", "]", "other", "=", "np", ".", "array", "(", "other", ",", "dtype", "=", "np", ".", "float32", ")", "tensor", "=", "Tensor", "(", "GetTensorName", "(", ")", ")", "ws", ".", "FeedTensor", "(", "tensor", ",", "other", ")", "other", "=", "tensor", "output", "=", "self", ".", "CreateOperator", "(", "inputs", "=", "[", "other", ",", "self", "]", ",", "nout", "=", "1", ",", "op_type", "=", "'RDiv'", ")", "if", "self", ".", "shape", "is", "not", "None", ":", "output", ".", "shape", "=", "self", ".", "shape", "[", ":", "]", "return", "output" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/core/tensor.py#L642-L666
RoboJackets/robocup-software
bce13ce53ddb2ecb9696266d980722c34617dc15
rj_gameplay/stp/skill/action_behavior.py
python
ActionBehavior.tick_once
( self, robot: rc.Robot, world_state: rc.WorldState, ctx=None )
return {self.robot.id: [self.action]}
Ticks its action using the robot given (if root) or the robot from its parent. This will probably become tick() or spin() once action server is implemented TODO: Should return a list of robot intents
Ticks its action using the robot given (if root) or the robot from its parent. This will probably become tick() or spin() once action server is implemented TODO: Should return a list of robot intents
[ "Ticks", "its", "action", "using", "the", "robot", "given", "(", "if", "root", ")", "or", "the", "robot", "from", "its", "parent", ".", "This", "will", "probably", "become", "tick", "()", "or", "spin", "()", "once", "action", "server", "is", "implemented", "TODO", ":", "Should", "return", "a", "list", "of", "robot", "intents" ]
def tick_once( self, robot: rc.Robot, world_state: rc.WorldState, ctx=None ) -> RobotActions: """ Ticks its action using the robot given (if root) or the robot from its parent. This will probably become tick() or spin() once action server is implemented TODO: Should return a list of robot intents """ if robot is not None: self.robot = robot else: self.robot = self.parent.robot self.action.robot_id = robot.id if world_state is not None: self.world_state = world_state else: self.world_state = self.parent.world_state # if robot is None: # self.robot = self.parent.robot self.ctx = ctx super().tick_once() return {self.robot.id: [self.action]}
[ "def", "tick_once", "(", "self", ",", "robot", ":", "rc", ".", "Robot", ",", "world_state", ":", "rc", ".", "WorldState", ",", "ctx", "=", "None", ")", "->", "RobotActions", ":", "if", "robot", "is", "not", "None", ":", "self", ".", "robot", "=", "robot", "else", ":", "self", ".", "robot", "=", "self", ".", "parent", ".", "robot", "self", ".", "action", ".", "robot_id", "=", "robot", ".", "id", "if", "world_state", "is", "not", "None", ":", "self", ".", "world_state", "=", "world_state", "else", ":", "self", ".", "world_state", "=", "self", ".", "parent", ".", "world_state", "# if robot is None:", "# self.robot = self.parent.robot", "self", ".", "ctx", "=", "ctx", "super", "(", ")", ".", "tick_once", "(", ")", "return", "{", "self", ".", "robot", ".", "id", ":", "[", "self", ".", "action", "]", "}" ]
https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/stp/skill/action_behavior.py#L32-L53
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/ctc_ops.py
python
ctc_loss_v2
(labels, logits, label_length, logit_length, logits_time_major=True, unique=None, blank_index=None, name=None)
return ctc_loss_dense( labels=labels, logits=logits, label_length=label_length, logit_length=logit_length, logits_time_major=logits_time_major, unique=unique, blank_index=blank_index, name=name)
Computes CTC (Connectionist Temporal Classification) loss. This op implements the CTC loss as presented in (Graves et al., 2006). Notes: - Same as the "Classic CTC" in TensorFlow 1.x's tf.compat.v1.nn.ctc_loss setting of preprocess_collapse_repeated=False, ctc_merge_repeated=True - Labels may be supplied as either a dense, zero-padded tensor with a vector of label sequence lengths OR as a SparseTensor. - On TPU and GPU: Only dense padded labels are supported. - On CPU: Caller may use SparseTensor or dense padded labels but calling with a SparseTensor will be significantly faster. - Default blank label is 0 rather num_classes - 1, unless overridden by blank_index. Args: labels: tensor of shape [batch_size, max_label_seq_length] or SparseTensor logits: tensor of shape [frames, batch_size, num_labels], if logits_time_major == False, shape is [batch_size, frames, num_labels]. label_length: tensor of shape [batch_size], None if labels is SparseTensor Length of reference label sequence in labels. logit_length: tensor of shape [batch_size] Length of input sequence in logits. logits_time_major: (optional) If True (default), logits is shaped [time, batch, logits]. If False, shape is [batch, time, logits] unique: (optional) Unique label indices as computed by ctc_unique_labels(labels). If supplied, enable a faster, memory efficient implementation on TPU. blank_index: (optional) Set the class index to use for the blank label. Negative values will start from num_classes, ie, -1 will reproduce the ctc_loss behavior of using num_classes - 1 for the blank symbol. There is some memory/performance overhead to switching from the default of 0 as an additional shifted copy of the logits may be created. name: A name for this `Op`. Defaults to "ctc_loss_dense". Returns: loss: tensor of shape [batch_size], negative log probabilities. References: Connectionist Temporal Classification - Labeling Unsegmented Sequence Data with Recurrent Neural Networks: [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891) ([pdf](http://www.cs.toronto.edu/~graves/icml_2006.pdf))
Computes CTC (Connectionist Temporal Classification) loss.
[ "Computes", "CTC", "(", "Connectionist", "Temporal", "Classification", ")", "loss", "." ]
def ctc_loss_v2(labels, logits, label_length, logit_length, logits_time_major=True, unique=None, blank_index=None, name=None): """Computes CTC (Connectionist Temporal Classification) loss. This op implements the CTC loss as presented in (Graves et al., 2006). Notes: - Same as the "Classic CTC" in TensorFlow 1.x's tf.compat.v1.nn.ctc_loss setting of preprocess_collapse_repeated=False, ctc_merge_repeated=True - Labels may be supplied as either a dense, zero-padded tensor with a vector of label sequence lengths OR as a SparseTensor. - On TPU and GPU: Only dense padded labels are supported. - On CPU: Caller may use SparseTensor or dense padded labels but calling with a SparseTensor will be significantly faster. - Default blank label is 0 rather num_classes - 1, unless overridden by blank_index. Args: labels: tensor of shape [batch_size, max_label_seq_length] or SparseTensor logits: tensor of shape [frames, batch_size, num_labels], if logits_time_major == False, shape is [batch_size, frames, num_labels]. label_length: tensor of shape [batch_size], None if labels is SparseTensor Length of reference label sequence in labels. logit_length: tensor of shape [batch_size] Length of input sequence in logits. logits_time_major: (optional) If True (default), logits is shaped [time, batch, logits]. If False, shape is [batch, time, logits] unique: (optional) Unique label indices as computed by ctc_unique_labels(labels). If supplied, enable a faster, memory efficient implementation on TPU. blank_index: (optional) Set the class index to use for the blank label. Negative values will start from num_classes, ie, -1 will reproduce the ctc_loss behavior of using num_classes - 1 for the blank symbol. There is some memory/performance overhead to switching from the default of 0 as an additional shifted copy of the logits may be created. name: A name for this `Op`. Defaults to "ctc_loss_dense". Returns: loss: tensor of shape [batch_size], negative log probabilities. References: Connectionist Temporal Classification - Labeling Unsegmented Sequence Data with Recurrent Neural Networks: [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891) ([pdf](http://www.cs.toronto.edu/~graves/icml_2006.pdf)) """ if isinstance(labels, sparse_tensor.SparseTensor): if blank_index is None: raise ValueError( "Argument `blank_index` must be provided when labels is a " "SparseTensor.") if blank_index < 0: blank_index += _get_dim(logits, 2) if blank_index != _get_dim(logits, 2) - 1: logits = array_ops.concat([ logits[:, :, :blank_index], logits[:, :, blank_index + 1:], logits[:, :, blank_index:blank_index + 1], ], axis=2) labels = sparse_tensor.SparseTensor( labels.indices, array_ops.where(labels.values < blank_index, labels.values, labels.values - 1), labels.dense_shape) return ctc_loss( labels=labels, inputs=logits, sequence_length=logit_length, time_major=logits_time_major) if blank_index is None: blank_index = 0 return ctc_loss_dense( labels=labels, logits=logits, label_length=label_length, logit_length=logit_length, logits_time_major=logits_time_major, unique=unique, blank_index=blank_index, name=name)
[ "def", "ctc_loss_v2", "(", "labels", ",", "logits", ",", "label_length", ",", "logit_length", ",", "logits_time_major", "=", "True", ",", "unique", "=", "None", ",", "blank_index", "=", "None", ",", "name", "=", "None", ")", ":", "if", "isinstance", "(", "labels", ",", "sparse_tensor", ".", "SparseTensor", ")", ":", "if", "blank_index", "is", "None", ":", "raise", "ValueError", "(", "\"Argument `blank_index` must be provided when labels is a \"", "\"SparseTensor.\"", ")", "if", "blank_index", "<", "0", ":", "blank_index", "+=", "_get_dim", "(", "logits", ",", "2", ")", "if", "blank_index", "!=", "_get_dim", "(", "logits", ",", "2", ")", "-", "1", ":", "logits", "=", "array_ops", ".", "concat", "(", "[", "logits", "[", ":", ",", ":", ",", ":", "blank_index", "]", ",", "logits", "[", ":", ",", ":", ",", "blank_index", "+", "1", ":", "]", ",", "logits", "[", ":", ",", ":", ",", "blank_index", ":", "blank_index", "+", "1", "]", ",", "]", ",", "axis", "=", "2", ")", "labels", "=", "sparse_tensor", ".", "SparseTensor", "(", "labels", ".", "indices", ",", "array_ops", ".", "where", "(", "labels", ".", "values", "<", "blank_index", ",", "labels", ".", "values", ",", "labels", ".", "values", "-", "1", ")", ",", "labels", ".", "dense_shape", ")", "return", "ctc_loss", "(", "labels", "=", "labels", ",", "inputs", "=", "logits", ",", "sequence_length", "=", "logit_length", ",", "time_major", "=", "logits_time_major", ")", "if", "blank_index", "is", "None", ":", "blank_index", "=", "0", "return", "ctc_loss_dense", "(", "labels", "=", "labels", ",", "logits", "=", "logits", ",", "label_length", "=", "label_length", ",", "logit_length", "=", "logit_length", ",", "logits_time_major", "=", "logits_time_major", ",", "unique", "=", "unique", ",", "blank_index", "=", "blank_index", ",", "name", "=", "name", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ctc_ops.py#L781-L872
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
utils/cpplint.py
python
_CppLintState.ResetErrorCounts
(self)
Sets the module's error statistic back to zero.
Sets the module's error statistic back to zero.
[ "Sets", "the", "module", "s", "error", "statistic", "back", "to", "zero", "." ]
def ResetErrorCounts(self): """Sets the module's error statistic back to zero.""" self.error_count = 0 self.errors_by_category = {}
[ "def", "ResetErrorCounts", "(", "self", ")", ":", "self", ".", "error_count", "=", "0", "self", ".", "errors_by_category", "=", "{", "}" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/utils/cpplint.py#L826-L829
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
build/android/pylib/results/report_results.py
python
LogFull
(results, test_type, test_package, annotation=None, flakiness_server=None)
Log the tests results for the test suite. The results will be logged three different ways: 1. Log to stdout. 2. Log to local files for aggregating multiple test steps (on buildbots only). 3. Log to flakiness dashboard (on buildbots only). Args: results: An instance of TestRunResults object. test_type: Type of the test (e.g. 'Instrumentation', 'Unit test', etc.). test_package: Test package name (e.g. 'ipc_tests' for gtests, 'ContentShellTest' for instrumentation tests) annotation: If instrumenation test type, this is a list of annotations (e.g. ['Smoke', 'SmallTest']). flakiness_server: If provider, upload the results to flakiness dashboard with this URL.
Log the tests results for the test suite.
[ "Log", "the", "tests", "results", "for", "the", "test", "suite", "." ]
def LogFull(results, test_type, test_package, annotation=None, flakiness_server=None): """Log the tests results for the test suite. The results will be logged three different ways: 1. Log to stdout. 2. Log to local files for aggregating multiple test steps (on buildbots only). 3. Log to flakiness dashboard (on buildbots only). Args: results: An instance of TestRunResults object. test_type: Type of the test (e.g. 'Instrumentation', 'Unit test', etc.). test_package: Test package name (e.g. 'ipc_tests' for gtests, 'ContentShellTest' for instrumentation tests) annotation: If instrumenation test type, this is a list of annotations (e.g. ['Smoke', 'SmallTest']). flakiness_server: If provider, upload the results to flakiness dashboard with this URL. """ if not results.DidRunPass(): logging.critical('*' * 80) logging.critical('Detailed Logs') logging.critical('*' * 80) for line in results.GetLogs().splitlines(): logging.critical(line) logging.critical('*' * 80) logging.critical('Summary') logging.critical('*' * 80) for line in results.GetGtestForm().splitlines(): logging.critical(line) logging.critical('*' * 80) if os.environ.get('BUILDBOT_BUILDERNAME'): # It is possible to have multiple buildbot steps for the same # instrumenation test package using different annotations. if annotation and len(annotation) == 1: suite_name = annotation[0] else: suite_name = test_package _LogToFile(results, test_type, suite_name) if flakiness_server: _LogToFlakinessDashboard(results, test_type, test_package, flakiness_server)
[ "def", "LogFull", "(", "results", ",", "test_type", ",", "test_package", ",", "annotation", "=", "None", ",", "flakiness_server", "=", "None", ")", ":", "if", "not", "results", ".", "DidRunPass", "(", ")", ":", "logging", ".", "critical", "(", "'*'", "*", "80", ")", "logging", ".", "critical", "(", "'Detailed Logs'", ")", "logging", ".", "critical", "(", "'*'", "*", "80", ")", "for", "line", "in", "results", ".", "GetLogs", "(", ")", ".", "splitlines", "(", ")", ":", "logging", ".", "critical", "(", "line", ")", "logging", ".", "critical", "(", "'*'", "*", "80", ")", "logging", ".", "critical", "(", "'Summary'", ")", "logging", ".", "critical", "(", "'*'", "*", "80", ")", "for", "line", "in", "results", ".", "GetGtestForm", "(", ")", ".", "splitlines", "(", ")", ":", "logging", ".", "critical", "(", "line", ")", "logging", ".", "critical", "(", "'*'", "*", "80", ")", "if", "os", ".", "environ", ".", "get", "(", "'BUILDBOT_BUILDERNAME'", ")", ":", "# It is possible to have multiple buildbot steps for the same", "# instrumenation test package using different annotations.", "if", "annotation", "and", "len", "(", "annotation", ")", "==", "1", ":", "suite_name", "=", "annotation", "[", "0", "]", "else", ":", "suite_name", "=", "test_package", "_LogToFile", "(", "results", ",", "test_type", ",", "suite_name", ")", "if", "flakiness_server", ":", "_LogToFlakinessDashboard", "(", "results", ",", "test_type", ",", "test_package", ",", "flakiness_server", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/pylib/results/report_results.py#L72-L116
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_txt.py
python
FileReadJob.Cancel
(self)
Cancel the running task
Cancel the running task
[ "Cancel", "the", "running", "task" ]
def Cancel(self): """Cancel the running task""" self.cancel = True
[ "def", "Cancel", "(", "self", ")", ":", "self", ".", "cancel", "=", "True" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_txt.py#L608-L610
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/third_party/Python/module/pexpect-2.4/pexpect.py
python
spawn.waitnoecho
(self, timeout=-1)
This waits until the terminal ECHO flag is set False. This returns True if the echo mode is off. This returns False if the ECHO flag was not set False before the timeout. This can be used to detect when the child is waiting for a password. Usually a child application will turn off echo mode when it is waiting for the user to enter a password. For example, instead of expecting the "password:" prompt you can wait for the child to set ECHO off:: p = pexpect.spawn ('ssh user@example.com') p.waitnoecho() p.sendline(mypassword) If timeout is None then this method to block forever until ECHO flag is False.
This waits until the terminal ECHO flag is set False. This returns True if the echo mode is off. This returns False if the ECHO flag was not set False before the timeout. This can be used to detect when the child is waiting for a password. Usually a child application will turn off echo mode when it is waiting for the user to enter a password. For example, instead of expecting the "password:" prompt you can wait for the child to set ECHO off::
[ "This", "waits", "until", "the", "terminal", "ECHO", "flag", "is", "set", "False", ".", "This", "returns", "True", "if", "the", "echo", "mode", "is", "off", ".", "This", "returns", "False", "if", "the", "ECHO", "flag", "was", "not", "set", "False", "before", "the", "timeout", ".", "This", "can", "be", "used", "to", "detect", "when", "the", "child", "is", "waiting", "for", "a", "password", ".", "Usually", "a", "child", "application", "will", "turn", "off", "echo", "mode", "when", "it", "is", "waiting", "for", "the", "user", "to", "enter", "a", "password", ".", "For", "example", "instead", "of", "expecting", "the", "password", ":", "prompt", "you", "can", "wait", "for", "the", "child", "to", "set", "ECHO", "off", "::" ]
def waitnoecho(self, timeout=-1): """This waits until the terminal ECHO flag is set False. This returns True if the echo mode is off. This returns False if the ECHO flag was not set False before the timeout. This can be used to detect when the child is waiting for a password. Usually a child application will turn off echo mode when it is waiting for the user to enter a password. For example, instead of expecting the "password:" prompt you can wait for the child to set ECHO off:: p = pexpect.spawn ('ssh user@example.com') p.waitnoecho() p.sendline(mypassword) If timeout is None then this method to block forever until ECHO flag is False. """ if timeout == -1: timeout = self.timeout if timeout is not None: end_time = time.time() + timeout while True: if not self.getecho(): return True if timeout < 0 and timeout is not None: return False if timeout is not None: timeout = end_time - time.time() time.sleep(0.1)
[ "def", "waitnoecho", "(", "self", ",", "timeout", "=", "-", "1", ")", ":", "if", "timeout", "==", "-", "1", ":", "timeout", "=", "self", ".", "timeout", "if", "timeout", "is", "not", "None", ":", "end_time", "=", "time", ".", "time", "(", ")", "+", "timeout", "while", "True", ":", "if", "not", "self", ".", "getecho", "(", ")", ":", "return", "True", "if", "timeout", "<", "0", "and", "timeout", "is", "not", "None", ":", "return", "False", "if", "timeout", "is", "not", "None", ":", "timeout", "=", "end_time", "-", "time", ".", "time", "(", ")", "time", ".", "sleep", "(", "0.1", ")" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/pexpect.py#L729-L758
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
MenuBar.Attach
(*args, **kwargs)
return _core_.MenuBar_Attach(*args, **kwargs)
Attach(self, wxFrame frame)
Attach(self, wxFrame frame)
[ "Attach", "(", "self", "wxFrame", "frame", ")" ]
def Attach(*args, **kwargs): """Attach(self, wxFrame frame)""" return _core_.MenuBar_Attach(*args, **kwargs)
[ "def", "Attach", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MenuBar_Attach", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L12371-L12373
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/imaplib.py
python
IMAP4.store
(self, message_set, command, flags)
return self._untagged_response(typ, dat, 'FETCH')
Alters flag dispositions for messages in mailbox. (typ, [data]) = <instance>.store(message_set, command, flags)
Alters flag dispositions for messages in mailbox.
[ "Alters", "flag", "dispositions", "for", "messages", "in", "mailbox", "." ]
def store(self, message_set, command, flags): """Alters flag dispositions for messages in mailbox. (typ, [data]) = <instance>.store(message_set, command, flags) """ if (flags[0],flags[-1]) != ('(',')'): flags = '(%s)' % flags # Avoid quoting the flags typ, dat = self._simple_command('STORE', message_set, command, flags) return self._untagged_response(typ, dat, 'FETCH')
[ "def", "store", "(", "self", ",", "message_set", ",", "command", ",", "flags", ")", ":", "if", "(", "flags", "[", "0", "]", ",", "flags", "[", "-", "1", "]", ")", "!=", "(", "'('", ",", "')'", ")", ":", "flags", "=", "'(%s)'", "%", "flags", "# Avoid quoting the flags", "typ", ",", "dat", "=", "self", ".", "_simple_command", "(", "'STORE'", ",", "message_set", ",", "command", ",", "flags", ")", "return", "self", ".", "_untagged_response", "(", "typ", ",", "dat", ",", "'FETCH'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/imaplib.py#L844-L852
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/dataview.py
python
DataViewListCtrl.AppendItem
(*args, **kwargs)
return _dataview.DataViewListCtrl_AppendItem(*args, **kwargs)
AppendItem(self, wxVariantVector values, UIntPtr data=None)
AppendItem(self, wxVariantVector values, UIntPtr data=None)
[ "AppendItem", "(", "self", "wxVariantVector", "values", "UIntPtr", "data", "=", "None", ")" ]
def AppendItem(*args, **kwargs): """AppendItem(self, wxVariantVector values, UIntPtr data=None)""" return _dataview.DataViewListCtrl_AppendItem(*args, **kwargs)
[ "def", "AppendItem", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewListCtrl_AppendItem", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L2157-L2159
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/systrace/systrace/decorators.py
python
ShouldSkip
(test, device)
return False
Returns whether the test should be skipped and the reason for it.
Returns whether the test should be skipped and the reason for it.
[ "Returns", "whether", "the", "test", "should", "be", "skipped", "and", "the", "reason", "for", "it", "." ]
def ShouldSkip(test, device): """Returns whether the test should be skipped and the reason for it.""" if hasattr(test, '_disabled_strings'): disabled_devices = getattr(test, '_disabled_strings') return device in disabled_devices return False
[ "def", "ShouldSkip", "(", "test", ",", "device", ")", ":", "if", "hasattr", "(", "test", ",", "'_disabled_strings'", ")", ":", "disabled_devices", "=", "getattr", "(", "test", ",", "'_disabled_strings'", ")", "return", "device", "in", "disabled_devices", "return", "False" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/systrace/systrace/decorators.py#L26-L31
CaoWGG/TensorRT-CenterNet
f949252e37b51e60f873808f46d3683f15735e79
onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py
python
Cursor.is_move_constructor
(self)
return conf.lib.clang_CXXConstructor_isMoveConstructor(self)
Returns True if the cursor refers to a C++ move constructor.
Returns True if the cursor refers to a C++ move constructor.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "C", "++", "move", "constructor", "." ]
def is_move_constructor(self): """Returns True if the cursor refers to a C++ move constructor. """ return conf.lib.clang_CXXConstructor_isMoveConstructor(self)
[ "def", "is_move_constructor", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CXXConstructor_isMoveConstructor", "(", "self", ")" ]
https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L1336-L1339
gnina/gnina
b9ae032f52fc7a8153987bde09c0efa3620d8bb6
caffe/scripts/cpp_lint.py
python
IsErrorSuppressedByNolint
(category, linenum)
return (linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set()))
Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment.
Returns true if the specified error category is suppressed on this line.
[ "Returns", "true", "if", "the", "specified", "error", "category", "is", "suppressed", "on", "this", "line", "." ]
def IsErrorSuppressedByNolint(category, linenum): """Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment. """ return (linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set()))
[ "def", "IsErrorSuppressedByNolint", "(", "category", ",", "linenum", ")", ":", "return", "(", "linenum", "in", "_error_suppressions", ".", "get", "(", "category", ",", "set", "(", ")", ")", "or", "linenum", "in", "_error_suppressions", ".", "get", "(", "None", ",", "set", "(", ")", ")", ")" ]
https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/scripts/cpp_lint.py#L504-L517
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
bindings/pyroot/cppyy/cppyy-backend/cling/setup.py
python
get_prefix
()
return prefix
cppyy-cling installation.
cppyy-cling installation.
[ "cppyy", "-", "cling", "installation", "." ]
def get_prefix(): """cppyy-cling installation.""" global prefix if prefix is None: prefix = os.path.join(get_builddir(), 'install', 'cppyy_backend') return prefix
[ "def", "get_prefix", "(", ")", ":", "global", "prefix", "if", "prefix", "is", "None", ":", "prefix", "=", "os", ".", "path", ".", "join", "(", "get_builddir", "(", ")", ",", "'install'", ",", "'cppyy_backend'", ")", "return", "prefix" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/bindings/pyroot/cppyy/cppyy-backend/cling/setup.py#L68-L73
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiToolBarItem.SetActive
(*args, **kwargs)
return _aui.AuiToolBarItem_SetActive(*args, **kwargs)
SetActive(self, bool b)
SetActive(self, bool b)
[ "SetActive", "(", "self", "bool", "b", ")" ]
def SetActive(*args, **kwargs): """SetActive(self, bool b)""" return _aui.AuiToolBarItem_SetActive(*args, **kwargs)
[ "def", "SetActive", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiToolBarItem_SetActive", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L1841-L1843
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TFIn.__init__
(self, *args)
__init__(TFIn self, TStr FNm) -> TFIn Parameters: FNm: TStr const & __init__(TFIn self, TStr FNm, bool & OpenedP) -> TFIn Parameters: FNm: TStr const & OpenedP: bool &
__init__(TFIn self, TStr FNm) -> TFIn
[ "__init__", "(", "TFIn", "self", "TStr", "FNm", ")", "-", ">", "TFIn" ]
def __init__(self, *args): """ __init__(TFIn self, TStr FNm) -> TFIn Parameters: FNm: TStr const & __init__(TFIn self, TStr FNm, bool & OpenedP) -> TFIn Parameters: FNm: TStr const & OpenedP: bool & """ _snap.TFIn_swiginit(self,_snap.new_TFIn(*args))
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "_snap", ".", "TFIn_swiginit", "(", "self", ",", "_snap", ".", "new_TFIn", "(", "*", "args", ")", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L2716-L2730
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/vm/theano/compile/function.py
python
GraphDef_Device
(meta_graph)
Inject the device option into GraphDef. Parameters ---------- meta_graph : dragon_pb2.GraphDef The definition of meta graph. Returns ------- None References ---------- `config.EnableCPU()`_ - How to use CPU device. `config.EnableCUDA(*args, **kwargs)`_ - How to use CUDA device. `config.SetRandomSeed(*args, **kwargs)`_ - How to set random seed.
Inject the device option into GraphDef.
[ "Inject", "the", "device", "option", "into", "GraphDef", "." ]
def GraphDef_Device(meta_graph): """Inject the device option into GraphDef. Parameters ---------- meta_graph : dragon_pb2.GraphDef The definition of meta graph. Returns ------- None References ---------- `config.EnableCPU()`_ - How to use CPU device. `config.EnableCUDA(*args, **kwargs)`_ - How to use CUDA device. `config.SetRandomSeed(*args, **kwargs)`_ - How to set random seed. """ from dragon.config import option if option['device'] is not 'None': supports = {'CPU': 0, 'CUDA': 1} device_option = pb.DeviceOption() device_option.device_type = supports[option['device']] device_option.gpu_id = option['gpu_id'] device_option.random_seed = option['random_seed'] if option['use_cudnn']: device_option.engine = 'CUDNN' meta_graph.device_option.CopyFrom(device_option)
[ "def", "GraphDef_Device", "(", "meta_graph", ")", ":", "from", "dragon", ".", "config", "import", "option", "if", "option", "[", "'device'", "]", "is", "not", "'None'", ":", "supports", "=", "{", "'CPU'", ":", "0", ",", "'CUDA'", ":", "1", "}", "device_option", "=", "pb", ".", "DeviceOption", "(", ")", "device_option", ".", "device_type", "=", "supports", "[", "option", "[", "'device'", "]", "]", "device_option", ".", "gpu_id", "=", "option", "[", "'gpu_id'", "]", "device_option", ".", "random_seed", "=", "option", "[", "'random_seed'", "]", "if", "option", "[", "'use_cudnn'", "]", ":", "device_option", ".", "engine", "=", "'CUDNN'", "meta_graph", ".", "device_option", ".", "CopyFrom", "(", "device_option", ")" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/theano/compile/function.py#L159-L188
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/egt/alpharank_visualizer.py
python
NetworkPlot._draw_network
(self)
Draws the NetworkX object representing the underlying graph.
Draws the NetworkX object representing the underlying graph.
[ "Draws", "the", "NetworkX", "object", "representing", "the", "underlying", "graph", "." ]
def _draw_network(self): """Draws the NetworkX object representing the underlying graph.""" plt.clf() if self.num_populations == 1: node_sizes = 5000 node_border_width = 1. else: node_sizes = 15000 node_border_width = 3. vmin, vmax = 0, np.max(self.pi) + 0.1 nx.draw_networkx_nodes( self.g, self.pos, node_size=node_sizes, node_color=self.node_colors, edgecolors="k", cmap=plt.cm.Blues, vmin=vmin, vmax=vmax, linewidths=node_border_width) nx.draw_networkx_edges( self.g, self.pos, node_size=node_sizes, arrowstyle="->", arrowsize=10, edge_color=self.edge_colors, edge_cmap=plt.cm.Blues, width=5) nx.draw_networkx_edge_labels(self.g, self.pos, edge_labels=self.edge_labels) if self.num_populations > 1: subnode_separation = 0.1 subgraph = nx.Graph() for i_population in range(self.num_populations): subgraph.add_node(i_population) for i_strat_profile in self.g: x, y = self.pos[i_strat_profile] if self.num_populations == 1: node_text = "$\\pi_{" + self.state_labels[i_strat_profile] + "}=$" node_text += str(np.round(self.pi[i_strat_profile], decimals=2)) else: node_text = "" # No text for multi-population case as plot gets messy txt = plt.text( x, y, node_text, horizontalalignment="center", verticalalignment="center", fontsize=12) txt.set_path_effects( [PathEffects.withStroke(linewidth=3, foreground="w")]) if self.num_populations > 1: sub_pos = nx.circular_layout(subgraph) subnode_labels = dict() strat_profile = utils.get_strat_profile_from_id( self.num_strats_per_population, i_strat_profile) for i_population in subgraph.nodes(): i_strat = strat_profile[i_population] subnode_labels[i_population] = "$s^{" + str(i_population + 1) + "}=" subnode_labels[i_population] += ( self.state_labels[i_population][i_strat] + "$") # Adjust the node positions generated by NetworkX's circular_layout(), # such that the node for the 1st strategy starts on the left. sub_pos[i_population] = (-sub_pos[i_population] * subnode_separation + self.pos[i_strat_profile]) nx.draw( subgraph, pos=sub_pos, with_labels=True, width=0., node_color="w", labels=subnode_labels, node_size=2500)
[ "def", "_draw_network", "(", "self", ")", ":", "plt", ".", "clf", "(", ")", "if", "self", ".", "num_populations", "==", "1", ":", "node_sizes", "=", "5000", "node_border_width", "=", "1.", "else", ":", "node_sizes", "=", "15000", "node_border_width", "=", "3.", "vmin", ",", "vmax", "=", "0", ",", "np", ".", "max", "(", "self", ".", "pi", ")", "+", "0.1", "nx", ".", "draw_networkx_nodes", "(", "self", ".", "g", ",", "self", ".", "pos", ",", "node_size", "=", "node_sizes", ",", "node_color", "=", "self", ".", "node_colors", ",", "edgecolors", "=", "\"k\"", ",", "cmap", "=", "plt", ".", "cm", ".", "Blues", ",", "vmin", "=", "vmin", ",", "vmax", "=", "vmax", ",", "linewidths", "=", "node_border_width", ")", "nx", ".", "draw_networkx_edges", "(", "self", ".", "g", ",", "self", ".", "pos", ",", "node_size", "=", "node_sizes", ",", "arrowstyle", "=", "\"->\"", ",", "arrowsize", "=", "10", ",", "edge_color", "=", "self", ".", "edge_colors", ",", "edge_cmap", "=", "plt", ".", "cm", ".", "Blues", ",", "width", "=", "5", ")", "nx", ".", "draw_networkx_edge_labels", "(", "self", ".", "g", ",", "self", ".", "pos", ",", "edge_labels", "=", "self", ".", "edge_labels", ")", "if", "self", ".", "num_populations", ">", "1", ":", "subnode_separation", "=", "0.1", "subgraph", "=", "nx", ".", "Graph", "(", ")", "for", "i_population", "in", "range", "(", "self", ".", "num_populations", ")", ":", "subgraph", ".", "add_node", "(", "i_population", ")", "for", "i_strat_profile", "in", "self", ".", "g", ":", "x", ",", "y", "=", "self", ".", "pos", "[", "i_strat_profile", "]", "if", "self", ".", "num_populations", "==", "1", ":", "node_text", "=", "\"$\\\\pi_{\"", "+", "self", ".", "state_labels", "[", "i_strat_profile", "]", "+", "\"}=$\"", "node_text", "+=", "str", "(", "np", ".", "round", "(", "self", ".", "pi", "[", "i_strat_profile", "]", ",", "decimals", "=", "2", ")", ")", "else", ":", "node_text", "=", "\"\"", "# No text for multi-population case as plot gets messy", "txt", "=", "plt", ".", "text", "(", "x", ",", "y", ",", "node_text", ",", "horizontalalignment", "=", "\"center\"", ",", "verticalalignment", "=", "\"center\"", ",", "fontsize", "=", "12", ")", "txt", ".", "set_path_effects", "(", "[", "PathEffects", ".", "withStroke", "(", "linewidth", "=", "3", ",", "foreground", "=", "\"w\"", ")", "]", ")", "if", "self", ".", "num_populations", ">", "1", ":", "sub_pos", "=", "nx", ".", "circular_layout", "(", "subgraph", ")", "subnode_labels", "=", "dict", "(", ")", "strat_profile", "=", "utils", ".", "get_strat_profile_from_id", "(", "self", ".", "num_strats_per_population", ",", "i_strat_profile", ")", "for", "i_population", "in", "subgraph", ".", "nodes", "(", ")", ":", "i_strat", "=", "strat_profile", "[", "i_population", "]", "subnode_labels", "[", "i_population", "]", "=", "\"$s^{\"", "+", "str", "(", "i_population", "+", "1", ")", "+", "\"}=\"", "subnode_labels", "[", "i_population", "]", "+=", "(", "self", ".", "state_labels", "[", "i_population", "]", "[", "i_strat", "]", "+", "\"$\"", ")", "# Adjust the node positions generated by NetworkX's circular_layout(),", "# such that the node for the 1st strategy starts on the left.", "sub_pos", "[", "i_population", "]", "=", "(", "-", "sub_pos", "[", "i_population", "]", "*", "subnode_separation", "+", "self", ".", "pos", "[", "i_strat_profile", "]", ")", "nx", ".", "draw", "(", "subgraph", ",", "pos", "=", "sub_pos", ",", "with_labels", "=", "True", ",", "width", "=", "0.", ",", "node_color", "=", "\"w\"", ",", "labels", "=", "subnode_labels", ",", "node_size", "=", "2500", ")" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/egt/alpharank_visualizer.py#L102-L182
Netflix/NfWebCrypto
499faf4eb9f9ccf0b21dc728e974970f54bd6c52
plugin/ppapi/ppapi/generators/idl_parser.py
python
IDLParser.p_expression_binop
(self, p)
expression : expression LSHIFT expression | expression RSHIFT expression | expression '|' expression | expression '&' expression | expression '^' expression | expression '+' expression | expression '-' expression | expression '*' expression | expression '/' expression
expression : expression LSHIFT expression | expression RSHIFT expression | expression '|' expression | expression '&' expression | expression '^' expression | expression '+' expression | expression '-' expression | expression '*' expression | expression '/' expression
[ "expression", ":", "expression", "LSHIFT", "expression", "|", "expression", "RSHIFT", "expression", "|", "expression", "|", "expression", "|", "expression", "&", "expression", "|", "expression", "^", "expression", "|", "expression", "+", "expression", "|", "expression", "-", "expression", "|", "expression", "*", "expression", "|", "expression", "/", "expression" ]
def p_expression_binop(self, p): """expression : expression LSHIFT expression | expression RSHIFT expression | expression '|' expression | expression '&' expression | expression '^' expression | expression '+' expression | expression '-' expression | expression '*' expression | expression '/' expression""" p[0] = "%s %s %s" % (str(p[1]), str(p[2]), str(p[3])) if self.parse_debug: DumpReduction('expression_binop', p)
[ "def", "p_expression_binop", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "\"%s %s %s\"", "%", "(", "str", "(", "p", "[", "1", "]", ")", ",", "str", "(", "p", "[", "2", "]", ")", ",", "str", "(", "p", "[", "3", "]", ")", ")", "if", "self", ".", "parse_debug", ":", "DumpReduction", "(", "'expression_binop'", ",", "p", ")" ]
https://github.com/Netflix/NfWebCrypto/blob/499faf4eb9f9ccf0b21dc728e974970f54bd6c52/plugin/ppapi/ppapi/generators/idl_parser.py#L510-L521
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
PrintPreview.SetCurrentPage
(*args, **kwargs)
return _windows_.PrintPreview_SetCurrentPage(*args, **kwargs)
SetCurrentPage(self, int pageNum) -> bool
SetCurrentPage(self, int pageNum) -> bool
[ "SetCurrentPage", "(", "self", "int", "pageNum", ")", "-", ">", "bool" ]
def SetCurrentPage(*args, **kwargs): """SetCurrentPage(self, int pageNum) -> bool""" return _windows_.PrintPreview_SetCurrentPage(*args, **kwargs)
[ "def", "SetCurrentPage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PrintPreview_SetCurrentPage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L5565-L5567
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/functools.py
python
_c3_mro
(cls, abcs=None)
return _c3_merge( [[cls]] + explicit_c3_mros + abstract_c3_mros + other_c3_mros + [explicit_bases] + [abstract_bases] + [other_bases] )
Computes the method resolution order using extended C3 linearization. If no *abcs* are given, the algorithm works exactly like the built-in C3 linearization used for method resolution. If given, *abcs* is a list of abstract base classes that should be inserted into the resulting MRO. Unrelated ABCs are ignored and don't end up in the result. The algorithm inserts ABCs where their functionality is introduced, i.e. issubclass(cls, abc) returns True for the class itself but returns False for all its direct base classes. Implicit ABCs for a given class (either registered or inferred from the presence of a special method like __len__) are inserted directly after the last ABC explicitly listed in the MRO of said class. If two implicit ABCs end up next to each other in the resulting MRO, their ordering depends on the order of types in *abcs*.
Computes the method resolution order using extended C3 linearization.
[ "Computes", "the", "method", "resolution", "order", "using", "extended", "C3", "linearization", "." ]
def _c3_mro(cls, abcs=None): """Computes the method resolution order using extended C3 linearization. If no *abcs* are given, the algorithm works exactly like the built-in C3 linearization used for method resolution. If given, *abcs* is a list of abstract base classes that should be inserted into the resulting MRO. Unrelated ABCs are ignored and don't end up in the result. The algorithm inserts ABCs where their functionality is introduced, i.e. issubclass(cls, abc) returns True for the class itself but returns False for all its direct base classes. Implicit ABCs for a given class (either registered or inferred from the presence of a special method like __len__) are inserted directly after the last ABC explicitly listed in the MRO of said class. If two implicit ABCs end up next to each other in the resulting MRO, their ordering depends on the order of types in *abcs*. """ for i, base in enumerate(reversed(cls.__bases__)): if hasattr(base, '__abstractmethods__'): boundary = len(cls.__bases__) - i break # Bases up to the last explicit ABC are considered first. else: boundary = 0 abcs = list(abcs) if abcs else [] explicit_bases = list(cls.__bases__[:boundary]) abstract_bases = [] other_bases = list(cls.__bases__[boundary:]) for base in abcs: if issubclass(cls, base) and not any( issubclass(b, base) for b in cls.__bases__ ): # If *cls* is the class that introduces behaviour described by # an ABC *base*, insert said ABC to its MRO. abstract_bases.append(base) for base in abstract_bases: abcs.remove(base) explicit_c3_mros = [_c3_mro(base, abcs=abcs) for base in explicit_bases] abstract_c3_mros = [_c3_mro(base, abcs=abcs) for base in abstract_bases] other_c3_mros = [_c3_mro(base, abcs=abcs) for base in other_bases] return _c3_merge( [[cls]] + explicit_c3_mros + abstract_c3_mros + other_c3_mros + [explicit_bases] + [abstract_bases] + [other_bases] )
[ "def", "_c3_mro", "(", "cls", ",", "abcs", "=", "None", ")", ":", "for", "i", ",", "base", "in", "enumerate", "(", "reversed", "(", "cls", ".", "__bases__", ")", ")", ":", "if", "hasattr", "(", "base", ",", "'__abstractmethods__'", ")", ":", "boundary", "=", "len", "(", "cls", ".", "__bases__", ")", "-", "i", "break", "# Bases up to the last explicit ABC are considered first.", "else", ":", "boundary", "=", "0", "abcs", "=", "list", "(", "abcs", ")", "if", "abcs", "else", "[", "]", "explicit_bases", "=", "list", "(", "cls", ".", "__bases__", "[", ":", "boundary", "]", ")", "abstract_bases", "=", "[", "]", "other_bases", "=", "list", "(", "cls", ".", "__bases__", "[", "boundary", ":", "]", ")", "for", "base", "in", "abcs", ":", "if", "issubclass", "(", "cls", ",", "base", ")", "and", "not", "any", "(", "issubclass", "(", "b", ",", "base", ")", "for", "b", "in", "cls", ".", "__bases__", ")", ":", "# If *cls* is the class that introduces behaviour described by", "# an ABC *base*, insert said ABC to its MRO.", "abstract_bases", ".", "append", "(", "base", ")", "for", "base", "in", "abstract_bases", ":", "abcs", ".", "remove", "(", "base", ")", "explicit_c3_mros", "=", "[", "_c3_mro", "(", "base", ",", "abcs", "=", "abcs", ")", "for", "base", "in", "explicit_bases", "]", "abstract_c3_mros", "=", "[", "_c3_mro", "(", "base", ",", "abcs", "=", "abcs", ")", "for", "base", "in", "abstract_bases", "]", "other_c3_mros", "=", "[", "_c3_mro", "(", "base", ",", "abcs", "=", "abcs", ")", "for", "base", "in", "other_bases", "]", "return", "_c3_merge", "(", "[", "[", "cls", "]", "]", "+", "explicit_c3_mros", "+", "abstract_c3_mros", "+", "other_c3_mros", "+", "[", "explicit_bases", "]", "+", "[", "abstract_bases", "]", "+", "[", "other_bases", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/functools.py#L651-L694
verilog-to-routing/vtr-verilog-to-routing
d9719cf7374821156c3cee31d66991cb85578562
vtr_flow/scripts/python_libs/vtr/log_parse.py
python
RangeAbsPassRequirement.min_value
(self)
return self._min_value
Return min value of ratio range
Return min value of ratio range
[ "Return", "min", "value", "of", "ratio", "range" ]
def min_value(self): """Return min value of ratio range""" return self._min_value
[ "def", "min_value", "(", "self", ")", ":", "return", "self", ".", "_min_value" ]
https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/python_libs/vtr/log_parse.py#L184-L186
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/dataview.py
python
DataViewTreeStoreContainerNode.IsExpanded
(*args, **kwargs)
return _dataview.DataViewTreeStoreContainerNode_IsExpanded(*args, **kwargs)
IsExpanded(self) -> bool
IsExpanded(self) -> bool
[ "IsExpanded", "(", "self", ")", "-", ">", "bool" ]
def IsExpanded(*args, **kwargs): """IsExpanded(self) -> bool""" return _dataview.DataViewTreeStoreContainerNode_IsExpanded(*args, **kwargs)
[ "def", "IsExpanded", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewTreeStoreContainerNode_IsExpanded", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L2346-L2348
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/RNN/rnn_quantizer/nndct_shared/utils/registry.py
python
Registry.lookup
(self, name)
Looks up "name". Args: name: a string specifying the registry key for the obj. Returns: Registered object if found Raises: LookupError: if "name" has not been registered.
Looks up "name".
[ "Looks", "up", "name", "." ]
def lookup(self, name): """Looks up "name". Args: name: a string specifying the registry key for the obj. Returns: Registered object if found Raises: LookupError: if "name" has not been registered. """ if name in self._registry: return self._registry[name] else: raise LookupError("%s registry has no entry for: %s" % (self._name, name))
[ "def", "lookup", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "_registry", ":", "return", "self", ".", "_registry", "[", "name", "]", "else", ":", "raise", "LookupError", "(", "\"%s registry has no entry for: %s\"", "%", "(", "self", ".", "_name", ",", "name", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/RNN/rnn_quantizer/nndct_shared/utils/registry.py#L63-L76
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/command/sdist.py
python
sdist.add_defaults
(self)
Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional.
Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional.
[ "Add", "all", "the", "default", "files", "to", "self", ".", "filelist", ":", "-", "README", "or", "README", ".", "txt", "-", "setup", ".", "py", "-", "test", "/", "test", "*", ".", "py", "-", "all", "pure", "Python", "modules", "mentioned", "in", "setup", "script", "-", "all", "files", "pointed", "by", "package_data", "(", "build_py", ")", "-", "all", "files", "defined", "in", "data_files", ".", "-", "all", "files", "defined", "as", "scripts", ".", "-", "all", "C", "sources", "listed", "as", "part", "of", "extensions", "or", "C", "libraries", "in", "the", "setup", "script", "(", "doesn", "t", "catch", "C", "headers!", ")", "Warns", "if", "(", "README", "or", "README", ".", "txt", ")", "or", "setup", ".", "py", "are", "missing", ";", "everything", "else", "is", "optional", "." ]
def add_defaults(self): """Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional. """ standards = [('README', 'README.txt'), self.distribution.script_name] for fn in standards: if isinstance(fn, tuple): alts = fn got_it = 0 for fn in alts: if os.path.exists(fn): got_it = 1 self.filelist.append(fn) break if not got_it: self.warn("standard file not found: should have one of " + string.join(alts, ', ')) else: if os.path.exists(fn): self.filelist.append(fn) else: self.warn("standard file '%s' not found" % fn) optional = ['test/test*.py', 'setup.cfg'] for pattern in optional: files = filter(os.path.isfile, glob(pattern)) if files: self.filelist.extend(files) # build_py is used to get: # - python modules # - files defined in package_data build_py = self.get_finalized_command('build_py') # getting python files if self.distribution.has_pure_modules(): self.filelist.extend(build_py.get_source_files()) # getting package_data files # (computed in build_py.data_files by build_py.finalize_options) for pkg, src_dir, build_dir, filenames in build_py.data_files: for filename in filenames: self.filelist.append(os.path.join(src_dir, filename)) # getting distribution.data_files if self.distribution.has_data_files(): for item in self.distribution.data_files: if isinstance(item, str): # plain file item = convert_path(item) if os.path.isfile(item): self.filelist.append(item) else: # a (dirname, filenames) tuple dirname, filenames = item for f in filenames: f = convert_path(f) if os.path.isfile(f): self.filelist.append(f) if self.distribution.has_ext_modules(): build_ext = self.get_finalized_command('build_ext') self.filelist.extend(build_ext.get_source_files()) if self.distribution.has_c_libraries(): build_clib = self.get_finalized_command('build_clib') self.filelist.extend(build_clib.get_source_files()) if self.distribution.has_scripts(): build_scripts = self.get_finalized_command('build_scripts') self.filelist.extend(build_scripts.get_source_files())
[ "def", "add_defaults", "(", "self", ")", ":", "standards", "=", "[", "(", "'README'", ",", "'README.txt'", ")", ",", "self", ".", "distribution", ".", "script_name", "]", "for", "fn", "in", "standards", ":", "if", "isinstance", "(", "fn", ",", "tuple", ")", ":", "alts", "=", "fn", "got_it", "=", "0", "for", "fn", "in", "alts", ":", "if", "os", ".", "path", ".", "exists", "(", "fn", ")", ":", "got_it", "=", "1", "self", ".", "filelist", ".", "append", "(", "fn", ")", "break", "if", "not", "got_it", ":", "self", ".", "warn", "(", "\"standard file not found: should have one of \"", "+", "string", ".", "join", "(", "alts", ",", "', '", ")", ")", "else", ":", "if", "os", ".", "path", ".", "exists", "(", "fn", ")", ":", "self", ".", "filelist", ".", "append", "(", "fn", ")", "else", ":", "self", ".", "warn", "(", "\"standard file '%s' not found\"", "%", "fn", ")", "optional", "=", "[", "'test/test*.py'", ",", "'setup.cfg'", "]", "for", "pattern", "in", "optional", ":", "files", "=", "filter", "(", "os", ".", "path", ".", "isfile", ",", "glob", "(", "pattern", ")", ")", "if", "files", ":", "self", ".", "filelist", ".", "extend", "(", "files", ")", "# build_py is used to get:", "# - python modules", "# - files defined in package_data", "build_py", "=", "self", ".", "get_finalized_command", "(", "'build_py'", ")", "# getting python files", "if", "self", ".", "distribution", ".", "has_pure_modules", "(", ")", ":", "self", ".", "filelist", ".", "extend", "(", "build_py", ".", "get_source_files", "(", ")", ")", "# getting package_data files", "# (computed in build_py.data_files by build_py.finalize_options)", "for", "pkg", ",", "src_dir", ",", "build_dir", ",", "filenames", "in", "build_py", ".", "data_files", ":", "for", "filename", "in", "filenames", ":", "self", ".", "filelist", ".", "append", "(", "os", ".", "path", ".", "join", "(", "src_dir", ",", "filename", ")", ")", "# getting distribution.data_files", "if", "self", ".", "distribution", ".", "has_data_files", "(", ")", ":", "for", "item", "in", "self", ".", "distribution", ".", "data_files", ":", "if", "isinstance", "(", "item", ",", "str", ")", ":", "# plain file", "item", "=", "convert_path", "(", "item", ")", "if", "os", ".", "path", ".", "isfile", "(", "item", ")", ":", "self", ".", "filelist", ".", "append", "(", "item", ")", "else", ":", "# a (dirname, filenames) tuple", "dirname", ",", "filenames", "=", "item", "for", "f", "in", "filenames", ":", "f", "=", "convert_path", "(", "f", ")", "if", "os", ".", "path", ".", "isfile", "(", "f", ")", ":", "self", ".", "filelist", ".", "append", "(", "f", ")", "if", "self", ".", "distribution", ".", "has_ext_modules", "(", ")", ":", "build_ext", "=", "self", ".", "get_finalized_command", "(", "'build_ext'", ")", "self", ".", "filelist", ".", "extend", "(", "build_ext", ".", "get_source_files", "(", ")", ")", "if", "self", ".", "distribution", ".", "has_c_libraries", "(", ")", ":", "build_clib", "=", "self", ".", "get_finalized_command", "(", "'build_clib'", ")", "self", ".", "filelist", ".", "extend", "(", "build_clib", ".", "get_source_files", "(", ")", ")", "if", "self", ".", "distribution", ".", "has_scripts", "(", ")", ":", "build_scripts", "=", "self", ".", "get_finalized_command", "(", "'build_scripts'", ")", "self", ".", "filelist", ".", "extend", "(", "build_scripts", ".", "get_source_files", "(", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/command/sdist.py#L218-L298
adventuregamestudio/ags
efa89736d868e9dfda4200149d33ba8637746399
Common/libsrc/freetype-2.1.3/src/tools/docmaker/content.py
python
ContentProcessor.add_markup
( self )
add a new markup section
add a new markup section
[ "add", "a", "new", "markup", "section" ]
def add_markup( self ): """add a new markup section""" if self.markup and self.markup_lines: # get rid of last line of markup if it's empty marks = self.markup_lines if len(marks) > 0 and not string.strip(marks[-1]): self.markup_lines = marks[:-1] m = DocMarkup( self.markup, self.markup_lines ) self.markups.append( m ) self.markup = None self.markup_lines = []
[ "def", "add_markup", "(", "self", ")", ":", "if", "self", ".", "markup", "and", "self", ".", "markup_lines", ":", "# get rid of last line of markup if it's empty", "marks", "=", "self", ".", "markup_lines", "if", "len", "(", "marks", ")", ">", "0", "and", "not", "string", ".", "strip", "(", "marks", "[", "-", "1", "]", ")", ":", "self", ".", "markup_lines", "=", "marks", "[", ":", "-", "1", "]", "m", "=", "DocMarkup", "(", "self", ".", "markup", ",", "self", ".", "markup_lines", ")", "self", ".", "markups", ".", "append", "(", "m", ")", "self", ".", "markup", "=", "None", "self", ".", "markup_lines", "=", "[", "]" ]
https://github.com/adventuregamestudio/ags/blob/efa89736d868e9dfda4200149d33ba8637746399/Common/libsrc/freetype-2.1.3/src/tools/docmaker/content.py#L329-L343
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/ply/example/ansic/cparse.py
python
p_iteration_statement_2
(t)
iteration_statement : FOR LPAREN expression_opt SEMI expression_opt SEMI expression_opt RPAREN statement
iteration_statement : FOR LPAREN expression_opt SEMI expression_opt SEMI expression_opt RPAREN statement
[ "iteration_statement", ":", "FOR", "LPAREN", "expression_opt", "SEMI", "expression_opt", "SEMI", "expression_opt", "RPAREN", "statement" ]
def p_iteration_statement_2(t): 'iteration_statement : FOR LPAREN expression_opt SEMI expression_opt SEMI expression_opt RPAREN statement ' pass
[ "def", "p_iteration_statement_2", "(", "t", ")", ":", "pass" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/ansic/cparse.py#L531-L533
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
BaseWidget.__init__
(self, master, widgetName, cnf={}, kw={}, extra=())
Construct a widget with the parent widget MASTER, a name WIDGETNAME and appropriate options.
Construct a widget with the parent widget MASTER, a name WIDGETNAME and appropriate options.
[ "Construct", "a", "widget", "with", "the", "parent", "widget", "MASTER", "a", "name", "WIDGETNAME", "and", "appropriate", "options", "." ]
def __init__(self, master, widgetName, cnf={}, kw={}, extra=()): """Construct a widget with the parent widget MASTER, a name WIDGETNAME and appropriate options.""" if kw: cnf = _cnfmerge((cnf, kw)) self.widgetName = widgetName BaseWidget._setup(self, master, cnf) if self._tclCommands is None: self._tclCommands = [] classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)] for k, v in classes: del cnf[k] self.tk.call( (widgetName, self._w) + extra + self._options(cnf)) for k, v in classes: k.configure(self, v)
[ "def", "__init__", "(", "self", ",", "master", ",", "widgetName", ",", "cnf", "=", "{", "}", ",", "kw", "=", "{", "}", ",", "extra", "=", "(", ")", ")", ":", "if", "kw", ":", "cnf", "=", "_cnfmerge", "(", "(", "cnf", ",", "kw", ")", ")", "self", ".", "widgetName", "=", "widgetName", "BaseWidget", ".", "_setup", "(", "self", ",", "master", ",", "cnf", ")", "if", "self", ".", "_tclCommands", "is", "None", ":", "self", ".", "_tclCommands", "=", "[", "]", "classes", "=", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "cnf", ".", "items", "(", ")", "if", "isinstance", "(", "k", ",", "type", ")", "]", "for", "k", ",", "v", "in", "classes", ":", "del", "cnf", "[", "k", "]", "self", ".", "tk", ".", "call", "(", "(", "widgetName", ",", "self", ".", "_w", ")", "+", "extra", "+", "self", ".", "_options", "(", "cnf", ")", ")", "for", "k", ",", "v", "in", "classes", ":", "k", ".", "configure", "(", "self", ",", "v", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L2286-L2301
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/tools/grit/grit/tool/build.py
python
RcBuilder.GenerateDepfile
(self, depfile, depdir, first_ids_file, depend_on_stamp)
Generate a depfile that contains the imlicit dependencies of the input grd. The depfile will be in the same format as a makefile, and will contain references to files relative to |depdir|. It will be put in |depfile|. For example, supposing we have three files in a directory src/ src/ blah.grd <- depends on input{1,2}.xtb input1.xtb input2.xtb and we run grit -i blah.grd -o ../out/gen \ --depdir ../out \ --depfile ../out/gen/blah.rd.d from the directory src/ we will generate a depfile ../out/gen/blah.grd.d that has the contents gen/blah.h: ../src/input1.xtb ../src/input2.xtb Where "gen/blah.h" is the first output (Ninja expects the .d file to list the first output in cases where there is more than one). If the flag --depend-on-stamp is specified, "gen/blah.rd.d.stamp" will be used that is 'touched' whenever a new depfile is generated. Note that all paths in the depfile are relative to ../out, the depdir.
Generate a depfile that contains the imlicit dependencies of the input grd. The depfile will be in the same format as a makefile, and will contain references to files relative to |depdir|. It will be put in |depfile|.
[ "Generate", "a", "depfile", "that", "contains", "the", "imlicit", "dependencies", "of", "the", "input", "grd", ".", "The", "depfile", "will", "be", "in", "the", "same", "format", "as", "a", "makefile", "and", "will", "contain", "references", "to", "files", "relative", "to", "|depdir|", ".", "It", "will", "be", "put", "in", "|depfile|", "." ]
def GenerateDepfile(self, depfile, depdir, first_ids_file, depend_on_stamp): '''Generate a depfile that contains the imlicit dependencies of the input grd. The depfile will be in the same format as a makefile, and will contain references to files relative to |depdir|. It will be put in |depfile|. For example, supposing we have three files in a directory src/ src/ blah.grd <- depends on input{1,2}.xtb input1.xtb input2.xtb and we run grit -i blah.grd -o ../out/gen \ --depdir ../out \ --depfile ../out/gen/blah.rd.d from the directory src/ we will generate a depfile ../out/gen/blah.grd.d that has the contents gen/blah.h: ../src/input1.xtb ../src/input2.xtb Where "gen/blah.h" is the first output (Ninja expects the .d file to list the first output in cases where there is more than one). If the flag --depend-on-stamp is specified, "gen/blah.rd.d.stamp" will be used that is 'touched' whenever a new depfile is generated. Note that all paths in the depfile are relative to ../out, the depdir. ''' depfile = os.path.abspath(depfile) depdir = os.path.abspath(depdir) infiles = self.res.GetInputFiles() # We want to trigger a rebuild if the first ids change. if first_ids_file is not None: infiles.append(first_ids_file) if (depend_on_stamp): output_file = depfile + ".stamp" # Touch the stamp file before generating the depfile. with open(output_file, 'a'): os.utime(output_file, None) else: # Get the first output file relative to the depdir. outputs = self.res.GetOutputFiles() output_file = os.path.join(self.output_directory, outputs[0].GetOutputFilename()) output_file = os.path.relpath(output_file, depdir) # The path prefix to prepend to dependencies in the depfile. prefix = os.path.relpath(os.getcwd(), depdir) deps_text = ' '.join([os.path.join(prefix, i) for i in infiles]) depfile_contents = output_file + ': ' + deps_text self.MakeDirectoriesTo(depfile) outfile = self.fo_create(depfile, 'w', encoding='utf-8') outfile.write(depfile_contents)
[ "def", "GenerateDepfile", "(", "self", ",", "depfile", ",", "depdir", ",", "first_ids_file", ",", "depend_on_stamp", ")", ":", "depfile", "=", "os", ".", "path", ".", "abspath", "(", "depfile", ")", "depdir", "=", "os", ".", "path", ".", "abspath", "(", "depdir", ")", "infiles", "=", "self", ".", "res", ".", "GetInputFiles", "(", ")", "# We want to trigger a rebuild if the first ids change.", "if", "first_ids_file", "is", "not", "None", ":", "infiles", ".", "append", "(", "first_ids_file", ")", "if", "(", "depend_on_stamp", ")", ":", "output_file", "=", "depfile", "+", "\".stamp\"", "# Touch the stamp file before generating the depfile.", "with", "open", "(", "output_file", ",", "'a'", ")", ":", "os", ".", "utime", "(", "output_file", ",", "None", ")", "else", ":", "# Get the first output file relative to the depdir.", "outputs", "=", "self", ".", "res", ".", "GetOutputFiles", "(", ")", "output_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "output_directory", ",", "outputs", "[", "0", "]", ".", "GetOutputFilename", "(", ")", ")", "output_file", "=", "os", ".", "path", ".", "relpath", "(", "output_file", ",", "depdir", ")", "# The path prefix to prepend to dependencies in the depfile.", "prefix", "=", "os", ".", "path", ".", "relpath", "(", "os", ".", "getcwd", "(", ")", ",", "depdir", ")", "deps_text", "=", "' '", ".", "join", "(", "[", "os", ".", "path", ".", "join", "(", "prefix", ",", "i", ")", "for", "i", "in", "infiles", "]", ")", "depfile_contents", "=", "output_file", "+", "': '", "+", "deps_text", "self", ".", "MakeDirectoriesTo", "(", "depfile", ")", "outfile", "=", "self", ".", "fo_create", "(", "depfile", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "outfile", ".", "write", "(", "depfile_contents", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/tool/build.py#L492-L549
sfzhang15/FaceBoxes
b52cc92f9362d3adc08d54666aeb9ebb62fdb7da
python/caffe/coord_map.py
python
coord_map
(fn)
Define the coordinate mapping by its - axis - scale: output coord[i * scale] <- input_coord[i] - shift: output coord[i] <- output_coord[i + shift] s.t. the identity mapping, as for pointwise layers like ReLu, is defined by (None, 1, 0) since it is independent of axis and does not transform coords.
Define the coordinate mapping by its - axis - scale: output coord[i * scale] <- input_coord[i] - shift: output coord[i] <- output_coord[i + shift] s.t. the identity mapping, as for pointwise layers like ReLu, is defined by (None, 1, 0) since it is independent of axis and does not transform coords.
[ "Define", "the", "coordinate", "mapping", "by", "its", "-", "axis", "-", "scale", ":", "output", "coord", "[", "i", "*", "scale", "]", "<", "-", "input_coord", "[", "i", "]", "-", "shift", ":", "output", "coord", "[", "i", "]", "<", "-", "output_coord", "[", "i", "+", "shift", "]", "s", ".", "t", ".", "the", "identity", "mapping", "as", "for", "pointwise", "layers", "like", "ReLu", "is", "defined", "by", "(", "None", "1", "0", ")", "since", "it", "is", "independent", "of", "axis", "and", "does", "not", "transform", "coords", "." ]
def coord_map(fn): """ Define the coordinate mapping by its - axis - scale: output coord[i * scale] <- input_coord[i] - shift: output coord[i] <- output_coord[i + shift] s.t. the identity mapping, as for pointwise layers like ReLu, is defined by (None, 1, 0) since it is independent of axis and does not transform coords. """ if fn.type_name in ['Convolution', 'Pooling', 'Im2col']: axis, stride, ks, pad = conv_params(fn) return axis, 1 / stride, (pad - (ks - 1) / 2) / stride elif fn.type_name == 'Deconvolution': axis, stride, ks, pad = conv_params(fn) return axis, stride, (ks - 1) / 2 - pad elif fn.type_name in PASS_THROUGH_LAYERS: return None, 1, 0 elif fn.type_name == 'Crop': axis, offset = crop_params(fn) axis -= 1 # -1 for last non-coordinate dim. return axis, 1, - offset else: raise UndefinedMapException
[ "def", "coord_map", "(", "fn", ")", ":", "if", "fn", ".", "type_name", "in", "[", "'Convolution'", ",", "'Pooling'", ",", "'Im2col'", "]", ":", "axis", ",", "stride", ",", "ks", ",", "pad", "=", "conv_params", "(", "fn", ")", "return", "axis", ",", "1", "/", "stride", ",", "(", "pad", "-", "(", "ks", "-", "1", ")", "/", "2", ")", "/", "stride", "elif", "fn", ".", "type_name", "==", "'Deconvolution'", ":", "axis", ",", "stride", ",", "ks", ",", "pad", "=", "conv_params", "(", "fn", ")", "return", "axis", ",", "stride", ",", "(", "ks", "-", "1", ")", "/", "2", "-", "pad", "elif", "fn", ".", "type_name", "in", "PASS_THROUGH_LAYERS", ":", "return", "None", ",", "1", ",", "0", "elif", "fn", ".", "type_name", "==", "'Crop'", ":", "axis", ",", "offset", "=", "crop_params", "(", "fn", ")", "axis", "-=", "1", "# -1 for last non-coordinate dim.", "return", "axis", ",", "1", ",", "-", "offset", "else", ":", "raise", "UndefinedMapException" ]
https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/python/caffe/coord_map.py#L57-L79
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py
python
Decimal.log10
(self, context=None)
return ans
Returns the base 10 logarithm of self.
Returns the base 10 logarithm of self.
[ "Returns", "the", "base", "10", "logarithm", "of", "self", "." ]
def log10(self, context=None): """Returns the base 10 logarithm of self.""" if context is None: context = getcontext() # log10(NaN) = NaN ans = self._check_nans(context=context) if ans: return ans # log10(0.0) == -Infinity if not self: return _NegativeInfinity # log10(Infinity) = Infinity if self._isinfinity() == 1: return _Infinity # log10(negative or -Infinity) raises InvalidOperation if self._sign == 1: return context._raise_error(InvalidOperation, 'log10 of a negative value') # log10(10**n) = n if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1): # answer may need rounding ans = Decimal(self._exp + len(self._int) - 1) else: # result is irrational, so necessarily inexact op = _WorkRep(self) c, e = op.int, op.exp p = context.prec # correctly rounded result: repeatedly increase precision # until result is unambiguously roundable places = p-self._log10_exp_bound()+2 while True: coeff = _dlog10(c, e, places) # assert len(str(abs(coeff)))-p >= 1 if coeff % (5*10**(len(str(abs(coeff)))-p-1)): break places += 3 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) context = context._shallow_copy() rounding = context._set_rounding(ROUND_HALF_EVEN) ans = ans._fix(context) context.rounding = rounding return ans
[ "def", "log10", "(", "self", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "# log10(NaN) = NaN", "ans", "=", "self", ".", "_check_nans", "(", "context", "=", "context", ")", "if", "ans", ":", "return", "ans", "# log10(0.0) == -Infinity", "if", "not", "self", ":", "return", "_NegativeInfinity", "# log10(Infinity) = Infinity", "if", "self", ".", "_isinfinity", "(", ")", "==", "1", ":", "return", "_Infinity", "# log10(negative or -Infinity) raises InvalidOperation", "if", "self", ".", "_sign", "==", "1", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'log10 of a negative value'", ")", "# log10(10**n) = n", "if", "self", ".", "_int", "[", "0", "]", "==", "'1'", "and", "self", ".", "_int", "[", "1", ":", "]", "==", "'0'", "*", "(", "len", "(", "self", ".", "_int", ")", "-", "1", ")", ":", "# answer may need rounding", "ans", "=", "Decimal", "(", "self", ".", "_exp", "+", "len", "(", "self", ".", "_int", ")", "-", "1", ")", "else", ":", "# result is irrational, so necessarily inexact", "op", "=", "_WorkRep", "(", "self", ")", "c", ",", "e", "=", "op", ".", "int", ",", "op", ".", "exp", "p", "=", "context", ".", "prec", "# correctly rounded result: repeatedly increase precision", "# until result is unambiguously roundable", "places", "=", "p", "-", "self", ".", "_log10_exp_bound", "(", ")", "+", "2", "while", "True", ":", "coeff", "=", "_dlog10", "(", "c", ",", "e", ",", "places", ")", "# assert len(str(abs(coeff)))-p >= 1", "if", "coeff", "%", "(", "5", "*", "10", "**", "(", "len", "(", "str", "(", "abs", "(", "coeff", ")", ")", ")", "-", "p", "-", "1", ")", ")", ":", "break", "places", "+=", "3", "ans", "=", "_dec_from_triple", "(", "int", "(", "coeff", "<", "0", ")", ",", "str", "(", "abs", "(", "coeff", ")", ")", ",", "-", "places", ")", "context", "=", "context", ".", "_shallow_copy", "(", ")", "rounding", "=", "context", ".", "_set_rounding", "(", "ROUND_HALF_EVEN", ")", "ans", "=", "ans", ".", "_fix", "(", "context", ")", "context", ".", "rounding", "=", "rounding", "return", "ans" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L3272-L3321
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pyparsing.py
python
ParserElement.__rand__
(self, other )
return other & self
Implementation of & operator when left operand is not a :class:`ParserElement`
Implementation of & operator when left operand is not a :class:`ParserElement`
[ "Implementation", "of", "&", "operator", "when", "left", "operand", "is", "not", "a", ":", "class", ":", "ParserElement" ]
def __rand__(self, other ): """ Implementation of & operator when left operand is not a :class:`ParserElement` """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other & self
[ "def", "__rand__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "other", "&", "self" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pyparsing.py#L2181-L2191
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextFileHandler.SetVisible
(*args, **kwargs)
return _richtext.RichTextFileHandler_SetVisible(*args, **kwargs)
SetVisible(self, bool visible)
SetVisible(self, bool visible)
[ "SetVisible", "(", "self", "bool", "visible", ")" ]
def SetVisible(*args, **kwargs): """SetVisible(self, bool visible)""" return _richtext.RichTextFileHandler_SetVisible(*args, **kwargs)
[ "def", "SetVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextFileHandler_SetVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2784-L2786
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf_kafka/versioneer.py
python
render_pep440_pre
(pieces)
return rendered
TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE
TAG[.post.devDISTANCE] -- No -dirty.
[ "TAG", "[", ".", "post", ".", "devDISTANCE", "]", "--", "No", "-", "dirty", "." ]
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered
[ "def", "render_pep440_pre", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", ":", "rendered", "+=", "\".post.dev%d\"", "%", "pieces", "[", "\"distance\"", "]", "else", ":", "# exception #1", "rendered", "=", "\"0.post.dev%d\"", "%", "pieces", "[", "\"distance\"", "]", "return", "rendered" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf_kafka/versioneer.py#L1307-L1320
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/joblib/joblib/externals/loky/backend/popen_loky_win32.py
python
main
()
Run code specified by data received over pipe
Run code specified by data received over pipe
[ "Run", "code", "specified", "by", "data", "received", "over", "pipe" ]
def main(): ''' Run code specified by data received over pipe ''' assert is_forking(sys.argv) handle = int(sys.argv[-1]) fd = msvcrt.open_osfhandle(handle, os.O_RDONLY) from_parent = os.fdopen(fd, 'rb') process.current_process()._inheriting = True preparation_data = load(from_parent) spawn.prepare(preparation_data) self = load(from_parent) process.current_process()._inheriting = False from_parent.close() exitcode = self._bootstrap() sys.exit(exitcode)
[ "def", "main", "(", ")", ":", "assert", "is_forking", "(", "sys", ".", "argv", ")", "handle", "=", "int", "(", "sys", ".", "argv", "[", "-", "1", "]", ")", "fd", "=", "msvcrt", ".", "open_osfhandle", "(", "handle", ",", "os", ".", "O_RDONLY", ")", "from_parent", "=", "os", ".", "fdopen", "(", "fd", ",", "'rb'", ")", "process", ".", "current_process", "(", ")", ".", "_inheriting", "=", "True", "preparation_data", "=", "load", "(", "from_parent", ")", "spawn", ".", "prepare", "(", "preparation_data", ")", "self", "=", "load", "(", "from_parent", ")", "process", ".", "current_process", "(", ")", ".", "_inheriting", "=", "False", "from_parent", ".", "close", "(", ")", "exitcode", "=", "self", ".", "_bootstrap", "(", ")", "sys", ".", "exit", "(", "exitcode", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/externals/loky/backend/popen_loky_win32.py#L154-L173
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/ordered_dict.py
python
OrderedDict.__repr__
(self, _repr_running={})
od.__repr__() <==> repr(od)
od.__repr__() <==> repr(od)
[ "od", ".", "__repr__", "()", "<", "==", ">", "repr", "(", "od", ")" ]
def __repr__(self, _repr_running={}): 'od.__repr__() <==> repr(od)' call_key = id(self), _get_ident() if call_key in _repr_running: return '...' _repr_running[call_key] = 1 try: if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) finally: del _repr_running[call_key]
[ "def", "__repr__", "(", "self", ",", "_repr_running", "=", "{", "}", ")", ":", "call_key", "=", "id", "(", "self", ")", ",", "_get_ident", "(", ")", "if", "call_key", "in", "_repr_running", ":", "return", "'...'", "_repr_running", "[", "call_key", "]", "=", "1", "try", ":", "if", "not", "self", ":", "return", "'%s()'", "%", "(", "self", ".", "__class__", ".", "__name__", ",", ")", "return", "'%s(%r)'", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "items", "(", ")", ")", "finally", ":", "del", "_repr_running", "[", "call_key", "]" ]
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/ordered_dict.py#L226-L237
kismetwireless/kismet
a7c0dc270c960fb1f58bd9cec4601c201885fd4e
capture_bt_geiger/KismetCaptureBtGeiger/kismetexternal/__init__.py
python
Datasource.set_probesource_cb
(self, cb)
Set callback for datasource probing :param cb: Callback function, taking seqno, source definition, option map :return: None
Set callback for datasource probing
[ "Set", "callback", "for", "datasource", "probing" ]
def set_probesource_cb(self, cb): """ Set callback for datasource probing :param cb: Callback function, taking seqno, source definition, option map :return: None """ self.probesource = cb
[ "def", "set_probesource_cb", "(", "self", ",", "cb", ")", ":", "self", ".", "probesource", "=", "cb" ]
https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_bt_geiger/KismetCaptureBtGeiger/kismetexternal/__init__.py#L786-L794
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pathlib2/pathlib2/__init__.py
python
_Flavour.join_parsed_parts
(self, drv, root, parts, drv2, root2, parts2)
return drv2, root2, parts2
Join the two paths represented by the respective (drive, root, parts) tuples. Return a new (drive, root, parts) tuple.
Join the two paths represented by the respective (drive, root, parts) tuples. Return a new (drive, root, parts) tuple.
[ "Join", "the", "two", "paths", "represented", "by", "the", "respective", "(", "drive", "root", "parts", ")", "tuples", ".", "Return", "a", "new", "(", "drive", "root", "parts", ")", "tuple", "." ]
def join_parsed_parts(self, drv, root, parts, drv2, root2, parts2): """ Join the two paths represented by the respective (drive, root, parts) tuples. Return a new (drive, root, parts) tuple. """ if root2: if not drv2 and drv: return drv, root2, [drv + root2] + parts2[1:] elif drv2: if drv2 == drv or self.casefold(drv2) == self.casefold(drv): # Same drive => second path is relative to the first return drv, root, parts + parts2[1:] else: # Second path is non-anchored (common case) return drv, root, parts + parts2 return drv2, root2, parts2
[ "def", "join_parsed_parts", "(", "self", ",", "drv", ",", "root", ",", "parts", ",", "drv2", ",", "root2", ",", "parts2", ")", ":", "if", "root2", ":", "if", "not", "drv2", "and", "drv", ":", "return", "drv", ",", "root2", ",", "[", "drv", "+", "root2", "]", "+", "parts2", "[", "1", ":", "]", "elif", "drv2", ":", "if", "drv2", "==", "drv", "or", "self", ".", "casefold", "(", "drv2", ")", "==", "self", ".", "casefold", "(", "drv", ")", ":", "# Same drive => second path is relative to the first", "return", "drv", ",", "root", ",", "parts", "+", "parts2", "[", "1", ":", "]", "else", ":", "# Second path is non-anchored (common case)", "return", "drv", ",", "root", ",", "parts", "+", "parts2", "return", "drv2", ",", "root2", ",", "parts2" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pathlib2/pathlib2/__init__.py#L275-L290
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/cookielib.py
python
CookiePolicy.set_ok
(self, cookie, request)
Return true if (and only if) cookie should be accepted from server. Currently, pre-expired cookies never get this far -- the CookieJar class deletes such cookies itself.
Return true if (and only if) cookie should be accepted from server.
[ "Return", "true", "if", "(", "and", "only", "if", ")", "cookie", "should", "be", "accepted", "from", "server", "." ]
def set_ok(self, cookie, request): """Return true if (and only if) cookie should be accepted from server. Currently, pre-expired cookies never get this far -- the CookieJar class deletes such cookies itself. """ raise NotImplementedError()
[ "def", "set_ok", "(", "self", ",", "cookie", ",", "request", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/cookielib.py#L830-L837
apple/foundationdb
f7118ad406f44ab7a33970fc8370647ed0085e18
bindings/python/fdb/directory_impl.py
python
DirectoryLayer.exists
(self, tr, path=())
return True
Returns whether or not the specified directory exists.
Returns whether or not the specified directory exists.
[ "Returns", "whether", "or", "not", "the", "specified", "directory", "exists", "." ]
def exists(self, tr, path=()): """Returns whether or not the specified directory exists.""" self._check_version(tr, write_access=False) path = _to_unicode_path(path) node = self._find(tr, path).prefetch_metadata(tr) if not node.exists(): return False if node.is_in_partition(): return node.get_contents(self).exists(tr, node.get_partition_subpath()) return True
[ "def", "exists", "(", "self", ",", "tr", ",", "path", "=", "(", ")", ")", ":", "self", ".", "_check_version", "(", "tr", ",", "write_access", "=", "False", ")", "path", "=", "_to_unicode_path", "(", "path", ")", "node", "=", "self", ".", "_find", "(", "tr", ",", "path", ")", ".", "prefetch_metadata", "(", "tr", ")", "if", "not", "node", ".", "exists", "(", ")", ":", "return", "False", "if", "node", ".", "is_in_partition", "(", ")", ":", "return", "node", ".", "get_contents", "(", "self", ")", ".", "exists", "(", "tr", ",", "node", ".", "get_partition_subpath", "(", ")", ")", "return", "True" ]
https://github.com/apple/foundationdb/blob/f7118ad406f44ab7a33970fc8370647ed0085e18/bindings/python/fdb/directory_impl.py#L427-L440
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
Misc.bell
(self, displayof=0)
Ring a display's bell.
Ring a display's bell.
[ "Ring", "a", "display", "s", "bell", "." ]
def bell(self, displayof=0): """Ring a display's bell.""" self.tk.call(('bell',) + self._displayof(displayof))
[ "def", "bell", "(", "self", ",", "displayof", "=", "0", ")", ":", "self", ".", "tk", ".", "call", "(", "(", "'bell'", ",", ")", "+", "self", ".", "_displayof", "(", "displayof", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L781-L783
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/threading.py
python
Thread._set_tstate_lock
(self)
Set a lock object which will be released by the interpreter when the underlying thread state (see pystate.h) gets deleted.
Set a lock object which will be released by the interpreter when the underlying thread state (see pystate.h) gets deleted.
[ "Set", "a", "lock", "object", "which", "will", "be", "released", "by", "the", "interpreter", "when", "the", "underlying", "thread", "state", "(", "see", "pystate", ".", "h", ")", "gets", "deleted", "." ]
def _set_tstate_lock(self): """ Set a lock object which will be released by the interpreter when the underlying thread state (see pystate.h) gets deleted. """ self._tstate_lock = _set_sentinel() self._tstate_lock.acquire() if not self.daemon: with _shutdown_locks_lock: _shutdown_locks.add(self._tstate_lock)
[ "def", "_set_tstate_lock", "(", "self", ")", ":", "self", ".", "_tstate_lock", "=", "_set_sentinel", "(", ")", "self", ".", "_tstate_lock", ".", "acquire", "(", ")", "if", "not", "self", ".", "daemon", ":", "with", "_shutdown_locks_lock", ":", "_shutdown_locks", ".", "add", "(", "self", ".", "_tstate_lock", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/threading.py#L899-L909
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
grc/core/ports/_virtual_connections.py
python
_sources_from_virtual_sink_port
(sink_port, _traversed=None)
return list(chain(*source_ports_per_virtual_connection))
Resolve the source port that is connected to the given virtual sink port. Use the get source from virtual source to recursively resolve subsequent ports.
Resolve the source port that is connected to the given virtual sink port. Use the get source from virtual source to recursively resolve subsequent ports.
[ "Resolve", "the", "source", "port", "that", "is", "connected", "to", "the", "given", "virtual", "sink", "port", ".", "Use", "the", "get", "source", "from", "virtual", "source", "to", "recursively", "resolve", "subsequent", "ports", "." ]
def _sources_from_virtual_sink_port(sink_port, _traversed=None): """ Resolve the source port that is connected to the given virtual sink port. Use the get source from virtual source to recursively resolve subsequent ports. """ source_ports_per_virtual_connection = ( # there can be multiple ports per virtual connection _sources_from_virtual_source_port( c.source_port, _traversed) # type: list for c in sink_port.connections(enabled=True) ) # concatenate generated lists of ports return list(chain(*source_ports_per_virtual_connection))
[ "def", "_sources_from_virtual_sink_port", "(", "sink_port", ",", "_traversed", "=", "None", ")", ":", "source_ports_per_virtual_connection", "=", "(", "# there can be multiple ports per virtual connection", "_sources_from_virtual_source_port", "(", "c", ".", "source_port", ",", "_traversed", ")", "# type: list", "for", "c", "in", "sink_port", ".", "connections", "(", "enabled", "=", "True", ")", ")", "# concatenate generated lists of ports", "return", "list", "(", "chain", "(", "*", "source_ports_per_virtual_connection", ")", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/ports/_virtual_connections.py#L24-L36
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py
python
Cursor.is_converting_constructor
(self)
return conf.lib.clang_CXXConstructor_isConvertingConstructor(self)
Returns True if the cursor refers to a C++ converting constructor.
Returns True if the cursor refers to a C++ converting constructor.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "C", "++", "converting", "constructor", "." ]
def is_converting_constructor(self): """Returns True if the cursor refers to a C++ converting constructor. """ return conf.lib.clang_CXXConstructor_isConvertingConstructor(self)
[ "def", "is_converting_constructor", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CXXConstructor_isConvertingConstructor", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py#L1352-L1355
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/auibook.py
python
AuiNotebook.GetAGWWindowStyleFlag
(self)
return self._agwFlags
Returns the AGW-specific style of the window. :see: :meth:`SetAGWWindowStyleFlag` for a list of possible AGW-specific window styles.
Returns the AGW-specific style of the window.
[ "Returns", "the", "AGW", "-", "specific", "style", "of", "the", "window", "." ]
def GetAGWWindowStyleFlag(self): """ Returns the AGW-specific style of the window. :see: :meth:`SetAGWWindowStyleFlag` for a list of possible AGW-specific window styles. """ return self._agwFlags
[ "def", "GetAGWWindowStyleFlag", "(", "self", ")", ":", "return", "self", ".", "_agwFlags" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibook.py#L3388-L3395
tuttleofx/TuttleOFX
36fc4cae15092a84ea8c29b9c6658c7cabfadb6e
applications/sam/common/samUtils.py
python
Sam._displayCommandLineHelp
(self, parser)
Display sam command line help.
Display sam command line help.
[ "Display", "sam", "command", "line", "help", "." ]
def _displayCommandLineHelp(self, parser): """ Display sam command line help. """ if not self.command: raise NotImplementedError subparser = getSubParser(parser, self.command) # if sam command is called from sam main command line if subparser is not None: puts(subparser.format_help()) else: parser.print_help()
[ "def", "_displayCommandLineHelp", "(", "self", ",", "parser", ")", ":", "if", "not", "self", ".", "command", ":", "raise", "NotImplementedError", "subparser", "=", "getSubParser", "(", "parser", ",", "self", ".", "command", ")", "# if sam command is called from sam main command line", "if", "subparser", "is", "not", "None", ":", "puts", "(", "subparser", ".", "format_help", "(", ")", ")", "else", ":", "parser", ".", "print_help", "(", ")" ]
https://github.com/tuttleofx/TuttleOFX/blob/36fc4cae15092a84ea8c29b9c6658c7cabfadb6e/applications/sam/common/samUtils.py#L99-L111
ideawu/ssdb-rocks
a3cbb322cafb2f493252829c608e2239df98c9ac
deps/cpy/antlr3/streams.py
python
CommonTokenStream.setTokenSource
(self, tokenSource)
Reset this token stream by setting its token source.
Reset this token stream by setting its token source.
[ "Reset", "this", "token", "stream", "by", "setting", "its", "token", "source", "." ]
def setTokenSource(self, tokenSource): """Reset this token stream by setting its token source.""" self.tokenSource = tokenSource self.tokens = [] self.p = -1 self.channel = DEFAULT_CHANNEL
[ "def", "setTokenSource", "(", "self", ",", "tokenSource", ")", ":", "self", ".", "tokenSource", "=", "tokenSource", "self", ".", "tokens", "=", "[", "]", "self", ".", "p", "=", "-", "1", "self", ".", "channel", "=", "DEFAULT_CHANNEL" ]
https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/streams.py#L646-L652
isl-org/Open3D
79aec3ddde6a571ce2f28e4096477e52ec465244
python/open3d/visualization/tensorboard_plugin/colormap.py
python
Colormap.calc_color_array
(self, values, range_min, range_max)
return [tex[int(u * n)] for u in u_array]
Generate the color array based on the minimum and maximum range passed. Args: values: The index of values. range_min: The minimum value in the range. range_max: The maximum value in the range. Returns: An array of color index based on the range passed.
Generate the color array based on the minimum and maximum range passed.
[ "Generate", "the", "color", "array", "based", "on", "the", "minimum", "and", "maximum", "range", "passed", "." ]
def calc_color_array(self, values, range_min, range_max): """Generate the color array based on the minimum and maximum range passed. Args: values: The index of values. range_min: The minimum value in the range. range_max: The maximum value in the range. Returns: An array of color index based on the range passed. """ u_array = self.calc_u_array(values, range_min, range_max) tex = [[1.0, 0.0, 1.0]] * 128 n = float(len(tex) - 1) idx = 0 for tex_idx in range(0, len(tex)): x = float(tex_idx) / n while idx < len(self.points) and x > self.points[idx].value: idx += 1 if idx == 0: tex[tex_idx] = self.points[0].color elif idx == len(self.points): tex[tex_idx] = self.points[-1].color else: p0 = self.points[idx - 1] p1 = self.points[idx] dist = p1.value - p0.value # Calc weights between 0 and 1 w0 = 1.0 - (x - p0.value) / dist w1 = (x - p0.value) / dist c = [ w0 * p0.color[0] + w1 * p1.color[0], w0 * p0.color[1] + w1 * p1.color[1], w0 * p0.color[2] + w1 * p1.color[2] ] tex[tex_idx] = c return [tex[int(u * n)] for u in u_array]
[ "def", "calc_color_array", "(", "self", ",", "values", ",", "range_min", ",", "range_max", ")", ":", "u_array", "=", "self", ".", "calc_u_array", "(", "values", ",", "range_min", ",", "range_max", ")", "tex", "=", "[", "[", "1.0", ",", "0.0", ",", "1.0", "]", "]", "*", "128", "n", "=", "float", "(", "len", "(", "tex", ")", "-", "1", ")", "idx", "=", "0", "for", "tex_idx", "in", "range", "(", "0", ",", "len", "(", "tex", ")", ")", ":", "x", "=", "float", "(", "tex_idx", ")", "/", "n", "while", "idx", "<", "len", "(", "self", ".", "points", ")", "and", "x", ">", "self", ".", "points", "[", "idx", "]", ".", "value", ":", "idx", "+=", "1", "if", "idx", "==", "0", ":", "tex", "[", "tex_idx", "]", "=", "self", ".", "points", "[", "0", "]", ".", "color", "elif", "idx", "==", "len", "(", "self", ".", "points", ")", ":", "tex", "[", "tex_idx", "]", "=", "self", ".", "points", "[", "-", "1", "]", ".", "color", "else", ":", "p0", "=", "self", ".", "points", "[", "idx", "-", "1", "]", "p1", "=", "self", ".", "points", "[", "idx", "]", "dist", "=", "p1", ".", "value", "-", "p0", ".", "value", "# Calc weights between 0 and 1", "w0", "=", "1.0", "-", "(", "x", "-", "p0", ".", "value", ")", "/", "dist", "w1", "=", "(", "x", "-", "p0", ".", "value", ")", "/", "dist", "c", "=", "[", "w0", "*", "p0", ".", "color", "[", "0", "]", "+", "w1", "*", "p1", ".", "color", "[", "0", "]", ",", "w0", "*", "p0", ".", "color", "[", "1", "]", "+", "w1", "*", "p1", ".", "color", "[", "1", "]", ",", "w0", "*", "p0", ".", "color", "[", "2", "]", "+", "w1", "*", "p1", ".", "color", "[", "2", "]", "]", "tex", "[", "tex_idx", "]", "=", "c", "return", "[", "tex", "[", "int", "(", "u", "*", "n", ")", "]", "for", "u", "in", "u_array", "]" ]
https://github.com/isl-org/Open3D/blob/79aec3ddde6a571ce2f28e4096477e52ec465244/python/open3d/visualization/tensorboard_plugin/colormap.py#L62-L101
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/webapp2/webapp2.py
python
SimpleRoute.regex
(self)
return re.compile(self.template)
Lazy regex compiler.
Lazy regex compiler.
[ "Lazy", "regex", "compiler", "." ]
def regex(self): """Lazy regex compiler.""" if not self.template.startswith('^'): self.template = '^' + self.template if not self.template.endswith('$'): self.template += '$' return re.compile(self.template)
[ "def", "regex", "(", "self", ")", ":", "if", "not", "self", ".", "template", ".", "startswith", "(", "'^'", ")", ":", "self", ".", "template", "=", "'^'", "+", "self", ".", "template", "if", "not", "self", ".", "template", ".", "endswith", "(", "'$'", ")", ":", "self", ".", "template", "+=", "'$'", "return", "re", ".", "compile", "(", "self", ".", "template", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2.py#L835-L843
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/numpy/math_ops.py
python
copysign
(x1, x2, dtype=None)
return res
Changes the sign of `x1` to that of `x2`, element-wise. If `x2` is a scalar, its sign will be copied to all elements of `x1`. Note: Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are not supported. Complex inputs are not supported now. Args: x1 (Union[int, float, list, tuple, Tensor]): Values to change the sign of. x2 (Union[int, float, list, tuple, Tensor]): The sign of x2 is copied to x1. If `x1.shape != x2.shape`, they must be broadcastable to a common shape (which becomes the shape of the output). dtype (:class:`mindspore.dtype`, optional): Defaults to None. Overrides the dtype of the output Tensor. Returns: Tensor or scalar. The values of `x1` with the sign of `x2`. This is a scalar if both `x1` and `x2` are scalars. Raises: TypeError: If dtype of the input is not in the given types or the input can not be converted to tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> import mindspore.numpy as np >>> output = np.copysign(np.array([1, -1, -1]), np.array([-1, 1, -1])) >>> print(output) [-1 1 -1]
Changes the sign of `x1` to that of `x2`, element-wise.
[ "Changes", "the", "sign", "of", "x1", "to", "that", "of", "x2", "element", "-", "wise", "." ]
def copysign(x1, x2, dtype=None): """ Changes the sign of `x1` to that of `x2`, element-wise. If `x2` is a scalar, its sign will be copied to all elements of `x1`. Note: Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are not supported. Complex inputs are not supported now. Args: x1 (Union[int, float, list, tuple, Tensor]): Values to change the sign of. x2 (Union[int, float, list, tuple, Tensor]): The sign of x2 is copied to x1. If `x1.shape != x2.shape`, they must be broadcastable to a common shape (which becomes the shape of the output). dtype (:class:`mindspore.dtype`, optional): Defaults to None. Overrides the dtype of the output Tensor. Returns: Tensor or scalar. The values of `x1` with the sign of `x2`. This is a scalar if both `x1` and `x2` are scalars. Raises: TypeError: If dtype of the input is not in the given types or the input can not be converted to tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> import mindspore.numpy as np >>> output = np.copysign(np.array([1, -1, -1]), np.array([-1, 1, -1])) >>> print(output) [-1 1 -1] """ if not isinstance(x1, (int, float, list, tuple, Tensor)): _raise_type_error('integer, float, list, tuple or Tensor are expected, but got', x1) if not isinstance(x2, (int, float, list, tuple, Tensor)): _raise_type_error('integer, float, list, tuple or Tensor are expected, but got', x2) x1, x2 = _to_tensor(x1, x2) shape_out = _infer_out_shape(F.shape(x1), F.shape(x2)) x1 = _broadcast_to_shape(x1, shape_out) x2 = _broadcast_to_shape(x2, shape_out) if _check_same_type(F.dtype(x1), mstype.bool_) or _check_same_type(F.dtype(x2), mstype.bool_): _raise_type_error("sign does not accept dtype bool.") original_dtype = x1.dtype if not _check_is_float(original_dtype): pos_tensor = F.absolute(x1.astype('float32')).astype(original_dtype) else: pos_tensor = F.absolute(x1) neg_tensor = F.neg_tensor(pos_tensor) less_zero = F.less(x2, 0) res = F.select(less_zero, neg_tensor, pos_tensor) if dtype is not None and not _check_same_type(F.dtype(res), dtype): res = F.cast(res, dtype) return res
[ "def", "copysign", "(", "x1", ",", "x2", ",", "dtype", "=", "None", ")", ":", "if", "not", "isinstance", "(", "x1", ",", "(", "int", ",", "float", ",", "list", ",", "tuple", ",", "Tensor", ")", ")", ":", "_raise_type_error", "(", "'integer, float, list, tuple or Tensor are expected, but got'", ",", "x1", ")", "if", "not", "isinstance", "(", "x2", ",", "(", "int", ",", "float", ",", "list", ",", "tuple", ",", "Tensor", ")", ")", ":", "_raise_type_error", "(", "'integer, float, list, tuple or Tensor are expected, but got'", ",", "x2", ")", "x1", ",", "x2", "=", "_to_tensor", "(", "x1", ",", "x2", ")", "shape_out", "=", "_infer_out_shape", "(", "F", ".", "shape", "(", "x1", ")", ",", "F", ".", "shape", "(", "x2", ")", ")", "x1", "=", "_broadcast_to_shape", "(", "x1", ",", "shape_out", ")", "x2", "=", "_broadcast_to_shape", "(", "x2", ",", "shape_out", ")", "if", "_check_same_type", "(", "F", ".", "dtype", "(", "x1", ")", ",", "mstype", ".", "bool_", ")", "or", "_check_same_type", "(", "F", ".", "dtype", "(", "x2", ")", ",", "mstype", ".", "bool_", ")", ":", "_raise_type_error", "(", "\"sign does not accept dtype bool.\"", ")", "original_dtype", "=", "x1", ".", "dtype", "if", "not", "_check_is_float", "(", "original_dtype", ")", ":", "pos_tensor", "=", "F", ".", "absolute", "(", "x1", ".", "astype", "(", "'float32'", ")", ")", ".", "astype", "(", "original_dtype", ")", "else", ":", "pos_tensor", "=", "F", ".", "absolute", "(", "x1", ")", "neg_tensor", "=", "F", ".", "neg_tensor", "(", "pos_tensor", ")", "less_zero", "=", "F", ".", "less", "(", "x2", ",", "0", ")", "res", "=", "F", ".", "select", "(", "less_zero", ",", "neg_tensor", ",", "pos_tensor", ")", "if", "dtype", "is", "not", "None", "and", "not", "_check_same_type", "(", "F", ".", "dtype", "(", "res", ")", ",", "dtype", ")", ":", "res", "=", "F", ".", "cast", "(", "res", ",", "dtype", ")", "return", "res" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/math_ops.py#L4492-L4549
google-ar/WebARonTango
e86965d2cbc652156b480e0fcf77c716745578cd
chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py
python
CustomHandler.WriteImmediateCmdSet
(self, func, f)
Overrriden from TypeHandler.
Overrriden from TypeHandler.
[ "Overrriden", "from", "TypeHandler", "." ]
def WriteImmediateCmdSet(self, func, f): """Overrriden from TypeHandler.""" copy_args = func.MakeCmdArgString("_", False) f.write(" void* Set(void* cmd%s) {\n" % func.MakeTypedCmdArgString("_", True)) self.WriteImmediateCmdGetTotalSize(func, f) f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args) f.write(" return NextImmediateCmdAddressTotalSize<ValueType>(" "cmd, total_size);\n") f.write(" }\n") f.write("\n")
[ "def", "WriteImmediateCmdSet", "(", "self", ",", "func", ",", "f", ")", ":", "copy_args", "=", "func", ".", "MakeCmdArgString", "(", "\"_\"", ",", "False", ")", "f", ".", "write", "(", "\" void* Set(void* cmd%s) {\\n\"", "%", "func", ".", "MakeTypedCmdArgString", "(", "\"_\"", ",", "True", ")", ")", "self", ".", "WriteImmediateCmdGetTotalSize", "(", "func", ",", "f", ")", "f", ".", "write", "(", "\" static_cast<ValueType*>(cmd)->Init(%s);\\n\"", "%", "copy_args", ")", "f", ".", "write", "(", "\" return NextImmediateCmdAddressTotalSize<ValueType>(\"", "\"cmd, total_size);\\n\"", ")", "f", ".", "write", "(", "\" }\\n\"", ")", "f", ".", "write", "(", "\"\\n\"", ")" ]
https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L5722-L5732
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/binary-search-tree-iterator-ii.py
python
BSTIterator.next
(self)
return self.__vals[self.__pos]
:rtype: int
:rtype: int
[ ":", "rtype", ":", "int" ]
def next(self): """ :rtype: int """ self.__pos += 1 if self.__pos == len(self.__vals): node = self.__stk.pop() self.__traversalLeft(node.right) self.__vals.append(node.val) return self.__vals[self.__pos]
[ "def", "next", "(", "self", ")", ":", "self", ".", "__pos", "+=", "1", "if", "self", ".", "__pos", "==", "len", "(", "self", ".", "__vals", ")", ":", "node", "=", "self", ".", "__stk", ".", "pop", "(", ")", "self", ".", "__traversalLeft", "(", "node", ".", "right", ")", "self", ".", "__vals", ".", "append", "(", "node", ".", "val", ")", "return", "self", ".", "__vals", "[", "self", ".", "__pos", "]" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/binary-search-tree-iterator-ii.py#L29-L38
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/shape_base.py
python
hstack
(tup)
Stack arrays in sequence horizontally (column wise). Take a sequence of arrays and stack them horizontally to make a single array. Rebuild arrays divided by `hsplit`. Parameters ---------- tup : sequence of ndarrays All arrays must have the same shape along all but the second axis. Returns ------- stacked : ndarray The array formed by stacking the given arrays. See Also -------- vstack : Stack arrays in sequence vertically (row wise). dstack : Stack arrays in sequence depth wise (along third axis). concatenate : Join a sequence of arrays together. hsplit : Split array along second axis. Notes ----- Equivalent to ``np.concatenate(tup, axis=1)`` Examples -------- >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.hstack((a,b)) array([1, 2, 3, 2, 3, 4]) >>> a = np.array([[1],[2],[3]]) >>> b = np.array([[2],[3],[4]]) >>> np.hstack((a,b)) array([[1, 2], [2, 3], [3, 4]])
Stack arrays in sequence horizontally (column wise).
[ "Stack", "arrays", "in", "sequence", "horizontally", "(", "column", "wise", ")", "." ]
def hstack(tup): """ Stack arrays in sequence horizontally (column wise). Take a sequence of arrays and stack them horizontally to make a single array. Rebuild arrays divided by `hsplit`. Parameters ---------- tup : sequence of ndarrays All arrays must have the same shape along all but the second axis. Returns ------- stacked : ndarray The array formed by stacking the given arrays. See Also -------- vstack : Stack arrays in sequence vertically (row wise). dstack : Stack arrays in sequence depth wise (along third axis). concatenate : Join a sequence of arrays together. hsplit : Split array along second axis. Notes ----- Equivalent to ``np.concatenate(tup, axis=1)`` Examples -------- >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.hstack((a,b)) array([1, 2, 3, 2, 3, 4]) >>> a = np.array([[1],[2],[3]]) >>> b = np.array([[2],[3],[4]]) >>> np.hstack((a,b)) array([[1, 2], [2, 3], [3, 4]]) """ arrs = [atleast_1d(_m) for _m in tup] # As a special case, dimension 0 of 1-dimensional arrays is "horizontal" if arrs[0].ndim == 1: return _nx.concatenate(arrs, 0) else: return _nx.concatenate(arrs, 1)
[ "def", "hstack", "(", "tup", ")", ":", "arrs", "=", "[", "atleast_1d", "(", "_m", ")", "for", "_m", "in", "tup", "]", "# As a special case, dimension 0 of 1-dimensional arrays is \"horizontal\"", "if", "arrs", "[", "0", "]", ".", "ndim", "==", "1", ":", "return", "_nx", ".", "concatenate", "(", "arrs", ",", "0", ")", "else", ":", "return", "_nx", ".", "concatenate", "(", "arrs", ",", "1", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/shape_base.py#L230-L277