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
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
scripts/cpp_lint.py
python
CheckStyle
(filename, clean_lines, linenum, file_extension, nesting_state, error)
Checks rules from the 'C++ style rules' section of cppguide.html. Most of these rules are hard to test (naming, comment style), but we do what we can. In particular we check for 2-space indents, line lengths, tab usage, spaces inside code, etc. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Checks rules from the 'C++ style rules' section of cppguide.html.
[ "Checks", "rules", "from", "the", "C", "++", "style", "rules", "section", "of", "cppguide", ".", "html", "." ]
def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, error): """Checks rules from the 'C++ style rules' section of cppguide.html. Most of these rules are hard to test (naming, comment style), but we do what we can. In particular we check for 2-space indents, line lengths, tab usage, spaces inside code, etc. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw_lines = clean_lines.lines_without_raw_strings line = raw_lines[linenum] if line.find('\t') != -1: error(filename, linenum, 'whitespace/tab', 1, 'Tab found; better to use spaces') # One or three blank spaces at the beginning of the line is weird; it's # hard to reconcile that with 2-space indents. # NOTE: here are the conditions rob pike used for his tests. Mine aren't # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces # if(RLENGTH > 20) complain = 0; # if(match($0, " +(error|private|public|protected):")) complain = 0; # if(match(prev, "&& *$")) complain = 0; # if(match(prev, "\\|\\| *$")) complain = 0; # if(match(prev, "[\",=><] *$")) complain = 0; # if(match($0, " <<")) complain = 0; # if(match(prev, " +for \\(")) complain = 0; # if(prevodd && match(prevprev, " +for \\(")) complain = 0; initial_spaces = 0 cleansed_line = clean_lines.elided[linenum] while initial_spaces < len(line) and line[initial_spaces] == ' ': initial_spaces += 1 if line and line[-1].isspace(): error(filename, linenum, 'whitespace/end_of_line', 4, 'Line ends in whitespace. Consider deleting these extra spaces.') # There are certain situations we allow one space, notably for section labels elif ((initial_spaces == 1 or initial_spaces == 3) and not Match(r'\s*\w+\s*:\s*$', cleansed_line)): error(filename, linenum, 'whitespace/indent', 3, 'Weird number of spaces at line-start. ' 'Are you using a 2-space indent?') # Check if the line is a header guard. is_header_guard = False if file_extension == 'h': cppvar = GetHeaderGuardCPPVariable(filename) if (line.startswith('#ifndef %s' % cppvar) or line.startswith('#define %s' % cppvar) or line.startswith('#endif // %s' % cppvar)): is_header_guard = True # #include lines and header guards can be long, since there's no clean way to # split them. # # URLs can be long too. It's possible to split these, but it makes them # harder to cut&paste. # # The "$Id:...$" comment may also get very long without it being the # developers fault. if (not line.startswith('#include') and not is_header_guard and not Match(r'^\s*//.*http(s?)://\S*$', line) and not Match(r'^// \$Id:.*#[0-9]+ \$$', line)): line_width = GetLineWidth(line) extended_length = int((_line_length * 1.25)) if line_width > extended_length: error(filename, linenum, 'whitespace/line_length', 4, 'Lines should very rarely be longer than %i characters' % extended_length) elif line_width > _line_length: error(filename, linenum, 'whitespace/line_length', 2, 'Lines should be <= %i characters long' % _line_length) if (cleansed_line.count(';') > 1 and # for loops are allowed two ;'s (and may run over two lines). cleansed_line.find('for') == -1 and (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and # It's ok to have many commands in a switch case that fits in 1 line not ((cleansed_line.find('case ') != -1 or cleansed_line.find('default:') != -1) and cleansed_line.find('break;') != -1)): error(filename, linenum, 'whitespace/newline', 0, 'More than one command on the same line') # Some more style checks CheckBraces(filename, clean_lines, linenum, error) CheckEmptyBlockBody(filename, clean_lines, linenum, error) CheckAccess(filename, clean_lines, linenum, nesting_state, error) CheckSpacing(filename, clean_lines, linenum, nesting_state, error) CheckCheck(filename, clean_lines, linenum, error) CheckAltTokens(filename, clean_lines, linenum, error) classinfo = nesting_state.InnermostClass() if classinfo: CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
[ "def", "CheckStyle", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "file_extension", ",", "nesting_state", ",", "error", ")", ":", "# Don't use \"elided\" lines here, otherwise we can't check commented lines.", "# Don't want to use \"raw\" either, because we don't want to check inside C++11", "# raw strings,", "raw_lines", "=", "clean_lines", ".", "lines_without_raw_strings", "line", "=", "raw_lines", "[", "linenum", "]", "if", "line", ".", "find", "(", "'\\t'", ")", "!=", "-", "1", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/tab'", ",", "1", ",", "'Tab found; better to use spaces'", ")", "# One or three blank spaces at the beginning of the line is weird; it's", "# hard to reconcile that with 2-space indents.", "# NOTE: here are the conditions rob pike used for his tests. Mine aren't", "# as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces", "# if(RLENGTH > 20) complain = 0;", "# if(match($0, \" +(error|private|public|protected):\")) complain = 0;", "# if(match(prev, \"&& *$\")) complain = 0;", "# if(match(prev, \"\\\\|\\\\| *$\")) complain = 0;", "# if(match(prev, \"[\\\",=><] *$\")) complain = 0;", "# if(match($0, \" <<\")) complain = 0;", "# if(match(prev, \" +for \\\\(\")) complain = 0;", "# if(prevodd && match(prevprev, \" +for \\\\(\")) complain = 0;", "initial_spaces", "=", "0", "cleansed_line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "while", "initial_spaces", "<", "len", "(", "line", ")", "and", "line", "[", "initial_spaces", "]", "==", "' '", ":", "initial_spaces", "+=", "1", "if", "line", "and", "line", "[", "-", "1", "]", ".", "isspace", "(", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/end_of_line'", ",", "4", ",", "'Line ends in whitespace. Consider deleting these extra spaces.'", ")", "# There are certain situations we allow one space, notably for section labels", "elif", "(", "(", "initial_spaces", "==", "1", "or", "initial_spaces", "==", "3", ")", "and", "not", "Match", "(", "r'\\s*\\w+\\s*:\\s*$'", ",", "cleansed_line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/indent'", ",", "3", ",", "'Weird number of spaces at line-start. '", "'Are you using a 2-space indent?'", ")", "# Check if the line is a header guard.", "is_header_guard", "=", "False", "if", "file_extension", "==", "'h'", ":", "cppvar", "=", "GetHeaderGuardCPPVariable", "(", "filename", ")", "if", "(", "line", ".", "startswith", "(", "'#ifndef %s'", "%", "cppvar", ")", "or", "line", ".", "startswith", "(", "'#define %s'", "%", "cppvar", ")", "or", "line", ".", "startswith", "(", "'#endif // %s'", "%", "cppvar", ")", ")", ":", "is_header_guard", "=", "True", "# #include lines and header guards can be long, since there's no clean way to", "# split them.", "#", "# URLs can be long too. It's possible to split these, but it makes them", "# harder to cut&paste.", "#", "# The \"$Id:...$\" comment may also get very long without it being the", "# developers fault.", "if", "(", "not", "line", ".", "startswith", "(", "'#include'", ")", "and", "not", "is_header_guard", "and", "not", "Match", "(", "r'^\\s*//.*http(s?)://\\S*$'", ",", "line", ")", "and", "not", "Match", "(", "r'^// \\$Id:.*#[0-9]+ \\$$'", ",", "line", ")", ")", ":", "line_width", "=", "GetLineWidth", "(", "line", ")", "extended_length", "=", "int", "(", "(", "_line_length", "*", "1.25", ")", ")", "if", "line_width", ">", "extended_length", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/line_length'", ",", "4", ",", "'Lines should very rarely be longer than %i characters'", "%", "extended_length", ")", "elif", "line_width", ">", "_line_length", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/line_length'", ",", "2", ",", "'Lines should be <= %i characters long'", "%", "_line_length", ")", "if", "(", "cleansed_line", ".", "count", "(", "';'", ")", ">", "1", "and", "# for loops are allowed two ;'s (and may run over two lines).", "cleansed_line", ".", "find", "(", "'for'", ")", "==", "-", "1", "and", "(", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", ".", "find", "(", "'for'", ")", "==", "-", "1", "or", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", ".", "find", "(", "';'", ")", "!=", "-", "1", ")", "and", "# It's ok to have many commands in a switch case that fits in 1 line", "not", "(", "(", "cleansed_line", ".", "find", "(", "'case '", ")", "!=", "-", "1", "or", "cleansed_line", ".", "find", "(", "'default:'", ")", "!=", "-", "1", ")", "and", "cleansed_line", ".", "find", "(", "'break;'", ")", "!=", "-", "1", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "0", ",", "'More than one command on the same line'", ")", "# Some more style checks", "CheckBraces", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "CheckEmptyBlockBody", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "CheckAccess", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", "CheckSpacing", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", "CheckCheck", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "CheckAltTokens", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "classinfo", "=", "nesting_state", ".", "InnermostClass", "(", ")", "if", "classinfo", ":", "CheckSectionSpacing", "(", "filename", ",", "clean_lines", ",", "classinfo", ",", "linenum", ",", "error", ")" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/scripts/cpp_lint.py#L3463-L3567
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
ListCtrl.ClearAll
(*args, **kwargs)
return _controls_.ListCtrl_ClearAll(*args, **kwargs)
ClearAll(self)
ClearAll(self)
[ "ClearAll", "(", "self", ")" ]
def ClearAll(*args, **kwargs): """ClearAll(self)""" return _controls_.ListCtrl_ClearAll(*args, **kwargs)
[ "def", "ClearAll", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListCtrl_ClearAll", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L4657-L4659
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/lib/io/file_io.py
python
create_dir_v2
(path)
Creates a directory with the name given by `path`. Args: path: string, name of the directory to be created Notes: The parent directories need to exist. Use `tf.io.gfile.makedirs` instead if there is the possibility that the parent dirs don't exist. Raises: errors.OpError: If the operation fails.
Creates a directory with the name given by `path`.
[ "Creates", "a", "directory", "with", "the", "name", "given", "by", "path", "." ]
def create_dir_v2(path): """Creates a directory with the name given by `path`. Args: path: string, name of the directory to be created Notes: The parent directories need to exist. Use `tf.io.gfile.makedirs` instead if there is the possibility that the parent dirs don't exist. Raises: errors.OpError: If the operation fails. """ _pywrap_file_io.CreateDir(compat.path_to_bytes(path))
[ "def", "create_dir_v2", "(", "path", ")", ":", "_pywrap_file_io", ".", "CreateDir", "(", "compat", ".", "path_to_bytes", "(", "path", ")", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/lib/io/file_io.py#L469-L481
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ftplib.py
python
FTP.login
(self, user = '', passwd = '', acct = '')
return resp
Login, default anonymous.
Login, default anonymous.
[ "Login", "default", "anonymous", "." ]
def login(self, user = '', passwd = '', acct = ''): '''Login, default anonymous.''' if not user: user = 'anonymous' if not passwd: passwd = '' if not acct: acct = '' if user == 'anonymous' and passwd in ('', '-'): # If there is no anonymous ftp password specified # then we'll just use anonymous@ # We don't send any other thing because: # - We want to remain anonymous # - We want to stop SPAM # - We don't want to let ftp sites to discriminate by the user, # host or country. passwd = passwd + 'anonymous@' resp = self.sendcmd('USER ' + user) if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd) if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct) if resp[0] != '2': raise error_reply, resp return resp
[ "def", "login", "(", "self", ",", "user", "=", "''", ",", "passwd", "=", "''", ",", "acct", "=", "''", ")", ":", "if", "not", "user", ":", "user", "=", "'anonymous'", "if", "not", "passwd", ":", "passwd", "=", "''", "if", "not", "acct", ":", "acct", "=", "''", "if", "user", "==", "'anonymous'", "and", "passwd", "in", "(", "''", ",", "'-'", ")", ":", "# If there is no anonymous ftp password specified", "# then we'll just use anonymous@", "# We don't send any other thing because:", "# - We want to remain anonymous", "# - We want to stop SPAM", "# - We don't want to let ftp sites to discriminate by the user,", "# host or country.", "passwd", "=", "passwd", "+", "'anonymous@'", "resp", "=", "self", ".", "sendcmd", "(", "'USER '", "+", "user", ")", "if", "resp", "[", "0", "]", "==", "'3'", ":", "resp", "=", "self", ".", "sendcmd", "(", "'PASS '", "+", "passwd", ")", "if", "resp", "[", "0", "]", "==", "'3'", ":", "resp", "=", "self", ".", "sendcmd", "(", "'ACCT '", "+", "acct", ")", "if", "resp", "[", "0", "]", "!=", "'2'", ":", "raise", "error_reply", ",", "resp", "return", "resp" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ftplib.py#L373-L392
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/gyp/util/resource_utils.py
python
RJavaBuildOptions.GenerateOnResourcesLoaded
(self, fake=False)
Generate an onResourcesLoaded() method. This Java method will be called at runtime by the framework when the corresponding library (which includes the R.java source file) will be loaded at runtime. This corresponds to the --shared-resources or --app-as-shared-lib flags of 'aapt package'. if |fake|, then the method will be empty bodied to compile faster. This useful for dummy R.java files that will eventually be replaced by real ones.
Generate an onResourcesLoaded() method.
[ "Generate", "an", "onResourcesLoaded", "()", "method", "." ]
def GenerateOnResourcesLoaded(self, fake=False): """Generate an onResourcesLoaded() method. This Java method will be called at runtime by the framework when the corresponding library (which includes the R.java source file) will be loaded at runtime. This corresponds to the --shared-resources or --app-as-shared-lib flags of 'aapt package'. if |fake|, then the method will be empty bodied to compile faster. This useful for dummy R.java files that will eventually be replaced by real ones. """ self.has_on_resources_loaded = True self.fake_on_resources_loaded = fake
[ "def", "GenerateOnResourcesLoaded", "(", "self", ",", "fake", "=", "False", ")", ":", "self", ".", "has_on_resources_loaded", "=", "True", "self", ".", "fake_on_resources_loaded", "=", "fake" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/util/resource_utils.py#L472-L485
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/coli.py
python
CommandlineWrapper.getID
(self)
Return the plugin ID
Return the plugin ID
[ "Return", "the", "plugin", "ID" ]
def getID(self): """Return the plugin ID""" raise NotImplementedError("getID must be implemented")
[ "def", "getID", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"getID must be implemented\"", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/coli.py#L254-L256
numworks/epsilon
8952d2f8b1de1c3f064eec8ffcea804c5594ba4c
build/device/usb/backend/__init__.py
python
IBackend.get_interface_descriptor
(self, dev, intf, alt, config)
r"""Return an interface descriptor of the given device. The object returned is required to have all the Interface Descriptor fields accessible as member variables. They must be convertible (but not required to be equal) to the int type. The dev parameter is the device identification object. The intf parameter is the interface logical index (not the bInterfaceNumber field) and alt is the alternate setting logical index (not the bAlternateSetting value). Not every interface has more than one alternate setting. In this case, the alt parameter should be zero. config is the configuration logical index (not the bConfigurationValue field).
r"""Return an interface descriptor of the given device.
[ "r", "Return", "an", "interface", "descriptor", "of", "the", "given", "device", "." ]
def get_interface_descriptor(self, dev, intf, alt, config): r"""Return an interface descriptor of the given device. The object returned is required to have all the Interface Descriptor fields accessible as member variables. They must be convertible (but not required to be equal) to the int type. The dev parameter is the device identification object. The intf parameter is the interface logical index (not the bInterfaceNumber field) and alt is the alternate setting logical index (not the bAlternateSetting value). Not every interface has more than one alternate setting. In this case, the alt parameter should be zero. config is the configuration logical index (not the bConfigurationValue field). """ _not_implemented(self.get_interface_descriptor)
[ "def", "get_interface_descriptor", "(", "self", ",", "dev", ",", "intf", ",", "alt", ",", "config", ")", ":", "_not_implemented", "(", "self", ".", "get_interface_descriptor", ")" ]
https://github.com/numworks/epsilon/blob/8952d2f8b1de1c3f064eec8ffcea804c5594ba4c/build/device/usb/backend/__init__.py#L139-L153
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/visitors/InstanceTopologyCppVisitor.py
python
InstanceTopologyCppVisitor.namespaceVisit
(self, obj)
Defined to generate namespace code within a file. Also any pre-condition code is generated. @param args: the instance of the concrete element to operation on.
Defined to generate namespace code within a file. Also any pre-condition code is generated.
[ "Defined", "to", "generate", "namespace", "code", "within", "a", "file", ".", "Also", "any", "pre", "-", "condition", "code", "is", "generated", "." ]
def namespaceVisit(self, obj): """ Defined to generate namespace code within a file. Also any pre-condition code is generated. @param args: the instance of the concrete element to operation on. """
[ "def", "namespaceVisit", "(", "self", ",", "obj", ")", ":" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/visitors/InstanceTopologyCppVisitor.py#L234-L239
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
Unsqueeze.backward
(self, dy)
return singa.Reshape(dy, self.cache)
Args: dy (CTensor): the gradient tensor from upper operations Returns: CTensor, the gradient over input
Args: dy (CTensor): the gradient tensor from upper operations Returns: CTensor, the gradient over input
[ "Args", ":", "dy", "(", "CTensor", ")", ":", "the", "gradient", "tensor", "from", "upper", "operations", "Returns", ":", "CTensor", "the", "gradient", "over", "input" ]
def backward(self, dy): """ Args: dy (CTensor): the gradient tensor from upper operations Returns: CTensor, the gradient over input """ return singa.Reshape(dy, self.cache)
[ "def", "backward", "(", "self", ",", "dy", ")", ":", "return", "singa", ".", "Reshape", "(", "dy", ",", "self", ".", "cache", ")" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L2588-L2595
rdiankov/openrave
d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7
sandbox/mintime/RRT_Smooth.py
python
linear_smooth_dichotomy
(robot,vp_list,coll_check_step)
Recursively smooth a list of via points
Recursively smooth a list of via points
[ "Recursively", "smooth", "a", "list", "of", "via", "points" ]
def linear_smooth_dichotomy(robot,vp_list,coll_check_step): """Recursively smooth a list of via points""" if len(vp_list)==2: return vp_list else: p1=vp_list[0] p2=vp_list[-1] d=linalg.norm(p2-p1) v_unit=(p2-p1)/d for t in linspace(0,d,d/coll_check_step+1): p=p1+t*v_unit with robot: robot.SetDOFValues(p) if robot.GetEnv().CheckCollision(robot): l1=linear_smooth_dichotomy(robot,vp_list[0:len(vp_list)/2+1],coll_check_step) l2=linear_smooth_dichotomy(robot,vp_list[len(vp_list)/2:len(vp_list)],coll_check_step) l1.extend(l2[1:]) return l1 return [p1,p2]
[ "def", "linear_smooth_dichotomy", "(", "robot", ",", "vp_list", ",", "coll_check_step", ")", ":", "if", "len", "(", "vp_list", ")", "==", "2", ":", "return", "vp_list", "else", ":", "p1", "=", "vp_list", "[", "0", "]", "p2", "=", "vp_list", "[", "-", "1", "]", "d", "=", "linalg", ".", "norm", "(", "p2", "-", "p1", ")", "v_unit", "=", "(", "p2", "-", "p1", ")", "/", "d", "for", "t", "in", "linspace", "(", "0", ",", "d", ",", "d", "/", "coll_check_step", "+", "1", ")", ":", "p", "=", "p1", "+", "t", "*", "v_unit", "with", "robot", ":", "robot", ".", "SetDOFValues", "(", "p", ")", "if", "robot", ".", "GetEnv", "(", ")", ".", "CheckCollision", "(", "robot", ")", ":", "l1", "=", "linear_smooth_dichotomy", "(", "robot", ",", "vp_list", "[", "0", ":", "len", "(", "vp_list", ")", "/", "2", "+", "1", "]", ",", "coll_check_step", ")", "l2", "=", "linear_smooth_dichotomy", "(", "robot", ",", "vp_list", "[", "len", "(", "vp_list", ")", "/", "2", ":", "len", "(", "vp_list", ")", "]", ",", "coll_check_step", ")", "l1", ".", "extend", "(", "l2", "[", "1", ":", "]", ")", "return", "l1", "return", "[", "p1", ",", "p2", "]" ]
https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/sandbox/mintime/RRT_Smooth.py#L56-L74
mickem/nscp
79f89fdbb6da63f91bc9dedb7aea202fe938f237
scripts/python/lib/google/protobuf/service.py
python
Service.GetDescriptor
()
Retrieves this service's descriptor.
Retrieves this service's descriptor.
[ "Retrieves", "this", "service", "s", "descriptor", "." ]
def GetDescriptor(): """Retrieves this service's descriptor.""" raise NotImplementedError
[ "def", "GetDescriptor", "(", ")", ":", "raise", "NotImplementedError" ]
https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/service.py#L61-L63
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/training/coordinator.py
python
LooperThread.start_loop
(self)
Called when the thread starts.
Called when the thread starts.
[ "Called", "when", "the", "thread", "starts", "." ]
def start_loop(self): """Called when the thread starts.""" pass
[ "def", "start_loop", "(", "self", ")", ":", "pass" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/coordinator.py#L481-L483
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/tools/pretty_gyp.py
python
mask_comments
(input)
return [search_re.sub(comment_replace, line) for line in input]
Mask the quoted strings so we skip braces inside quoted strings.
Mask the quoted strings so we skip braces inside quoted strings.
[ "Mask", "the", "quoted", "strings", "so", "we", "skip", "braces", "inside", "quoted", "strings", "." ]
def mask_comments(input): """Mask the quoted strings so we skip braces inside quoted strings.""" search_re = re.compile(r'(.*?)(#)(.*)') return [search_re.sub(comment_replace, line) for line in input]
[ "def", "mask_comments", "(", "input", ")", ":", "search_re", "=", "re", ".", "compile", "(", "r'(.*?)(#)(.*)'", ")", "return", "[", "search_re", ".", "sub", "(", "comment_replace", ",", "line", ")", "for", "line", "in", "input", "]" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/tools/pretty_gyp.py#L28-L31
CanalTP/navitia
cb84ce9859070187e708818b058e6a7e0b7f891b
source/jormungandr/jormungandr/authentication.py
python
has_access
(region, api, abort, user)
Check the Authorization of the current user for this region and this API. If abort is True, the request is aborted with the appropriate HTTP code. Warning: Please this function is cached therefore it should not be dependent of the request context, so keep it as a pure function.
Check the Authorization of the current user for this region and this API. If abort is True, the request is aborted with the appropriate HTTP code. Warning: Please this function is cached therefore it should not be dependent of the request context, so keep it as a pure function.
[ "Check", "the", "Authorization", "of", "the", "current", "user", "for", "this", "region", "and", "this", "API", ".", "If", "abort", "is", "True", "the", "request", "is", "aborted", "with", "the", "appropriate", "HTTP", "code", ".", "Warning", ":", "Please", "this", "function", "is", "cached", "therefore", "it", "should", "not", "be", "dependent", "of", "the", "request", "context", "so", "keep", "it", "as", "a", "pure", "function", "." ]
def has_access(region, api, abort, user): """ Check the Authorization of the current user for this region and this API. If abort is True, the request is aborted with the appropriate HTTP code. Warning: Please this function is cached therefore it should not be dependent of the request context, so keep it as a pure function. """ # if jormungandr is on public mode or database is not accessible, we skip the authentication process if current_app.config.get('PUBLIC', False) or (not can_connect_to_database()): return True if not user: # no user --> no need to continue, we can abort, a user is mandatory even for free region # To manage database error of the following type we should fetch one more time from database # Can connect to database but at least one table/attribute is not accessible due to transaction problem if can_read_user(): abort_request(user=user) else: return True try: model_instance = Instance.get_by_name(region) except Exception as e: logging.getLogger(__name__).error('No access to table Instance (error: {})'.format(e)) g.can_connect_to_database = False return True if not model_instance: if abort: raise RegionNotFound(region) return False if (model_instance.is_free and user.have_access_to_free_instances) or user.has_access( model_instance.id, api ): return True else: if abort: abort_request(user=user) else: return False
[ "def", "has_access", "(", "region", ",", "api", ",", "abort", ",", "user", ")", ":", "# if jormungandr is on public mode or database is not accessible, we skip the authentication process", "if", "current_app", ".", "config", ".", "get", "(", "'PUBLIC'", ",", "False", ")", "or", "(", "not", "can_connect_to_database", "(", ")", ")", ":", "return", "True", "if", "not", "user", ":", "# no user --> no need to continue, we can abort, a user is mandatory even for free region", "# To manage database error of the following type we should fetch one more time from database", "# Can connect to database but at least one table/attribute is not accessible due to transaction problem", "if", "can_read_user", "(", ")", ":", "abort_request", "(", "user", "=", "user", ")", "else", ":", "return", "True", "try", ":", "model_instance", "=", "Instance", ".", "get_by_name", "(", "region", ")", "except", "Exception", "as", "e", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "error", "(", "'No access to table Instance (error: {})'", ".", "format", "(", "e", ")", ")", "g", ".", "can_connect_to_database", "=", "False", "return", "True", "if", "not", "model_instance", ":", "if", "abort", ":", "raise", "RegionNotFound", "(", "region", ")", "return", "False", "if", "(", "model_instance", ".", "is_free", "and", "user", ".", "have_access_to_free_instances", ")", "or", "user", ".", "has_access", "(", "model_instance", ".", "id", ",", "api", ")", ":", "return", "True", "else", ":", "if", "abort", ":", "abort_request", "(", "user", "=", "user", ")", "else", ":", "return", "False" ]
https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/jormungandr/jormungandr/authentication.py#L131-L170
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
chrome/common/extensions/docs/examples/apps/hello-python/oauth2/__init__.py
python
generate_timestamp
()
return int(time.time())
Get seconds since epoch (UTC).
Get seconds since epoch (UTC).
[ "Get", "seconds", "since", "epoch", "(", "UTC", ")", "." ]
def generate_timestamp(): """Get seconds since epoch (UTC).""" return int(time.time())
[ "def", "generate_timestamp", "(", ")", ":", "return", "int", "(", "time", ".", "time", "(", ")", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/examples/apps/hello-python/oauth2/__init__.py#L89-L91
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py
python
splitdoc
(doc)
return '', '\n'.join(lines)
Split a doc string into a synopsis line (if any) and the rest.
Split a doc string into a synopsis line (if any) and the rest.
[ "Split", "a", "doc", "string", "into", "a", "synopsis", "line", "(", "if", "any", ")", "and", "the", "rest", "." ]
def splitdoc(doc): """Split a doc string into a synopsis line (if any) and the rest.""" lines = doc.strip().split('\n') if len(lines) == 1: return lines[0], '' elif len(lines) >= 2 and not lines[1].rstrip(): return lines[0], '\n'.join(lines[2:]) return '', '\n'.join(lines)
[ "def", "splitdoc", "(", "doc", ")", ":", "lines", "=", "doc", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "if", "len", "(", "lines", ")", "==", "1", ":", "return", "lines", "[", "0", "]", ",", "''", "elif", "len", "(", "lines", ")", ">=", "2", "and", "not", "lines", "[", "1", "]", ".", "rstrip", "(", ")", ":", "return", "lines", "[", "0", "]", ",", "'\\n'", ".", "join", "(", "lines", "[", "2", ":", "]", ")", "return", "''", ",", "'\\n'", ".", "join", "(", "lines", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py#L98-L105
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.SetHotspotSingleLine
(*args, **kwargs)
return _stc.StyledTextCtrl_SetHotspotSingleLine(*args, **kwargs)
SetHotspotSingleLine(self, bool singleLine) Limit hotspots to single line so hotspots on two lines don't merge.
SetHotspotSingleLine(self, bool singleLine)
[ "SetHotspotSingleLine", "(", "self", "bool", "singleLine", ")" ]
def SetHotspotSingleLine(*args, **kwargs): """ SetHotspotSingleLine(self, bool singleLine) Limit hotspots to single line so hotspots on two lines don't merge. """ return _stc.StyledTextCtrl_SetHotspotSingleLine(*args, **kwargs)
[ "def", "SetHotspotSingleLine", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetHotspotSingleLine", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L5264-L5270
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
JoystickEvent.__init__
(self, *args, **kwargs)
__init__(self, EventType type=wxEVT_NULL, int state=0, int joystick=JOYSTICK1, int change=0) -> JoystickEvent
__init__(self, EventType type=wxEVT_NULL, int state=0, int joystick=JOYSTICK1, int change=0) -> JoystickEvent
[ "__init__", "(", "self", "EventType", "type", "=", "wxEVT_NULL", "int", "state", "=", "0", "int", "joystick", "=", "JOYSTICK1", "int", "change", "=", "0", ")", "-", ">", "JoystickEvent" ]
def __init__(self, *args, **kwargs): """ __init__(self, EventType type=wxEVT_NULL, int state=0, int joystick=JOYSTICK1, int change=0) -> JoystickEvent """ _misc_.JoystickEvent_swiginit(self,_misc_.new_JoystickEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_misc_", ".", "JoystickEvent_swiginit", "(", "self", ",", "_misc_", ".", "new_JoystickEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L2336-L2341
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/maximal-network-rank.py
python
Solution2.maximalNetworkRank
(self, n, roads)
return result
:type n: int :type roads: List[List[int]] :rtype: int
:type n: int :type roads: List[List[int]] :rtype: int
[ ":", "type", "n", ":", "int", ":", "type", "roads", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "int" ]
def maximalNetworkRank(self, n, roads): """ :type n: int :type roads: List[List[int]] :rtype: int """ degree = [0]*n adj = collections.defaultdict(set) for a, b in roads: degree[a] += 1 degree[b] += 1 adj[a].add(b) adj[b].add(a) sorted_idx = range(n) sorted_idx.sort(key=lambda x:-degree[x]) m = 2 while m < n: if degree[sorted_idx[m]] != degree[sorted_idx[1]]: break m += 1 result = degree[sorted_idx[0]] + degree[sorted_idx[1]] - 1 # at least sum(top2 values) - 1 for i in xrange(m-1): # only need to check pairs of top2 values for j in xrange(i+1, m): if degree[sorted_idx[i]]+degree[sorted_idx[j]]-int(sorted_idx[i] in adj and sorted_idx[j] in adj[sorted_idx[i]]) > result: # if equal to ideal sum of top2 values, break return degree[sorted_idx[i]]+degree[sorted_idx[j]]-int(sorted_idx[i] in adj and sorted_idx[j] in adj[sorted_idx[i]]) return result
[ "def", "maximalNetworkRank", "(", "self", ",", "n", ",", "roads", ")", ":", "degree", "=", "[", "0", "]", "*", "n", "adj", "=", "collections", ".", "defaultdict", "(", "set", ")", "for", "a", ",", "b", "in", "roads", ":", "degree", "[", "a", "]", "+=", "1", "degree", "[", "b", "]", "+=", "1", "adj", "[", "a", "]", ".", "add", "(", "b", ")", "adj", "[", "b", "]", ".", "add", "(", "a", ")", "sorted_idx", "=", "range", "(", "n", ")", "sorted_idx", ".", "sort", "(", "key", "=", "lambda", "x", ":", "-", "degree", "[", "x", "]", ")", "m", "=", "2", "while", "m", "<", "n", ":", "if", "degree", "[", "sorted_idx", "[", "m", "]", "]", "!=", "degree", "[", "sorted_idx", "[", "1", "]", "]", ":", "break", "m", "+=", "1", "result", "=", "degree", "[", "sorted_idx", "[", "0", "]", "]", "+", "degree", "[", "sorted_idx", "[", "1", "]", "]", "-", "1", "# at least sum(top2 values) - 1", "for", "i", "in", "xrange", "(", "m", "-", "1", ")", ":", "# only need to check pairs of top2 values", "for", "j", "in", "xrange", "(", "i", "+", "1", ",", "m", ")", ":", "if", "degree", "[", "sorted_idx", "[", "i", "]", "]", "+", "degree", "[", "sorted_idx", "[", "j", "]", "]", "-", "int", "(", "sorted_idx", "[", "i", "]", "in", "adj", "and", "sorted_idx", "[", "j", "]", "in", "adj", "[", "sorted_idx", "[", "i", "]", "]", ")", ">", "result", ":", "# if equal to ideal sum of top2 values, break", "return", "degree", "[", "sorted_idx", "[", "i", "]", "]", "+", "degree", "[", "sorted_idx", "[", "j", "]", "]", "-", "int", "(", "sorted_idx", "[", "i", "]", "in", "adj", "and", "sorted_idx", "[", "j", "]", "in", "adj", "[", "sorted_idx", "[", "i", "]", "]", ")", "return", "result" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximal-network-rank.py#L60-L85
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py
python
CompoundKernel.theta
(self)
return np.hstack([kernel.theta for kernel in self.kernels])
Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel's hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns ------- theta : array, shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel
Returns the (flattened, log-transformed) non-fixed hyperparameters.
[ "Returns", "the", "(", "flattened", "log", "-", "transformed", ")", "non", "-", "fixed", "hyperparameters", "." ]
def theta(self): """Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel's hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns ------- theta : array, shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel """ return np.hstack([kernel.theta for kernel in self.kernels])
[ "def", "theta", "(", "self", ")", ":", "return", "np", ".", "hstack", "(", "[", "kernel", ".", "theta", "for", "kernel", "in", "self", ".", "kernels", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py#L420-L433
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py
python
XCObject.Copy
(self)
return that
Make a copy of this object. The new object will have its own copy of lists and dicts. Any XCObject objects owned by this object (marked "strong") will be copied in the new object, even those found in lists. If this object has any weak references to other XCObjects, the same references are added to the new object without making a copy.
Make a copy of this object.
[ "Make", "a", "copy", "of", "this", "object", "." ]
def Copy(self): """Make a copy of this object. The new object will have its own copy of lists and dicts. Any XCObject objects owned by this object (marked "strong") will be copied in the new object, even those found in lists. If this object has any weak references to other XCObjects, the same references are added to the new object without making a copy. """ that = self.__class__(id=self.id, parent=self.parent) for key, value in self._properties.iteritems(): is_strong = self._schema[key][2] if isinstance(value, XCObject): if is_strong: new_value = value.Copy() new_value.parent = that that._properties[key] = new_value else: that._properties[key] = value elif isinstance(value, str) or isinstance(value, unicode) or \ isinstance(value, int): that._properties[key] = value elif isinstance(value, list): if is_strong: # If is_strong is True, each element is an XCObject, so it's safe to # call Copy. that._properties[key] = [] for item in value: new_item = item.Copy() new_item.parent = that that._properties[key].append(new_item) else: that._properties[key] = value[:] elif isinstance(value, dict): # dicts are never strong. if is_strong: raise TypeError('Strong dict for key ' + key + ' in ' + \ self.__class__.__name__) else: that._properties[key] = value.copy() else: raise TypeError('Unexpected type ' + value.__class__.__name__ + \ ' for key ' + key + ' in ' + self.__class__.__name__) return that
[ "def", "Copy", "(", "self", ")", ":", "that", "=", "self", ".", "__class__", "(", "id", "=", "self", ".", "id", ",", "parent", "=", "self", ".", "parent", ")", "for", "key", ",", "value", "in", "self", ".", "_properties", ".", "iteritems", "(", ")", ":", "is_strong", "=", "self", ".", "_schema", "[", "key", "]", "[", "2", "]", "if", "isinstance", "(", "value", ",", "XCObject", ")", ":", "if", "is_strong", ":", "new_value", "=", "value", ".", "Copy", "(", ")", "new_value", ".", "parent", "=", "that", "that", ".", "_properties", "[", "key", "]", "=", "new_value", "else", ":", "that", ".", "_properties", "[", "key", "]", "=", "value", "elif", "isinstance", "(", "value", ",", "str", ")", "or", "isinstance", "(", "value", ",", "unicode", ")", "or", "isinstance", "(", "value", ",", "int", ")", ":", "that", ".", "_properties", "[", "key", "]", "=", "value", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "if", "is_strong", ":", "# If is_strong is True, each element is an XCObject, so it's safe to", "# call Copy.", "that", ".", "_properties", "[", "key", "]", "=", "[", "]", "for", "item", "in", "value", ":", "new_item", "=", "item", ".", "Copy", "(", ")", "new_item", ".", "parent", "=", "that", "that", ".", "_properties", "[", "key", "]", ".", "append", "(", "new_item", ")", "else", ":", "that", ".", "_properties", "[", "key", "]", "=", "value", "[", ":", "]", "elif", "isinstance", "(", "value", ",", "dict", ")", ":", "# dicts are never strong.", "if", "is_strong", ":", "raise", "TypeError", "(", "'Strong dict for key '", "+", "key", "+", "' in '", "+", "self", ".", "__class__", ".", "__name__", ")", "else", ":", "that", ".", "_properties", "[", "key", "]", "=", "value", ".", "copy", "(", ")", "else", ":", "raise", "TypeError", "(", "'Unexpected type '", "+", "value", ".", "__class__", ".", "__name__", "+", "' for key '", "+", "key", "+", "' in '", "+", "self", ".", "__class__", ".", "__name__", ")", "return", "that" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L306-L352
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/abc.py
python
SourceLoader.set_data
(self, path, data)
Write the bytes to the path (if possible). Accepts a str path and data as bytes. Any needed intermediary directories are to be created. If for some reason the file cannot be written because of permissions, fail silently.
Write the bytes to the path (if possible).
[ "Write", "the", "bytes", "to", "the", "path", "(", "if", "possible", ")", "." ]
def set_data(self, path, data): """Write the bytes to the path (if possible). Accepts a str path and data as bytes. Any needed intermediary directories are to be created. If for some reason the file cannot be written because of permissions, fail silently. """
[ "def", "set_data", "(", "self", ",", "path", ",", "data", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/abc.py#L332-L340
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/autograd.py
python
_parse_head
(heads, head_grads)
return head_handles, hgrad_handles
parse head gradient for backward and grad.
parse head gradient for backward and grad.
[ "parse", "head", "gradient", "for", "backward", "and", "grad", "." ]
def _parse_head(heads, head_grads): """parse head gradient for backward and grad.""" if isinstance(heads, NDArray): heads = [heads] if isinstance(head_grads, NDArray): head_grads = [head_grads] head_handles = c_handle_array(heads) if head_grads is None: hgrad_handles = ctypes.c_void_p(0) else: msg = "heads and head_grads must be lists of the same length: {} vs. {}" assert len(heads) == len(head_grads), msg.format(len(heads), len(head_grads)) hgrad_handles = c_array(NDArrayHandle, [i.handle if i is not None else NDArrayHandle(0) for i in head_grads]) return head_handles, hgrad_handles
[ "def", "_parse_head", "(", "heads", ",", "head_grads", ")", ":", "if", "isinstance", "(", "heads", ",", "NDArray", ")", ":", "heads", "=", "[", "heads", "]", "if", "isinstance", "(", "head_grads", ",", "NDArray", ")", ":", "head_grads", "=", "[", "head_grads", "]", "head_handles", "=", "c_handle_array", "(", "heads", ")", "if", "head_grads", "is", "None", ":", "hgrad_handles", "=", "ctypes", ".", "c_void_p", "(", "0", ")", "else", ":", "msg", "=", "\"heads and head_grads must be lists of the same length: {} vs. {}\"", "assert", "len", "(", "heads", ")", "==", "len", "(", "head_grads", ")", ",", "msg", ".", "format", "(", "len", "(", "heads", ")", ",", "len", "(", "head_grads", ")", ")", "hgrad_handles", "=", "c_array", "(", "NDArrayHandle", ",", "[", "i", ".", "handle", "if", "i", "is", "not", "None", "else", "NDArrayHandle", "(", "0", ")", "for", "i", "in", "head_grads", "]", ")", "return", "head_handles", ",", "hgrad_handles" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/autograd.py#L225-L242
ucbrise/confluo
578883a4f7fbbb4aea78c342d366f5122ef598f7
pyclient/confluo/rpc/rpc_service.py
python
Iface.predef_filter
(self, mid, filter_id, beg_ms, end_ms)
Parameters: - mid - filter_id - beg_ms - end_ms
Parameters: - mid - filter_id - beg_ms - end_ms
[ "Parameters", ":", "-", "mid", "-", "filter_id", "-", "beg_ms", "-", "end_ms" ]
def predef_filter(self, mid, filter_id, beg_ms, end_ms): """ Parameters: - mid - filter_id - beg_ms - end_ms """ pass
[ "def", "predef_filter", "(", "self", ",", "mid", ",", "filter_id", ",", "beg_ms", ",", "end_ms", ")", ":", "pass" ]
https://github.com/ucbrise/confluo/blob/578883a4f7fbbb4aea78c342d366f5122ef598f7/pyclient/confluo/rpc/rpc_service.py#L212-L221
netease-youdao/hex
d7b8773dae8dde63f3807cef1d48c017077db727
tools/svn_util.py
python
get_svn_info
(path)
return {'url': url, 'revision': rev}
Retrieves the URL and revision from svn info.
Retrieves the URL and revision from svn info.
[ "Retrieves", "the", "URL", "and", "revision", "from", "svn", "info", "." ]
def get_svn_info(path): """ Retrieves the URL and revision from svn info. """ url = 'None' rev = 'None' if path[0:4] == 'http' or os.path.exists(path): try: stream = os.popen('svn info '+path) for line in stream: if line[0:4] == "URL:": url = check_url(line[5:-1]) elif line[0:9] == "Revision:": rev = str(int(line[10:-1])) except IOError, (errno, strerror): sys.stderr.write('Failed to read svn info: '+strerror+"\n") raise return {'url': url, 'revision': rev}
[ "def", "get_svn_info", "(", "path", ")", ":", "url", "=", "'None'", "rev", "=", "'None'", "if", "path", "[", "0", ":", "4", "]", "==", "'http'", "or", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "try", ":", "stream", "=", "os", ".", "popen", "(", "'svn info '", "+", "path", ")", "for", "line", "in", "stream", ":", "if", "line", "[", "0", ":", "4", "]", "==", "\"URL:\"", ":", "url", "=", "check_url", "(", "line", "[", "5", ":", "-", "1", "]", ")", "elif", "line", "[", "0", ":", "9", "]", "==", "\"Revision:\"", ":", "rev", "=", "str", "(", "int", "(", "line", "[", "10", ":", "-", "1", "]", ")", ")", "except", "IOError", ",", "(", "errno", ",", "strerror", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Failed to read svn info: '", "+", "strerror", "+", "\"\\n\"", ")", "raise", "return", "{", "'url'", ":", "url", ",", "'revision'", ":", "rev", "}" ]
https://github.com/netease-youdao/hex/blob/d7b8773dae8dde63f3807cef1d48c017077db727/tools/svn_util.py#L19-L34
vicaya/hypertable
e7386f799c238c109ae47973417c2a2c7f750825
src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py
python
Client.open_scanner
(self, name, scan_spec, retry_table_not_found)
return self.recv_open_scanner()
Open a table scanner @param name - table name @param scan_spec - scan specification @param retry_table_not_found - whether to retry upon errors caused by drop/create tables with the same name Parameters: - name - scan_spec - retry_table_not_found
Open a table scanner
[ "Open", "a", "table", "scanner" ]
def open_scanner(self, name, scan_spec, retry_table_not_found): """ Open a table scanner @param name - table name @param scan_spec - scan specification @param retry_table_not_found - whether to retry upon errors caused by drop/create tables with the same name Parameters: - name - scan_spec - retry_table_not_found """ self.send_open_scanner(name, scan_spec, retry_table_not_found) return self.recv_open_scanner()
[ "def", "open_scanner", "(", "self", ",", "name", ",", "scan_spec", ",", "retry_table_not_found", ")", ":", "self", ".", "send_open_scanner", "(", "name", ",", "scan_spec", ",", "retry_table_not_found", ")", "return", "self", ".", "recv_open_scanner", "(", ")" ]
https://github.com/vicaya/hypertable/blob/e7386f799c238c109ae47973417c2a2c7f750825/src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py#L363-L380
baidu/AnyQ
d94d450d2aaa5f7ed73424b10aa4539835b97527
tools/simnet/train/tf/layers/tf_layers.py
python
SoftsignLayer.__init__
(self)
init function
init function
[ "init", "function" ]
def __init__(self): """ init function """ pass
[ "def", "__init__", "(", "self", ")", ":", "pass" ]
https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/simnet/train/tf/layers/tf_layers.py#L343-L347
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
prj/app/lib/util/xml.py
python
single_text_child
(element)
return element.childNodes[0].data
Return the text contents of an element, assuming that the element contains a single text node. Zero-length child nodes are also supported, for example: <foo> </foo> -> returns string ' ' <foo></foo> -> returns string '' <foo/> -> returns string '' An exception is raised if these assumption are not true.
Return the text contents of an element, assuming that the element contains a single text node.
[ "Return", "the", "text", "contents", "of", "an", "element", "assuming", "that", "the", "element", "contains", "a", "single", "text", "node", "." ]
def single_text_child(element): """Return the text contents of an element, assuming that the element contains a single text node. Zero-length child nodes are also supported, for example: <foo> </foo> -> returns string ' ' <foo></foo> -> returns string '' <foo/> -> returns string '' An exception is raised if these assumption are not true. """ if not element.childNodes: return '' if len(element.childNodes) != 1 or element.childNodes[0].nodeType != element.TEXT_NODE: error_msg = xml_error_str(element, "expect a single text node as element child.") raise SystemParseError(error_msg) return element.childNodes[0].data
[ "def", "single_text_child", "(", "element", ")", ":", "if", "not", "element", ".", "childNodes", ":", "return", "''", "if", "len", "(", "element", ".", "childNodes", ")", "!=", "1", "or", "element", ".", "childNodes", "[", "0", "]", ".", "nodeType", "!=", "element", ".", "TEXT_NODE", ":", "error_msg", "=", "xml_error_str", "(", "element", ",", "\"expect a single text node as element child.\"", ")", "raise", "SystemParseError", "(", "error_msg", ")", "return", "element", ".", "childNodes", "[", "0", "]", ".", "data" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/prj/app/lib/util/xml.py#L200-L219
LLNL/lbann
26083e6c86050302ce33148aea70f62e61cacb92
python/lbann/plot/plot.py
python
_get_time_axis
(time_list, units='hours')
return time_axis
Convert time to sequential format and convert time units.
Convert time to sequential format and convert time units.
[ "Convert", "time", "to", "sequential", "format", "and", "convert", "time", "units", "." ]
def _get_time_axis(time_list, units='hours'): """Convert time to sequential format and convert time units.""" time_axis = [] for i in range(len(time_list)): time_sum = sum(time_list[:i]) if units == 'seconds': pass elif units == 'minutes': time_sum /= 60.0 elif units == 'hours': time_sum /= 3600.0 time_axis.append(time_sum) return time_axis
[ "def", "_get_time_axis", "(", "time_list", ",", "units", "=", "'hours'", ")", ":", "time_axis", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "time_list", ")", ")", ":", "time_sum", "=", "sum", "(", "time_list", "[", ":", "i", "]", ")", "if", "units", "==", "'seconds'", ":", "pass", "elif", "units", "==", "'minutes'", ":", "time_sum", "/=", "60.0", "elif", "units", "==", "'hours'", ":", "time_sum", "/=", "3600.0", "time_axis", ".", "append", "(", "time_sum", ")", "return", "time_axis" ]
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/python/lbann/plot/plot.py#L14-L26
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/sparse/construct.py
python
spdiags
(data, diags, m, n, format=None)
return dia_matrix((data, diags), shape=(m,n)).asformat(format)
Return a sparse matrix from diagonals. Parameters ---------- data : array_like matrix diagonals stored row-wise diags : diagonals to set - k = 0 the main diagonal - k > 0 the k-th upper diagonal - k < 0 the k-th lower diagonal m, n : int shape of the result format : str, optional Format of the result. By default (format=None) an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- diags : more convenient form of this function dia_matrix : the sparse DIAgonal format. Examples -------- >>> from scipy.sparse import spdiags >>> data = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) >>> diags = np.array([0, -1, 2]) >>> spdiags(data, diags, 4, 4).toarray() array([[1, 0, 3, 0], [1, 2, 0, 4], [0, 2, 3, 0], [0, 0, 3, 4]])
Return a sparse matrix from diagonals.
[ "Return", "a", "sparse", "matrix", "from", "diagonals", "." ]
def spdiags(data, diags, m, n, format=None): """ Return a sparse matrix from diagonals. Parameters ---------- data : array_like matrix diagonals stored row-wise diags : diagonals to set - k = 0 the main diagonal - k > 0 the k-th upper diagonal - k < 0 the k-th lower diagonal m, n : int shape of the result format : str, optional Format of the result. By default (format=None) an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- diags : more convenient form of this function dia_matrix : the sparse DIAgonal format. Examples -------- >>> from scipy.sparse import spdiags >>> data = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) >>> diags = np.array([0, -1, 2]) >>> spdiags(data, diags, 4, 4).toarray() array([[1, 0, 3, 0], [1, 2, 0, 4], [0, 2, 3, 0], [0, 0, 3, 4]]) """ return dia_matrix((data, diags), shape=(m,n)).asformat(format)
[ "def", "spdiags", "(", "data", ",", "diags", ",", "m", ",", "n", ",", "format", "=", "None", ")", ":", "return", "dia_matrix", "(", "(", "data", ",", "diags", ")", ",", "shape", "=", "(", "m", ",", "n", ")", ")", ".", "asformat", "(", "format", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/construct.py#L27-L62
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Image_HSVtoRGB
(*args, **kwargs)
return _core_.Image_HSVtoRGB(*args, **kwargs)
Image_HSVtoRGB(Image_HSVValue hsv) -> Image_RGBValue Converts a color in HSV color space to RGB color space.
Image_HSVtoRGB(Image_HSVValue hsv) -> Image_RGBValue
[ "Image_HSVtoRGB", "(", "Image_HSVValue", "hsv", ")", "-", ">", "Image_RGBValue" ]
def Image_HSVtoRGB(*args, **kwargs): """ Image_HSVtoRGB(Image_HSVValue hsv) -> Image_RGBValue Converts a color in HSV color space to RGB color space. """ return _core_.Image_HSVtoRGB(*args, **kwargs)
[ "def", "Image_HSVtoRGB", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_HSVtoRGB", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L3838-L3844
facebookresearch/ELF
1f790173095cd910976d9f651b80beb872ec5d12
vendor/pybind11/tools/clang/cindex.py
python
Cursor.get_tokens
(self)
return TokenGroup.get_tokens(self._tu, self.extent)
Obtain Token instances formulating that compose this Cursor. This is a generator for Token instances. It returns all tokens which occupy the extent this cursor occupies.
Obtain Token instances formulating that compose this Cursor.
[ "Obtain", "Token", "instances", "formulating", "that", "compose", "this", "Cursor", "." ]
def get_tokens(self): """Obtain Token instances formulating that compose this Cursor. This is a generator for Token instances. It returns all tokens which occupy the extent this cursor occupies. """ return TokenGroup.get_tokens(self._tu, self.extent)
[ "def", "get_tokens", "(", "self", ")", ":", "return", "TokenGroup", ".", "get_tokens", "(", "self", ".", "_tu", ",", "self", ".", "extent", ")" ]
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/vendor/pybind11/tools/clang/cindex.py#L1671-L1677
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
ci/detect-changes.py
python
get_windows_shell_eval
(env)
return "\n".join(('set "{0}={1}"'.format(k, v) for k, v in env.items()))
Return a shell-evalable string to setup some environment variables.
Return a shell-evalable string to setup some environment variables.
[ "Return", "a", "shell", "-", "evalable", "string", "to", "setup", "some", "environment", "variables", "." ]
def get_windows_shell_eval(env): """ Return a shell-evalable string to setup some environment variables. """ return "\n".join(('set "{0}={1}"'.format(k, v) for k, v in env.items()))
[ "def", "get_windows_shell_eval", "(", "env", ")", ":", "return", "\"\\n\"", ".", "join", "(", "(", "'set \"{0}={1}\"'", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "env", ".", "items", "(", ")", ")", ")" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/ci/detect-changes.py#L219-L224
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/sched.py
python
scheduler.enterabs
(self, time, priority, action, argument)
return event
Enter a new event in the queue at an absolute time. Returns an ID for the event which can be used to remove it, if necessary.
Enter a new event in the queue at an absolute time.
[ "Enter", "a", "new", "event", "in", "the", "queue", "at", "an", "absolute", "time", "." ]
def enterabs(self, time, priority, action, argument): """Enter a new event in the queue at an absolute time. Returns an ID for the event which can be used to remove it, if necessary. """ event = Event(time, priority, action, argument) heapq.heappush(self._queue, event) return event
[ "def", "enterabs", "(", "self", ",", "time", ",", "priority", ",", "action", ",", "argument", ")", ":", "event", "=", "Event", "(", "time", ",", "priority", ",", "action", ",", "argument", ")", "heapq", ".", "heappush", "(", "self", ".", "_queue", ",", "event", ")", "return", "event" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/sched.py#L46-L55
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
demo/Main.py
python
LookForExternals
(externalDemos, demoName)
return pkg, overview
Checks if a demo name is in any of the external packages (like AGW) or if the user clicked on one of the external packages parent items in the tree, in which case it returns the html overview for the package.
Checks if a demo name is in any of the external packages (like AGW) or if the user clicked on one of the external packages parent items in the tree, in which case it returns the html overview for the package.
[ "Checks", "if", "a", "demo", "name", "is", "in", "any", "of", "the", "external", "packages", "(", "like", "AGW", ")", "or", "if", "the", "user", "clicked", "on", "one", "of", "the", "external", "packages", "parent", "items", "in", "the", "tree", "in", "which", "case", "it", "returns", "the", "html", "overview", "for", "the", "package", "." ]
def LookForExternals(externalDemos, demoName): """ Checks if a demo name is in any of the external packages (like AGW) or if the user clicked on one of the external packages parent items in the tree, in which case it returns the html overview for the package. """ pkg = overview = None # Loop over all the external demos for key, package in externalDemos.items(): # Get the tree item name for the package and its demos treeName, treeDemos = package.GetDemos() # Get the overview for the package treeOverview = package.GetOverview() if treeName == demoName: # The user clicked on the parent tree item, return the overview return pkg, treeOverview elif demoName in treeDemos: # The user clicked on a real demo, return the package return key, overview # No match found, return None for both return pkg, overview
[ "def", "LookForExternals", "(", "externalDemos", ",", "demoName", ")", ":", "pkg", "=", "overview", "=", "None", "# Loop over all the external demos", "for", "key", ",", "package", "in", "externalDemos", ".", "items", "(", ")", ":", "# Get the tree item name for the package and its demos", "treeName", ",", "treeDemos", "=", "package", ".", "GetDemos", "(", ")", "# Get the overview for the package", "treeOverview", "=", "package", ".", "GetOverview", "(", ")", "if", "treeName", "==", "demoName", ":", "# The user clicked on the parent tree item, return the overview", "return", "pkg", ",", "treeOverview", "elif", "demoName", "in", "treeDemos", ":", "# The user clicked on a real demo, return the package", "return", "key", ",", "overview", "# No match found, return None for both", "return", "pkg", ",", "overview" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/demo/Main.py#L1257-L1279
axw/cmonster
4bb5131add306abdd0481488764d8949ca7114d3
lib/cmonster/_preprocessor.py
python
Preprocessor
(*args, **kwargs)
return parser.preprocessor
Convenience function for creating a Parser and returning its Preprocessor.
Convenience function for creating a Parser and returning its Preprocessor.
[ "Convenience", "function", "for", "creating", "a", "Parser", "and", "returning", "its", "Preprocessor", "." ]
def Preprocessor(*args, **kwargs): """ Convenience function for creating a Parser and returning its Preprocessor. """ from ._parser import Parser parser = Parser(*args, **kwargs) return parser.preprocessor
[ "def", "Preprocessor", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", ".", "_parser", "import", "Parser", "parser", "=", "Parser", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "parser", ".", "preprocessor" ]
https://github.com/axw/cmonster/blob/4bb5131add306abdd0481488764d8949ca7114d3/lib/cmonster/_preprocessor.py#L54-L61
syoyo/tinygltf
e7f1ff5c59d3ca2489923beb239bdf93d863498f
deps/cpplint.py
python
_BlockInfo.IsBlockInfo
(self)
return self.__class__ == _BlockInfo
Returns true if this block is a _BlockInfo. This is convenient for verifying that an object is an instance of a _BlockInfo, but not an instance of any of the derived classes. Returns: True for this class, False for derived classes.
Returns true if this block is a _BlockInfo.
[ "Returns", "true", "if", "this", "block", "is", "a", "_BlockInfo", "." ]
def IsBlockInfo(self): """Returns true if this block is a _BlockInfo. This is convenient for verifying that an object is an instance of a _BlockInfo, but not an instance of any of the derived classes. Returns: True for this class, False for derived classes. """ return self.__class__ == _BlockInfo
[ "def", "IsBlockInfo", "(", "self", ")", ":", "return", "self", ".", "__class__", "==", "_BlockInfo" ]
https://github.com/syoyo/tinygltf/blob/e7f1ff5c59d3ca2489923beb239bdf93d863498f/deps/cpplint.py#L2034-L2043
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
lldb/examples/python/file_extract.py
python
FileExtract.set_byte_order
(self, b)
Set the byte order, valid values are "big", "little", "swap", "native", "<", ">", "@", "="
Set the byte order, valid values are "big", "little", "swap", "native", "<", ">", "
[ "Set", "the", "byte", "order", "valid", "values", "are", "big", "little", "swap", "native", "<", ">" ]
def set_byte_order(self, b): '''Set the byte order, valid values are "big", "little", "swap", "native", "<", ">", "@", "="''' if b == 'big': self.byte_order = '>' elif b == 'little': self.byte_order = '<' elif b == 'swap': # swap what ever the current byte order is self.byte_order = swap_unpack_char() elif b == 'native': self.byte_order = '=' elif b == '<' or b == '>' or b == '@' or b == '=': self.byte_order = b else: print("error: invalid byte order specified: '%s'" % b)
[ "def", "set_byte_order", "(", "self", ",", "b", ")", ":", "if", "b", "==", "'big'", ":", "self", ".", "byte_order", "=", "'>'", "elif", "b", "==", "'little'", ":", "self", ".", "byte_order", "=", "'<'", "elif", "b", "==", "'swap'", ":", "# swap what ever the current byte order is", "self", ".", "byte_order", "=", "swap_unpack_char", "(", ")", "elif", "b", "==", "'native'", ":", "self", ".", "byte_order", "=", "'='", "elif", "b", "==", "'<'", "or", "b", "==", "'>'", "or", "b", "==", "'@'", "or", "b", "==", "'='", ":", "self", ".", "byte_order", "=", "b", "else", ":", "print", "(", "\"error: invalid byte order specified: '%s'\"", "%", "b", ")" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/examples/python/file_extract.py#L18-L32
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Node.py
python
Node.relpath
(self)
return self.srcpath()
If a file in the build directory, bldpath, else srcpath
If a file in the build directory, bldpath, else srcpath
[ "If", "a", "file", "in", "the", "build", "directory", "bldpath", "else", "srcpath" ]
def relpath(self): "If a file in the build directory, bldpath, else srcpath" cur = self x = id(self.ctx.bldnode) while cur.parent: if id(cur) == x: return self.bldpath() cur = cur.parent return self.srcpath()
[ "def", "relpath", "(", "self", ")", ":", "cur", "=", "self", "x", "=", "id", "(", "self", ".", "ctx", ".", "bldnode", ")", "while", "cur", ".", "parent", ":", "if", "id", "(", "cur", ")", "==", "x", ":", "return", "self", ".", "bldpath", "(", ")", "cur", "=", "cur", ".", "parent", "return", "self", ".", "srcpath", "(", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Node.py#L774-L782
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
PNEANet.DelAttrN
(self, *args)
return _snap.PNEANet_DelAttrN(self, *args)
DelAttrN(PNEANet self, TStr attr) -> int Parameters: attr: TStr const &
DelAttrN(PNEANet self, TStr attr) -> int
[ "DelAttrN", "(", "PNEANet", "self", "TStr", "attr", ")", "-", ">", "int" ]
def DelAttrN(self, *args): """ DelAttrN(PNEANet self, TStr attr) -> int Parameters: attr: TStr const & """ return _snap.PNEANet_DelAttrN(self, *args)
[ "def", "DelAttrN", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "PNEANet_DelAttrN", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L24367-L24375
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py
python
LoggerAdapter.isEnabledFor
(self, level)
return self.logger.isEnabledFor(level)
Is this logger enabled for level 'level'?
Is this logger enabled for level 'level'?
[ "Is", "this", "logger", "enabled", "for", "level", "level", "?" ]
def isEnabledFor(self, level): """ Is this logger enabled for level 'level'? """ return self.logger.isEnabledFor(level)
[ "def", "isEnabledFor", "(", "self", ",", "level", ")", ":", "return", "self", ".", "logger", ".", "isEnabledFor", "(", "level", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py#L1768-L1772
MhLiao/TextBoxes_plusplus
39d4898de1504c53a2ed3d67966a57b3595836d0
scripts/cpp_lint.py
python
FilesBelongToSameModule
(filename_cc, filename_h)
return files_belong_to_same_module, common_path
Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file.
Check if these two filenames belong to the same module.
[ "Check", "if", "these", "two", "filenames", "belong", "to", "the", "same", "module", "." ]
def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ if not filename_cc.endswith('.cc'): return (False, '') filename_cc = filename_cc[:-len('.cc')] if filename_cc.endswith('_unittest'): filename_cc = filename_cc[:-len('_unittest')] elif filename_cc.endswith('_test'): filename_cc = filename_cc[:-len('_test')] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') if not filename_h.endswith('.h'): return (False, '') filename_h = filename_h[:-len('.h')] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path
[ "def", "FilesBelongToSameModule", "(", "filename_cc", ",", "filename_h", ")", ":", "if", "not", "filename_cc", ".", "endswith", "(", "'.cc'", ")", ":", "return", "(", "False", ",", "''", ")", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "'.cc'", ")", "]", "if", "filename_cc", ".", "endswith", "(", "'_unittest'", ")", ":", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "'_unittest'", ")", "]", "elif", "filename_cc", ".", "endswith", "(", "'_test'", ")", ":", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "'_test'", ")", "]", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "if", "not", "filename_h", ".", "endswith", "(", "'.h'", ")", ":", "return", "(", "False", ",", "''", ")", "filename_h", "=", "filename_h", "[", ":", "-", "len", "(", "'.h'", ")", "]", "if", "filename_h", ".", "endswith", "(", "'-inl'", ")", ":", "filename_h", "=", "filename_h", "[", ":", "-", "len", "(", "'-inl'", ")", "]", "filename_h", "=", "filename_h", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_h", "=", "filename_h", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "files_belong_to_same_module", "=", "filename_cc", ".", "endswith", "(", "filename_h", ")", "common_path", "=", "''", "if", "files_belong_to_same_module", ":", "common_path", "=", "filename_cc", "[", ":", "-", "len", "(", "filename_h", ")", "]", "return", "files_belong_to_same_module", ",", "common_path" ]
https://github.com/MhLiao/TextBoxes_plusplus/blob/39d4898de1504c53a2ed3d67966a57b3595836d0/scripts/cpp_lint.py#L4403-L4455
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/jinja2/ext.py
python
InternationalizationExtension.parse
(self, parser)
Parse a translatable tag.
Parse a translatable tag.
[ "Parse", "a", "translatable", "tag", "." ]
def parse(self, parser): """Parse a translatable tag.""" lineno = next(parser.stream).lineno num_called_num = False # find all the variables referenced. Additionally a variable can be # defined in the body of the trans block too, but this is checked at # a later state. plural_expr = None plural_expr_assignment = None variables = {} trimmed = None while parser.stream.current.type != 'block_end': if variables: parser.stream.expect('comma') # skip colon for python compatibility if parser.stream.skip_if('colon'): break name = parser.stream.expect('name') if name.value in variables: parser.fail('translatable variable %r defined twice.' % name.value, name.lineno, exc=TemplateAssertionError) # expressions if parser.stream.current.type == 'assign': next(parser.stream) variables[name.value] = var = parser.parse_expression() elif trimmed is None and name.value in ('trimmed', 'notrimmed'): trimmed = name.value == 'trimmed' continue else: variables[name.value] = var = nodes.Name(name.value, 'load') if plural_expr is None: if isinstance(var, nodes.Call): plural_expr = nodes.Name('_trans', 'load') variables[name.value] = plural_expr plural_expr_assignment = nodes.Assign( nodes.Name('_trans', 'store'), var) else: plural_expr = var num_called_num = name.value == 'num' parser.stream.expect('block_end') plural = None have_plural = False referenced = set() # now parse until endtrans or pluralize singular_names, singular = self._parse_block(parser, True) if singular_names: referenced.update(singular_names) if plural_expr is None: plural_expr = nodes.Name(singular_names[0], 'load') num_called_num = singular_names[0] == 'num' # if we have a pluralize block, we parse that too if parser.stream.current.test('name:pluralize'): have_plural = True next(parser.stream) if parser.stream.current.type != 'block_end': name = parser.stream.expect('name') if name.value not in variables: parser.fail('unknown variable %r for pluralization' % name.value, name.lineno, exc=TemplateAssertionError) plural_expr = variables[name.value] num_called_num = name.value == 'num' parser.stream.expect('block_end') plural_names, plural = self._parse_block(parser, False) next(parser.stream) referenced.update(plural_names) else: next(parser.stream) # register free names as simple name expressions for var in referenced: if var not in variables: variables[var] = nodes.Name(var, 'load') if not have_plural: plural_expr = None elif plural_expr is None: parser.fail('pluralize without variables', lineno) if trimmed is None: trimmed = self.environment.policies['ext.i18n.trimmed'] if trimmed: singular = self._trim_whitespace(singular) if plural: plural = self._trim_whitespace(plural) node = self._make_node(singular, plural, variables, plural_expr, bool(referenced), num_called_num and have_plural) node.set_lineno(lineno) if plural_expr_assignment is not None: return [plural_expr_assignment, node] else: return node
[ "def", "parse", "(", "self", ",", "parser", ")", ":", "lineno", "=", "next", "(", "parser", ".", "stream", ")", ".", "lineno", "num_called_num", "=", "False", "# find all the variables referenced. Additionally a variable can be", "# defined in the body of the trans block too, but this is checked at", "# a later state.", "plural_expr", "=", "None", "plural_expr_assignment", "=", "None", "variables", "=", "{", "}", "trimmed", "=", "None", "while", "parser", ".", "stream", ".", "current", ".", "type", "!=", "'block_end'", ":", "if", "variables", ":", "parser", ".", "stream", ".", "expect", "(", "'comma'", ")", "# skip colon for python compatibility", "if", "parser", ".", "stream", ".", "skip_if", "(", "'colon'", ")", ":", "break", "name", "=", "parser", ".", "stream", ".", "expect", "(", "'name'", ")", "if", "name", ".", "value", "in", "variables", ":", "parser", ".", "fail", "(", "'translatable variable %r defined twice.'", "%", "name", ".", "value", ",", "name", ".", "lineno", ",", "exc", "=", "TemplateAssertionError", ")", "# expressions", "if", "parser", ".", "stream", ".", "current", ".", "type", "==", "'assign'", ":", "next", "(", "parser", ".", "stream", ")", "variables", "[", "name", ".", "value", "]", "=", "var", "=", "parser", ".", "parse_expression", "(", ")", "elif", "trimmed", "is", "None", "and", "name", ".", "value", "in", "(", "'trimmed'", ",", "'notrimmed'", ")", ":", "trimmed", "=", "name", ".", "value", "==", "'trimmed'", "continue", "else", ":", "variables", "[", "name", ".", "value", "]", "=", "var", "=", "nodes", ".", "Name", "(", "name", ".", "value", ",", "'load'", ")", "if", "plural_expr", "is", "None", ":", "if", "isinstance", "(", "var", ",", "nodes", ".", "Call", ")", ":", "plural_expr", "=", "nodes", ".", "Name", "(", "'_trans'", ",", "'load'", ")", "variables", "[", "name", ".", "value", "]", "=", "plural_expr", "plural_expr_assignment", "=", "nodes", ".", "Assign", "(", "nodes", ".", "Name", "(", "'_trans'", ",", "'store'", ")", ",", "var", ")", "else", ":", "plural_expr", "=", "var", "num_called_num", "=", "name", ".", "value", "==", "'num'", "parser", ".", "stream", ".", "expect", "(", "'block_end'", ")", "plural", "=", "None", "have_plural", "=", "False", "referenced", "=", "set", "(", ")", "# now parse until endtrans or pluralize", "singular_names", ",", "singular", "=", "self", ".", "_parse_block", "(", "parser", ",", "True", ")", "if", "singular_names", ":", "referenced", ".", "update", "(", "singular_names", ")", "if", "plural_expr", "is", "None", ":", "plural_expr", "=", "nodes", ".", "Name", "(", "singular_names", "[", "0", "]", ",", "'load'", ")", "num_called_num", "=", "singular_names", "[", "0", "]", "==", "'num'", "# if we have a pluralize block, we parse that too", "if", "parser", ".", "stream", ".", "current", ".", "test", "(", "'name:pluralize'", ")", ":", "have_plural", "=", "True", "next", "(", "parser", ".", "stream", ")", "if", "parser", ".", "stream", ".", "current", ".", "type", "!=", "'block_end'", ":", "name", "=", "parser", ".", "stream", ".", "expect", "(", "'name'", ")", "if", "name", ".", "value", "not", "in", "variables", ":", "parser", ".", "fail", "(", "'unknown variable %r for pluralization'", "%", "name", ".", "value", ",", "name", ".", "lineno", ",", "exc", "=", "TemplateAssertionError", ")", "plural_expr", "=", "variables", "[", "name", ".", "value", "]", "num_called_num", "=", "name", ".", "value", "==", "'num'", "parser", ".", "stream", ".", "expect", "(", "'block_end'", ")", "plural_names", ",", "plural", "=", "self", ".", "_parse_block", "(", "parser", ",", "False", ")", "next", "(", "parser", ".", "stream", ")", "referenced", ".", "update", "(", "plural_names", ")", "else", ":", "next", "(", "parser", ".", "stream", ")", "# register free names as simple name expressions", "for", "var", "in", "referenced", ":", "if", "var", "not", "in", "variables", ":", "variables", "[", "var", "]", "=", "nodes", ".", "Name", "(", "var", ",", "'load'", ")", "if", "not", "have_plural", ":", "plural_expr", "=", "None", "elif", "plural_expr", "is", "None", ":", "parser", ".", "fail", "(", "'pluralize without variables'", ",", "lineno", ")", "if", "trimmed", "is", "None", ":", "trimmed", "=", "self", ".", "environment", ".", "policies", "[", "'ext.i18n.trimmed'", "]", "if", "trimmed", ":", "singular", "=", "self", ".", "_trim_whitespace", "(", "singular", ")", "if", "plural", ":", "plural", "=", "self", ".", "_trim_whitespace", "(", "plural", ")", "node", "=", "self", ".", "_make_node", "(", "singular", ",", "plural", ",", "variables", ",", "plural_expr", ",", "bool", "(", "referenced", ")", ",", "num_called_num", "and", "have_plural", ")", "node", ".", "set_lineno", "(", "lineno", ")", "if", "plural_expr_assignment", "is", "not", "None", ":", "return", "[", "plural_expr_assignment", ",", "node", "]", "else", ":", "return", "node" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/ext.py#L217-L320
nest/nest-simulator
f2623eb78518cdbd55e77e0ed486bf1111bcb62f
pynest/nest/lib/hl_api_parallel_computing.py
python
Rank
()
return spp()
Return the MPI rank of the local process. Returns ------- int: MPI rank of the local process Note ---- DO NOT USE `Rank()` TO EXECUTE ANY FUNCTION IMPORTED FROM THE `nest` MODULE ON A SUBSET OF RANKS IN AN MPI-PARALLEL SIMULATION. This will lead to unpredictable behavior. Symptoms may be an error message about non-synchronous global random number generators or deadlocks during simulation. In the worst case, the simulation may complete but generate nonsensical results.
Return the MPI rank of the local process.
[ "Return", "the", "MPI", "rank", "of", "the", "local", "process", "." ]
def Rank(): """Return the MPI rank of the local process. Returns ------- int: MPI rank of the local process Note ---- DO NOT USE `Rank()` TO EXECUTE ANY FUNCTION IMPORTED FROM THE `nest` MODULE ON A SUBSET OF RANKS IN AN MPI-PARALLEL SIMULATION. This will lead to unpredictable behavior. Symptoms may be an error message about non-synchronous global random number generators or deadlocks during simulation. In the worst case, the simulation may complete but generate nonsensical results. """ sr("Rank") return spp()
[ "def", "Rank", "(", ")", ":", "sr", "(", "\"Rank\"", ")", "return", "spp", "(", ")" ]
https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/nest/lib/hl_api_parallel_computing.py#L40-L60
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_grad/grad_array_ops.py
python
get_bprop_select
(self)
return bprop
Generate bprop for Select
Generate bprop for Select
[ "Generate", "bprop", "for", "Select" ]
def get_bprop_select(self): """Generate bprop for Select""" select = P.Select() def bprop(cond, x, y, out, dout): return zeros_like(cond), select(cond, dout, zeros_like(x)), select(cond, zeros_like(y), dout) return bprop
[ "def", "get_bprop_select", "(", "self", ")", ":", "select", "=", "P", ".", "Select", "(", ")", "def", "bprop", "(", "cond", ",", "x", ",", "y", ",", "out", ",", "dout", ")", ":", "return", "zeros_like", "(", "cond", ")", ",", "select", "(", "cond", ",", "dout", ",", "zeros_like", "(", "x", ")", ")", ",", "select", "(", "cond", ",", "zeros_like", "(", "y", ")", ",", "dout", ")", "return", "bprop" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_array_ops.py#L717-L724
gnina/gnina
b9ae032f52fc7a8153987bde09c0efa3620d8bb6
caffe/python/caffe/net_spec.py
python
to_proto
(*tops)
return net
Generate a NetParameter that contains all layers needed to compute all arguments.
Generate a NetParameter that contains all layers needed to compute all arguments.
[ "Generate", "a", "NetParameter", "that", "contains", "all", "layers", "needed", "to", "compute", "all", "arguments", "." ]
def to_proto(*tops): """Generate a NetParameter that contains all layers needed to compute all arguments.""" layers = OrderedDict() autonames = Counter() for top in tops: top.fn._to_proto(layers, {}, autonames) net = caffe_pb2.NetParameter() net.layer.extend(layers.values()) return net
[ "def", "to_proto", "(", "*", "tops", ")", ":", "layers", "=", "OrderedDict", "(", ")", "autonames", "=", "Counter", "(", ")", "for", "top", "in", "tops", ":", "top", ".", "fn", ".", "_to_proto", "(", "layers", ",", "{", "}", ",", "autonames", ")", "net", "=", "caffe_pb2", ".", "NetParameter", "(", ")", "net", ".", "layer", ".", "extend", "(", "layers", ".", "values", "(", ")", ")", "return", "net" ]
https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/python/caffe/net_spec.py#L43-L53
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/connection.py
python
S3Connection.head_bucket
(self, bucket_name, headers=None)
Determines if a bucket exists by name. If the bucket does not exist, an ``S3ResponseError`` will be raised. :type bucket_name: string :param bucket_name: The name of the bucket :type headers: dict :param headers: Additional headers to pass along with the request to AWS. :returns: A <Bucket> object
Determines if a bucket exists by name.
[ "Determines", "if", "a", "bucket", "exists", "by", "name", "." ]
def head_bucket(self, bucket_name, headers=None): """ Determines if a bucket exists by name. If the bucket does not exist, an ``S3ResponseError`` will be raised. :type bucket_name: string :param bucket_name: The name of the bucket :type headers: dict :param headers: Additional headers to pass along with the request to AWS. :returns: A <Bucket> object """ response = self.make_request('HEAD', bucket_name, headers=headers) body = response.read() if response.status == 200: return self.bucket_class(self, bucket_name) elif response.status == 403: # For backward-compatibility, we'll populate part of the exception # with the most-common default. err = self.provider.storage_response_error( response.status, response.reason, body ) err.error_code = 'AccessDenied' err.error_message = 'Access Denied' raise err elif response.status == 404: # For backward-compatibility, we'll populate part of the exception # with the most-common default. err = self.provider.storage_response_error( response.status, response.reason, body ) err.error_code = 'NoSuchBucket' err.error_message = 'The specified bucket does not exist' raise err else: raise self.provider.storage_response_error( response.status, response.reason, body)
[ "def", "head_bucket", "(", "self", ",", "bucket_name", ",", "headers", "=", "None", ")", ":", "response", "=", "self", ".", "make_request", "(", "'HEAD'", ",", "bucket_name", ",", "headers", "=", "headers", ")", "body", "=", "response", ".", "read", "(", ")", "if", "response", ".", "status", "==", "200", ":", "return", "self", ".", "bucket_class", "(", "self", ",", "bucket_name", ")", "elif", "response", ".", "status", "==", "403", ":", "# For backward-compatibility, we'll populate part of the exception", "# with the most-common default.", "err", "=", "self", ".", "provider", ".", "storage_response_error", "(", "response", ".", "status", ",", "response", ".", "reason", ",", "body", ")", "err", ".", "error_code", "=", "'AccessDenied'", "err", ".", "error_message", "=", "'Access Denied'", "raise", "err", "elif", "response", ".", "status", "==", "404", ":", "# For backward-compatibility, we'll populate part of the exception", "# with the most-common default.", "err", "=", "self", ".", "provider", ".", "storage_response_error", "(", "response", ".", "status", ",", "response", ".", "reason", ",", "body", ")", "err", ".", "error_code", "=", "'NoSuchBucket'", "err", ".", "error_message", "=", "'The specified bucket does not exist'", "raise", "err", "else", ":", "raise", "self", ".", "provider", ".", "storage_response_error", "(", "response", ".", "status", ",", "response", ".", "reason", ",", "body", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/connection.py#L506-L549
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/scriptutils.py
python
IsOnPythonPath
(path)
return 0
Given a path only, see if it is on the Pythonpath. Assumes path is a full path spec.
Given a path only, see if it is on the Pythonpath. Assumes path is a full path spec.
[ "Given", "a", "path", "only", "see", "if", "it", "is", "on", "the", "Pythonpath", ".", "Assumes", "path", "is", "a", "full", "path", "spec", "." ]
def IsOnPythonPath(path): "Given a path only, see if it is on the Pythonpath. Assumes path is a full path spec." # must check that the command line arg's path is in sys.path for syspath in sys.path: try: # Python 1.5 and later allows an empty sys.path entry. if syspath and win32ui.FullPath(syspath)==path: return 1 except win32ui.error, details: print "Warning: The sys.path entry '%s' is invalid\n%s" % (syspath, details) return 0
[ "def", "IsOnPythonPath", "(", "path", ")", ":", "# must check that the command line arg's path is in sys.path", "for", "syspath", "in", "sys", ".", "path", ":", "try", ":", "# Python 1.5 and later allows an empty sys.path entry.", "if", "syspath", "and", "win32ui", ".", "FullPath", "(", "syspath", ")", "==", "path", ":", "return", "1", "except", "win32ui", ".", "error", ",", "details", ":", "print", "\"Warning: The sys.path entry '%s' is invalid\\n%s\"", "%", "(", "syspath", ",", "details", ")", "return", "0" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/scriptutils.py#L75-L85
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/relu_grad_v2_ds.py
python
_relu_grad_v2_ds_tbe
()
return
ReluGradV2 TBE register
ReluGradV2 TBE register
[ "ReluGradV2", "TBE", "register" ]
def _relu_grad_v2_ds_tbe(): """ReluGradV2 TBE register""" return
[ "def", "_relu_grad_v2_ds_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/relu_grad_v2_ds.py#L39-L41
jtv/libpqxx
c0b7e682b629241fc53d037920fb33dfa4ed873d
tools/template2mak.py
python
expand_foreach
(globs, block, outfile)
Expand a foreach block for each file matching one of globs. Write the results to outfile.
Expand a foreach block for each file matching one of globs.
[ "Expand", "a", "foreach", "block", "for", "each", "file", "matching", "one", "of", "globs", "." ]
def expand_foreach(globs, block, outfile): """Expand a foreach block for each file matching one of globs. Write the results to outfile. """ # We'll be iterating over block a variable number of times. Turn it # from a generic iterable into an immutable array. block = tuple(block) for path in match_globs(globs): expand_foreach_file(path, block, outfile)
[ "def", "expand_foreach", "(", "globs", ",", "block", ",", "outfile", ")", ":", "# We'll be iterating over block a variable number of times. Turn it", "# from a generic iterable into an immutable array.", "block", "=", "tuple", "(", "block", ")", "for", "path", "in", "match_globs", "(", "globs", ")", ":", "expand_foreach_file", "(", "path", ",", "block", ",", "outfile", ")" ]
https://github.com/jtv/libpqxx/blob/c0b7e682b629241fc53d037920fb33dfa4ed873d/tools/template2mak.py#L67-L76
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/graphviz/py3/graphviz/tools.py
python
attach
(object: typing.Any, name: str)
return decorator
Return a decorator doing ``setattr(object, name)`` with its argument. >>> spam = type('Spam', (object,), {})() >>> @attach(spam, 'eggs') ... def func(): ... pass >>> spam.eggs # doctest: +ELLIPSIS <function func at 0x...>
Return a decorator doing ``setattr(object, name)`` with its argument.
[ "Return", "a", "decorator", "doing", "setattr", "(", "object", "name", ")", "with", "its", "argument", "." ]
def attach(object: typing.Any, name: str) -> typing.Callable: """Return a decorator doing ``setattr(object, name)`` with its argument. >>> spam = type('Spam', (object,), {})() >>> @attach(spam, 'eggs') ... def func(): ... pass >>> spam.eggs # doctest: +ELLIPSIS <function func at 0x...> """ def decorator(func): setattr(object, name, func) return func return decorator
[ "def", "attach", "(", "object", ":", "typing", ".", "Any", ",", "name", ":", "str", ")", "->", "typing", ".", "Callable", ":", "def", "decorator", "(", "func", ")", ":", "setattr", "(", "object", ",", "name", ",", "func", ")", "return", "func", "return", "decorator" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/graphviz/py3/graphviz/tools.py#L11-L26
RobotLocomotion/drake
0e18a34604c45ed65bc9018a54f7610f91cdad5b
tools/workspace/drake_visualizer/_drake_visualizer_builtin_scripts/show_hydroelastic_contact.py
python
HydroelasticContactVisualizer.update_max_pressure
(self, pressure)
Tests to see if the maximum pressure needs to be increased. If so, updates the dialog.
Tests to see if the maximum pressure needs to be increased. If so, updates the dialog.
[ "Tests", "to", "see", "if", "the", "maximum", "pressure", "needs", "to", "be", "increased", ".", "If", "so", "updates", "the", "dialog", "." ]
def update_max_pressure(self, pressure): """Tests to see if the maximum pressure needs to be increased. If so, updates the dialog.""" if pressure > self.max_pressure_observed: self.max_pressure_observed = pressure # Note: This is a *horrible* hack rendered necessary because # PythonQt doesn't provide QtCore.QObject *or* QtCore.pyqtSignal so # we can't define signals on this class that connect to dialog # slots. self.dlg.set_max_pressure(pressure)
[ "def", "update_max_pressure", "(", "self", ",", "pressure", ")", ":", "if", "pressure", ">", "self", ".", "max_pressure_observed", ":", "self", ".", "max_pressure_observed", "=", "pressure", "# Note: This is a *horrible* hack rendered necessary because", "# PythonQt doesn't provide QtCore.QObject *or* QtCore.pyqtSignal so", "# we can't define signals on this class that connect to dialog", "# slots.", "self", ".", "dlg", ".", "set_max_pressure", "(", "pressure", ")" ]
https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/tools/workspace/drake_visualizer/_drake_visualizer_builtin_scripts/show_hydroelastic_contact.py#L1109-L1118
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/AI/freeorion_tools/_freeorion_tools.py
python
get_ship_part
(part_name: str)
return part_type
Return the shipPart object (fo.getShipPart(part_name)) of the given part_name. As the function in late game may be called some thousand times, the results are cached.
Return the shipPart object (fo.getShipPart(part_name)) of the given part_name.
[ "Return", "the", "shipPart", "object", "(", "fo", ".", "getShipPart", "(", "part_name", "))", "of", "the", "given", "part_name", "." ]
def get_ship_part(part_name: str): """Return the shipPart object (fo.getShipPart(part_name)) of the given part_name. As the function in late game may be called some thousand times, the results are cached. """ if not part_name: return None part_type = fo.getShipPart(part_name) if not part_type: warning("Could not find part %s" % part_name) return part_type
[ "def", "get_ship_part", "(", "part_name", ":", "str", ")", ":", "if", "not", "part_name", ":", "return", "None", "part_type", "=", "fo", ".", "getShipPart", "(", "part_name", ")", "if", "not", "part_type", ":", "warning", "(", "\"Could not find part %s\"", "%", "part_name", ")", "return", "part_type" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/freeorion_tools/_freeorion_tools.py#L306-L318
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py
python
Mozilla_suite_Events.Go
(self, _object, _attributes={}, **_arguments)
Go: navigate a window: back, forward, again(reload), home) Required argument: window Keyword argument direction: undocumented, typecode 'dire' Keyword argument _attributes: AppleEvent attribute dictionary
Go: navigate a window: back, forward, again(reload), home) Required argument: window Keyword argument direction: undocumented, typecode 'dire' Keyword argument _attributes: AppleEvent attribute dictionary
[ "Go", ":", "navigate", "a", "window", ":", "back", "forward", "again", "(", "reload", ")", "home", ")", "Required", "argument", ":", "window", "Keyword", "argument", "direction", ":", "undocumented", "typecode", "dire", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def Go(self, _object, _attributes={}, **_arguments): """Go: navigate a window: back, forward, again(reload), home) Required argument: window Keyword argument direction: undocumented, typecode 'dire' Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'MOSS' _subcode = 'gogo' aetools.keysubst(_arguments, self._argmap_Go) _arguments['----'] = _object aetools.enumsubst(_arguments, 'dire', _Enum_dire) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "Go", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'MOSS'", "_subcode", "=", "'gogo'", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", "_argmap_Go", ")", "_arguments", "[", "'----'", "]", "=", "_object", "aetools", ".", "enumsubst", "(", "_arguments", ",", "'dire'", ",", "_Enum_dire", ")", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py#L79-L99
tensorflow/io
92b44e180674a8af0e12e405530f7343e3e693e4
tensorflow_io/python/experimental/serial_ops.py
python
_bytes_feature
(value)
return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
value: list
value: list
[ "value", ":", "list" ]
def _bytes_feature(value): """value: list""" return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
[ "def", "_bytes_feature", "(", "value", ")", ":", "return", "tf", ".", "train", ".", "Feature", "(", "bytes_list", "=", "tf", ".", "train", ".", "BytesList", "(", "value", "=", "value", ")", ")" ]
https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/experimental/serial_ops.py#L48-L50
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/boost/boost_1_68_0/tools/build/src/build/project.py
python
ProjectRegistry.push_current
(self, project)
Temporary changes the current project to 'project'. Should be followed by 'pop-current'.
Temporary changes the current project to 'project'. Should be followed by 'pop-current'.
[ "Temporary", "changes", "the", "current", "project", "to", "project", ".", "Should", "be", "followed", "by", "pop", "-", "current", "." ]
def push_current(self, project): """Temporary changes the current project to 'project'. Should be followed by 'pop-current'.""" if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) self.saved_current_project.append(self.current_project) self.current_project = project
[ "def", "push_current", "(", "self", ",", "project", ")", ":", "if", "__debug__", ":", "from", ".", "targets", "import", "ProjectTarget", "assert", "isinstance", "(", "project", ",", "ProjectTarget", ")", "self", ".", "saved_current_project", ".", "append", "(", "self", ".", "current_project", ")", "self", ".", "current_project", "=", "project" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/build/project.py#L572-L579
syoyo/tinygltf
e7f1ff5c59d3ca2489923beb239bdf93d863498f
deps/cpplint.py
python
CheckInvalidIncrement
(filename, clean_lines, linenum, error)
Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. 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.
Checks for invalid increment *count++.
[ "Checks", "for", "invalid", "increment", "*", "count", "++", "." ]
def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. 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] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).')
[ "def", "CheckInvalidIncrement", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "_RE_PATTERN_INVALID_INCREMENT", ".", "match", "(", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/invalid_increment'", ",", "5", ",", "'Changing pointer instead of value (or unused value of operator*).'", ")" ]
https://github.com/syoyo/tinygltf/blob/e7f1ff5c59d3ca2489923beb239bdf93d863498f/deps/cpplint.py#L1961-L1980
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/builder.py
python
IRBuilder.fence
(self, ordering, targetscope=None, name='')
return inst
Add a memory barrier, preventing certain reorderings of load and/or store accesses with respect to other processors and devices.
Add a memory barrier, preventing certain reorderings of load and/or store accesses with respect to other processors and devices.
[ "Add", "a", "memory", "barrier", "preventing", "certain", "reorderings", "of", "load", "and", "/", "or", "store", "accesses", "with", "respect", "to", "other", "processors", "and", "devices", "." ]
def fence(self, ordering, targetscope=None, name=''): """ Add a memory barrier, preventing certain reorderings of load and/or store accesses with respect to other processors and devices. """ inst = instructions.Fence(self.block, ordering, targetscope, name=name) self._insert(inst) return inst
[ "def", "fence", "(", "self", ",", "ordering", ",", "targetscope", "=", "None", ",", "name", "=", "''", ")", ":", "inst", "=", "instructions", ".", "Fence", "(", "self", ".", "block", ",", "ordering", ",", "targetscope", ",", "name", "=", "name", ")", "self", ".", "_insert", "(", "inst", ")", "return", "inst" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/builder.py#L991-L998
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowser.py
python
FitPropertyBrowser.update_legend
(self)
This needs to be called to update plot's legend after removing lines.
This needs to be called to update plot's legend after removing lines.
[ "This", "needs", "to", "be", "called", "to", "update", "plot", "s", "legend", "after", "removing", "lines", "." ]
def update_legend(self): """ This needs to be called to update plot's legend after removing lines. """ ax = self.get_axes() # only create a legend if the plot already had one if ax.get_legend(): ax.make_legend()
[ "def", "update_legend", "(", "self", ")", ":", "ax", "=", "self", ".", "get_axes", "(", ")", "# only create a legend if the plot already had one", "if", "ax", ".", "get_legend", "(", ")", ":", "ax", ".", "make_legend", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowser.py#L331-L338
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/linalg/_interpolative_backend.py
python
idzp_rid
(eps, m, n, matveca)
return k, idx, proj
Compute ID of a complex matrix to a specified relative precision using random matrix-vector multiplication. :param eps: Relative precision. :type eps: float :param m: Matrix row dimension. :type m: int :param n: Matrix column dimension. :type n: int :param matveca: Function to apply the matrix adjoint to a vector, with call signature `y = matveca(x)`, where `x` and `y` are the input and output vectors, respectively. :type matveca: function :return: Rank of ID. :rtype: int :return: Column index array. :rtype: :class:`numpy.ndarray` :return: Interpolation coefficients. :rtype: :class:`numpy.ndarray`
Compute ID of a complex matrix to a specified relative precision using random matrix-vector multiplication.
[ "Compute", "ID", "of", "a", "complex", "matrix", "to", "a", "specified", "relative", "precision", "using", "random", "matrix", "-", "vector", "multiplication", "." ]
def idzp_rid(eps, m, n, matveca): """ Compute ID of a complex matrix to a specified relative precision using random matrix-vector multiplication. :param eps: Relative precision. :type eps: float :param m: Matrix row dimension. :type m: int :param n: Matrix column dimension. :type n: int :param matveca: Function to apply the matrix adjoint to a vector, with call signature `y = matveca(x)`, where `x` and `y` are the input and output vectors, respectively. :type matveca: function :return: Rank of ID. :rtype: int :return: Column index array. :rtype: :class:`numpy.ndarray` :return: Interpolation coefficients. :rtype: :class:`numpy.ndarray` """ proj = np.empty( m + 1 + 2*n*(min(m, n) + 1), dtype=np.complex128, order='F') k, idx, proj, ier = _id.idzp_rid(eps, m, n, matveca, proj) if ier: raise _RETCODE_ERROR proj = proj[:k*(n-k)].reshape((k, n-k), order='F') return k, idx, proj
[ "def", "idzp_rid", "(", "eps", ",", "m", ",", "n", ",", "matveca", ")", ":", "proj", "=", "np", ".", "empty", "(", "m", "+", "1", "+", "2", "*", "n", "*", "(", "min", "(", "m", ",", "n", ")", "+", "1", ")", ",", "dtype", "=", "np", ".", "complex128", ",", "order", "=", "'F'", ")", "k", ",", "idx", ",", "proj", ",", "ier", "=", "_id", ".", "idzp_rid", "(", "eps", ",", "m", ",", "n", ",", "matveca", ",", "proj", ")", "if", "ier", ":", "raise", "_RETCODE_ERROR", "proj", "=", "proj", "[", ":", "k", "*", "(", "n", "-", "k", ")", "]", ".", "reshape", "(", "(", "k", ",", "n", "-", "k", ")", ",", "order", "=", "'F'", ")", "return", "k", ",", "idx", ",", "proj" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/linalg/_interpolative_backend.py#L1381-L1418
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextObject.GetPosition
(*args, **kwargs)
return _richtext.RichTextObject_GetPosition(*args, **kwargs)
GetPosition(self) -> Point
GetPosition(self) -> Point
[ "GetPosition", "(", "self", ")", "-", ">", "Point" ]
def GetPosition(*args, **kwargs): """GetPosition(self) -> Point""" return _richtext.RichTextObject_GetPosition(*args, **kwargs)
[ "def", "GetPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextObject_GetPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1293-L1295
OpenChemistry/tomviz
0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a
tomviz/python/tomviz/state/_views.py
python
Camera.zoom
(self, factor)
Decrease the view angle by the specified factor. A value greater than 1 is a zoom-in, a value less than 1 is a zoom-out.
Decrease the view angle by the specified factor. A value greater than 1 is a zoom-in, a value less than 1 is a zoom-out.
[ "Decrease", "the", "view", "angle", "by", "the", "specified", "factor", ".", "A", "value", "greater", "than", "1", "is", "a", "zoom", "-", "in", "a", "value", "less", "than", "1", "is", "a", "zoom", "-", "out", "." ]
def zoom(self, factor): """ Decrease the view angle by the specified factor. A value greater than 1 is a zoom-in, a value less than 1 is a zoom-out. """ self._camera.Zoom(factor) Render(self._render_view)
[ "def", "zoom", "(", "self", ",", "factor", ")", ":", "self", ".", "_camera", ".", "Zoom", "(", "factor", ")", "Render", "(", "self", ".", "_render_view", ")" ]
https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/tomviz/state/_views.py#L139-L145
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/s3fs/core.py
python
S3FileSystem.touch
(self, path, truncate=True, data=None, **kwargs)
Create empty file or truncate
Create empty file or truncate
[ "Create", "empty", "file", "or", "truncate" ]
def touch(self, path, truncate=True, data=None, **kwargs): """Create empty file or truncate""" bucket, key, version_id = self.split_path(path) if version_id: raise ValueError("S3 does not support touching existing versions of files") if not truncate and self.exists(path): raise ValueError("S3 does not support touching existent files") try: self._call_s3(self.s3.put_object, kwargs, Bucket=bucket, Key=key) except ClientError as ex: raise translate_boto_error(ex) self.invalidate_cache(self._parent(path))
[ "def", "touch", "(", "self", ",", "path", ",", "truncate", "=", "True", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "bucket", ",", "key", ",", "version_id", "=", "self", ".", "split_path", "(", "path", ")", "if", "version_id", ":", "raise", "ValueError", "(", "\"S3 does not support touching existing versions of files\"", ")", "if", "not", "truncate", "and", "self", ".", "exists", "(", "path", ")", ":", "raise", "ValueError", "(", "\"S3 does not support touching existent files\"", ")", "try", ":", "self", ".", "_call_s3", "(", "self", ".", "s3", ".", "put_object", ",", "kwargs", ",", "Bucket", "=", "bucket", ",", "Key", "=", "key", ")", "except", "ClientError", "as", "ex", ":", "raise", "translate_boto_error", "(", "ex", ")", "self", ".", "invalidate_cache", "(", "self", ".", "_parent", "(", "path", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/s3fs/core.py#L503-L514
IDI-Systems/acre2
821bd25e7eb748e35aaf48b06002d564cc60a88d
tools/make.py
python
color
(color)
Set the color. Works on Win32 and normal terminals.
Set the color. Works on Win32 and normal terminals.
[ "Set", "the", "color", ".", "Works", "on", "Win32", "and", "normal", "terminals", "." ]
def color(color): """Set the color. Works on Win32 and normal terminals.""" if sys.platform == "win32": if color == "green": set_text_attr(FOREGROUND_GREEN | get_text_attr() & 0x0070 | FOREGROUND_INTENSITY) elif color == "yellow": set_text_attr(FOREGROUND_YELLOW | get_text_attr() & 0x0070 | FOREGROUND_INTENSITY) elif color == "red": set_text_attr(FOREGROUND_RED | get_text_attr() & 0x0070 | FOREGROUND_INTENSITY) elif color == "blue": set_text_attr(FOREGROUND_BLUE | get_text_attr() & 0x0070 | FOREGROUND_INTENSITY) elif color == "reset": set_text_attr(FOREGROUND_GREY | get_text_attr() & 0x0070) elif color == "grey": set_text_attr(FOREGROUND_GREY | get_text_attr() & 0x0070) else : if color == "green": sys.stdout.write('\033[92m') elif color == "red": sys.stdout.write('\033[91m') elif color == "blue": sys.stdout.write('\033[94m') elif color == "reset": sys.stdout.write('\033[0m')
[ "def", "color", "(", "color", ")", ":", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "if", "color", "==", "\"green\"", ":", "set_text_attr", "(", "FOREGROUND_GREEN", "|", "get_text_attr", "(", ")", "&", "0x0070", "|", "FOREGROUND_INTENSITY", ")", "elif", "color", "==", "\"yellow\"", ":", "set_text_attr", "(", "FOREGROUND_YELLOW", "|", "get_text_attr", "(", ")", "&", "0x0070", "|", "FOREGROUND_INTENSITY", ")", "elif", "color", "==", "\"red\"", ":", "set_text_attr", "(", "FOREGROUND_RED", "|", "get_text_attr", "(", ")", "&", "0x0070", "|", "FOREGROUND_INTENSITY", ")", "elif", "color", "==", "\"blue\"", ":", "set_text_attr", "(", "FOREGROUND_BLUE", "|", "get_text_attr", "(", ")", "&", "0x0070", "|", "FOREGROUND_INTENSITY", ")", "elif", "color", "==", "\"reset\"", ":", "set_text_attr", "(", "FOREGROUND_GREY", "|", "get_text_attr", "(", ")", "&", "0x0070", ")", "elif", "color", "==", "\"grey\"", ":", "set_text_attr", "(", "FOREGROUND_GREY", "|", "get_text_attr", "(", ")", "&", "0x0070", ")", "else", ":", "if", "color", "==", "\"green\"", ":", "sys", ".", "stdout", ".", "write", "(", "'\\033[92m'", ")", "elif", "color", "==", "\"red\"", ":", "sys", ".", "stdout", ".", "write", "(", "'\\033[91m'", ")", "elif", "color", "==", "\"blue\"", ":", "sys", ".", "stdout", ".", "write", "(", "'\\033[94m'", ")", "elif", "color", "==", "\"reset\"", ":", "sys", ".", "stdout", ".", "write", "(", "'\\033[0m'", ")" ]
https://github.com/IDI-Systems/acre2/blob/821bd25e7eb748e35aaf48b06002d564cc60a88d/tools/make.py#L275-L298
MegaGlest/megaglest-source
e3af470288a3c9cc179f63b5a1eb414a669e3772
mk/windoze/symbolstore.py
python
GetPlatformSpecificDumper
(**kwargs)
return {'Windows': Dumper_Win32, 'Microsoft': Dumper_Win32, 'Linux': Dumper_Linux, 'Sunos5': Dumper_Solaris, 'Darwin': Dumper_Mac}[platform.system()](**kwargs)
This function simply returns a instance of a subclass of Dumper that is appropriate for the current platform.
This function simply returns a instance of a subclass of Dumper that is appropriate for the current platform.
[ "This", "function", "simply", "returns", "a", "instance", "of", "a", "subclass", "of", "Dumper", "that", "is", "appropriate", "for", "the", "current", "platform", "." ]
def GetPlatformSpecificDumper(**kwargs): """This function simply returns a instance of a subclass of Dumper that is appropriate for the current platform.""" # Python 2.5 has a bug where platform.system() returns 'Microsoft'. # Remove this when we no longer support Python 2.5. return {'Windows': Dumper_Win32, 'Microsoft': Dumper_Win32, 'Linux': Dumper_Linux, 'Sunos5': Dumper_Solaris, 'Darwin': Dumper_Mac}[platform.system()](**kwargs)
[ "def", "GetPlatformSpecificDumper", "(", "*", "*", "kwargs", ")", ":", "# Python 2.5 has a bug where platform.system() returns 'Microsoft'.", "# Remove this when we no longer support Python 2.5.", "return", "{", "'Windows'", ":", "Dumper_Win32", ",", "'Microsoft'", ":", "Dumper_Win32", ",", "'Linux'", ":", "Dumper_Linux", ",", "'Sunos5'", ":", "Dumper_Solaris", ",", "'Darwin'", ":", "Dumper_Mac", "}", "[", "platform", ".", "system", "(", ")", "]", "(", "*", "*", "kwargs", ")" ]
https://github.com/MegaGlest/megaglest-source/blob/e3af470288a3c9cc179f63b5a1eb414a669e3772/mk/windoze/symbolstore.py#L283-L292
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/stats/_distn_infrastructure.py
python
rv_continuous.fit_loc_scale
(self, data, *args)
return Lhat, Shat
Estimate loc and scale parameters from data using 1st and 2nd moments. Parameters ---------- data : array_like Data to fit. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). Returns ------- Lhat : float Estimated location parameter for the data. Shat : float Estimated scale parameter for the data.
Estimate loc and scale parameters from data using 1st and 2nd moments.
[ "Estimate", "loc", "and", "scale", "parameters", "from", "data", "using", "1st", "and", "2nd", "moments", "." ]
def fit_loc_scale(self, data, *args): """ Estimate loc and scale parameters from data using 1st and 2nd moments. Parameters ---------- data : array_like Data to fit. arg1, arg2, arg3,... : array_like The shape parameter(s) for the distribution (see docstring of the instance object for more information). Returns ------- Lhat : float Estimated location parameter for the data. Shat : float Estimated scale parameter for the data. """ mu, mu2 = self.stats(*args, **{'moments': 'mv'}) tmp = asarray(data) muhat = tmp.mean() mu2hat = tmp.var() Shat = sqrt(mu2hat / mu2) Lhat = muhat - Shat*mu if not np.isfinite(Lhat): Lhat = 0 if not (np.isfinite(Shat) and (0 < Shat)): Shat = 1 return Lhat, Shat
[ "def", "fit_loc_scale", "(", "self", ",", "data", ",", "*", "args", ")", ":", "mu", ",", "mu2", "=", "self", ".", "stats", "(", "*", "args", ",", "*", "*", "{", "'moments'", ":", "'mv'", "}", ")", "tmp", "=", "asarray", "(", "data", ")", "muhat", "=", "tmp", ".", "mean", "(", ")", "mu2hat", "=", "tmp", ".", "var", "(", ")", "Shat", "=", "sqrt", "(", "mu2hat", "/", "mu2", ")", "Lhat", "=", "muhat", "-", "Shat", "*", "mu", "if", "not", "np", ".", "isfinite", "(", "Lhat", ")", ":", "Lhat", "=", "0", "if", "not", "(", "np", ".", "isfinite", "(", "Shat", ")", "and", "(", "0", "<", "Shat", ")", ")", ":", "Shat", "=", "1", "return", "Lhat", ",", "Shat" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/_distn_infrastructure.py#L2291-L2321
esa/pykep
b410363653623730b577de257c04b0e0289f2014
pykep/trajopt/_indirect.py
python
indirect_pt2pt.__init__
(self, x0=[-51051524893.335152, -142842795180.97464, 1139935.2553601924, 30488.847061907356, -10612.482697050367, -204.23284335657095, 1000], xf=[24753885674.871033, 231247560000.17883, 4236305010.4256544, - 23171.900670190855, 4635.6817290400222, 666.44019588506023, 910.48383959441833], thrust=0.3, isp=3000, mu=pk.MU_SUN, tof=[276.15166075931495, 276.15166075931495], freetime=False, alpha=0, # quadratic control bound=False, atol=1e-12, rtol=1e-12)
Constructs an instance of the ``pykep.trajopt.indirect_pt2pt`` problem. Args: - x0 (``list``, ``tuple``, ``numpy.ndarray``): Departure state [m, m, m, m/s, m/s, m/s, kg]. - xf (``list``, ``tuple``, ``numpy.ndarray``): Arrival state [m, m, m, m/s, m/s, m/s, kg]. - tof (``list``): Transfer time bounds [days]. - thrust (``float``, ``int``): Spacecraft maximum thrust [N]. - isp (``float``, ``int``): Spacecraft specific impulse [s]. - mu (``float``): Gravitational parameter of primary body [m^3/s^2]. - freetime (``bool``): Activates final time transversality condition. Allows final time to vary. - alpha (``float``, ``int``): Homotopy parameter (0 -quadratic control, 1 - mass optimal) - bound (``bool``): Activates bounded control, in which the control throttle is bounded between 0 and 1, otherwise the control throttle is allowed to unbounded. - atol (``float``, ``int``): Absolute integration solution tolerance. - rtol (``float``, ``int``): Relative integration solution tolerance.
Constructs an instance of the ``pykep.trajopt.indirect_pt2pt`` problem.
[ "Constructs", "an", "instance", "of", "the", "pykep", ".", "trajopt", ".", "indirect_pt2pt", "problem", "." ]
def __init__(self, x0=[-51051524893.335152, -142842795180.97464, 1139935.2553601924, 30488.847061907356, -10612.482697050367, -204.23284335657095, 1000], xf=[24753885674.871033, 231247560000.17883, 4236305010.4256544, - 23171.900670190855, 4635.6817290400222, 666.44019588506023, 910.48383959441833], thrust=0.3, isp=3000, mu=pk.MU_SUN, tof=[276.15166075931495, 276.15166075931495], freetime=False, alpha=0, # quadratic control bound=False, atol=1e-12, rtol=1e-12): """ Constructs an instance of the ``pykep.trajopt.indirect_pt2pt`` problem. Args: - x0 (``list``, ``tuple``, ``numpy.ndarray``): Departure state [m, m, m, m/s, m/s, m/s, kg]. - xf (``list``, ``tuple``, ``numpy.ndarray``): Arrival state [m, m, m, m/s, m/s, m/s, kg]. - tof (``list``): Transfer time bounds [days]. - thrust (``float``, ``int``): Spacecraft maximum thrust [N]. - isp (``float``, ``int``): Spacecraft specific impulse [s]. - mu (``float``): Gravitational parameter of primary body [m^3/s^2]. - freetime (``bool``): Activates final time transversality condition. Allows final time to vary. - alpha (``float``, ``int``): Homotopy parameter (0 -quadratic control, 1 - mass optimal) - bound (``bool``): Activates bounded control, in which the control throttle is bounded between 0 and 1, otherwise the control throttle is allowed to unbounded. - atol (``float``, ``int``): Absolute integration solution tolerance. - rtol (``float``, ``int``): Relative integration solution tolerance. """ # Cartesian states if not all([(isinstance(x, list) or isinstance(x, tuple) or isinstance(x, np.ndarray)) for x in [x0, xf]]): raise TypeError( "Both x0 and xf must be supplied as an instance of either list, tuple, or numpy.ndarray.") elif not all([len(x) == 7 for x in [x0, xf]]): raise TypeError( "Both x0 and xf must be supplied with 7 dimensions.") else: self.x0 = pk.sims_flanagan.sc_state() self.x0.set(x0) self.xf = pk.sims_flanagan.sc_state() self.xf.set(xf) self.tof = tof # initialise base _indirect_base.__init__( self, x0[-1], thrust, isp, mu, True, freetime, alpha, bound, atol, rtol )
[ "def", "__init__", "(", "self", ",", "x0", "=", "[", "-", "51051524893.335152", ",", "-", "142842795180.97464", ",", "1139935.2553601924", ",", "30488.847061907356", ",", "-", "10612.482697050367", ",", "-", "204.23284335657095", ",", "1000", "]", ",", "xf", "=", "[", "24753885674.871033", ",", "231247560000.17883", ",", "4236305010.4256544", ",", "-", "23171.900670190855", ",", "4635.6817290400222", ",", "666.44019588506023", ",", "910.48383959441833", "]", ",", "thrust", "=", "0.3", ",", "isp", "=", "3000", ",", "mu", "=", "pk", ".", "MU_SUN", ",", "tof", "=", "[", "276.15166075931495", ",", "276.15166075931495", "]", ",", "freetime", "=", "False", ",", "alpha", "=", "0", ",", "# quadratic control", "bound", "=", "False", ",", "atol", "=", "1e-12", ",", "rtol", "=", "1e-12", ")", ":", "# Cartesian states", "if", "not", "all", "(", "[", "(", "isinstance", "(", "x", ",", "list", ")", "or", "isinstance", "(", "x", ",", "tuple", ")", "or", "isinstance", "(", "x", ",", "np", ".", "ndarray", ")", ")", "for", "x", "in", "[", "x0", ",", "xf", "]", "]", ")", ":", "raise", "TypeError", "(", "\"Both x0 and xf must be supplied as an instance of either list, tuple, or numpy.ndarray.\"", ")", "elif", "not", "all", "(", "[", "len", "(", "x", ")", "==", "7", "for", "x", "in", "[", "x0", ",", "xf", "]", "]", ")", ":", "raise", "TypeError", "(", "\"Both x0 and xf must be supplied with 7 dimensions.\"", ")", "else", ":", "self", ".", "x0", "=", "pk", ".", "sims_flanagan", ".", "sc_state", "(", ")", "self", ".", "x0", ".", "set", "(", "x0", ")", "self", ".", "xf", "=", "pk", ".", "sims_flanagan", ".", "sc_state", "(", ")", "self", ".", "xf", ".", "set", "(", "xf", ")", "self", ".", "tof", "=", "tof", "# initialise base", "_indirect_base", ".", "__init__", "(", "self", ",", "x0", "[", "-", "1", "]", ",", "thrust", ",", "isp", ",", "mu", ",", "True", ",", "freetime", ",", "alpha", ",", "bound", ",", "atol", ",", "rtol", ")" ]
https://github.com/esa/pykep/blob/b410363653623730b577de257c04b0e0289f2014/pykep/trajopt/_indirect.py#L178-L228
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/saved_model/loader_impl.py
python
SavedModelLoader.load_graph
(self, graph, tags, import_scope=None, **saver_kwargs)
Load ops and nodes from SavedModel MetaGraph into graph. Args: graph: tf.Graph object. tags: a set of string tags identifying a MetaGraphDef. import_scope: Optional `string` -- if specified, prepend this string followed by '/' to all loaded tensor names. This scope is applied to tensor instances loaded into the passed session, but it is *not* written through to the static `MetaGraphDef` protocol buffer that is returned. **saver_kwargs: keyword arguments to pass to tf.train.import_meta_graph. Returns: A tuple of * Saver defined by the MetaGraph, which can be used to restore the variable values. * List of `Operation`/`Tensor` objects returned from `tf.import_graph_def` (may be `None`).
Load ops and nodes from SavedModel MetaGraph into graph.
[ "Load", "ops", "and", "nodes", "from", "SavedModel", "MetaGraph", "into", "graph", "." ]
def load_graph(self, graph, tags, import_scope=None, **saver_kwargs): """Load ops and nodes from SavedModel MetaGraph into graph. Args: graph: tf.Graph object. tags: a set of string tags identifying a MetaGraphDef. import_scope: Optional `string` -- if specified, prepend this string followed by '/' to all loaded tensor names. This scope is applied to tensor instances loaded into the passed session, but it is *not* written through to the static `MetaGraphDef` protocol buffer that is returned. **saver_kwargs: keyword arguments to pass to tf.train.import_meta_graph. Returns: A tuple of * Saver defined by the MetaGraph, which can be used to restore the variable values. * List of `Operation`/`Tensor` objects returned from `tf.import_graph_def` (may be `None`). """ meta_graph_def = self.get_meta_graph_def_from_tags(tags) if sys.byteorder == "big": saved_model_utils.swap_function_tensor_content(meta_graph_def, "little", "big") with graph.as_default(): return tf_saver._import_meta_graph_with_return_elements( # pylint: disable=protected-access meta_graph_def, import_scope=import_scope, **saver_kwargs)
[ "def", "load_graph", "(", "self", ",", "graph", ",", "tags", ",", "import_scope", "=", "None", ",", "*", "*", "saver_kwargs", ")", ":", "meta_graph_def", "=", "self", ".", "get_meta_graph_def_from_tags", "(", "tags", ")", "if", "sys", ".", "byteorder", "==", "\"big\"", ":", "saved_model_utils", ".", "swap_function_tensor_content", "(", "meta_graph_def", ",", "\"little\"", ",", "\"big\"", ")", "with", "graph", ".", "as_default", "(", ")", ":", "return", "tf_saver", ".", "_import_meta_graph_with_return_elements", "(", "# pylint: disable=protected-access", "meta_graph_def", ",", "import_scope", "=", "import_scope", ",", "*", "*", "saver_kwargs", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/loader_impl.py#L399-L424
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/inputs/forces.py
python
InputForces.store
(self, flist)
Stores a list of the output objects, creating a sequence of dynamic containers. Args: flist: A list of tuples, with each tuple being of the form ('type', 'object') where 'type' is the type of forcefield and 'object' is a forcefield object of that type.
Stores a list of the output objects, creating a sequence of dynamic containers.
[ "Stores", "a", "list", "of", "the", "output", "objects", "creating", "a", "sequence", "of", "dynamic", "containers", "." ]
def store(self, flist): """Stores a list of the output objects, creating a sequence of dynamic containers. Args: flist: A list of tuples, with each tuple being of the form ('type', 'object') where 'type' is the type of forcefield and 'object' is a forcefield object of that type. """ super(InputForces, self).store() self.extra = [] for el in flist: if el[0]=="socket": iff = InputFBSocket() iff.store(el[1]) self.extra.append(("socket", iff))
[ "def", "store", "(", "self", ",", "flist", ")", ":", "super", "(", "InputForces", ",", "self", ")", ".", "store", "(", ")", "self", ".", "extra", "=", "[", "]", "for", "el", "in", "flist", ":", "if", "el", "[", "0", "]", "==", "\"socket\"", ":", "iff", "=", "InputFBSocket", "(", ")", "iff", ".", "store", "(", "el", "[", "1", "]", ")", "self", ".", "extra", ".", "append", "(", "(", "\"socket\"", ",", "iff", ")", ")" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/inputs/forces.py#L159-L176
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
win32/scripts/ce/pysynch.py
python
delete
(args)
delete file, ... Delete one or more remote files
delete file, ... Delete one or more remote files
[ "delete", "file", "...", "Delete", "one", "or", "more", "remote", "files" ]
def delete(args): """delete file, ... Delete one or more remote files """ for arg in args: try: wincerapi.CeDeleteFile(arg) print("Deleted: %s" % arg) except win32api.error as details: print_error(details, "Error deleting '%s'" % arg)
[ "def", "delete", "(", "args", ")", ":", "for", "arg", "in", "args", ":", "try", ":", "wincerapi", ".", "CeDeleteFile", "(", "arg", ")", "print", "(", "\"Deleted: %s\"", "%", "arg", ")", "except", "win32api", ".", "error", "as", "details", ":", "print_error", "(", "details", ",", "\"Error deleting '%s'\"", "%", "arg", ")" ]
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/win32/scripts/ce/pysynch.py#L229-L238
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/gradients_util.py
python
_HasAnyNotNoneGrads
(grads, op)
return False
Return true iff op has real gradient.
Return true iff op has real gradient.
[ "Return", "true", "iff", "op", "has", "real", "gradient", "." ]
def _HasAnyNotNoneGrads(grads, op): """Return true iff op has real gradient.""" out_grads = _GetGrads(grads, op) for out_grad in out_grads: if isinstance(out_grad, (ops.Tensor, indexed_slices.IndexedSlices)): return True if out_grad and isinstance(out_grad, collections_abc.Sequence): if any(g is not None for g in out_grad): return True return False
[ "def", "_HasAnyNotNoneGrads", "(", "grads", ",", "op", ")", ":", "out_grads", "=", "_GetGrads", "(", "grads", ",", "op", ")", "for", "out_grad", "in", "out_grads", ":", "if", "isinstance", "(", "out_grad", ",", "(", "ops", ".", "Tensor", ",", "indexed_slices", ".", "IndexedSlices", ")", ")", ":", "return", "True", "if", "out_grad", "and", "isinstance", "(", "out_grad", ",", "collections_abc", ".", "Sequence", ")", ":", "if", "any", "(", "g", "is", "not", "None", "for", "g", "in", "out_grad", ")", ":", "return", "True", "return", "False" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/gradients_util.py#L727-L736
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/dask_cudf/dask_cudf/accessors.py
python
StructMethods.field
(self, key)
return self.d_series.map_partitions( lambda s: s.struct.field(key), meta=self.d_series._meta._constructor([], dtype=typ), )
Extract children of the specified struct column in the Series Parameters ---------- key: int or str index/position or field name of the respective struct column Returns ------- Series Examples -------- >>> s = cudf.Series([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]) >>> ds = dask_cudf.from_cudf(s, 2) >>> ds.struct.field(0).compute() 0 1 1 3 dtype: int64 >>> ds.struct.field('a').compute() 0 1 1 3 dtype: int64
Extract children of the specified struct column in the Series Parameters ---------- key: int or str index/position or field name of the respective struct column Returns ------- Series Examples -------- >>> s = cudf.Series([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]) >>> ds = dask_cudf.from_cudf(s, 2) >>> ds.struct.field(0).compute() 0 1 1 3 dtype: int64 >>> ds.struct.field('a').compute() 0 1 1 3 dtype: int64
[ "Extract", "children", "of", "the", "specified", "struct", "column", "in", "the", "Series", "Parameters", "----------", "key", ":", "int", "or", "str", "index", "/", "position", "or", "field", "name", "of", "the", "respective", "struct", "column", "Returns", "-------", "Series", "Examples", "--------", ">>>", "s", "=", "cudf", ".", "Series", "(", "[", "{", "a", ":", "1", "b", ":", "2", "}", "{", "a", ":", "3", "b", ":", "4", "}", "]", ")", ">>>", "ds", "=", "dask_cudf", ".", "from_cudf", "(", "s", "2", ")", ">>>", "ds", ".", "struct", ".", "field", "(", "0", ")", ".", "compute", "()", "0", "1", "1", "3", "dtype", ":", "int64", ">>>", "ds", ".", "struct", ".", "field", "(", "a", ")", ".", "compute", "()", "0", "1", "1", "3", "dtype", ":", "int64" ]
def field(self, key): """ Extract children of the specified struct column in the Series Parameters ---------- key: int or str index/position or field name of the respective struct column Returns ------- Series Examples -------- >>> s = cudf.Series([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]) >>> ds = dask_cudf.from_cudf(s, 2) >>> ds.struct.field(0).compute() 0 1 1 3 dtype: int64 >>> ds.struct.field('a').compute() 0 1 1 3 dtype: int64 """ typ = self.d_series._meta.struct.field(key).dtype return self.d_series.map_partitions( lambda s: s.struct.field(key), meta=self.d_series._meta._constructor([], dtype=typ), )
[ "def", "field", "(", "self", ",", "key", ")", ":", "typ", "=", "self", ".", "d_series", ".", "_meta", ".", "struct", ".", "field", "(", "key", ")", ".", "dtype", "return", "self", ".", "d_series", ".", "map_partitions", "(", "lambda", "s", ":", "s", ".", "struct", ".", "field", "(", "key", ")", ",", "meta", "=", "self", ".", "d_series", ".", "_meta", ".", "_constructor", "(", "[", "]", ",", "dtype", "=", "typ", ")", ",", ")" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/dask_cudf/dask_cudf/accessors.py#L8-L38
gwaldron/osgearth
4c521857d59a69743e4a9cedba00afe570f984e8
src/third_party/tinygltf/deps/cpplint.py
python
IsInitializerList
(clean_lines, linenum)
return False
Check if current line is inside constructor initializer list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line appears to be inside constructor initializer list, False otherwise.
Check if current line is inside constructor initializer list.
[ "Check", "if", "current", "line", "is", "inside", "constructor", "initializer", "list", "." ]
def IsInitializerList(clean_lines, linenum): """Check if current line is inside constructor initializer list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line appears to be inside constructor initializer list, False otherwise. """ for i in xrange(linenum, 1, -1): line = clean_lines.elided[i] if i == linenum: remove_function_body = Match(r'^(.*)\{\s*$', line) if remove_function_body: line = remove_function_body.group(1) if Search(r'\s:\s*\w+[({]', line): # A lone colon tend to indicate the start of a constructor # initializer list. It could also be a ternary operator, which # also tend to appear in constructor initializer lists as # opposed to parameter lists. return True if Search(r'\}\s*,\s*$', line): # A closing brace followed by a comma is probably the end of a # brace-initialized member in constructor initializer list. return True if Search(r'[{};]\s*$', line): # Found one of the following: # - A closing brace or semicolon, probably the end of the previous # function. # - An opening brace, probably the start of current class or namespace. # # Current line is probably not inside an initializer list since # we saw one of those things without seeing the starting colon. return False # Got to the beginning of the file without seeing the start of # constructor initializer list. return False
[ "def", "IsInitializerList", "(", "clean_lines", ",", "linenum", ")", ":", "for", "i", "in", "xrange", "(", "linenum", ",", "1", ",", "-", "1", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "i", "]", "if", "i", "==", "linenum", ":", "remove_function_body", "=", "Match", "(", "r'^(.*)\\{\\s*$'", ",", "line", ")", "if", "remove_function_body", ":", "line", "=", "remove_function_body", ".", "group", "(", "1", ")", "if", "Search", "(", "r'\\s:\\s*\\w+[({]'", ",", "line", ")", ":", "# A lone colon tend to indicate the start of a constructor", "# initializer list. It could also be a ternary operator, which", "# also tend to appear in constructor initializer lists as", "# opposed to parameter lists.", "return", "True", "if", "Search", "(", "r'\\}\\s*,\\s*$'", ",", "line", ")", ":", "# A closing brace followed by a comma is probably the end of a", "# brace-initialized member in constructor initializer list.", "return", "True", "if", "Search", "(", "r'[{};]\\s*$'", ",", "line", ")", ":", "# Found one of the following:", "# - A closing brace or semicolon, probably the end of the previous", "# function.", "# - An opening brace, probably the start of current class or namespace.", "#", "# Current line is probably not inside an initializer list since", "# we saw one of those things without seeing the starting colon.", "return", "False", "# Got to the beginning of the file without seeing the start of", "# constructor initializer list.", "return", "False" ]
https://github.com/gwaldron/osgearth/blob/4c521857d59a69743e4a9cedba00afe570f984e8/src/third_party/tinygltf/deps/cpplint.py#L5038-L5077
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/training/saver.py
python
BaseSaverBuilder._AddShardedSaveOps
(self, filename_tensor, per_device)
Add ops to save the params per shard. Args: filename_tensor: a scalar String Tensor. per_device: A list of (device, BaseSaverBuilder.SaveableObject) pairs, as returned by _GroupByDevices(). Returns: An op to save the variables.
Add ops to save the params per shard.
[ "Add", "ops", "to", "save", "the", "params", "per", "shard", "." ]
def _AddShardedSaveOps(self, filename_tensor, per_device): """Add ops to save the params per shard. Args: filename_tensor: a scalar String Tensor. per_device: A list of (device, BaseSaverBuilder.SaveableObject) pairs, as returned by _GroupByDevices(). Returns: An op to save the variables. """ if self._write_version == saver_pb2.SaverDef.V2: return self._AddShardedSaveOpsForV2(filename_tensor, per_device) num_shards = len(per_device) sharded_saves = [] num_shards_tensor = constant_op.constant(num_shards, name="num_shards") for shard, (device, saveables) in enumerate(per_device): with ops.device(device): sharded_filename = self.sharded_filename(filename_tensor, shard, num_shards_tensor) sharded_saves.append(self._AddSaveOps(sharded_filename, saveables)) # Return the sharded name for the save path. with ops.control_dependencies([x.op for x in sharded_saves]): return gen_io_ops.sharded_filespec(filename_tensor, num_shards_tensor)
[ "def", "_AddShardedSaveOps", "(", "self", ",", "filename_tensor", ",", "per_device", ")", ":", "if", "self", ".", "_write_version", "==", "saver_pb2", ".", "SaverDef", ".", "V2", ":", "return", "self", ".", "_AddShardedSaveOpsForV2", "(", "filename_tensor", ",", "per_device", ")", "num_shards", "=", "len", "(", "per_device", ")", "sharded_saves", "=", "[", "]", "num_shards_tensor", "=", "constant_op", ".", "constant", "(", "num_shards", ",", "name", "=", "\"num_shards\"", ")", "for", "shard", ",", "(", "device", ",", "saveables", ")", "in", "enumerate", "(", "per_device", ")", ":", "with", "ops", ".", "device", "(", "device", ")", ":", "sharded_filename", "=", "self", ".", "sharded_filename", "(", "filename_tensor", ",", "shard", ",", "num_shards_tensor", ")", "sharded_saves", ".", "append", "(", "self", ".", "_AddSaveOps", "(", "sharded_filename", ",", "saveables", ")", ")", "# Return the sharded name for the save path.", "with", "ops", ".", "control_dependencies", "(", "[", "x", ".", "op", "for", "x", "in", "sharded_saves", "]", ")", ":", "return", "gen_io_ops", ".", "sharded_filespec", "(", "filename_tensor", ",", "num_shards_tensor", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/saver.py#L315-L339
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/factorization/python/ops/gmm.py
python
GMM.__init__
(self, num_clusters, model_dir=None, random_seed=0, params='wmc', initial_clusters='random', covariance_type='full', batch_size=128, steps=10, continue_training=False, config=None, verbose=1)
Creates a model for running GMM training and inference. Args: num_clusters: number of clusters to train. model_dir: the directory to save the model results and log files. random_seed: Python integer. Seed for PRNG used to initialize centers. params: Controls which parameters are updated in the training process. Can contain any combination of "w" for weights, "m" for means, and "c" for covars. initial_clusters: specifies how to initialize the clusters for training. See gmm_ops.gmm for the possible values. covariance_type: one of "full", "diag". batch_size: See TensorFlowEstimator steps: See TensorFlowEstimator continue_training: See TensorFlowEstimator config: See TensorFlowEstimator verbose: See TensorFlowEstimator
Creates a model for running GMM training and inference.
[ "Creates", "a", "model", "for", "running", "GMM", "training", "and", "inference", "." ]
def __init__(self, num_clusters, model_dir=None, random_seed=0, params='wmc', initial_clusters='random', covariance_type='full', batch_size=128, steps=10, continue_training=False, config=None, verbose=1): """Creates a model for running GMM training and inference. Args: num_clusters: number of clusters to train. model_dir: the directory to save the model results and log files. random_seed: Python integer. Seed for PRNG used to initialize centers. params: Controls which parameters are updated in the training process. Can contain any combination of "w" for weights, "m" for means, and "c" for covars. initial_clusters: specifies how to initialize the clusters for training. See gmm_ops.gmm for the possible values. covariance_type: one of "full", "diag". batch_size: See TensorFlowEstimator steps: See TensorFlowEstimator continue_training: See TensorFlowEstimator config: See TensorFlowEstimator verbose: See TensorFlowEstimator """ super(GMM, self).__init__( model_dir=model_dir, config=config) self.batch_size = batch_size self.steps = steps self.continue_training = continue_training self.verbose = verbose self._num_clusters = num_clusters self._params = params self._training_initial_clusters = initial_clusters self._covariance_type = covariance_type self._training_graph = None self._random_seed = random_seed
[ "def", "__init__", "(", "self", ",", "num_clusters", ",", "model_dir", "=", "None", ",", "random_seed", "=", "0", ",", "params", "=", "'wmc'", ",", "initial_clusters", "=", "'random'", ",", "covariance_type", "=", "'full'", ",", "batch_size", "=", "128", ",", "steps", "=", "10", ",", "continue_training", "=", "False", ",", "config", "=", "None", ",", "verbose", "=", "1", ")", ":", "super", "(", "GMM", ",", "self", ")", ".", "__init__", "(", "model_dir", "=", "model_dir", ",", "config", "=", "config", ")", "self", ".", "batch_size", "=", "batch_size", "self", ".", "steps", "=", "steps", "self", ".", "continue_training", "=", "continue_training", "self", ".", "verbose", "=", "verbose", "self", ".", "_num_clusters", "=", "num_clusters", "self", ".", "_params", "=", "params", "self", ".", "_training_initial_clusters", "=", "initial_clusters", "self", ".", "_covariance_type", "=", "covariance_type", "self", ".", "_training_graph", "=", "None", "self", ".", "_random_seed", "=", "random_seed" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/factorization/python/ops/gmm.py#L43-L85
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/skia_gold_common/skia_gold_session.py
python
SkiaGoldSession._GetDiffGoldInstance
(self)
return str(self._instance) + '-public'
Gets the Skia Gold instance to use for the Diff step. This can differ based on how a particular instance is set up, mainly depending on whether it is set up for internal results or not.
Gets the Skia Gold instance to use for the Diff step.
[ "Gets", "the", "Skia", "Gold", "instance", "to", "use", "for", "the", "Diff", "step", "." ]
def _GetDiffGoldInstance(self): """Gets the Skia Gold instance to use for the Diff step. This can differ based on how a particular instance is set up, mainly depending on whether it is set up for internal results or not. """ # TODO(skbug.com/10610): Decide whether to use the public or # non-public instance once authentication is fixed for the non-public # instance. return str(self._instance) + '-public'
[ "def", "_GetDiffGoldInstance", "(", "self", ")", ":", "# TODO(skbug.com/10610): Decide whether to use the public or", "# non-public instance once authentication is fixed for the non-public", "# instance.", "return", "str", "(", "self", ".", "_instance", ")", "+", "'-public'" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/skia_gold_common/skia_gold_session.py#L514-L523
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
PyAuiTabArt._setCallbackInfo
(*args, **kwargs)
return _aui.PyAuiTabArt__setCallbackInfo(*args, **kwargs)
_setCallbackInfo(self, PyObject self, PyObject _class)
_setCallbackInfo(self, PyObject self, PyObject _class)
[ "_setCallbackInfo", "(", "self", "PyObject", "self", "PyObject", "_class", ")" ]
def _setCallbackInfo(*args, **kwargs): """_setCallbackInfo(self, PyObject self, PyObject _class)""" return _aui.PyAuiTabArt__setCallbackInfo(*args, **kwargs)
[ "def", "_setCallbackInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "PyAuiTabArt__setCallbackInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L2431-L2433
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
PageSetupDialogData.SetDefaultInfo
(*args, **kwargs)
return _windows_.PageSetupDialogData_SetDefaultInfo(*args, **kwargs)
SetDefaultInfo(self, bool flag)
SetDefaultInfo(self, bool flag)
[ "SetDefaultInfo", "(", "self", "bool", "flag", ")" ]
def SetDefaultInfo(*args, **kwargs): """SetDefaultInfo(self, bool flag)""" return _windows_.PageSetupDialogData_SetDefaultInfo(*args, **kwargs)
[ "def", "SetDefaultInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PageSetupDialogData_SetDefaultInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L4947-L4949
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/mailbox.py
python
Mailbox.__init__
(self, path, factory=None, create=True)
Initialize a Mailbox instance.
Initialize a Mailbox instance.
[ "Initialize", "a", "Mailbox", "instance", "." ]
def __init__(self, path, factory=None, create=True): """Initialize a Mailbox instance.""" self._path = os.path.abspath(os.path.expanduser(path)) self._factory = factory
[ "def", "__init__", "(", "self", ",", "path", ",", "factory", "=", "None", ",", "create", "=", "True", ")", ":", "self", ".", "_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "self", ".", "_factory", "=", "factory" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L43-L46
jsk-ros-pkg/jsk_visualization
278abbff394c1275925b0419a4f359cda07fde61
jsk_rviz_plugins/scripts/contact_state_marker.py
python
callback
(msgs)
msgs = ContactStatesStamped
msgs = ContactStatesStamped
[ "msgs", "=", "ContactStatesStamped" ]
def callback(msgs): "msgs = ContactStatesStamped" global g_config if g_config.use_parent_link: urdf_robot = URDF.from_parameter_server() marker_array = MarkerArray() for msg, i in zip(msgs.states, range(len(msgs.states))): marker = Marker() link_name = msg.header.frame_id if g_config.use_parent_link: # lookup parent link chain = urdf_robot.get_chain(urdf_robot.get_root(), link_name) link_name = chain[-3] mesh_file, offset = find_mesh(link_name) marker.header.frame_id = link_name marker.header.stamp = rospy.Time.now() marker.type = Marker.MESH_RESOURCE if msg.state.state == ContactState.ON: marker.color.a = g_config.on_alpha marker.color.r = g_config.on_red marker.color.g = g_config.on_green marker.color.b = g_config.on_blue elif msg.state.state == ContactState.OFF: marker.color.a = g_config.off_alpha marker.color.r = g_config.off_red marker.color.g = g_config.off_green marker.color.b = g_config.off_blue marker.scale.x = g_config.marker_scale marker.scale.y = g_config.marker_scale marker.scale.z = g_config.marker_scale marker.pose = offset marker.mesh_resource = mesh_file marker.frame_locked = True marker.id = i if msg.state.state == ContactState.OFF: if not g_config.visualize_off: marker.action = Marker.DELETE marker_array.markers.append(marker) pub.publish(marker_array)
[ "def", "callback", "(", "msgs", ")", ":", "global", "g_config", "if", "g_config", ".", "use_parent_link", ":", "urdf_robot", "=", "URDF", ".", "from_parameter_server", "(", ")", "marker_array", "=", "MarkerArray", "(", ")", "for", "msg", ",", "i", "in", "zip", "(", "msgs", ".", "states", ",", "range", "(", "len", "(", "msgs", ".", "states", ")", ")", ")", ":", "marker", "=", "Marker", "(", ")", "link_name", "=", "msg", ".", "header", ".", "frame_id", "if", "g_config", ".", "use_parent_link", ":", "# lookup parent link", "chain", "=", "urdf_robot", ".", "get_chain", "(", "urdf_robot", ".", "get_root", "(", ")", ",", "link_name", ")", "link_name", "=", "chain", "[", "-", "3", "]", "mesh_file", ",", "offset", "=", "find_mesh", "(", "link_name", ")", "marker", ".", "header", ".", "frame_id", "=", "link_name", "marker", ".", "header", ".", "stamp", "=", "rospy", ".", "Time", ".", "now", "(", ")", "marker", ".", "type", "=", "Marker", ".", "MESH_RESOURCE", "if", "msg", ".", "state", ".", "state", "==", "ContactState", ".", "ON", ":", "marker", ".", "color", ".", "a", "=", "g_config", ".", "on_alpha", "marker", ".", "color", ".", "r", "=", "g_config", ".", "on_red", "marker", ".", "color", ".", "g", "=", "g_config", ".", "on_green", "marker", ".", "color", ".", "b", "=", "g_config", ".", "on_blue", "elif", "msg", ".", "state", ".", "state", "==", "ContactState", ".", "OFF", ":", "marker", ".", "color", ".", "a", "=", "g_config", ".", "off_alpha", "marker", ".", "color", ".", "r", "=", "g_config", ".", "off_red", "marker", ".", "color", ".", "g", "=", "g_config", ".", "off_green", "marker", ".", "color", ".", "b", "=", "g_config", ".", "off_blue", "marker", ".", "scale", ".", "x", "=", "g_config", ".", "marker_scale", "marker", ".", "scale", ".", "y", "=", "g_config", ".", "marker_scale", "marker", ".", "scale", ".", "z", "=", "g_config", ".", "marker_scale", "marker", ".", "pose", "=", "offset", "marker", ".", "mesh_resource", "=", "mesh_file", "marker", ".", "frame_locked", "=", "True", "marker", ".", "id", "=", "i", "if", "msg", ".", "state", ".", "state", "==", "ContactState", ".", "OFF", ":", "if", "not", "g_config", ".", "visualize_off", ":", "marker", ".", "action", "=", "Marker", ".", "DELETE", "marker_array", ".", "markers", ".", "append", "(", "marker", ")", "pub", ".", "publish", "(", "marker_array", ")" ]
https://github.com/jsk-ros-pkg/jsk_visualization/blob/278abbff394c1275925b0419a4f359cda07fde61/jsk_rviz_plugins/scripts/contact_state_marker.py#L47-L85
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/fit_function_options_view.py
python
FitFunctionOptionsView.set_slot_for_exclude_range_state_changed
(self, slot)
Connect the slot for the exclude range checkbox.
Connect the slot for the exclude range checkbox.
[ "Connect", "the", "slot", "for", "the", "exclude", "range", "checkbox", "." ]
def set_slot_for_exclude_range_state_changed(self, slot) -> None: """Connect the slot for the exclude range checkbox.""" self.exclude_range_checkbox.stateChanged.connect(slot)
[ "def", "set_slot_for_exclude_range_state_changed", "(", "self", ",", "slot", ")", "->", "None", ":", "self", ".", "exclude_range_checkbox", ".", "stateChanged", ".", "connect", "(", "slot", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/fit_function_options_view.py#L106-L108
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/signal/filter_design.py
python
lp2hp_zpk
(z, p, k, wo=1.0)
return z_hp, p_hp, k_hp
r""" Transform a lowpass filter prototype to a highpass filter. Return an analog high-pass filter with cutoff frequency `wo` from an analog low-pass filter prototype with unity cutoff frequency, using zeros, poles, and gain ('zpk') representation. Parameters ---------- z : array_like Zeros of the analog filter transfer function. p : array_like Poles of the analog filter transfer function. k : float System gain of the analog filter transfer function. wo : float Desired cutoff, as angular frequency (e.g. rad/s). Defaults to no change. Returns ------- z : ndarray Zeros of the transformed high-pass filter transfer function. p : ndarray Poles of the transformed high-pass filter transfer function. k : float System gain of the transformed high-pass filter. See Also -------- lp2lp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear lp2hp Notes ----- This is derived from the s-plane substitution .. math:: s \rightarrow \frac{\omega_0}{s} This maintains symmetry of the lowpass and highpass responses on a logarithmic scale. .. versionadded:: 1.1.0
r""" Transform a lowpass filter prototype to a highpass filter.
[ "r", "Transform", "a", "lowpass", "filter", "prototype", "to", "a", "highpass", "filter", "." ]
def lp2hp_zpk(z, p, k, wo=1.0): r""" Transform a lowpass filter prototype to a highpass filter. Return an analog high-pass filter with cutoff frequency `wo` from an analog low-pass filter prototype with unity cutoff frequency, using zeros, poles, and gain ('zpk') representation. Parameters ---------- z : array_like Zeros of the analog filter transfer function. p : array_like Poles of the analog filter transfer function. k : float System gain of the analog filter transfer function. wo : float Desired cutoff, as angular frequency (e.g. rad/s). Defaults to no change. Returns ------- z : ndarray Zeros of the transformed high-pass filter transfer function. p : ndarray Poles of the transformed high-pass filter transfer function. k : float System gain of the transformed high-pass filter. See Also -------- lp2lp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear lp2hp Notes ----- This is derived from the s-plane substitution .. math:: s \rightarrow \frac{\omega_0}{s} This maintains symmetry of the lowpass and highpass responses on a logarithmic scale. .. versionadded:: 1.1.0 """ z = atleast_1d(z) p = atleast_1d(p) wo = float(wo) degree = _relative_degree(z, p) # Invert positions radially about unit circle to convert LPF to HPF # Scale all points radially from origin to shift cutoff frequency z_hp = wo / z p_hp = wo / p # If lowpass had zeros at infinity, inverting moves them to origin. z_hp = append(z_hp, zeros(degree)) # Cancel out gain change caused by inversion k_hp = k * real(prod(-z) / prod(-p)) return z_hp, p_hp, k_hp
[ "def", "lp2hp_zpk", "(", "z", ",", "p", ",", "k", ",", "wo", "=", "1.0", ")", ":", "z", "=", "atleast_1d", "(", "z", ")", "p", "=", "atleast_1d", "(", "p", ")", "wo", "=", "float", "(", "wo", ")", "degree", "=", "_relative_degree", "(", "z", ",", "p", ")", "# Invert positions radially about unit circle to convert LPF to HPF", "# Scale all points radially from origin to shift cutoff frequency", "z_hp", "=", "wo", "/", "z", "p_hp", "=", "wo", "/", "p", "# If lowpass had zeros at infinity, inverting moves them to origin.", "z_hp", "=", "append", "(", "z_hp", ",", "zeros", "(", "degree", ")", ")", "# Cancel out gain change caused by inversion", "k_hp", "=", "k", "*", "real", "(", "prod", "(", "-", "z", ")", "/", "prod", "(", "-", "p", ")", ")", "return", "z_hp", ",", "p_hp", ",", "k_hp" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/filter_design.py#L2265-L2328
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/amp/grad_scaler.py
python
GradScaler.minimize
(self, optimizer, *args, **kwargs)
return super(GradScaler, self).minimize(optimizer, *args, **kwargs)
This function is similar as `optimizer.minimize()`, which performs parameters updating. If the scaled gradients of parameters contains NAN or INF, the parameters updating is skipped. Otherwise, if `unscale_()` has not been called, it first unscales the scaled gradients of parameters, then updates the parameters. Finally, the loss scaling ratio is updated. Args: optimizer(Optimizer): The optimizer used to update parameters. args: Arguments, which will be forward to `optimizer.minimize()`. kwargs: Keyword arguments, which will be forward to `optimizer.minimize()`. Examples: .. code-block:: python import paddle model = paddle.nn.Conv2D(3, 2, 3, bias_attr=True) optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) scaler = paddle.amp.GradScaler(init_loss_scaling=1024) data = paddle.rand([10, 3, 32, 32]) with paddle.amp.auto_cast(): conv = model(data) loss = paddle.mean(conv) scaled = scaler.scale(loss) # scale the loss scaled.backward() # do backward scaler.minimize(optimizer, scaled) # update parameters optimizer.clear_grad()
This function is similar as `optimizer.minimize()`, which performs parameters updating. If the scaled gradients of parameters contains NAN or INF, the parameters updating is skipped. Otherwise, if `unscale_()` has not been called, it first unscales the scaled gradients of parameters, then updates the parameters.
[ "This", "function", "is", "similar", "as", "optimizer", ".", "minimize", "()", "which", "performs", "parameters", "updating", ".", "If", "the", "scaled", "gradients", "of", "parameters", "contains", "NAN", "or", "INF", "the", "parameters", "updating", "is", "skipped", ".", "Otherwise", "if", "unscale_", "()", "has", "not", "been", "called", "it", "first", "unscales", "the", "scaled", "gradients", "of", "parameters", "then", "updates", "the", "parameters", "." ]
def minimize(self, optimizer, *args, **kwargs): """ This function is similar as `optimizer.minimize()`, which performs parameters updating. If the scaled gradients of parameters contains NAN or INF, the parameters updating is skipped. Otherwise, if `unscale_()` has not been called, it first unscales the scaled gradients of parameters, then updates the parameters. Finally, the loss scaling ratio is updated. Args: optimizer(Optimizer): The optimizer used to update parameters. args: Arguments, which will be forward to `optimizer.minimize()`. kwargs: Keyword arguments, which will be forward to `optimizer.minimize()`. Examples: .. code-block:: python import paddle model = paddle.nn.Conv2D(3, 2, 3, bias_attr=True) optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) scaler = paddle.amp.GradScaler(init_loss_scaling=1024) data = paddle.rand([10, 3, 32, 32]) with paddle.amp.auto_cast(): conv = model(data) loss = paddle.mean(conv) scaled = scaler.scale(loss) # scale the loss scaled.backward() # do backward scaler.minimize(optimizer, scaled) # update parameters optimizer.clear_grad() """ return super(GradScaler, self).minimize(optimizer, *args, **kwargs)
[ "def", "minimize", "(", "self", ",", "optimizer", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "GradScaler", ",", "self", ")", ".", "minimize", "(", "optimizer", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/amp/grad_scaler.py#L123-L157
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/third_party/jinja2/filters.py
python
do_title
(s)
return ''.join( [item[0].upper() + item[1:].lower() for item in _word_beginning_split_re.split(soft_unicode(s)) if item])
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
[ "Return", "a", "titlecased", "version", "of", "the", "value", ".", "I", ".", "e", ".", "words", "will", "start", "with", "uppercase", "letters", "all", "remaining", "characters", "are", "lowercase", "." ]
def do_title(s): """Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase. """ return ''.join( [item[0].upper() + item[1:].lower() for item in _word_beginning_split_re.split(soft_unicode(s)) if item])
[ "def", "do_title", "(", "s", ")", ":", "return", "''", ".", "join", "(", "[", "item", "[", "0", "]", ".", "upper", "(", ")", "+", "item", "[", "1", ":", "]", ".", "lower", "(", ")", "for", "item", "in", "_word_beginning_split_re", ".", "split", "(", "soft_unicode", "(", "s", ")", ")", "if", "item", "]", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/filters.py#L196-L203
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
Font.MakeSmaller
(*args, **kwargs)
return _gdi_.Font_MakeSmaller(*args, **kwargs)
MakeSmaller(self) -> Font
MakeSmaller(self) -> Font
[ "MakeSmaller", "(", "self", ")", "-", ">", "Font" ]
def MakeSmaller(*args, **kwargs): """MakeSmaller(self) -> Font""" return _gdi_.Font_MakeSmaller(*args, **kwargs)
[ "def", "MakeSmaller", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Font_MakeSmaller", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L2557-L2559
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Netscape/Standard_Suite.py
python
Standard_Suite_Events.set
(self, _object, _attributes={}, **_arguments)
set: Set an object\xd5s data Required argument: the object to change Keyword argument to: the new value Keyword argument _attributes: AppleEvent attribute dictionary
set: Set an object\xd5s data Required argument: the object to change Keyword argument to: the new value Keyword argument _attributes: AppleEvent attribute dictionary
[ "set", ":", "Set", "an", "object", "\\", "xd5s", "data", "Required", "argument", ":", "the", "object", "to", "change", "Keyword", "argument", "to", ":", "the", "new", "value", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def set(self, _object, _attributes={}, **_arguments): """set: Set an object\xd5s data Required argument: the object to change Keyword argument to: the new value Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'core' _subcode = 'setd' aetools.keysubst(_arguments, self._argmap_set) _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "set", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'core'", "_subcode", "=", "'setd'", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", "_argmap_set", ")", "_arguments", "[", "'----'", "]", "=", "_object", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Netscape/Standard_Suite.py#L82-L101
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/control_flow_ops.py
python
_pfor_impl
(loop_fn, iters, parallel_iterations=None, pfor_config=None)
Implementation of pfor.
Implementation of pfor.
[ "Implementation", "of", "pfor", "." ]
def _pfor_impl(loop_fn, iters, parallel_iterations=None, pfor_config=None): """Implementation of pfor.""" loop_fn_has_config = _loop_fn_has_config(loop_fn) existing_ops = set(ops.get_default_graph().get_operations()) # Run the loop body with ops.name_scope("loop_body"): loop_var = array_ops.placeholder(dtypes.int32, shape=[]) if loop_fn_has_config: if pfor_config is None: pfor_config = PForConfig() pfor_config._set_iters(iters) # pylint: disable=protected-access loop_fn_outputs = loop_fn(loop_var, **{PFOR_CONFIG_ARG: pfor_config}) else: assert pfor_config is None loop_fn_outputs = loop_fn(loop_var) # Convert outputs to Tensor if needed. tmp_loop_fn_outputs = [] for loop_fn_output in nest.flatten(loop_fn_outputs): if (loop_fn_output is not None and not isinstance( loop_fn_output, (ops.Operation, ops.Tensor, sparse_tensor.SparseTensor))): if isinstance(loop_fn_output, indexed_slices.IndexedSlices): logging.warn("Converting %s to a dense representation may make it slow." " Alternatively, output the indices and values of the" " IndexedSlices separately, and handle the vectorized" " outputs directly." % loop_fn_output) loop_fn_output = ops.convert_to_tensor(loop_fn_output) tmp_loop_fn_outputs.append(loop_fn_output) loop_fn_outputs = nest.pack_sequence_as(loop_fn_outputs, tmp_loop_fn_outputs) new_ops = set(ops.get_default_graph().get_operations()) - existing_ops iters = ops.convert_to_tensor(iters) if parallel_iterations is not None: if parallel_iterations < 1: raise ValueError("parallel_iterations must be None or a positive integer") if parallel_iterations == 1: raise ValueError("Found parallel_iterations == 1. Use for_loop instead.") iters_value = tensor_util.constant_value(iters) if iters_value is not None and iters_value < parallel_iterations: parallel_iterations = None if parallel_iterations is None: with ops.name_scope("pfor"): converter = PFor(loop_var, iters, new_ops, pfor_config=pfor_config) outputs = [] for loop_fn_output in nest.flatten(loop_fn_outputs): outputs.append(converter.convert(loop_fn_output)) return nest.pack_sequence_as(loop_fn_outputs, outputs) else: if pfor_config is not None and pfor_config._has_reductions(): # pylint: disable=protected-access raise ValueError("Setting parallel_iterations currently unsupported if" " reductions across iterations are performed.") num_tiled_iterations = iters // parallel_iterations num_remaining_iterations = iters % parallel_iterations # TODO(agarwal): Avoid calling loop_fn twice. Generate the loop body inside # a tf.function and extract the graph from there to vectorize it. with ops.name_scope("pfor_untiled"): converter = PFor(loop_var, num_remaining_iterations, new_ops, pfor_config=pfor_config) remaining_outputs = [] flattened_loop_fn_outputs = nest.flatten(loop_fn_outputs) for loop_fn_output in flattened_loop_fn_outputs: remaining_outputs.append(converter.convert(loop_fn_output)) with ops.name_scope("pfor_tiled"): loop_fn_dtypes = [ops.convert_to_tensor(x).dtype for x in flattened_loop_fn_outputs] def tiled_loop_body(j): offset = j * parallel_iterations + num_remaining_iterations def tiled_loop_fn(i, pfor_config=None): if loop_fn_has_config: return nest.flatten(loop_fn(i + offset, pfor_config=pfor_config)) else: return nest.flatten(loop_fn(i + offset)) return _pfor_impl( tiled_loop_fn, parallel_iterations, pfor_config=pfor_config) tiled_outputs = for_loop(tiled_loop_body, loop_fn_dtypes, num_tiled_iterations, parallel_iterations=1) tiled_outputs = [_flatten_first_two_dims(y) for y in tiled_outputs] with ops.name_scope("pfor"): iters_value = tensor_util.constant_value(iters) if iters_value is None or iters_value % parallel_iterations: outputs = control_flow_ops.cond( math_ops.equal(num_remaining_iterations, 0), lambda: tiled_outputs, lambda: [array_ops.concat([x, y], axis=0) for x, y in zip(remaining_outputs, tiled_outputs)]) else: outputs = tiled_outputs return nest.pack_sequence_as(loop_fn_outputs, nest.flatten(outputs))
[ "def", "_pfor_impl", "(", "loop_fn", ",", "iters", ",", "parallel_iterations", "=", "None", ",", "pfor_config", "=", "None", ")", ":", "loop_fn_has_config", "=", "_loop_fn_has_config", "(", "loop_fn", ")", "existing_ops", "=", "set", "(", "ops", ".", "get_default_graph", "(", ")", ".", "get_operations", "(", ")", ")", "# Run the loop body", "with", "ops", ".", "name_scope", "(", "\"loop_body\"", ")", ":", "loop_var", "=", "array_ops", ".", "placeholder", "(", "dtypes", ".", "int32", ",", "shape", "=", "[", "]", ")", "if", "loop_fn_has_config", ":", "if", "pfor_config", "is", "None", ":", "pfor_config", "=", "PForConfig", "(", ")", "pfor_config", ".", "_set_iters", "(", "iters", ")", "# pylint: disable=protected-access", "loop_fn_outputs", "=", "loop_fn", "(", "loop_var", ",", "*", "*", "{", "PFOR_CONFIG_ARG", ":", "pfor_config", "}", ")", "else", ":", "assert", "pfor_config", "is", "None", "loop_fn_outputs", "=", "loop_fn", "(", "loop_var", ")", "# Convert outputs to Tensor if needed.", "tmp_loop_fn_outputs", "=", "[", "]", "for", "loop_fn_output", "in", "nest", ".", "flatten", "(", "loop_fn_outputs", ")", ":", "if", "(", "loop_fn_output", "is", "not", "None", "and", "not", "isinstance", "(", "loop_fn_output", ",", "(", "ops", ".", "Operation", ",", "ops", ".", "Tensor", ",", "sparse_tensor", ".", "SparseTensor", ")", ")", ")", ":", "if", "isinstance", "(", "loop_fn_output", ",", "indexed_slices", ".", "IndexedSlices", ")", ":", "logging", ".", "warn", "(", "\"Converting %s to a dense representation may make it slow.\"", "\" Alternatively, output the indices and values of the\"", "\" IndexedSlices separately, and handle the vectorized\"", "\" outputs directly.\"", "%", "loop_fn_output", ")", "loop_fn_output", "=", "ops", ".", "convert_to_tensor", "(", "loop_fn_output", ")", "tmp_loop_fn_outputs", ".", "append", "(", "loop_fn_output", ")", "loop_fn_outputs", "=", "nest", ".", "pack_sequence_as", "(", "loop_fn_outputs", ",", "tmp_loop_fn_outputs", ")", "new_ops", "=", "set", "(", "ops", ".", "get_default_graph", "(", ")", ".", "get_operations", "(", ")", ")", "-", "existing_ops", "iters", "=", "ops", ".", "convert_to_tensor", "(", "iters", ")", "if", "parallel_iterations", "is", "not", "None", ":", "if", "parallel_iterations", "<", "1", ":", "raise", "ValueError", "(", "\"parallel_iterations must be None or a positive integer\"", ")", "if", "parallel_iterations", "==", "1", ":", "raise", "ValueError", "(", "\"Found parallel_iterations == 1. Use for_loop instead.\"", ")", "iters_value", "=", "tensor_util", ".", "constant_value", "(", "iters", ")", "if", "iters_value", "is", "not", "None", "and", "iters_value", "<", "parallel_iterations", ":", "parallel_iterations", "=", "None", "if", "parallel_iterations", "is", "None", ":", "with", "ops", ".", "name_scope", "(", "\"pfor\"", ")", ":", "converter", "=", "PFor", "(", "loop_var", ",", "iters", ",", "new_ops", ",", "pfor_config", "=", "pfor_config", ")", "outputs", "=", "[", "]", "for", "loop_fn_output", "in", "nest", ".", "flatten", "(", "loop_fn_outputs", ")", ":", "outputs", ".", "append", "(", "converter", ".", "convert", "(", "loop_fn_output", ")", ")", "return", "nest", ".", "pack_sequence_as", "(", "loop_fn_outputs", ",", "outputs", ")", "else", ":", "if", "pfor_config", "is", "not", "None", "and", "pfor_config", ".", "_has_reductions", "(", ")", ":", "# pylint: disable=protected-access", "raise", "ValueError", "(", "\"Setting parallel_iterations currently unsupported if\"", "\" reductions across iterations are performed.\"", ")", "num_tiled_iterations", "=", "iters", "//", "parallel_iterations", "num_remaining_iterations", "=", "iters", "%", "parallel_iterations", "# TODO(agarwal): Avoid calling loop_fn twice. Generate the loop body inside", "# a tf.function and extract the graph from there to vectorize it.", "with", "ops", ".", "name_scope", "(", "\"pfor_untiled\"", ")", ":", "converter", "=", "PFor", "(", "loop_var", ",", "num_remaining_iterations", ",", "new_ops", ",", "pfor_config", "=", "pfor_config", ")", "remaining_outputs", "=", "[", "]", "flattened_loop_fn_outputs", "=", "nest", ".", "flatten", "(", "loop_fn_outputs", ")", "for", "loop_fn_output", "in", "flattened_loop_fn_outputs", ":", "remaining_outputs", ".", "append", "(", "converter", ".", "convert", "(", "loop_fn_output", ")", ")", "with", "ops", ".", "name_scope", "(", "\"pfor_tiled\"", ")", ":", "loop_fn_dtypes", "=", "[", "ops", ".", "convert_to_tensor", "(", "x", ")", ".", "dtype", "for", "x", "in", "flattened_loop_fn_outputs", "]", "def", "tiled_loop_body", "(", "j", ")", ":", "offset", "=", "j", "*", "parallel_iterations", "+", "num_remaining_iterations", "def", "tiled_loop_fn", "(", "i", ",", "pfor_config", "=", "None", ")", ":", "if", "loop_fn_has_config", ":", "return", "nest", ".", "flatten", "(", "loop_fn", "(", "i", "+", "offset", ",", "pfor_config", "=", "pfor_config", ")", ")", "else", ":", "return", "nest", ".", "flatten", "(", "loop_fn", "(", "i", "+", "offset", ")", ")", "return", "_pfor_impl", "(", "tiled_loop_fn", ",", "parallel_iterations", ",", "pfor_config", "=", "pfor_config", ")", "tiled_outputs", "=", "for_loop", "(", "tiled_loop_body", ",", "loop_fn_dtypes", ",", "num_tiled_iterations", ",", "parallel_iterations", "=", "1", ")", "tiled_outputs", "=", "[", "_flatten_first_two_dims", "(", "y", ")", "for", "y", "in", "tiled_outputs", "]", "with", "ops", ".", "name_scope", "(", "\"pfor\"", ")", ":", "iters_value", "=", "tensor_util", ".", "constant_value", "(", "iters", ")", "if", "iters_value", "is", "None", "or", "iters_value", "%", "parallel_iterations", ":", "outputs", "=", "control_flow_ops", ".", "cond", "(", "math_ops", ".", "equal", "(", "num_remaining_iterations", ",", "0", ")", ",", "lambda", ":", "tiled_outputs", ",", "lambda", ":", "[", "array_ops", ".", "concat", "(", "[", "x", ",", "y", "]", ",", "axis", "=", "0", ")", "for", "x", ",", "y", "in", "zip", "(", "remaining_outputs", ",", "tiled_outputs", ")", "]", ")", "else", ":", "outputs", "=", "tiled_outputs", "return", "nest", ".", "pack_sequence_as", "(", "loop_fn_outputs", ",", "nest", ".", "flatten", "(", "outputs", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/control_flow_ops.py#L211-L305
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
veles/external/pydot.py
python
Graph.del_node
(self, name, index=None)
return False
Delete a node from the graph. Given a node's name all node(s) with that same name will be deleted if 'index' is not specified or set to None. If there are several nodes with that same name and 'index' is given, only the node in that position will be deleted. 'index' should be an integer specifying the position of the node to delete. If index is larger than the number of nodes with that name, no action is taken. If nodes are deleted it returns True. If no action is taken it returns False.
Delete a node from the graph. Given a node's name all node(s) with that same name will be deleted if 'index' is not specified or set to None. If there are several nodes with that same name and 'index' is given, only the node in that position will be deleted. 'index' should be an integer specifying the position of the node to delete. If index is larger than the number of nodes with that name, no action is taken. If nodes are deleted it returns True. If no action is taken it returns False.
[ "Delete", "a", "node", "from", "the", "graph", ".", "Given", "a", "node", "s", "name", "all", "node", "(", "s", ")", "with", "that", "same", "name", "will", "be", "deleted", "if", "index", "is", "not", "specified", "or", "set", "to", "None", ".", "If", "there", "are", "several", "nodes", "with", "that", "same", "name", "and", "index", "is", "given", "only", "the", "node", "in", "that", "position", "will", "be", "deleted", ".", "index", "should", "be", "an", "integer", "specifying", "the", "position", "of", "the", "node", "to", "delete", ".", "If", "index", "is", "larger", "than", "the", "number", "of", "nodes", "with", "that", "name", "no", "action", "is", "taken", ".", "If", "nodes", "are", "deleted", "it", "returns", "True", ".", "If", "no", "action", "is", "taken", "it", "returns", "False", "." ]
def del_node(self, name, index=None): """Delete a node from the graph. Given a node's name all node(s) with that same name will be deleted if 'index' is not specified or set to None. If there are several nodes with that same name and 'index' is given, only the node in that position will be deleted. 'index' should be an integer specifying the position of the node to delete. If index is larger than the number of nodes with that name, no action is taken. If nodes are deleted it returns True. If no action is taken it returns False. """ if isinstance(name, Node): name = name.get_name() if name in self.obj_dict['nodes']: if index is not None and index < len(self.obj_dict['nodes'][name]): del self.obj_dict['nodes'][name][index] return True else: del self.obj_dict['nodes'][name] return True return False
[ "def", "del_node", "(", "self", ",", "name", ",", "index", "=", "None", ")", ":", "if", "isinstance", "(", "name", ",", "Node", ")", ":", "name", "=", "name", ".", "get_name", "(", ")", "if", "name", "in", "self", ".", "obj_dict", "[", "'nodes'", "]", ":", "if", "index", "is", "not", "None", "and", "index", "<", "len", "(", "self", ".", "obj_dict", "[", "'nodes'", "]", "[", "name", "]", ")", ":", "del", "self", ".", "obj_dict", "[", "'nodes'", "]", "[", "name", "]", "[", "index", "]", "return", "True", "else", ":", "del", "self", ".", "obj_dict", "[", "'nodes'", "]", "[", "name", "]", "return", "True", "return", "False" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/pydot.py#L1280-L1310
nest/nest-simulator
f2623eb78518cdbd55e77e0ed486bf1111bcb62f
pynest/nest/spatial/hl_api_spatial.py
python
source_pos.n
(dimension)
return CreateParameter('position', {'dimension': dimension, 'synaptic_endpoint': 1})
Position of source node in given dimension. Parameters ---------- dimension : int Dimension in which to get the position. Returns ------- Parameter: Object yielding the position in the given dimension.
Position of source node in given dimension.
[ "Position", "of", "source", "node", "in", "given", "dimension", "." ]
def n(dimension): """ Position of source node in given dimension. Parameters ---------- dimension : int Dimension in which to get the position. Returns ------- Parameter: Object yielding the position in the given dimension. """ return CreateParameter('position', {'dimension': dimension, 'synaptic_endpoint': 1})
[ "def", "n", "(", "dimension", ")", ":", "return", "CreateParameter", "(", "'position'", ",", "{", "'dimension'", ":", "dimension", ",", "'synaptic_endpoint'", ":", "1", "}", ")" ]
https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/nest/spatial/hl_api_spatial.py#L132-L147
RLBot/RLBot
34332b12cf158b3ef8dbf174ae67c53683368a9d
src/main/python/rlbot/setup_manager.py
python
setup_manager_context
(launcher_preference: RocketLeagueLauncherPreference = None)
Creates a initialized context manager which shuts down at the end of the `with` block. usage: >>> with setup_manager_context() as setup_manager: ... setup_manager.load_config(...) ... # ... Run match
Creates a initialized context manager which shuts down at the end of the `with` block.
[ "Creates", "a", "initialized", "context", "manager", "which", "shuts", "down", "at", "the", "end", "of", "the", "with", "block", "." ]
def setup_manager_context(launcher_preference: RocketLeagueLauncherPreference = None): """ Creates a initialized context manager which shuts down at the end of the `with` block. usage: >>> with setup_manager_context() as setup_manager: ... setup_manager.load_config(...) ... # ... Run match """ setup_manager = SetupManager() setup_manager.connect_to_game(launcher_preference) try: yield setup_manager except Exception as e: get_logger(DEFAULT_LOGGER).error(e) raise e finally: setup_manager.shut_down(kill_all_pids=True)
[ "def", "setup_manager_context", "(", "launcher_preference", ":", "RocketLeagueLauncherPreference", "=", "None", ")", ":", "setup_manager", "=", "SetupManager", "(", ")", "setup_manager", ".", "connect_to_game", "(", "launcher_preference", ")", "try", ":", "yield", "setup_manager", "except", "Exception", "as", "e", ":", "get_logger", "(", "DEFAULT_LOGGER", ")", ".", "error", "(", "e", ")", "raise", "e", "finally", ":", "setup_manager", ".", "shut_down", "(", "kill_all_pids", "=", "True", ")" ]
https://github.com/RLBot/RLBot/blob/34332b12cf158b3ef8dbf174ae67c53683368a9d/src/main/python/rlbot/setup_manager.py#L88-L106
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/mox.py
python
UnorderedGroup.MethodCalled
(self, mock_method)
Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raises: UnexpectedMethodCallError if the mock_method was not in the group.
Remove a method call from the group.
[ "Remove", "a", "method", "call", "from", "the", "group", "." ]
def MethodCalled(self, mock_method): """Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raises: UnexpectedMethodCallError if the mock_method was not in the group. """ # Check to see if this method exists, and if so, remove it from the set # and return it. for method in self._methods: if method == mock_method: # Remove the called mock_method instead of the method in the group. # The called method will match any comparators when equality is checked # during removal. The method in the group could pass a comparator to # another comparator during the equality check. self._methods.remove(mock_method) # If this group is not empty, put it back at the head of the queue. if not self.IsSatisfied(): mock_method._call_queue.appendleft(self) return self, method raise UnexpectedMethodCallError(mock_method, self)
[ "def", "MethodCalled", "(", "self", ",", "mock_method", ")", ":", "# Check to see if this method exists, and if so, remove it from the set", "# and return it.", "for", "method", "in", "self", ".", "_methods", ":", "if", "method", "==", "mock_method", ":", "# Remove the called mock_method instead of the method in the group.", "# The called method will match any comparators when equality is checked", "# during removal. The method in the group could pass a comparator to", "# another comparator during the equality check.", "self", ".", "_methods", ".", "remove", "(", "mock_method", ")", "# If this group is not empty, put it back at the head of the queue.", "if", "not", "self", ".", "IsSatisfied", "(", ")", ":", "mock_method", ".", "_call_queue", ".", "appendleft", "(", "self", ")", "return", "self", ",", "method", "raise", "UnexpectedMethodCallError", "(", "mock_method", ",", "self", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/mox.py#L1223-L1255
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
distrib/propgrid/cpp_header_parser.py
python
class_obj.find_super_class
(self, classes_dict, any_of_these)
return None
\ Tries to find a specific class in one of the super classes. classes_dict: dictionary of classes available (should include self). any_of_these: One of these is acceptable name of super class.
\ Tries to find a specific class in one of the super classes.
[ "\\", "Tries", "to", "find", "a", "specific", "class", "in", "one", "of", "the", "super", "classes", "." ]
def find_super_class(self, classes_dict, any_of_these): """\ Tries to find a specific class in one of the super classes. classes_dict: dictionary of classes available (should include self). any_of_these: One of these is acceptable name of super class. """ for scls in self.base_classes: if scls in any_of_these: return scls try: return classes_dict[scls].find_super_class(classes_dict, any_of_these) except KeyError: pass return None
[ "def", "find_super_class", "(", "self", ",", "classes_dict", ",", "any_of_these", ")", ":", "for", "scls", "in", "self", ".", "base_classes", ":", "if", "scls", "in", "any_of_these", ":", "return", "scls", "try", ":", "return", "classes_dict", "[", "scls", "]", ".", "find_super_class", "(", "classes_dict", ",", "any_of_these", ")", "except", "KeyError", ":", "pass", "return", "None" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/distrib/propgrid/cpp_header_parser.py#L23-L40
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/meta_graph.py
python
import_scoped_meta_graph_with_return_elements
( meta_graph_or_file, clear_devices=False, graph=None, import_scope=None, input_map=None, unbound_inputs_col_name="unbound_inputs", restore_collections_predicate=(lambda key: True), return_elements=None)
return var_list, imported_return_elements
Imports graph from `MetaGraphDef` and returns vars and return elements. This function takes a `MetaGraphDef` protocol buffer as input. If the argument is a file containing a `MetaGraphDef` protocol buffer , it constructs a protocol buffer from the file content. The function then adds all the nodes from the `graph_def` field to the current graph, recreates the desired collections, and returns a dictionary of all the Variables imported into the name scope. In combination with `export_scoped_meta_graph()`, this function can be used to * Serialize a graph along with other Python objects such as `QueueRunner`, `Variable` into a `MetaGraphDef`. * Restart training from a saved graph and checkpoints. * Run inference from a saved graph and checkpoints. Args: meta_graph_or_file: `MetaGraphDef` protocol buffer or filename (including the path) containing a `MetaGraphDef`. clear_devices: Boolean which controls whether to clear device information from graph_def. Default false. graph: The `Graph` to import into. If `None`, use the default graph. import_scope: Optional `string`. Name scope into which to import the subgraph. If `None`, the graph is imported to the root name scope. input_map: A dictionary mapping input names (as strings) in `graph_def` to `Tensor` objects. The values of the named input tensors in the imported graph will be re-mapped to the respective `Tensor` values. unbound_inputs_col_name: Collection name for looking up unbound inputs. restore_collections_predicate: a predicate on collection names. A collection named c (i.e whose key is c) will be restored iff 1) `restore_collections_predicate(c)` is True, and 2) `c != unbound_inputs_col_name`. return_elements: A list of strings containing operation names in the `MetaGraphDef` that will be returned as `Operation` objects; and/or tensor names in `MetaGraphDef` that will be returned as `Tensor` objects. Returns: A tuple of ( dictionary of all the `Variables` imported into the name scope, list of `Operation` or `Tensor` objects from the `return_elements` list). Raises: ValueError: If the graph_def contains unbound inputs.
Imports graph from `MetaGraphDef` and returns vars and return elements.
[ "Imports", "graph", "from", "MetaGraphDef", "and", "returns", "vars", "and", "return", "elements", "." ]
def import_scoped_meta_graph_with_return_elements( meta_graph_or_file, clear_devices=False, graph=None, import_scope=None, input_map=None, unbound_inputs_col_name="unbound_inputs", restore_collections_predicate=(lambda key: True), return_elements=None): """Imports graph from `MetaGraphDef` and returns vars and return elements. This function takes a `MetaGraphDef` protocol buffer as input. If the argument is a file containing a `MetaGraphDef` protocol buffer , it constructs a protocol buffer from the file content. The function then adds all the nodes from the `graph_def` field to the current graph, recreates the desired collections, and returns a dictionary of all the Variables imported into the name scope. In combination with `export_scoped_meta_graph()`, this function can be used to * Serialize a graph along with other Python objects such as `QueueRunner`, `Variable` into a `MetaGraphDef`. * Restart training from a saved graph and checkpoints. * Run inference from a saved graph and checkpoints. Args: meta_graph_or_file: `MetaGraphDef` protocol buffer or filename (including the path) containing a `MetaGraphDef`. clear_devices: Boolean which controls whether to clear device information from graph_def. Default false. graph: The `Graph` to import into. If `None`, use the default graph. import_scope: Optional `string`. Name scope into which to import the subgraph. If `None`, the graph is imported to the root name scope. input_map: A dictionary mapping input names (as strings) in `graph_def` to `Tensor` objects. The values of the named input tensors in the imported graph will be re-mapped to the respective `Tensor` values. unbound_inputs_col_name: Collection name for looking up unbound inputs. restore_collections_predicate: a predicate on collection names. A collection named c (i.e whose key is c) will be restored iff 1) `restore_collections_predicate(c)` is True, and 2) `c != unbound_inputs_col_name`. return_elements: A list of strings containing operation names in the `MetaGraphDef` that will be returned as `Operation` objects; and/or tensor names in `MetaGraphDef` that will be returned as `Tensor` objects. Returns: A tuple of ( dictionary of all the `Variables` imported into the name scope, list of `Operation` or `Tensor` objects from the `return_elements` list). Raises: ValueError: If the graph_def contains unbound inputs. """ if context.executing_eagerly(): raise ValueError("Exporting/importing meta graphs is not supported when " "eager execution is enabled.") if isinstance(meta_graph_or_file, meta_graph_pb2.MetaGraphDef): meta_graph_def = meta_graph_or_file else: meta_graph_def = read_meta_graph_file(meta_graph_or_file) if unbound_inputs_col_name: for key, col_def in meta_graph_def.collection_def.items(): if key == unbound_inputs_col_name: kind = col_def.WhichOneof("kind") field = getattr(col_def, kind) if field.value and ( not input_map or sorted([compat.as_str(v) for v in field.value]) != sorted(input_map)): raise ValueError("Graph contains unbound inputs: %s. Must " "provide these inputs through input_map." % ",".join([compat.as_str(v) for v in field.value if not input_map or v not in input_map])) break # Sets graph to default graph if it's not passed in. graph = graph or ops.get_default_graph() # Gathers the list of nodes we are interested in. with graph.as_default(): producer_op_list = None if meta_graph_def.meta_info_def.HasField("stripped_op_list"): producer_op_list = meta_graph_def.meta_info_def.stripped_op_list input_graph_def = meta_graph_def.graph_def # Remove all the explicit device specifications for this node. This helps to # make the graph more portable. if clear_devices: for node in input_graph_def.node: node.device = "" scope_to_prepend_to_names = graph.unique_name( import_scope or "", mark_as_used=False) imported_return_elements = importer.import_graph_def( input_graph_def, name=(import_scope or scope_to_prepend_to_names), input_map=input_map, producer_op_list=producer_op_list, return_elements=return_elements) # TensorFlow versions before 1.9 (not inclusive) exported SavedModels # without a VariableDef.trainable field set. tf_version = meta_graph_def.meta_info_def.tensorflow_version if not tf_version: variables_have_trainable = True else: variables_have_trainable = ( distutils_version.LooseVersion(tf_version) >= distutils_version.LooseVersion("1.9")) # Sort collections so we see TRAINABLE_VARIABLES first and can default these # variables to trainable if the value is not set in their VariableDef. sorted_collections = [] if ops.GraphKeys.TRAINABLE_VARIABLES in meta_graph_def.collection_def: sorted_collections.append( (ops.GraphKeys.TRAINABLE_VARIABLES, meta_graph_def.collection_def[ops.GraphKeys.TRAINABLE_VARIABLES])) for key, value in sorted(meta_graph_def.collection_def.items()): if key != ops.GraphKeys.TRAINABLE_VARIABLES: sorted_collections.append((key, value)) # Restores all the other collections. variable_objects = {} for key, col_def in sorted_collections: # Don't add unbound_inputs to the new graph. if key == unbound_inputs_col_name: continue if not restore_collections_predicate(key): continue kind = col_def.WhichOneof("kind") if kind is None: logging.error("Cannot identify data type for collection %s. Skipping.", key) continue from_proto = ops.get_from_proto_function(key) # Temporary change to allow the TFMA evaluator to read metric variables # saved as a bytes list. # TODO(kathywu): Remove this hack once cl/248406059 has been submitted. if key == ops.GraphKeys.METRIC_VARIABLES: # Metric variables will use the same proto functions as GLOBAL_VARIABLES from_proto = ops.get_from_proto_function(ops.GraphKeys.GLOBAL_VARIABLES) if from_proto and kind == "bytes_list": proto_type = ops.get_collection_proto_type(key) if key in ops.GraphKeys._VARIABLE_COLLECTIONS: # pylint: disable=protected-access for value in col_def.bytes_list.value: variable = variable_objects.get(value, None) if variable is None: proto = proto_type() proto.ParseFromString(value) if not variables_have_trainable: # If the VariableDef proto does not contain a "trainable" # property because it was exported before that property was # added, we default it to whether the variable is in the # TRAINABLE_VARIABLES collection. We've sorted # TRAINABLE_VARIABLES to be first, so trainable variables will # be created from that collection. proto.trainable = (key == ops.GraphKeys.TRAINABLE_VARIABLES) variable = from_proto( proto, import_scope=scope_to_prepend_to_names) variable_objects[value] = variable graph.add_to_collection(key, variable) else: for value in col_def.bytes_list.value: proto = proto_type() proto.ParseFromString(value) graph.add_to_collection( key, from_proto( proto, import_scope=scope_to_prepend_to_names)) else: field = getattr(col_def, kind) if key in _COMPAT_COLLECTION_LIST: logging.warning( "The saved meta_graph is possibly from an older release:\n" "'%s' collection should be of type 'byte_list', but instead " "is of type '%s'.", key, kind) if kind == "node_list": for value in field.value: col_op = graph.as_graph_element( ops.prepend_name_scope(value, scope_to_prepend_to_names)) graph.add_to_collection(key, col_op) elif kind == "int64_list": # NOTE(opensource): This force conversion is to work around the fact # that Python2 distinguishes between int and long, while Python3 has # only int. for value in field.value: graph.add_to_collection(key, int(value)) else: for value in field.value: graph.add_to_collection( key, ops.prepend_name_scope(value, scope_to_prepend_to_names)) var_list = {} variables = graph.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, scope=scope_to_prepend_to_names) for v in variables: var_list[ops.strip_name_scope(v.name, scope_to_prepend_to_names)] = v return var_list, imported_return_elements
[ "def", "import_scoped_meta_graph_with_return_elements", "(", "meta_graph_or_file", ",", "clear_devices", "=", "False", ",", "graph", "=", "None", ",", "import_scope", "=", "None", ",", "input_map", "=", "None", ",", "unbound_inputs_col_name", "=", "\"unbound_inputs\"", ",", "restore_collections_predicate", "=", "(", "lambda", "key", ":", "True", ")", ",", "return_elements", "=", "None", ")", ":", "if", "context", ".", "executing_eagerly", "(", ")", ":", "raise", "ValueError", "(", "\"Exporting/importing meta graphs is not supported when \"", "\"eager execution is enabled.\"", ")", "if", "isinstance", "(", "meta_graph_or_file", ",", "meta_graph_pb2", ".", "MetaGraphDef", ")", ":", "meta_graph_def", "=", "meta_graph_or_file", "else", ":", "meta_graph_def", "=", "read_meta_graph_file", "(", "meta_graph_or_file", ")", "if", "unbound_inputs_col_name", ":", "for", "key", ",", "col_def", "in", "meta_graph_def", ".", "collection_def", ".", "items", "(", ")", ":", "if", "key", "==", "unbound_inputs_col_name", ":", "kind", "=", "col_def", ".", "WhichOneof", "(", "\"kind\"", ")", "field", "=", "getattr", "(", "col_def", ",", "kind", ")", "if", "field", ".", "value", "and", "(", "not", "input_map", "or", "sorted", "(", "[", "compat", ".", "as_str", "(", "v", ")", "for", "v", "in", "field", ".", "value", "]", ")", "!=", "sorted", "(", "input_map", ")", ")", ":", "raise", "ValueError", "(", "\"Graph contains unbound inputs: %s. Must \"", "\"provide these inputs through input_map.\"", "%", "\",\"", ".", "join", "(", "[", "compat", ".", "as_str", "(", "v", ")", "for", "v", "in", "field", ".", "value", "if", "not", "input_map", "or", "v", "not", "in", "input_map", "]", ")", ")", "break", "# Sets graph to default graph if it's not passed in.", "graph", "=", "graph", "or", "ops", ".", "get_default_graph", "(", ")", "# Gathers the list of nodes we are interested in.", "with", "graph", ".", "as_default", "(", ")", ":", "producer_op_list", "=", "None", "if", "meta_graph_def", ".", "meta_info_def", ".", "HasField", "(", "\"stripped_op_list\"", ")", ":", "producer_op_list", "=", "meta_graph_def", ".", "meta_info_def", ".", "stripped_op_list", "input_graph_def", "=", "meta_graph_def", ".", "graph_def", "# Remove all the explicit device specifications for this node. This helps to", "# make the graph more portable.", "if", "clear_devices", ":", "for", "node", "in", "input_graph_def", ".", "node", ":", "node", ".", "device", "=", "\"\"", "scope_to_prepend_to_names", "=", "graph", ".", "unique_name", "(", "import_scope", "or", "\"\"", ",", "mark_as_used", "=", "False", ")", "imported_return_elements", "=", "importer", ".", "import_graph_def", "(", "input_graph_def", ",", "name", "=", "(", "import_scope", "or", "scope_to_prepend_to_names", ")", ",", "input_map", "=", "input_map", ",", "producer_op_list", "=", "producer_op_list", ",", "return_elements", "=", "return_elements", ")", "# TensorFlow versions before 1.9 (not inclusive) exported SavedModels", "# without a VariableDef.trainable field set.", "tf_version", "=", "meta_graph_def", ".", "meta_info_def", ".", "tensorflow_version", "if", "not", "tf_version", ":", "variables_have_trainable", "=", "True", "else", ":", "variables_have_trainable", "=", "(", "distutils_version", ".", "LooseVersion", "(", "tf_version", ")", ">=", "distutils_version", ".", "LooseVersion", "(", "\"1.9\"", ")", ")", "# Sort collections so we see TRAINABLE_VARIABLES first and can default these", "# variables to trainable if the value is not set in their VariableDef.", "sorted_collections", "=", "[", "]", "if", "ops", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", "in", "meta_graph_def", ".", "collection_def", ":", "sorted_collections", ".", "append", "(", "(", "ops", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ",", "meta_graph_def", ".", "collection_def", "[", "ops", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", "]", ")", ")", "for", "key", ",", "value", "in", "sorted", "(", "meta_graph_def", ".", "collection_def", ".", "items", "(", ")", ")", ":", "if", "key", "!=", "ops", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ":", "sorted_collections", ".", "append", "(", "(", "key", ",", "value", ")", ")", "# Restores all the other collections.", "variable_objects", "=", "{", "}", "for", "key", ",", "col_def", "in", "sorted_collections", ":", "# Don't add unbound_inputs to the new graph.", "if", "key", "==", "unbound_inputs_col_name", ":", "continue", "if", "not", "restore_collections_predicate", "(", "key", ")", ":", "continue", "kind", "=", "col_def", ".", "WhichOneof", "(", "\"kind\"", ")", "if", "kind", "is", "None", ":", "logging", ".", "error", "(", "\"Cannot identify data type for collection %s. Skipping.\"", ",", "key", ")", "continue", "from_proto", "=", "ops", ".", "get_from_proto_function", "(", "key", ")", "# Temporary change to allow the TFMA evaluator to read metric variables", "# saved as a bytes list.", "# TODO(kathywu): Remove this hack once cl/248406059 has been submitted.", "if", "key", "==", "ops", ".", "GraphKeys", ".", "METRIC_VARIABLES", ":", "# Metric variables will use the same proto functions as GLOBAL_VARIABLES", "from_proto", "=", "ops", ".", "get_from_proto_function", "(", "ops", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", ")", "if", "from_proto", "and", "kind", "==", "\"bytes_list\"", ":", "proto_type", "=", "ops", ".", "get_collection_proto_type", "(", "key", ")", "if", "key", "in", "ops", ".", "GraphKeys", ".", "_VARIABLE_COLLECTIONS", ":", "# pylint: disable=protected-access", "for", "value", "in", "col_def", ".", "bytes_list", ".", "value", ":", "variable", "=", "variable_objects", ".", "get", "(", "value", ",", "None", ")", "if", "variable", "is", "None", ":", "proto", "=", "proto_type", "(", ")", "proto", ".", "ParseFromString", "(", "value", ")", "if", "not", "variables_have_trainable", ":", "# If the VariableDef proto does not contain a \"trainable\"", "# property because it was exported before that property was", "# added, we default it to whether the variable is in the", "# TRAINABLE_VARIABLES collection. We've sorted", "# TRAINABLE_VARIABLES to be first, so trainable variables will", "# be created from that collection.", "proto", ".", "trainable", "=", "(", "key", "==", "ops", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ")", "variable", "=", "from_proto", "(", "proto", ",", "import_scope", "=", "scope_to_prepend_to_names", ")", "variable_objects", "[", "value", "]", "=", "variable", "graph", ".", "add_to_collection", "(", "key", ",", "variable", ")", "else", ":", "for", "value", "in", "col_def", ".", "bytes_list", ".", "value", ":", "proto", "=", "proto_type", "(", ")", "proto", ".", "ParseFromString", "(", "value", ")", "graph", ".", "add_to_collection", "(", "key", ",", "from_proto", "(", "proto", ",", "import_scope", "=", "scope_to_prepend_to_names", ")", ")", "else", ":", "field", "=", "getattr", "(", "col_def", ",", "kind", ")", "if", "key", "in", "_COMPAT_COLLECTION_LIST", ":", "logging", ".", "warning", "(", "\"The saved meta_graph is possibly from an older release:\\n\"", "\"'%s' collection should be of type 'byte_list', but instead \"", "\"is of type '%s'.\"", ",", "key", ",", "kind", ")", "if", "kind", "==", "\"node_list\"", ":", "for", "value", "in", "field", ".", "value", ":", "col_op", "=", "graph", ".", "as_graph_element", "(", "ops", ".", "prepend_name_scope", "(", "value", ",", "scope_to_prepend_to_names", ")", ")", "graph", ".", "add_to_collection", "(", "key", ",", "col_op", ")", "elif", "kind", "==", "\"int64_list\"", ":", "# NOTE(opensource): This force conversion is to work around the fact", "# that Python2 distinguishes between int and long, while Python3 has", "# only int.", "for", "value", "in", "field", ".", "value", ":", "graph", ".", "add_to_collection", "(", "key", ",", "int", "(", "value", ")", ")", "else", ":", "for", "value", "in", "field", ".", "value", ":", "graph", ".", "add_to_collection", "(", "key", ",", "ops", ".", "prepend_name_scope", "(", "value", ",", "scope_to_prepend_to_names", ")", ")", "var_list", "=", "{", "}", "variables", "=", "graph", ".", "get_collection", "(", "ops", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", ",", "scope", "=", "scope_to_prepend_to_names", ")", "for", "v", "in", "variables", ":", "var_list", "[", "ops", ".", "strip_name_scope", "(", "v", ".", "name", ",", "scope_to_prepend_to_names", ")", "]", "=", "v", "return", "var_list", ",", "imported_return_elements" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/meta_graph.py#L707-L910
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/v8/tools/sanitizers/sancov_formatter.py
python
write_instrumented
(options)
Implements the 'all' action of this tool.
Implements the 'all' action of this tool.
[ "Implements", "the", "all", "action", "of", "this", "tool", "." ]
def write_instrumented(options): """Implements the 'all' action of this tool.""" exe_list = list(executables(options.build_dir)) logging.info('Reading instrumented lines from %d executables.', len(exe_list)) pool = Pool(CPUS) try: results = pool.imap_unordered(get_instrumented_lines, exe_list) finally: pool.close() # Merge multiprocessing results and prepare output data. data = merge_instrumented_line_results(exe_list, results) logging.info('Read data from %d executables, which covers %d files.', len(data['tests']), len(data['files'])) logging.info('Writing results to %s', options.json_output) # Write json output. with open(options.json_output, 'w') as f: json.dump(data, f, sort_keys=True)
[ "def", "write_instrumented", "(", "options", ")", ":", "exe_list", "=", "list", "(", "executables", "(", "options", ".", "build_dir", ")", ")", "logging", ".", "info", "(", "'Reading instrumented lines from %d executables.'", ",", "len", "(", "exe_list", ")", ")", "pool", "=", "Pool", "(", "CPUS", ")", "try", ":", "results", "=", "pool", ".", "imap_unordered", "(", "get_instrumented_lines", ",", "exe_list", ")", "finally", ":", "pool", ".", "close", "(", ")", "# Merge multiprocessing results and prepare output data.", "data", "=", "merge_instrumented_line_results", "(", "exe_list", ",", "results", ")", "logging", ".", "info", "(", "'Read data from %d executables, which covers %d files.'", ",", "len", "(", "data", "[", "'tests'", "]", ")", ",", "len", "(", "data", "[", "'files'", "]", ")", ")", "logging", ".", "info", "(", "'Writing results to %s'", ",", "options", ".", "json_output", ")", "# Write json output.", "with", "open", "(", "options", ".", "json_output", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ",", "sort_keys", "=", "True", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/tools/sanitizers/sancov_formatter.py#L214-L234
zyq8709/DexHunter
9d829a9f6f608ebad26923f29a294ae9c68d0441
art/tools/cpplint.py
python
CheckPosixThreading
(filename, clean_lines, linenum, error)
Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). 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.
Checks for calls to thread-unsafe functions.
[ "Checks", "for", "calls", "to", "thread", "-", "unsafe", "functions", "." ]
def CheckPosixThreading(filename, clean_lines, linenum, error): """Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). 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] for single_thread_function, multithread_safe_function in threading_list: ix = line.find(single_thread_function) # Comparisons made explicit for clarity -- pylint: disable-msg=C6403 if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and line[ix - 1] not in ('_', '.', '>'))): error(filename, linenum, 'runtime/threadsafe_fn', 2, 'Consider using ' + multithread_safe_function + '...) instead of ' + single_thread_function + '...) for improved thread safety.')
[ "def", "CheckPosixThreading", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "for", "single_thread_function", ",", "multithread_safe_function", "in", "threading_list", ":", "ix", "=", "line", ".", "find", "(", "single_thread_function", ")", "# Comparisons made explicit for clarity -- pylint: disable-msg=C6403", "if", "ix", ">=", "0", "and", "(", "ix", "==", "0", "or", "(", "not", "line", "[", "ix", "-", "1", "]", ".", "isalnum", "(", ")", "and", "line", "[", "ix", "-", "1", "]", "not", "in", "(", "'_'", ",", "'.'", ",", "'>'", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/threadsafe_fn'", ",", "2", ",", "'Consider using '", "+", "multithread_safe_function", "+", "'...) instead of '", "+", "single_thread_function", "+", "'...) for improved thread safety.'", ")" ]
https://github.com/zyq8709/DexHunter/blob/9d829a9f6f608ebad26923f29a294ae9c68d0441/art/tools/cpplint.py#L1309-L1333
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py
python
file_ns_handler
(importer, path_item, packageName, module)
Compute an ns-package subpath for a filesystem or zipfile importer
Compute an ns-package subpath for a filesystem or zipfile importer
[ "Compute", "an", "ns", "-", "package", "subpath", "for", "a", "filesystem", "or", "zipfile", "importer" ]
def file_ns_handler(importer, path_item, packageName, module): """Compute an ns-package subpath for a filesystem or zipfile importer""" subpath = os.path.join(path_item, packageName.split('.')[-1]) normalized = _normalize_cached(subpath) for item in module.__path__: if _normalize_cached(item) == normalized: break else: # Only return the path if it's not already there return subpath
[ "def", "file_ns_handler", "(", "importer", ",", "path_item", ",", "packageName", ",", "module", ")", ":", "subpath", "=", "os", ".", "path", ".", "join", "(", "path_item", ",", "packageName", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ")", "normalized", "=", "_normalize_cached", "(", "subpath", ")", "for", "item", "in", "module", ".", "__path__", ":", "if", "_normalize_cached", "(", "item", ")", "==", "normalized", ":", "break", "else", ":", "# Only return the path if it's not already there", "return", "subpath" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py#L2320-L2330
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/asynchat.py
python
async_chat.writable
(self)
return self.producer_fifo or (not self.connected)
predicate for inclusion in the writable for select()
predicate for inclusion in the writable for select()
[ "predicate", "for", "inclusion", "in", "the", "writable", "for", "select", "()" ]
def writable(self): "predicate for inclusion in the writable for select()" return self.producer_fifo or (not self.connected)
[ "def", "writable", "(", "self", ")", ":", "return", "self", ".", "producer_fifo", "or", "(", "not", "self", ".", "connected", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asynchat.py#L216-L218
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/debug/cli/analyzer_cli.py
python
DebugAnalyzer.__init__
(self, debug_dump, config)
DebugAnalyzer constructor. Args: debug_dump: A DebugDumpDir object. config: A `cli_config.CLIConfig` object that carries user-facing configurations.
DebugAnalyzer constructor.
[ "DebugAnalyzer", "constructor", "." ]
def __init__(self, debug_dump, config): """DebugAnalyzer constructor. Args: debug_dump: A DebugDumpDir object. config: A `cli_config.CLIConfig` object that carries user-facing configurations. """ self._debug_dump = debug_dump self._evaluator = evaluator.ExpressionEvaluator(self._debug_dump) # Initialize tensor filters state. self._tensor_filters = {} self._build_argument_parsers(config) config.set_callback("graph_recursion_depth", self._build_argument_parsers)
[ "def", "__init__", "(", "self", ",", "debug_dump", ",", "config", ")", ":", "self", ".", "_debug_dump", "=", "debug_dump", "self", ".", "_evaluator", "=", "evaluator", ".", "ExpressionEvaluator", "(", "self", ".", "_debug_dump", ")", "# Initialize tensor filters state.", "self", ".", "_tensor_filters", "=", "{", "}", "self", ".", "_build_argument_parsers", "(", "config", ")", "config", ".", "set_callback", "(", "\"graph_recursion_depth\"", ",", "self", ".", "_build_argument_parsers", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/cli/analyzer_cli.py#L144-L161
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/boost/boost_1_68_0/libs/metaparse/tools/benchmark/generate.py
python
Template.property
(self, name)
return self._get_line(in_comment(name + ':[ \t]*(.*)'))
Parses and returns a property
Parses and returns a property
[ "Parses", "and", "returns", "a", "property" ]
def property(self, name): """Parses and returns a property""" return self._get_line(in_comment(name + ':[ \t]*(.*)'))
[ "def", "property", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_get_line", "(", "in_comment", "(", "name", "+", "':[ \\t]*(.*)'", ")", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/libs/metaparse/tools/benchmark/generate.py#L155-L157
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/xmlreader.py
python
InputSource.getSystemId
(self)
return self.__system_id
Returns the system identifier of this InputSource.
Returns the system identifier of this InputSource.
[ "Returns", "the", "system", "identifier", "of", "this", "InputSource", "." ]
def getSystemId(self): "Returns the system identifier of this InputSource." return self.__system_id
[ "def", "getSystemId", "(", "self", ")", ":", "return", "self", ".", "__system_id" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/xmlreader.py#L224-L226