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
keyboardio/Kaleidoscope
d59604e98b2439d108647f15be52984a6837d360
bin/cpplint.py
python
_NamespaceInfo.CheckEnd
(self, filename, clean_lines, linenum, error)
Check end of namespace comments.
Check end of namespace comments.
[ "Check", "end", "of", "namespace", "comments", "." ]
def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. if self.name: # Named namespace if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): # If "// namespace anonymous" or "// anonymous namespace (more text)", # mention "// anonymous namespace" as an acceptable form if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line): error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"' ' or "// anonymous namespace"') else: error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"')
[ "def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "raw_lines", "[", "linenum", "]", "# Check how many lines is enclosed in this namespace. Don't issue", "# warning for missing n...
https://github.com/keyboardio/Kaleidoscope/blob/d59604e98b2439d108647f15be52984a6837d360/bin/cpplint.py#L2562-L2612
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/tools/graphviz.py
python
LoadEdges
(filename, targets)
return target_edges
Load the edges map from the dump file, and filter it to only show targets in |targets| and their depedendents.
Load the edges map from the dump file, and filter it to only show targets in |targets| and their depedendents.
[ "Load", "the", "edges", "map", "from", "the", "dump", "file", "and", "filter", "it", "to", "only", "show", "targets", "in", "|targets|", "and", "their", "depedendents", "." ]
def LoadEdges(filename, targets): """Load the edges map from the dump file, and filter it to only show targets in |targets| and their depedendents.""" file = open('dump.json') edges = json.load(file) file.close() # Copy out only the edges we're interested in from the full edge list. target_edges = {} to_visit = targets[:] while to_visit: src = to_visit.pop() if src in target_edges: continue target_edges[src] = edges[src] to_visit.extend(edges[src]) return target_edges
[ "def", "LoadEdges", "(", "filename", ",", "targets", ")", ":", "file", "=", "open", "(", "'dump.json'", ")", "edges", "=", "json", ".", "load", "(", "file", ")", "file", ".", "close", "(", ")", "# Copy out only the edges we're interested in from the full edge li...
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/tools/graphviz.py#L22-L40
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rospy/src/rospy/core.py
python
set_initialized
(initialized)
set the initialization state of the local node @param initialized: True if node initialized @type initialized: bool
set the initialization state of the local node
[ "set", "the", "initialization", "state", "of", "the", "local", "node" ]
def set_initialized(initialized): """ set the initialization state of the local node @param initialized: True if node initialized @type initialized: bool """ global _client_ready _client_ready = initialized
[ "def", "set_initialized", "(", "initialized", ")", ":", "global", "_client_ready", "_client_ready", "=", "initialized" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/core.py#L324-L331
15172658790/Blog
46e5036f5fbcad535af2255dc0e095cebcd8d710
计算机与信息类/算法基础/lab-徐云/2018/lab4&sch_2/work_dispatch.py
python
dispatch
(mat)
return total,rst
mat: matrix of c_ij
mat: matrix of c_ij
[ "mat", ":", "matrix", "of", "c_ij" ]
def dispatch(mat): '''mat: matrix of c_ij''' def _util(i,arrange,cost): ''' for i-th work''' nonlocal total,used,rst if i==n: total=cost rst = arrange.copy() # copy is needed else: for j in range(n): if not used[j] and( total is None or cost+mat[i][j]<total): used[j]=True arrange[i] = j _util(i+1,arrange,cost+mat[i][j]) used[j]=False total = None rst = None n = len(mat) used = [False for i in range(n)] _util(0,[-1]*n,0) return total,rst
[ "def", "dispatch", "(", "mat", ")", ":", "def", "_util", "(", "i", ",", "arrange", ",", "cost", ")", ":", "''' for i-th work'''", "nonlocal", "total", ",", "used", ",", "rst", "if", "i", "==", "n", ":", "total", "=", "cost", "rst", "=", "arrange", ...
https://github.com/15172658790/Blog/blob/46e5036f5fbcad535af2255dc0e095cebcd8d710/计算机与信息类/算法基础/lab-徐云/2018/lab4&sch_2/work_dispatch.py#L4-L24
v8mips/v8mips
f0c9cc0bbfd461c7f516799d9a58e9a7395f737e
tools/push-to-trunk/common_includes.py
python
MakeChangeLogBugReference
(body)
Grep for "BUG=xxxx" lines in the commit message and convert them to "(issue xxxx)".
Grep for "BUG=xxxx" lines in the commit message and convert them to "(issue xxxx)".
[ "Grep", "for", "BUG", "=", "xxxx", "lines", "in", "the", "commit", "message", "and", "convert", "them", "to", "(", "issue", "xxxx", ")", "." ]
def MakeChangeLogBugReference(body): """Grep for "BUG=xxxx" lines in the commit message and convert them to "(issue xxxx)". """ crbugs = [] v8bugs = [] def AddIssues(text): ref = re.match(r"^BUG[ \t]*=[ \t]*(.+)$", text.strip()) if not ref: return for bug in ref.group(1).split(","): bug = bug.strip() match = re.match(r"^v8:(\d+)$", bug) if match: v8bugs.append(int(match.group(1))) else: match = re.match(r"^(?:chromium:)?(\d+)$", bug) if match: crbugs.append(int(match.group(1))) # Add issues to crbugs and v8bugs. map(AddIssues, body.splitlines()) # Filter duplicates, sort, stringify. crbugs = map(str, sorted(set(crbugs))) v8bugs = map(str, sorted(set(v8bugs))) bug_groups = [] def FormatIssues(prefix, bugs): if len(bugs) > 0: plural = "s" if len(bugs) > 1 else "" bug_groups.append("%sissue%s %s" % (prefix, plural, ", ".join(bugs))) FormatIssues("", v8bugs) FormatIssues("Chromium ", crbugs) if len(bug_groups) > 0: return "(%s)" % ", ".join(bug_groups) else: return ""
[ "def", "MakeChangeLogBugReference", "(", "body", ")", ":", "crbugs", "=", "[", "]", "v8bugs", "=", "[", "]", "def", "AddIssues", "(", "text", ")", ":", "ref", "=", "re", ".", "match", "(", "r\"^BUG[ \\t]*=[ \\t]*(.+)$\"", ",", "text", ".", "strip", "(", ...
https://github.com/v8mips/v8mips/blob/f0c9cc0bbfd461c7f516799d9a58e9a7395f737e/tools/push-to-trunk/common_includes.py#L133-L171
tuttleofx/TuttleOFX
36fc4cae15092a84ea8c29b9c6658c7cabfadb6e
applications/sam/sam_ls.py
python
Sam_ls._isAlreadyPrinted
(self, item)
return False
Return if the given item has already been printed. @see _printItem
Return if the given item has already been printed.
[ "Return", "if", "the", "given", "item", "has", "already", "been", "printed", "." ]
def _isAlreadyPrinted(self, item): """ Return if the given item has already been printed. @see _printItem """ if item.getAbsoluteFilepath() in self._itemPrinted: return True return False
[ "def", "_isAlreadyPrinted", "(", "self", ",", "item", ")", ":", "if", "item", ".", "getAbsoluteFilepath", "(", ")", "in", "self", ".", "_itemPrinted", ":", "return", "True", "return", "False" ]
https://github.com/tuttleofx/TuttleOFX/blob/36fc4cae15092a84ea8c29b9c6658c7cabfadb6e/applications/sam/sam_ls.py#L66-L73
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/Irnn.py
python
Irnn.input_weights
(self)
return Blob.Blob(self._internal.get_input_weights())
Gets the FC_input weights. The dimensions: - **BatchLength** * **BatchWidth** * **ListSize** is hidden_size - **Height** * **Width** * **Depth** * **Channels** is the same as for the input
Gets the FC_input weights. The dimensions:
[ "Gets", "the", "FC_input", "weights", ".", "The", "dimensions", ":" ]
def input_weights(self): """Gets the FC_input weights. The dimensions: - **BatchLength** * **BatchWidth** * **ListSize** is hidden_size - **Height** * **Width** * **Depth** * **Channels** is the same as for the input """ return Blob.Blob(self._internal.get_input_weights())
[ "def", "input_weights", "(", "self", ")", ":", "return", "Blob", ".", "Blob", "(", "self", ".", "_internal", ".", "get_input_weights", "(", ")", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Irnn.py#L140-L146
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/openmc_utils.py
python
get_e_bounds_from_openmc_sp
(filename, tally_id)
return e_bounds
This function reads OpenMC state point file to get the energy boundaries for a specific tally number. Parameters: ----------- filename : str The OpenMC state point file name. tally_id : int Tally id to read. Returns: -------- e_bounds : numpy array Energy boundries with size of (num_e_groups + 1).
This function reads OpenMC state point file to get the energy boundaries for a specific tally number.
[ "This", "function", "reads", "OpenMC", "state", "point", "file", "to", "get", "the", "energy", "boundaries", "for", "a", "specific", "tally", "number", "." ]
def get_e_bounds_from_openmc_sp(filename, tally_id): """ This function reads OpenMC state point file to get the energy boundaries for a specific tally number. Parameters: ----------- filename : str The OpenMC state point file name. tally_id : int Tally id to read. Returns: -------- e_bounds : numpy array Energy boundries with size of (num_e_groups + 1). """ sp = openmc.StatePoint(filename) tally = sp.get_tally(id=tally_id) # check filter to find EnergyFilter for flt in tally.filters: if isinstance(flt, openmc.filter.EnergyFilter): energy_filter = flt e_bounds = energy_filter.values return e_bounds
[ "def", "get_e_bounds_from_openmc_sp", "(", "filename", ",", "tally_id", ")", ":", "sp", "=", "openmc", ".", "StatePoint", "(", "filename", ")", "tally", "=", "sp", ".", "get_tally", "(", "id", "=", "tally_id", ")", "# check filter to find EnergyFilter", "for", ...
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/openmc_utils.py#L177-L202
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/colourchooser/pycolourslider.py
python
PyColourSlider.GetValue
(self, pos)
return self.buffer.GetPixelColour(0, pos)
Returns the colour value for a position on the slider. The position must be within the valid height of the slider, or results can be unpredictable.
Returns the colour value for a position on the slider. The position must be within the valid height of the slider, or results can be unpredictable.
[ "Returns", "the", "colour", "value", "for", "a", "position", "on", "the", "slider", ".", "The", "position", "must", "be", "within", "the", "valid", "height", "of", "the", "slider", "or", "results", "can", "be", "unpredictable", "." ]
def GetValue(self, pos): """Returns the colour value for a position on the slider. The position must be within the valid height of the slider, or results can be unpredictable.""" return self.buffer.GetPixelColour(0, pos)
[ "def", "GetValue", "(", "self", ",", "pos", ")", ":", "return", "self", ".", "buffer", ".", "GetPixelColour", "(", "0", ",", "pos", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/colourchooser/pycolourslider.py#L67-L71
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/urlgrabber/grabber.py
python
set_user_agent
(new_user_agent)
Deprecated. Use: default_grabber.user_agent = new_user_agent
Deprecated. Use: default_grabber.user_agent = new_user_agent
[ "Deprecated", ".", "Use", ":", "default_grabber", ".", "user_agent", "=", "new_user_agent" ]
def set_user_agent(new_user_agent): """Deprecated. Use: default_grabber.user_agent = new_user_agent""" default_grabber.user_agent = new_user_agent
[ "def", "set_user_agent", "(", "new_user_agent", ")", ":", "default_grabber", ".", "user_agent", "=", "new_user_agent" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/urlgrabber/grabber.py#L1349-L1351
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/hotshot/__init__.py
python
Profile.runctx
(self, cmd, globals, locals)
return self
Evaluate an exec-compatible string in a specific environment. The string is compiled before profiling begins.
Evaluate an exec-compatible string in a specific environment.
[ "Evaluate", "an", "exec", "-", "compatible", "string", "in", "a", "specific", "environment", "." ]
def runctx(self, cmd, globals, locals): """Evaluate an exec-compatible string in a specific environment. The string is compiled before profiling begins. """ code = compile(cmd, "<string>", "exec") self._prof.runcode(code, globals, locals) return self
[ "def", "runctx", "(", "self", ",", "cmd", ",", "globals", ",", "locals", ")", ":", "code", "=", "compile", "(", "cmd", ",", "\"<string>\"", ",", "\"exec\"", ")", "self", ".", "_prof", ".", "runcode", "(", "code", ",", "globals", ",", "locals", ")", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/hotshot/__init__.py#L60-L68
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
clang/docs/tools/dump_ast_matchers.py
python
strip_doxygen
(comment)
return comment
Returns the given comment without \-escaped words.
Returns the given comment without \-escaped words.
[ "Returns", "the", "given", "comment", "without", "\\", "-", "escaped", "words", "." ]
def strip_doxygen(comment): """Returns the given comment without \-escaped words.""" # If there is only a doxygen keyword in the line, delete the whole line. comment = re.sub(r'^\\[^\s]+\n', r'', comment, flags=re.M) # If there is a doxygen \see command, change the \see prefix into "See also:". # FIXME: it would be better to turn this into a link to the target instead. comment = re.sub(r'\\see', r'See also:', comment) # Delete the doxygen command and the following whitespace. comment = re.sub(r'\\[^\s]+\s+', r'', comment) return comment
[ "def", "strip_doxygen", "(", "comment", ")", ":", "# If there is only a doxygen keyword in the line, delete the whole line.", "comment", "=", "re", ".", "sub", "(", "r'^\\\\[^\\s]+\\n'", ",", "r''", ",", "comment", ",", "flags", "=", "re", ".", "M", ")", "# If there...
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/docs/tools/dump_ast_matchers.py#L94-L105
apache/impala
8ddac48f3428c86f2cbd037ced89cfb903298b12
lib/python/impala_py_lib/helpers.py
python
find_all_files
(fname_pattern, base_dir=os.getenv('IMPALA_HOME', '.'))
return matching_files
General utility to recursively find files matching a certain unix-like file pattern. Args: fname_pattern: Unix glob base_dir: the root directory where searching should start Returns: A list of full paths relative to the give base_dir
General utility to recursively find files matching a certain unix-like file pattern.
[ "General", "utility", "to", "recursively", "find", "files", "matching", "a", "certain", "unix", "-", "like", "file", "pattern", "." ]
def find_all_files(fname_pattern, base_dir=os.getenv('IMPALA_HOME', '.')): """ General utility to recursively find files matching a certain unix-like file pattern. Args: fname_pattern: Unix glob base_dir: the root directory where searching should start Returns: A list of full paths relative to the give base_dir """ file_glob = fnmatch.translate(fname_pattern) matching_files = [] for root, dirs, files in os.walk(base_dir): matching_files += [os.path.join(root, f) for f in files if re.match(file_glob, f)] return matching_files
[ "def", "find_all_files", "(", "fname_pattern", ",", "base_dir", "=", "os", ".", "getenv", "(", "'IMPALA_HOME'", ",", "'.'", ")", ")", ":", "file_glob", "=", "fnmatch", ".", "translate", "(", "fname_pattern", ")", "matching_files", "=", "[", "]", "for", "ro...
https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/lib/python/impala_py_lib/helpers.py#L49-L66
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/internal/python_message.py
python
_AddHasExtensionMethod
(cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddHasExtensionMethod(cls): """Helper for _AddMessageMethods().""" def HasExtension(self, extension_handle): extension_dict._VerifyExtensionHandle(self, extension_handle) if extension_handle.label == _FieldDescriptor.LABEL_REPEATED: raise KeyError('"%s" is repeated.' % extension_handle.full_name) if extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: value = self._fields.get(extension_handle) return value is not None and value._is_present_in_parent else: return extension_handle in self._fields cls.HasExtension = HasExtension
[ "def", "_AddHasExtensionMethod", "(", "cls", ")", ":", "def", "HasExtension", "(", "self", ",", "extension_handle", ")", ":", "extension_dict", ".", "_VerifyExtensionHandle", "(", "self", ",", "extension_handle", ")", "if", "extension_handle", ".", "label", "==", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/python_message.py#L935-L947
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/boost_1_66_0/tools/build/src/build/virtual_target.py
python
VirtualTargetRegistry.add_suffix
(self, specified_name, file_type, prop_set)
Appends the suffix appropriate to 'type/property_set' combination to the specified name and returns the result.
Appends the suffix appropriate to 'type/property_set' combination to the specified name and returns the result.
[ "Appends", "the", "suffix", "appropriate", "to", "type", "/", "property_set", "combination", "to", "the", "specified", "name", "and", "returns", "the", "result", "." ]
def add_suffix (self, specified_name, file_type, prop_set): """ Appends the suffix appropriate to 'type/property_set' combination to the specified name and returns the result. """ assert isinstance(specified_name, basestring) assert isinstance(file_type, basestring) assert isinstance(prop_set, property_set.PropertySet) suffix = b2.build.type.generated_target_suffix (file_type, prop_set) if suffix: return specified_name + '.' + suffix else: return specified_name
[ "def", "add_suffix", "(", "self", ",", "specified_name", ",", "file_type", ",", "prop_set", ")", ":", "assert", "isinstance", "(", "specified_name", ",", "basestring", ")", "assert", "isinstance", "(", "file_type", ",", "basestring", ")", "assert", "isinstance",...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/build/virtual_target.py#L248-L261
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_DictionaryAttackParameters_REQUEST.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(TPM2_DictionaryAttackParameters_REQUEST)
Returns new TPM2_DictionaryAttackParameters_REQUEST object constructed from its marshaled representation in the given byte buffer
Returns new TPM2_DictionaryAttackParameters_REQUEST object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "TPM2_DictionaryAttackParameters_REQUEST", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new TPM2_DictionaryAttackParameters_REQUEST object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(TPM2_DictionaryAttackParameters_REQUEST)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "TPM2_DictionaryAttackParameters_REQUEST", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L15741-L15745
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/packaging/markers.py
python
Marker.evaluate
(self, environment=None)
return _evaluate_markers(self._markers, current_environment)
Evaluate a marker. Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. The environment is determined from the current Python process.
Evaluate a marker.
[ "Evaluate", "a", "marker", "." ]
def evaluate(self, environment=None): """Evaluate a marker. Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. The environment is determined from the current Python process. """ current_environment = default_environment() if environment is not None: current_environment.update(environment) return _evaluate_markers(self._markers, current_environment)
[ "def", "evaluate", "(", "self", ",", "environment", "=", "None", ")", ":", "current_environment", "=", "default_environment", "(", ")", "if", "environment", "is", "not", "None", ":", "current_environment", ".", "update", "(", "environment", ")", "return", "_ev...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/packaging/markers.py#L283-L296
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
_Stream.seek
(self, pos=0)
return self.pos
Set the stream's file pointer to pos. Negative seeking is forbidden.
Set the stream's file pointer to pos. Negative seeking is forbidden.
[ "Set", "the", "stream", "s", "file", "pointer", "to", "pos", ".", "Negative", "seeking", "is", "forbidden", "." ]
def seek(self, pos=0): """Set the stream's file pointer to pos. Negative seeking is forbidden. """ if pos - self.pos >= 0: blocks, remainder = divmod(pos - self.pos, self.bufsize) for i in range(blocks): self.read(self.bufsize) self.read(remainder) else: raise StreamError("seeking backwards is not allowed") return self.pos
[ "def", "seek", "(", "self", ",", "pos", "=", "0", ")", ":", "if", "pos", "-", "self", ".", "pos", ">=", "0", ":", "blocks", ",", "remainder", "=", "divmod", "(", "pos", "-", "self", ".", "pos", ",", "self", ".", "bufsize", ")", "for", "i", "i...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L552-L563
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/ShallowWaterApplication/python_scripts/postprocess/convergence_output_process.py
python
ConvergenceOutputProcess.IsOutputStep
(self)
return False
Check if the current time step is near enough to the specified printing times.
Check if the current time step is near enough to the specified printing times.
[ "Check", "if", "the", "current", "time", "step", "is", "near", "enough", "to", "the", "specified", "printing", "times", "." ]
def IsOutputStep(self): """Check if the current time step is near enough to the specified printing times.""" time = self.model_part.ProcessInfo.GetValue(KM.TIME) for i in range(len(self.printing_times)): if time >= self.printing_times[i] and not self.is_printed[i]: self.is_printed[i] = True return True return False
[ "def", "IsOutputStep", "(", "self", ")", ":", "time", "=", "self", ".", "model_part", ".", "ProcessInfo", ".", "GetValue", "(", "KM", ".", "TIME", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "printing_times", ")", ")", ":", "if", ...
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ShallowWaterApplication/python_scripts/postprocess/convergence_output_process.py#L57-L64
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/framework/python/ops/variables.py
python
assert_or_get_global_step
(graph=None, global_step_tensor=None)
return global_step_tensor
Verifies that a global step tensor is valid or gets one if None is given. If `global_step_tensor` is not None, check that it is a valid global step tensor (using `assert_global_step`). Otherwise find a global step tensor using `get_global_step` and return it. Args: graph: The graph to find the global step tensor for. global_step_tensor: The tensor to check for suitability as a global step. If None is given (the default), find a global step tensor. Returns: A tensor suitable as a global step, or `None` if none was provided and none was found.
Verifies that a global step tensor is valid or gets one if None is given.
[ "Verifies", "that", "a", "global", "step", "tensor", "is", "valid", "or", "gets", "one", "if", "None", "is", "given", "." ]
def assert_or_get_global_step(graph=None, global_step_tensor=None): """Verifies that a global step tensor is valid or gets one if None is given. If `global_step_tensor` is not None, check that it is a valid global step tensor (using `assert_global_step`). Otherwise find a global step tensor using `get_global_step` and return it. Args: graph: The graph to find the global step tensor for. global_step_tensor: The tensor to check for suitability as a global step. If None is given (the default), find a global step tensor. Returns: A tensor suitable as a global step, or `None` if none was provided and none was found. """ if global_step_tensor is None: # Get the global step tensor the same way the supervisor would. global_step_tensor = get_global_step(graph) else: assert_global_step(global_step_tensor) return global_step_tensor
[ "def", "assert_or_get_global_step", "(", "graph", "=", "None", ",", "global_step_tensor", "=", "None", ")", ":", "if", "global_step_tensor", "is", "None", ":", "# Get the global step tensor the same way the supervisor would.", "global_step_tensor", "=", "get_global_step", "...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/framework/python/ops/variables.py#L77-L98
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/internals/blocks.py
python
ExtensionBlock._maybe_coerce_values
(self, values)
return values
Unbox to an extension array. This will unbox an ExtensionArray stored in an Index or Series. ExtensionArrays pass through. No dtype coercion is done. Parameters ---------- values : Index, Series, ExtensionArray Returns ------- ExtensionArray
Unbox to an extension array.
[ "Unbox", "to", "an", "extension", "array", "." ]
def _maybe_coerce_values(self, values): """Unbox to an extension array. This will unbox an ExtensionArray stored in an Index or Series. ExtensionArrays pass through. No dtype coercion is done. Parameters ---------- values : Index, Series, ExtensionArray Returns ------- ExtensionArray """ if isinstance(values, (ABCIndexClass, ABCSeries)): values = values._values return values
[ "def", "_maybe_coerce_values", "(", "self", ",", "values", ")", ":", "if", "isinstance", "(", "values", ",", "(", "ABCIndexClass", ",", "ABCSeries", ")", ")", ":", "values", "=", "values", ".", "_values", "return", "values" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/internals/blocks.py#L1683-L1699
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/lib2to3/fixer_base.py
python
BaseFix.cannot_convert
(self, node, reason=None)
Warn the user that a given chunk of code is not valid Python 3, but that it cannot be converted automatically. First argument is the top-level node for the code in question. Optional second argument is why it can't be converted.
Warn the user that a given chunk of code is not valid Python 3, but that it cannot be converted automatically.
[ "Warn", "the", "user", "that", "a", "given", "chunk", "of", "code", "is", "not", "valid", "Python", "3", "but", "that", "it", "cannot", "be", "converted", "automatically", "." ]
def cannot_convert(self, node, reason=None): """Warn the user that a given chunk of code is not valid Python 3, but that it cannot be converted automatically. First argument is the top-level node for the code in question. Optional second argument is why it can't be converted. """ lineno = node.get_lineno() for_output = node.clone() for_output.prefix = "" msg = "Line %d: could not convert: %s" self.log_message(msg % (lineno, for_output)) if reason: self.log_message(reason)
[ "def", "cannot_convert", "(", "self", ",", "node", ",", "reason", "=", "None", ")", ":", "lineno", "=", "node", ".", "get_lineno", "(", ")", "for_output", "=", "node", ".", "clone", "(", ")", "for_output", ".", "prefix", "=", "\"\"", "msg", "=", "\"L...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/lib2to3/fixer_base.py#L122-L135
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/Direct/ISISDirecInelasticConfig.py
python
UserProperties.rb_dir
(self)
return rb folder used in last actual instrument
return rb folder used in last actual instrument
[ "return", "rb", "folder", "used", "in", "last", "actual", "instrument" ]
def rb_dir(self): """return rb folder used in last actual instrument""" if self._recent_dateID: return self._rb_dirs[self._recent_dateID] else: raise RuntimeError("User's experiment date is not defined. User undefined")
[ "def", "rb_dir", "(", "self", ")", ":", "if", "self", ".", "_recent_dateID", ":", "return", "self", ".", "_rb_dirs", "[", "self", ".", "_recent_dateID", "]", "else", ":", "raise", "RuntimeError", "(", "\"User's experiment date is not defined. User undefined\"", ")...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py#L144-L149
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
site_scons/site_tools/ninja.py
python
get_path
(node)
return str(node)
Return a fake path if necessary. As an example Aliases use this as their target name in Ninja.
Return a fake path if necessary.
[ "Return", "a", "fake", "path", "if", "necessary", "." ]
def get_path(node): """ Return a fake path if necessary. As an example Aliases use this as their target name in Ninja. """ if hasattr(node, "get_path"): return node.get_path() return str(node)
[ "def", "get_path", "(", "node", ")", ":", "if", "hasattr", "(", "node", ",", "\"get_path\"", ")", ":", "return", "node", ".", "get_path", "(", ")", "return", "str", "(", "node", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/site_scons/site_tools/ninja.py#L879-L887
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tarfile.py
python
itn
(n, digits=8, format=DEFAULT_FORMAT)
return s
Convert a python number to a number field.
Convert a python number to a number field.
[ "Convert", "a", "python", "number", "to", "a", "number", "field", "." ]
def itn(n, digits=8, format=DEFAULT_FORMAT): """Convert a python number to a number field. """ # POSIX 1003.1-1988 requires numbers to be encoded as a string of # octal digits followed by a null-byte, this allows values up to # (8**(digits-1))-1. GNU tar allows storing numbers greater than # that if necessary. A leading 0o200 or 0o377 byte indicate this # particular encoding, the following digits-1 bytes are a big-endian # base-256 representation. This allows values up to (256**(digits-1))-1. # A 0o200 byte indicates a positive number, a 0o377 byte a negative # number. n = int(n) if 0 <= n < 8 ** (digits - 1): s = bytes("%0*o" % (digits - 1, n), "ascii") + NUL elif format == GNU_FORMAT and -256 ** (digits - 1) <= n < 256 ** (digits - 1): if n >= 0: s = bytearray([0o200]) else: s = bytearray([0o377]) n = 256 ** digits + n for i in range(digits - 1): s.insert(1, n & 0o377) n >>= 8 else: raise ValueError("overflow in number field") return s
[ "def", "itn", "(", "n", ",", "digits", "=", "8", ",", "format", "=", "DEFAULT_FORMAT", ")", ":", "# POSIX 1003.1-1988 requires numbers to be encoded as a string of", "# octal digits followed by a null-byte, this allows values up to", "# (8**(digits-1))-1. GNU tar allows storing numbe...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tarfile.py#L192-L219
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/html.py
python
HelpControllerBase.Initialize
(*args)
return _html.HelpControllerBase_Initialize(*args)
Initialize(self, String file, int server) -> bool Initialize(self, String file) -> bool
Initialize(self, String file, int server) -> bool Initialize(self, String file) -> bool
[ "Initialize", "(", "self", "String", "file", "int", "server", ")", "-", ">", "bool", "Initialize", "(", "self", "String", "file", ")", "-", ">", "bool" ]
def Initialize(*args): """ Initialize(self, String file, int server) -> bool Initialize(self, String file) -> bool """ return _html.HelpControllerBase_Initialize(*args)
[ "def", "Initialize", "(", "*", "args", ")", ":", "return", "_html", ".", "HelpControllerBase_Initialize", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L1861-L1866
stellar-deprecated/stellard
67eabb2217bdfa9a6ea317f62338fb6bca458c90
src/protobuf/python/google/protobuf/internal/python_message.py
python
_AddEnumValues
(descriptor, cls)
Sets class-level attributes for all enum fields defined in this message. Also exporting a class-level object that can name enum values. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type.
Sets class-level attributes for all enum fields defined in this message.
[ "Sets", "class", "-", "level", "attributes", "for", "all", "enum", "fields", "defined", "in", "this", "message", "." ]
def _AddEnumValues(descriptor, cls): """Sets class-level attributes for all enum fields defined in this message. Also exporting a class-level object that can name enum values. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type. """ for enum_type in descriptor.enum_types: setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type)) for enum_value in enum_type.values: setattr(cls, enum_value.name, enum_value.number)
[ "def", "_AddEnumValues", "(", "descriptor", ",", "cls", ")", ":", "for", "enum_type", "in", "descriptor", ".", "enum_types", ":", "setattr", "(", "cls", ",", "enum_type", ".", "name", ",", "enum_type_wrapper", ".", "EnumTypeWrapper", "(", "enum_type", ")", "...
https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/internal/python_message.py#L233-L245
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/utils/vim-lldb/python-vim-lldb/vim_ui.py
python
UI.haveBreakpoint
(self, file, line)
return (file, line) in self.markedBreakpoints
Returns True if we have a breakpoint at file:line, False otherwise
Returns True if we have a breakpoint at file:line, False otherwise
[ "Returns", "True", "if", "we", "have", "a", "breakpoint", "at", "file", ":", "line", "False", "otherwise" ]
def haveBreakpoint(self, file, line): """ Returns True if we have a breakpoint at file:line, False otherwise """ return (file, line) in self.markedBreakpoints
[ "def", "haveBreakpoint", "(", "self", ",", "file", ",", "line", ")", ":", "return", "(", "file", ",", "line", ")", "in", "self", ".", "markedBreakpoints" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/utils/vim-lldb/python-vim-lldb/vim_ui.py#L224-L226
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/pathlib.py
python
PurePath.relative_to
(self, *other)
return self._from_parsed_parts('', root if n == 1 else '', abs_parts[n:])
Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not a subpath of the other path), raise ValueError.
Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not a subpath of the other path), raise ValueError.
[ "Return", "the", "relative", "path", "to", "another", "path", "identified", "by", "the", "passed", "arguments", ".", "If", "the", "operation", "is", "not", "possible", "(", "because", "this", "is", "not", "a", "subpath", "of", "the", "other", "path", ")", ...
def relative_to(self, *other): """Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not a subpath of the other path), raise ValueError. """ # For the purpose of this method, drive and root are considered # separate parts, i.e.: # Path('c:/').relative_to('c:') gives Path('/') # Path('c:/').relative_to('/') raise ValueError if not other: raise TypeError("need at least one argument") parts = self._parts drv = self._drv root = self._root if root: abs_parts = [drv, root] + parts[1:] else: abs_parts = parts to_drv, to_root, to_parts = self._parse_args(other) if to_root: to_abs_parts = [to_drv, to_root] + to_parts[1:] else: to_abs_parts = to_parts n = len(to_abs_parts) cf = self._flavour.casefold_parts if (root or drv) if n == 0 else cf(abs_parts[:n]) != cf(to_abs_parts): formatted = self._format_parsed_parts(to_drv, to_root, to_parts) raise ValueError("{!r} is not in the subpath of {!r}" " OR one path is relative and the other is absolute." .format(str(self), str(formatted))) return self._from_parsed_parts('', root if n == 1 else '', abs_parts[n:])
[ "def", "relative_to", "(", "self", ",", "*", "other", ")", ":", "# For the purpose of this method, drive and root are considered", "# separate parts, i.e.:", "# Path('c:/').relative_to('c:') gives Path('/')", "# Path('c:/').relative_to('/') raise ValueError", "if", "not", "other...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pathlib.py#L912-L943
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/boxing.py
python
unbox_set
(typ, obj, c)
return NativeValue(c.builder.load(setptr), is_error=c.builder.load(errorptr), cleanup=cleanup)
Convert set *obj* to a native set. If set was previously unboxed, we reuse the existing native set to ensure consistency.
Convert set *obj* to a native set.
[ "Convert", "set", "*", "obj", "*", "to", "a", "native", "set", "." ]
def unbox_set(typ, obj, c): """ Convert set *obj* to a native set. If set was previously unboxed, we reuse the existing native set to ensure consistency. """ size = c.pyapi.set_size(obj) errorptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit) setptr = cgutils.alloca_once(c.builder, c.context.get_value_type(typ)) # See if the set was previously unboxed, if so, re-use the meminfo. ptr = c.pyapi.object_get_private_data(obj) with c.builder.if_else(cgutils.is_not_null(c.builder, ptr)) \ as (has_meminfo, otherwise): with has_meminfo: # Set was previously unboxed => reuse meminfo inst = setobj.SetInstance.from_meminfo(c.context, c.builder, typ, ptr) if typ.reflected: inst.parent = obj c.builder.store(inst.value, setptr) with otherwise: _python_set_to_native(typ, obj, c, size, setptr, errorptr) def cleanup(): # Clean up the associated pointer, as the meminfo is now invalid. c.pyapi.object_reset_private_data(obj) return NativeValue(c.builder.load(setptr), is_error=c.builder.load(errorptr), cleanup=cleanup)
[ "def", "unbox_set", "(", "typ", ",", "obj", ",", "c", ")", ":", "size", "=", "c", ".", "pyapi", ".", "set_size", "(", "obj", ")", "errorptr", "=", "cgutils", ".", "alloca_once_value", "(", "c", ".", "builder", ",", "cgutils", ".", "false_bit", ")", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/boxing.py#L862-L896
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/control-examples/OperationalSpaceController.py
python
LinkTask.getSensedValue
(self, q)
return x
Get link x, which is rotation matrix and/or translation
Get link x, which is rotation matrix and/or translation
[ "Get", "link", "x", "which", "is", "rotation", "matrix", "and", "/", "or", "translation" ]
def getSensedValue(self, q): """Get link x, which is rotation matrix and/or translation """ self.robot.setConfig(q) T = self.link.getTransform() #check if relative transform task, modify T to local transform if self.baseLinkNo >= 0: Tb = self.baseLink.getTransform() Tbinv = se3.inv(Tb) T = se3.mul(Tbinv,T) if self.taskType == 'po': x = (T[0],se3.apply(T,self.localPosition)) elif self.taskType == 'position': x = se3.apply(T,self.localPosition) elif self.taskType == 'orientation': x = T[0] else: raise ValueError("Invalid taskType "+self.taskType) return x
[ "def", "getSensedValue", "(", "self", ",", "q", ")", ":", "self", ".", "robot", ".", "setConfig", "(", "q", ")", "T", "=", "self", ".", "link", ".", "getTransform", "(", ")", "#check if relative transform task, modify T to local transform", "if", "self", ".", ...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/control-examples/OperationalSpaceController.py#L732-L750
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/mailbox.py
python
MH.get_sequences
(self)
return results
Return a name-to-key-list dictionary to define each sequence.
Return a name-to-key-list dictionary to define each sequence.
[ "Return", "a", "name", "-", "to", "-", "key", "-", "list", "dictionary", "to", "define", "each", "sequence", "." ]
def get_sequences(self): """Return a name-to-key-list dictionary to define each sequence.""" results = {} with open(os.path.join(self._path, '.mh_sequences'), 'r', encoding='ASCII') as f: all_keys = set(self.keys()) for line in f: try: name, contents = line.split(':') keys = set() for spec in contents.split(): if spec.isdigit(): keys.add(int(spec)) else: start, stop = (int(x) for x in spec.split('-')) keys.update(range(start, stop + 1)) results[name] = [key for key in sorted(keys) \ if key in all_keys] if len(results[name]) == 0: del results[name] except ValueError: raise FormatError('Invalid sequence specification: %s' % line.rstrip()) return results
[ "def", "get_sequences", "(", "self", ")", ":", "results", "=", "{", "}", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "'.mh_sequences'", ")", ",", "'r'", ",", "encoding", "=", "'ASCII'", ")", "as", "f", ":", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L1146-L1168
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
SizerFlags.GetFlags
(*args, **kwargs)
return _core_.SizerFlags_GetFlags(*args, **kwargs)
GetFlags(self) -> int Returns the flags value to be used in the sizer item.
GetFlags(self) -> int
[ "GetFlags", "(", "self", ")", "-", ">", "int" ]
def GetFlags(*args, **kwargs): """ GetFlags(self) -> int Returns the flags value to be used in the sizer item. """ return _core_.SizerFlags_GetFlags(*args, **kwargs)
[ "def", "GetFlags", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "SizerFlags_GetFlags", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L13935-L13941
mysql/mysql-workbench
2f35f9034f015cbcd22139a60e1baa2e3e8e795c
library/python/workbench/os_utils.py
python
FileUtils.check_path_exists
(self, path)
return os.path.exists(path)
Function Type : Boolean
Function Type : Boolean
[ "Function", "Type", ":", "Boolean" ]
def check_path_exists(self, path): """ Function Type : Boolean """ return os.path.exists(path)
[ "def", "check_path_exists", "(", "self", ",", "path", ")", ":", "return", "os", ".", "path", ".", "exists", "(", "path", ")" ]
https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/library/python/workbench/os_utils.py#L117-L121
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/turtle.py
python
TNavigator.xcor
(self)
return self._position[0]
Return the turtle's x coordinate. No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.xcor() 50.0
Return the turtle's x coordinate.
[ "Return", "the", "turtle", "s", "x", "coordinate", "." ]
def xcor(self): """ Return the turtle's x coordinate. No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.xcor() 50.0 """ return self._position[0]
[ "def", "xcor", "(", "self", ")", ":", "return", "self", ".", "_position", "[", "0", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/turtle.py#L1630-L1642
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/service_reflection.py
python
GeneratedServiceStubType.__init__
(cls, name, bases, dictionary)
Creates a message service stub class. Args: name: Name of the class (ignored, here). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this protocol service type.
Creates a message service stub class.
[ "Creates", "a", "message", "service", "stub", "class", "." ]
def __init__(cls, name, bases, dictionary): """Creates a message service stub class. Args: name: Name of the class (ignored, here). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this protocol service type. """ super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary) # Don't do anything if this class doesn't have a descriptor. This happens # when a service stub is subclassed. if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary: return descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY] service_stub_builder = _ServiceStubBuilder(descriptor) service_stub_builder.BuildServiceStub(cls)
[ "def", "__init__", "(", "cls", ",", "name", ",", "bases", ",", "dictionary", ")", ":", "super", "(", "GeneratedServiceStubType", ",", "cls", ")", ".", "__init__", "(", "name", ",", "bases", ",", "dictionary", ")", "# Don't do anything if this class doesn't have ...
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/service_reflection.py#L94-L111
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Canvas.create_window
(self, *args, **kw)
return self._create('window', args, kw)
Create window with coordinates x1,y1,x2,y2.
Create window with coordinates x1,y1,x2,y2.
[ "Create", "window", "with", "coordinates", "x1", "y1", "x2", "y2", "." ]
def create_window(self, *args, **kw): """Create window with coordinates x1,y1,x2,y2.""" return self._create('window', args, kw)
[ "def", "create_window", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "_create", "(", "'window'", ",", "args", ",", "kw", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L2505-L2507
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/command_parser.py
python
parse_readable_size_str
(size_str)
Convert a human-readable str representation to number of bytes. Only the units "kB", "MB", "GB" are supported. The "B character at the end of the input `str` may be omitted. Args: size_str: (`str`) A human-readable str representing a number of bytes (e.g., "0", "1023", "1.1kB", "24 MB", "23GB", "100 G". Returns: (`int`) The parsed number of bytes. Raises: ValueError: on failure to parse the input `size_str`.
Convert a human-readable str representation to number of bytes.
[ "Convert", "a", "human", "-", "readable", "str", "representation", "to", "number", "of", "bytes", "." ]
def parse_readable_size_str(size_str): """Convert a human-readable str representation to number of bytes. Only the units "kB", "MB", "GB" are supported. The "B character at the end of the input `str` may be omitted. Args: size_str: (`str`) A human-readable str representing a number of bytes (e.g., "0", "1023", "1.1kB", "24 MB", "23GB", "100 G". Returns: (`int`) The parsed number of bytes. Raises: ValueError: on failure to parse the input `size_str`. """ size_str = size_str.strip() if size_str.endswith("B"): size_str = size_str[:-1] if size_str.isdigit(): return int(size_str) elif size_str.endswith("k"): return int(float(size_str[:-1]) * 1024) elif size_str.endswith("M"): return int(float(size_str[:-1]) * 1048576) elif size_str.endswith("G"): return int(float(size_str[:-1]) * 1073741824) else: raise ValueError("Failed to parsed human-readable byte size str: \"%s\"" % size_str)
[ "def", "parse_readable_size_str", "(", "size_str", ")", ":", "size_str", "=", "size_str", ".", "strip", "(", ")", "if", "size_str", ".", "endswith", "(", "\"B\"", ")", ":", "size_str", "=", "size_str", "[", ":", "-", "1", "]", "if", "size_str", ".", "i...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/command_parser.py#L409-L440
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/mailbox.py
python
Mailbox.discard
(self, key)
If the keyed message exists, remove it.
If the keyed message exists, remove it.
[ "If", "the", "keyed", "message", "exists", "remove", "it", "." ]
def discard(self, key): """If the keyed message exists, remove it.""" try: self.remove(key) except KeyError: pass
[ "def", "discard", "(", "self", ",", "key", ")", ":", "try", ":", "self", ".", "remove", "(", "key", ")", "except", "KeyError", ":", "pass" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L59-L64
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.AppendCols
(*args, **kwargs)
return _grid.Grid_AppendCols(*args, **kwargs)
AppendCols(self, int numCols=1, bool updateLabels=True) -> bool
AppendCols(self, int numCols=1, bool updateLabels=True) -> bool
[ "AppendCols", "(", "self", "int", "numCols", "=", "1", "bool", "updateLabels", "=", "True", ")", "-", ">", "bool" ]
def AppendCols(*args, **kwargs): """AppendCols(self, int numCols=1, bool updateLabels=True) -> bool""" return _grid.Grid_AppendCols(*args, **kwargs)
[ "def", "AppendCols", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_AppendCols", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1283-L1285
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/protobuf/python/google/protobuf/internal/well_known_types.py
python
_AddFieldPaths
(node, prefix, field_mask)
Adds the field paths descended from node to field_mask.
Adds the field paths descended from node to field_mask.
[ "Adds", "the", "field", "paths", "descended", "from", "node", "to", "field_mask", "." ]
def _AddFieldPaths(node, prefix, field_mask): """Adds the field paths descended from node to field_mask.""" if not node: field_mask.paths.append(prefix) return for name in sorted(node): if prefix: child_path = prefix + '.' + name else: child_path = name _AddFieldPaths(node[name], child_path, field_mask)
[ "def", "_AddFieldPaths", "(", "node", ",", "prefix", ",", "field_mask", ")", ":", "if", "not", "node", ":", "field_mask", ".", "paths", ".", "append", "(", "prefix", ")", "return", "for", "name", "in", "sorted", "(", "node", ")", ":", "if", "prefix", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/internal/well_known_types.py#L613-L623
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap_external.py
python
ExtensionFileLoader.create_module
(self, spec)
return module
Create an unitialized extension module
Create an unitialized extension module
[ "Create", "an", "unitialized", "extension", "module" ]
def create_module(self, spec): """Create an unitialized extension module""" module = _bootstrap._call_with_frames_removed( _imp.create_dynamic, spec) _bootstrap._verbose_message('extension module {!r} loaded from {!r}', spec.name, self.path) return module
[ "def", "create_module", "(", "self", ",", "spec", ")", ":", "module", "=", "_bootstrap", ".", "_call_with_frames_removed", "(", "_imp", ".", "create_dynamic", ",", "spec", ")", "_bootstrap", ".", "_verbose_message", "(", "'extension module {!r} loaded from {!r}'", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/importlib/_bootstrap_external.py#L1040-L1046
Qihoo360/mongosync
55b647e81c072ebe91daaa3b9dc1a953c3c22e19
dep/mongo-cxx-driver/site_scons/buildscripts/cpplint.py
python
CleansedLines.NumLines
(self)
return self.num_lines
Returns the number of lines represented.
Returns the number of lines represented.
[ "Returns", "the", "number", "of", "lines", "represented", "." ]
def NumLines(self): """Returns the number of lines represented.""" return self.num_lines
[ "def", "NumLines", "(", "self", ")", ":", "return", "self", ".", "num_lines" ]
https://github.com/Qihoo360/mongosync/blob/55b647e81c072ebe91daaa3b9dc1a953c3c22e19/dep/mongo-cxx-driver/site_scons/buildscripts/cpplint.py#L942-L944
mkeeter/antimony
ee525bbdad34ae94879fd055821f92bcef74e83f
py/fab/shapes.py
python
circle_edge
(x0, y0, x1, y1)
return circle(xmid, ymid, r)
Defines a circle from two points on its radius.
Defines a circle from two points on its radius.
[ "Defines", "a", "circle", "from", "two", "points", "on", "its", "radius", "." ]
def circle_edge(x0, y0, x1, y1): """ Defines a circle from two points on its radius. """ xmid = (x0+x1)/2.0 ymid = (y0+y1)/2.0 r = math.sqrt((xmid-x0)**2 +(ymid-y0)**2) return circle(xmid, ymid, r)
[ "def", "circle_edge", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "xmid", "=", "(", "x0", "+", "x1", ")", "/", "2.0", "ymid", "=", "(", "y0", "+", "y1", ")", "/", "2.0", "r", "=", "math", ".", "sqrt", "(", "(", "xmid", "-", "x0"...
https://github.com/mkeeter/antimony/blob/ee525bbdad34ae94879fd055821f92bcef74e83f/py/fab/shapes.py#L82-L88
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Menu.SetInvokingWindow
(*args, **kwargs)
return _core_.Menu_SetInvokingWindow(*args, **kwargs)
SetInvokingWindow(self, Window win)
SetInvokingWindow(self, Window win)
[ "SetInvokingWindow", "(", "self", "Window", "win", ")" ]
def SetInvokingWindow(*args, **kwargs): """SetInvokingWindow(self, Window win)""" return _core_.Menu_SetInvokingWindow(*args, **kwargs)
[ "def", "SetInvokingWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Menu_SetInvokingWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L12206-L12208
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/gyp/input.py
python
DependencyGraphNode._LinkDependenciesInternal
(self, targets, include_shared_libraries, dependencies=None, initial=True)
return dependencies
Returns an OrderedSet of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outside callers should always leave |initial| at its default setting. When adding a target to the list of dependencies, this function will recurse into itself with |initial| set to False, to collect dependencies that are linked into the linkable target for which the list is being built. If |include_shared_libraries| is False, the resulting dependencies will not include shared_library targets that are linked into this target.
Returns an OrderedSet of dependency targets that are linked into this target.
[ "Returns", "an", "OrderedSet", "of", "dependency", "targets", "that", "are", "linked", "into", "this", "target", "." ]
def _LinkDependenciesInternal(self, targets, include_shared_libraries, dependencies=None, initial=True): """Returns an OrderedSet of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outside callers should always leave |initial| at its default setting. When adding a target to the list of dependencies, this function will recurse into itself with |initial| set to False, to collect dependencies that are linked into the linkable target for which the list is being built. If |include_shared_libraries| is False, the resulting dependencies will not include shared_library targets that are linked into this target. """ if dependencies is None: # Using a list to get ordered output and a set to do fast "is it # already added" checks. dependencies = OrderedSet() # Check for None, corresponding to the root node. if self.ref is None: return dependencies # It's kind of sucky that |targets| has to be passed into this function, # but that's presently the easiest way to access the target dicts so that # this function can find target types. if 'target_name' not in targets[self.ref]: raise GypError("Missing 'target_name' field in target.") if 'type' not in targets[self.ref]: raise GypError("Missing 'type' field in target %s" % targets[self.ref]['target_name']) target_type = targets[self.ref]['type'] is_linkable = target_type in linkable_types if initial and not is_linkable: # If this is the first target being examined and it's not linkable, # return an empty list of link dependencies, because the link # dependencies are intended to apply to the target itself (initial is # True) and this target won't be linked. return dependencies # Don't traverse 'none' targets if explicitly excluded. if (target_type == 'none' and not targets[self.ref].get('dependencies_traverse', True)): dependencies.add(self.ref) return dependencies # Executables, mac kernel extensions, windows drivers and loadable modules # are already fully and finally linked. Nothing else can be a link # dependency of them, there can only be dependencies in the sense that a # dependent target might run an executable or load the loadable_module. if not initial and target_type in ('executable', 'loadable_module', 'mac_kernel_extension', 'windows_driver'): return dependencies # Shared libraries are already fully linked. They should only be included # in |dependencies| when adjusting static library dependencies (in order to # link against the shared_library's import lib), but should not be included # in |dependencies| when propagating link_settings. # The |include_shared_libraries| flag controls which of these two cases we # are handling. if (not initial and target_type == 'shared_library' and not include_shared_libraries): return dependencies # The target is linkable, add it to the list of link dependencies. if self.ref not in dependencies: dependencies.add(self.ref) if initial or not is_linkable: # If this is a subsequent target and it's linkable, don't look any # further for linkable dependencies, as they'll already be linked into # this target linkable. Always look at dependencies of the initial # target, and always look at dependencies of non-linkables. for dependency in self.dependencies: dependency._LinkDependenciesInternal(targets, include_shared_libraries, dependencies, False) return dependencies
[ "def", "_LinkDependenciesInternal", "(", "self", ",", "targets", ",", "include_shared_libraries", ",", "dependencies", "=", "None", ",", "initial", "=", "True", ")", ":", "if", "dependencies", "is", "None", ":", "# Using a list to get ordered output and a set to do fast...
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/input.py#L1452-L1529
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/hub.py
python
help
(github, model, force_reload=False, skip_validation=False)
return entry.__doc__
r""" Show the docstring of entrypoint ``model``. Args: github (string): a string with format <repo_owner/repo_name[:tag_name]> with an optional tag/branch. If ``tag_name`` is not specified, the default branch is assumed to be ``main`` if it exists, and otherwise ``master``. Example: 'pytorch/vision:0.10' model (string): a string of entrypoint name defined in repo's ``hubconf.py`` force_reload (bool, optional): whether to discard the existing cache and force a fresh download. Default is ``False``. skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit specified by the ``github`` argument properly belongs to the repo owner. This will make requests to the GitHub API; you can specify a non-default GitHub token by setting the ``GITHUB_TOKEN`` environment variable. Default is ``False``. Example: >>> print(torch.hub.help('pytorch/vision', 'resnet18', force_reload=True))
r""" Show the docstring of entrypoint ``model``.
[ "r", "Show", "the", "docstring", "of", "entrypoint", "model", "." ]
def help(github, model, force_reload=False, skip_validation=False): r""" Show the docstring of entrypoint ``model``. Args: github (string): a string with format <repo_owner/repo_name[:tag_name]> with an optional tag/branch. If ``tag_name`` is not specified, the default branch is assumed to be ``main`` if it exists, and otherwise ``master``. Example: 'pytorch/vision:0.10' model (string): a string of entrypoint name defined in repo's ``hubconf.py`` force_reload (bool, optional): whether to discard the existing cache and force a fresh download. Default is ``False``. skip_validation (bool, optional): if ``False``, torchhub will check that the branch or commit specified by the ``github`` argument properly belongs to the repo owner. This will make requests to the GitHub API; you can specify a non-default GitHub token by setting the ``GITHUB_TOKEN`` environment variable. Default is ``False``. Example: >>> print(torch.hub.help('pytorch/vision', 'resnet18', force_reload=True)) """ repo_dir = _get_cache_or_reload(github, force_reload, verbose=True, skip_validation=skip_validation) sys.path.insert(0, repo_dir) hubconf_path = os.path.join(repo_dir, MODULE_HUBCONF) hub_module = _import_module(MODULE_HUBCONF, hubconf_path) sys.path.remove(repo_dir) entry = _load_entry_from_hubconf(hub_module, model) return entry.__doc__
[ "def", "help", "(", "github", ",", "model", ",", "force_reload", "=", "False", ",", "skip_validation", "=", "False", ")", ":", "repo_dir", "=", "_get_cache_or_reload", "(", "github", ",", "force_reload", ",", "verbose", "=", "True", ",", "skip_validation", "...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/hub.py#L311-L341
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/tools/grit/grit/util.py
python
EscapeHtml
(text, escape_quotes = False)
return out
Returns 'text' with <, > and & (and optionally ") escaped to named HTML entities. Any existing named entity or HTML entity defined by decimal or hex code will be left untouched. This is appropriate for escaping text for inclusion in HTML, but not for XML.
Returns 'text' with <, > and & (and optionally ") escaped to named HTML entities. Any existing named entity or HTML entity defined by decimal or hex code will be left untouched. This is appropriate for escaping text for inclusion in HTML, but not for XML.
[ "Returns", "text", "with", "<", ">", "and", "&", "(", "and", "optionally", ")", "escaped", "to", "named", "HTML", "entities", ".", "Any", "existing", "named", "entity", "or", "HTML", "entity", "defined", "by", "decimal", "or", "hex", "code", "will", "be"...
def EscapeHtml(text, escape_quotes = False): '''Returns 'text' with <, > and & (and optionally ") escaped to named HTML entities. Any existing named entity or HTML entity defined by decimal or hex code will be left untouched. This is appropriate for escaping text for inclusion in HTML, but not for XML. ''' def Replace(match): if match.group() == '&': return '&amp;' elif match.group() == '<': return '&lt;' elif match.group() == '>': return '&gt;' elif match.group() == '"': if escape_quotes: return '&quot;' else: return match.group() else: assert False out = _HTML_CHARS_TO_ESCAPE.sub(Replace, text) return out
[ "def", "EscapeHtml", "(", "text", ",", "escape_quotes", "=", "False", ")", ":", "def", "Replace", "(", "match", ")", ":", "if", "match", ".", "group", "(", ")", "==", "'&'", ":", "return", "'&amp;'", "elif", "match", ".", "group", "(", ")", "==", "...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/util.py#L244-L259
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/pot/openvino/tools/pot/graph/nx_model.py
python
CompressedModel._remove_models_prefix
(self)
Removes model name prefix from node names
Removes model name prefix from node names
[ "Removes", "model", "name", "prefix", "from", "node", "names" ]
def _remove_models_prefix(self): """Removes model name prefix from node names""" if self._prefix_is_applied: self._prefix_is_applied = False for model_dict in self._models: model_name, model = model_dict['name'], model_dict['model'] self._cache.node_names[model_name] = [] for node in ge.get_all_operation_nodes(model, recursively=False): if node.name.startswith(model_name): rename_node(node, node.name.replace(model_name + '_', '', 1)) self._cache.node_names[model_name].append(node.name)
[ "def", "_remove_models_prefix", "(", "self", ")", ":", "if", "self", ".", "_prefix_is_applied", ":", "self", ".", "_prefix_is_applied", "=", "False", "for", "model_dict", "in", "self", ".", "_models", ":", "model_name", ",", "model", "=", "model_dict", "[", ...
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/pot/openvino/tools/pot/graph/nx_model.py#L190-L200
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/python/convert.py
python
build_toco_convert_protos
(input_tensors, output_tensors, inference_type=lite_constants.FLOAT, inference_input_type=None, input_format=lite_constants.TENSORFLOW_GRAPHDEF, input_shapes=None, output_format=lite_constants.TFLITE, quantized_input_stats=None, default_ranges_stats=None, drop_control_dependency=True, reorder_across_fake_quant=False, allow_custom_ops=False, change_concat_input_ranges=False, post_training_quantize=False, quantize_to_float16=False, dump_graphviz_dir=None, dump_graphviz_video=False, target_ops=None, allow_nonexistent_arrays=False, debug_info=None)
return model, toco, debug_info
Builds protocol buffers describing a conversion of a model using TOCO. Typically this is to convert from TensorFlow GraphDef to TFLite, in which case the default `input_format` and `output_format` are sufficient. Args: input_tensors: List of input tensors. Type and shape are computed using `foo.shape` and `foo.dtype`. output_tensors: List of output tensors (only .name is used from this). inference_type: Target data type of real-number arrays in the output file. Must be `{tf.float32, tf.uint8}`. (default tf.float32) Must be `{tf.float32, tf.uint8}`. (default `inference_type`) inference_input_type: Target data type of real-number input arrays. Allows for a different type for input arrays in the case of quantization. input_format: Type of data to read Currently must be `{TENSORFLOW_GRAPHDEF}`. (default TENSORFLOW_GRAPHDEF) input_shapes: Input array shape. It needs to be a list of the same length as `input_tensors`, or None. (default None) output_format: Output file format. Currently must be `{TFLITE, GRAPHVIZ_DOT}`. (default TFLITE) quantized_input_stats: List of tuples of floats representing the mean and standard deviation. Each tuple maps to the corresponding input tensor. Only need if `inference_input_type` is `QUANTIZED_UINT8`. real_input_value = (quantized_input_value - mean_value) / std_dev_value. (default None) default_ranges_stats: Tuple of integers representing (min, max) range values for all arrays without a specified range. Intended for experimenting with quantization via "dummy quantization". (default None) drop_control_dependency: Boolean indicating whether to drop control dependencies silently. This is due to TFLite not supporting control dependencies. (default True) reorder_across_fake_quant: Boolean indicating whether to reorder FakeQuant nodes in unexpected locations. Used when the location of the FakeQuant nodes is preventing graph transformations necessary to convert the graph. Results in a graph that differs from the quantized training graph, potentially causing differing arithmetic behavior. (default False) allow_custom_ops: Boolean indicating whether to allow custom operations. When false any unknown operation is an error. When true, custom ops are created for any op that is unknown. The developer will need to provide these to the TensorFlow Lite runtime with a custom resolver. (default False) change_concat_input_ranges: Boolean to change behavior of min/max ranges for inputs and outputs of the concat operator for quantized models. Changes the ranges of concat operator overlap when true. (default False) post_training_quantize: Boolean indicating whether to quantize the weights of the converted float model. Model size will be reduced and there will be latency improvements (at the cost of accuracy). (default False) quantize_to_float16: Boolean indicating whether to convert float buffers to float16. (default False) dump_graphviz_dir: Full filepath of folder to dump the graphs at various stages of processing GraphViz .dot files. Preferred over --output_format=GRAPHVIZ_DOT in order to keep the requirements of the output file. (default None) dump_graphviz_video: Boolean indicating whether to dump the graph after every graph transformation. (default False) target_ops: Experimental flag, subject to change. Set of OpsSet options indicating which converter to use. (default set([OpsSet.TFLITE_BUILTINS])) allow_nonexistent_arrays: Allow specifying array names that don't exist or are unused in the final graph. (default False) debug_info: `GraphDebugInfo` proto containing the stack traces for the original nodes referred by the converted graph. Returns: model_flags, toco_flags, debug_info: three protocol buffers describing the conversion process and debug information. Raises: ValueError: If the input tensor type is unknown Missing mean_values or std_dev_values RuntimeError: If TOCO fails to convert (in which case the runtime error's error text will contain the TOCO error log)
Builds protocol buffers describing a conversion of a model using TOCO.
[ "Builds", "protocol", "buffers", "describing", "a", "conversion", "of", "a", "model", "using", "TOCO", "." ]
def build_toco_convert_protos(input_tensors, output_tensors, inference_type=lite_constants.FLOAT, inference_input_type=None, input_format=lite_constants.TENSORFLOW_GRAPHDEF, input_shapes=None, output_format=lite_constants.TFLITE, quantized_input_stats=None, default_ranges_stats=None, drop_control_dependency=True, reorder_across_fake_quant=False, allow_custom_ops=False, change_concat_input_ranges=False, post_training_quantize=False, quantize_to_float16=False, dump_graphviz_dir=None, dump_graphviz_video=False, target_ops=None, allow_nonexistent_arrays=False, debug_info=None): """Builds protocol buffers describing a conversion of a model using TOCO. Typically this is to convert from TensorFlow GraphDef to TFLite, in which case the default `input_format` and `output_format` are sufficient. Args: input_tensors: List of input tensors. Type and shape are computed using `foo.shape` and `foo.dtype`. output_tensors: List of output tensors (only .name is used from this). inference_type: Target data type of real-number arrays in the output file. Must be `{tf.float32, tf.uint8}`. (default tf.float32) Must be `{tf.float32, tf.uint8}`. (default `inference_type`) inference_input_type: Target data type of real-number input arrays. Allows for a different type for input arrays in the case of quantization. input_format: Type of data to read Currently must be `{TENSORFLOW_GRAPHDEF}`. (default TENSORFLOW_GRAPHDEF) input_shapes: Input array shape. It needs to be a list of the same length as `input_tensors`, or None. (default None) output_format: Output file format. Currently must be `{TFLITE, GRAPHVIZ_DOT}`. (default TFLITE) quantized_input_stats: List of tuples of floats representing the mean and standard deviation. Each tuple maps to the corresponding input tensor. Only need if `inference_input_type` is `QUANTIZED_UINT8`. real_input_value = (quantized_input_value - mean_value) / std_dev_value. (default None) default_ranges_stats: Tuple of integers representing (min, max) range values for all arrays without a specified range. Intended for experimenting with quantization via "dummy quantization". (default None) drop_control_dependency: Boolean indicating whether to drop control dependencies silently. This is due to TFLite not supporting control dependencies. (default True) reorder_across_fake_quant: Boolean indicating whether to reorder FakeQuant nodes in unexpected locations. Used when the location of the FakeQuant nodes is preventing graph transformations necessary to convert the graph. Results in a graph that differs from the quantized training graph, potentially causing differing arithmetic behavior. (default False) allow_custom_ops: Boolean indicating whether to allow custom operations. When false any unknown operation is an error. When true, custom ops are created for any op that is unknown. The developer will need to provide these to the TensorFlow Lite runtime with a custom resolver. (default False) change_concat_input_ranges: Boolean to change behavior of min/max ranges for inputs and outputs of the concat operator for quantized models. Changes the ranges of concat operator overlap when true. (default False) post_training_quantize: Boolean indicating whether to quantize the weights of the converted float model. Model size will be reduced and there will be latency improvements (at the cost of accuracy). (default False) quantize_to_float16: Boolean indicating whether to convert float buffers to float16. (default False) dump_graphviz_dir: Full filepath of folder to dump the graphs at various stages of processing GraphViz .dot files. Preferred over --output_format=GRAPHVIZ_DOT in order to keep the requirements of the output file. (default None) dump_graphviz_video: Boolean indicating whether to dump the graph after every graph transformation. (default False) target_ops: Experimental flag, subject to change. Set of OpsSet options indicating which converter to use. (default set([OpsSet.TFLITE_BUILTINS])) allow_nonexistent_arrays: Allow specifying array names that don't exist or are unused in the final graph. (default False) debug_info: `GraphDebugInfo` proto containing the stack traces for the original nodes referred by the converted graph. Returns: model_flags, toco_flags, debug_info: three protocol buffers describing the conversion process and debug information. Raises: ValueError: If the input tensor type is unknown Missing mean_values or std_dev_values RuntimeError: If TOCO fails to convert (in which case the runtime error's error text will contain the TOCO error log) """ toco = _toco_flags_pb2.TocoFlags() toco.input_format = input_format toco.output_format = output_format toco.inference_type = util.convert_dtype_to_tflite_type(inference_type) if inference_input_type: toco.inference_input_type = util.convert_dtype_to_tflite_type( inference_input_type) else: toco.inference_input_type = toco.inference_type toco.drop_control_dependency = drop_control_dependency toco.reorder_across_fake_quant = reorder_across_fake_quant toco.allow_custom_ops = allow_custom_ops toco.post_training_quantize = post_training_quantize toco.quantize_to_float16 = quantize_to_float16 if default_ranges_stats: toco.default_ranges_min = default_ranges_stats[0] toco.default_ranges_max = default_ranges_stats[1] if dump_graphviz_dir: toco.dump_graphviz_dir = dump_graphviz_dir toco.dump_graphviz_include_video = dump_graphviz_video if target_ops: if set(target_ops) == set([OpsSet.TFLITE_BUILTINS, OpsSet.SELECT_TF_OPS]): toco.enable_select_tf_ops = True elif set(target_ops) == set([OpsSet.SELECT_TF_OPS]): toco.enable_select_tf_ops = True toco.force_select_tf_ops = True model = _model_flags_pb2.ModelFlags() model.change_concat_input_ranges = change_concat_input_ranges for idx, input_tensor in enumerate(input_tensors): input_array = model.input_arrays.add() input_array.name = util.get_tensor_name(input_tensor) input_array.data_type = util.convert_dtype_to_tflite_type( input_tensor.dtype) if toco.inference_input_type == _types_pb2.QUANTIZED_UINT8: if not quantized_input_stats: raise ValueError("std_dev and mean must be defined when " "inference_input_type is QUANTIZED_UINT8.") input_array.mean_value, input_array.std_value = quantized_input_stats[idx] if input_shapes is None: shape = input_tensor.shape else: shape = input_shapes[idx] input_array.shape.dims.extend(map(int, shape)) for output_tensor in output_tensors: model.output_arrays.append(util.get_tensor_name(output_tensor)) model.allow_nonexistent_arrays = allow_nonexistent_arrays return model, toco, debug_info
[ "def", "build_toco_convert_protos", "(", "input_tensors", ",", "output_tensors", ",", "inference_type", "=", "lite_constants", ".", "FLOAT", ",", "inference_input_type", "=", "None", ",", "input_format", "=", "lite_constants", ".", "TENSORFLOW_GRAPHDEF", ",", "input_sha...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/lite/python/convert.py#L211-L357
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/lldbutils/lldbutils/layout.py
python
frametree
(debugger, command, result, dict)
Dumps the frame tree containing the given nsIFrame*.
Dumps the frame tree containing the given nsIFrame*.
[ "Dumps", "the", "frame", "tree", "containing", "the", "given", "nsIFrame", "*", "." ]
def frametree(debugger, command, result, dict): """Dumps the frame tree containing the given nsIFrame*.""" debugger.HandleCommand('expr (' + command + ')->DumpFrameTree()')
[ "def", "frametree", "(", "debugger", ",", "command", ",", "result", ",", "dict", ")", ":", "debugger", ".", "HandleCommand", "(", "'expr ('", "+", "command", "+", "')->DumpFrameTree()'", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/lldbutils/lldbutils/layout.py#L3-L5
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/email/message.py
python
Message.as_string
(self, unixfrom=False, maxheaderlen=0, policy=None)
return fp.getvalue()
Return the entire formatted message as a string. Optional 'unixfrom', when true, means include the Unix From_ envelope header. For backward compatibility reasons, if maxheaderlen is not specified it defaults to 0, so you must override it explicitly if you want a different maxheaderlen. 'policy' is passed to the Generator instance used to serialize the mesasge; if it is not specified the policy associated with the message instance is used. If the message object contains binary data that is not encoded according to RFC standards, the non-compliant data will be replaced by unicode "unknown character" code points.
Return the entire formatted message as a string.
[ "Return", "the", "entire", "formatted", "message", "as", "a", "string", "." ]
def as_string(self, unixfrom=False, maxheaderlen=0, policy=None): """Return the entire formatted message as a string. Optional 'unixfrom', when true, means include the Unix From_ envelope header. For backward compatibility reasons, if maxheaderlen is not specified it defaults to 0, so you must override it explicitly if you want a different maxheaderlen. 'policy' is passed to the Generator instance used to serialize the mesasge; if it is not specified the policy associated with the message instance is used. If the message object contains binary data that is not encoded according to RFC standards, the non-compliant data will be replaced by unicode "unknown character" code points. """ from email.generator import Generator policy = self.policy if policy is None else policy fp = StringIO() g = Generator(fp, mangle_from_=False, maxheaderlen=maxheaderlen, policy=policy) g.flatten(self, unixfrom=unixfrom) return fp.getvalue()
[ "def", "as_string", "(", "self", ",", "unixfrom", "=", "False", ",", "maxheaderlen", "=", "0", ",", "policy", "=", "None", ")", ":", "from", "email", ".", "generator", "import", "Generator", "policy", "=", "self", ".", "policy", "if", "policy", "is", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/message.py#L137-L159
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/boost/boost.py
python
AutoBoost.network_auto_process_eval
(self, network)
return network
r""" Boost network eval. Args: network (Cell): The inference network.
r""" Boost network eval.
[ "r", "Boost", "network", "eval", "." ]
def network_auto_process_eval(self, network): r""" Boost network eval. Args: network (Cell): The inference network. """ if self.boost_config["dim_reduce"]: return network if self.boost_config["less_bn"]: network = LessBN(network) return network
[ "def", "network_auto_process_eval", "(", "self", ",", "network", ")", ":", "if", "self", ".", "boost_config", "[", "\"dim_reduce\"", "]", ":", "return", "network", "if", "self", ".", "boost_config", "[", "\"less_bn\"", "]", ":", "network", "=", "LessBN", "("...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/boost/boost.py#L197-L209
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/4sum-ii.py
python
Solution.fourSumCount
(self, A, B, C, D)
return sum(A_B_sum[-c-d] for c in C for d in D)
:type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int
:type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int
[ ":", "type", "A", ":", "List", "[", "int", "]", ":", "type", "B", ":", "List", "[", "int", "]", ":", "type", "C", ":", "List", "[", "int", "]", ":", "type", "D", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def fourSumCount(self, A, B, C, D): """ :type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int """ A_B_sum = collections.Counter(a+b for a in A for b in B) return sum(A_B_sum[-c-d] for c in C for d in D)
[ "def", "fourSumCount", "(", "self", ",", "A", ",", "B", ",", "C", ",", "D", ")", ":", "A_B_sum", "=", "collections", ".", "Counter", "(", "a", "+", "b", "for", "a", "in", "A", "for", "b", "in", "B", ")", "return", "sum", "(", "A_B_sum", "[", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/4sum-ii.py#L8-L17
Cantera/cantera
0119484b261967ccb55a0066c020599cacc312e4
interfaces/cython/cantera/ctml_writer.py
python
phase.conc_dim
(self)
return (1, -self._dim)
Concentration dimensions. Used in computing the units for reaction rate coefficients.
Concentration dimensions. Used in computing the units for reaction rate coefficients.
[ "Concentration", "dimensions", ".", "Used", "in", "computing", "the", "units", "for", "reaction", "rate", "coefficients", "." ]
def conc_dim(self): """Concentration dimensions. Used in computing the units for reaction rate coefficients.""" return (1, -self._dim)
[ "def", "conc_dim", "(", "self", ")", ":", "return", "(", "1", ",", "-", "self", ".", "_dim", ")" ]
https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/ctml_writer.py#L1855-L1858
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/bandwidth.py
python
BandwidthLimiter.get_bandwith_limited_stream
(self, fileobj, transfer_coordinator, enabled=True)
return stream
Wraps a fileobj in a bandwidth limited stream wrapper :type fileobj: file-like obj :param fileobj: The file-like obj to wrap :type transfer_coordinator: s3transfer.futures.TransferCoordinator param transfer_coordinator: The coordinator for the general transfer that the wrapped stream is a part of :type enabled: boolean :param enabled: Whether bandwidth limiting should be enabled to start
Wraps a fileobj in a bandwidth limited stream wrapper
[ "Wraps", "a", "fileobj", "in", "a", "bandwidth", "limited", "stream", "wrapper" ]
def get_bandwith_limited_stream(self, fileobj, transfer_coordinator, enabled=True): """Wraps a fileobj in a bandwidth limited stream wrapper :type fileobj: file-like obj :param fileobj: The file-like obj to wrap :type transfer_coordinator: s3transfer.futures.TransferCoordinator param transfer_coordinator: The coordinator for the general transfer that the wrapped stream is a part of :type enabled: boolean :param enabled: Whether bandwidth limiting should be enabled to start """ stream = BandwidthLimitedStream( fileobj, self._leaky_bucket, transfer_coordinator, self._time_utils) if not enabled: stream.disable_bandwidth_limiting() return stream
[ "def", "get_bandwith_limited_stream", "(", "self", ",", "fileobj", ",", "transfer_coordinator", ",", "enabled", "=", "True", ")", ":", "stream", "=", "BandwidthLimitedStream", "(", "fileobj", ",", "self", ".", "_leaky_bucket", ",", "transfer_coordinator", ",", "se...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/bandwidth.py#L78-L97
jubatus/jubatus
1251ce551bac980488a6313728e72b3fe0b79a9f
tools/codestyle/cpplint/cpplint.py
python
CheckForCopyright
(filename, lines, error)
Logs an error if no Copyright message appears at the top of the file.
Logs an error if no Copyright message appears at the top of the file.
[ "Logs", "an", "error", "if", "no", "Copyright", "message", "appears", "at", "the", "top", "of", "the", "file", "." ]
def CheckForCopyright(filename, lines, error): """Logs an error if no Copyright message appears at the top of the file.""" # We'll say it should occur by line 10. Don't forget there's a # dummy line at the front. for line in xrange(1, min(len(lines), 11)): if re.search(r'Copyright', lines[line], re.I): break else: # means no copyright line was found error(filename, 0, 'legal/copyright', 5, 'No copyright message found. ' 'You should have a line: "Copyright [year] <Copyright Owner>"')
[ "def", "CheckForCopyright", "(", "filename", ",", "lines", ",", "error", ")", ":", "# We'll say it should occur by line 10. Don't forget there's a", "# dummy line at the front.", "for", "line", "in", "xrange", "(", "1", ",", "min", "(", "len", "(", "lines", ")", ","...
https://github.com/jubatus/jubatus/blob/1251ce551bac980488a6313728e72b3fe0b79a9f/tools/codestyle/cpplint/cpplint.py#L1022-L1032
sfzhang15/RefineDet
52b6fe23dc1a160fe710b7734576dca509bf4fae
python/caffe/io.py
python
resize_image
(im, new_dims, interp_order=1)
return resized_im.astype(np.float32)
Resize an image array with interpolation. Parameters ---------- im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. interp_order : interpolation order, default is linear. Returns ------- im : resized ndarray with shape (new_dims[0], new_dims[1], K)
Resize an image array with interpolation.
[ "Resize", "an", "image", "array", "with", "interpolation", "." ]
def resize_image(im, new_dims, interp_order=1): """ Resize an image array with interpolation. Parameters ---------- im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. interp_order : interpolation order, default is linear. Returns ------- im : resized ndarray with shape (new_dims[0], new_dims[1], K) """ if im.shape[-1] == 1 or im.shape[-1] == 3: im_min, im_max = im.min(), im.max() if im_max > im_min: # skimage is fast but only understands {1,3} channel images # in [0, 1]. im_std = (im - im_min) / (im_max - im_min) resized_std = resize(im_std, new_dims, order=interp_order) resized_im = resized_std * (im_max - im_min) + im_min else: # the image is a constant -- avoid divide by 0 ret = np.empty((new_dims[0], new_dims[1], im.shape[-1]), dtype=np.float32) ret.fill(im_min) return ret else: # ndimage interpolates anything but more slowly. scale = tuple(np.array(new_dims, dtype=float) / np.array(im.shape[:2])) resized_im = zoom(im, scale + (1,), order=interp_order) return resized_im.astype(np.float32)
[ "def", "resize_image", "(", "im", ",", "new_dims", ",", "interp_order", "=", "1", ")", ":", "if", "im", ".", "shape", "[", "-", "1", "]", "==", "1", "or", "im", ".", "shape", "[", "-", "1", "]", "==", "3", ":", "im_min", ",", "im_max", "=", "...
https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/python/caffe/io.py#L306-L338
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/npdatetime.py
python
alloc_timedelta_result
(builder, name='ret')
return ret
Allocate a NaT-initialized datetime64 (or timedelta64) result slot.
Allocate a NaT-initialized datetime64 (or timedelta64) result slot.
[ "Allocate", "a", "NaT", "-", "initialized", "datetime64", "(", "or", "timedelta64", ")", "result", "slot", "." ]
def alloc_timedelta_result(builder, name='ret'): """ Allocate a NaT-initialized datetime64 (or timedelta64) result slot. """ ret = cgutils.alloca_once(builder, TIMEDELTA64, name=name) builder.store(NAT, ret) return ret
[ "def", "alloc_timedelta_result", "(", "builder", ",", "name", "=", "'ret'", ")", ":", "ret", "=", "cgutils", ".", "alloca_once", "(", "builder", ",", "TIMEDELTA64", ",", "name", "=", "name", ")", "builder", ".", "store", "(", "NAT", ",", "ret", ")", "r...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/npdatetime.py#L75-L81
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/v8/third_party/jinja2/filters.py
python
do_select
(*args, **kwargs)
return select_or_reject(args, kwargs, lambda x: x, False)
Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding. If no test is specified, each object will be evaluated as a boolean. Example usage: .. sourcecode:: jinja {{ numbers|select("odd") }} {{ numbers|select("odd") }} {{ numbers|select("divisibleby", 3) }} {{ numbers|select("lessthan", 42) }} {{ strings|select("equalto", "mystring") }} .. versionadded:: 2.7
Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding.
[ "Filters", "a", "sequence", "of", "objects", "by", "applying", "a", "test", "to", "each", "object", "and", "only", "selecting", "the", "objects", "with", "the", "test", "succeeding", "." ]
def do_select(*args, **kwargs): """Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding. If no test is specified, each object will be evaluated as a boolean. Example usage: .. sourcecode:: jinja {{ numbers|select("odd") }} {{ numbers|select("odd") }} {{ numbers|select("divisibleby", 3) }} {{ numbers|select("lessthan", 42) }} {{ strings|select("equalto", "mystring") }} .. versionadded:: 2.7 """ return select_or_reject(args, kwargs, lambda x: x, False)
[ "def", "do_select", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "select_or_reject", "(", "args", ",", "kwargs", ",", "lambda", "x", ":", "x", ",", "False", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/filters.py#L967-L985
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/guidance/fast_cnn.py
python
default_hparams
()
return tf.contrib.training.HParams( conv_layers=3, mid_layers=1, final_layers=1, filter_width=5, hidden_size=1024)
Default values for model hyperparameters.
Default values for model hyperparameters.
[ "Default", "values", "for", "model", "hyperparameters", "." ]
def default_hparams(): """Default values for model hyperparameters.""" return tf.contrib.training.HParams( conv_layers=3, mid_layers=1, final_layers=1, filter_width=5, hidden_size=1024)
[ "def", "default_hparams", "(", ")", ":", "return", "tf", ".", "contrib", ".", "training", ".", "HParams", "(", "conv_layers", "=", "3", ",", "mid_layers", "=", "1", ",", "final_layers", "=", "1", ",", "filter_width", "=", "5", ",", "hidden_size", "=", ...
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/guidance/fast_cnn.py#L30-L37
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py
python
_is_class_var
(annot)
return str(annot).startswith(_classvar_prefixes)
Check whether *annot* is a typing.ClassVar. The string comparison hack is used to avoid evaluating all string annotations which would put attrs-based classes at a performance disadvantage compared to plain old classes.
Check whether *annot* is a typing.ClassVar.
[ "Check", "whether", "*", "annot", "*", "is", "a", "typing", ".", "ClassVar", "." ]
def _is_class_var(annot): """ Check whether *annot* is a typing.ClassVar. The string comparison hack is used to avoid evaluating all string annotations which would put attrs-based classes at a performance disadvantage compared to plain old classes. """ return str(annot).startswith(_classvar_prefixes)
[ "def", "_is_class_var", "(", "annot", ")", ":", "return", "str", "(", "annot", ")", ".", "startswith", "(", "_classvar_prefixes", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py#L274-L282
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/pyyaml/lib/yaml/__init__.py
python
dump
(data, stream=None, Dumper=Dumper, **kwds)
return dump_all([data], stream, Dumper=Dumper, **kwds)
Serialize a Python object into a YAML stream. If stream is None, return the produced string instead.
Serialize a Python object into a YAML stream. If stream is None, return the produced string instead.
[ "Serialize", "a", "Python", "object", "into", "a", "YAML", "stream", ".", "If", "stream", "is", "None", "return", "the", "produced", "string", "instead", "." ]
def dump(data, stream=None, Dumper=Dumper, **kwds): """ Serialize a Python object into a YAML stream. If stream is None, return the produced string instead. """ return dump_all([data], stream, Dumper=Dumper, **kwds)
[ "def", "dump", "(", "data", ",", "stream", "=", "None", ",", "Dumper", "=", "Dumper", ",", "*", "*", "kwds", ")", ":", "return", "dump_all", "(", "[", "data", "]", ",", "stream", ",", "Dumper", "=", "Dumper", ",", "*", "*", "kwds", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/pyyaml/lib/yaml/__init__.py#L197-L202
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py3/google/protobuf/internal/python_message.py
python
_BytesForNonRepeatedElement
(value, field_number, field_type)
Returns the number of bytes needed to serialize a non-repeated element. The returned byte count includes space for tag information and any other additional space associated with serializing value. Args: value: Value we're serializing. field_number: Field number of this value. (Since the field number is stored as part of a varint-encoded tag, this has an impact on the total bytes required to serialize the value). field_type: The type of the field. One of the TYPE_* constants within FieldDescriptor.
Returns the number of bytes needed to serialize a non-repeated element. The returned byte count includes space for tag information and any other additional space associated with serializing value.
[ "Returns", "the", "number", "of", "bytes", "needed", "to", "serialize", "a", "non", "-", "repeated", "element", ".", "The", "returned", "byte", "count", "includes", "space", "for", "tag", "information", "and", "any", "other", "additional", "space", "associated...
def _BytesForNonRepeatedElement(value, field_number, field_type): """Returns the number of bytes needed to serialize a non-repeated element. The returned byte count includes space for tag information and any other additional space associated with serializing value. Args: value: Value we're serializing. field_number: Field number of this value. (Since the field number is stored as part of a varint-encoded tag, this has an impact on the total bytes required to serialize the value). field_type: The type of the field. One of the TYPE_* constants within FieldDescriptor. """ try: fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type] return fn(field_number, value) except KeyError: raise message_mod.EncodeError('Unrecognized field type: %d' % field_type)
[ "def", "_BytesForNonRepeatedElement", "(", "value", ",", "field_number", ",", "field_type", ")", ":", "try", ":", "fn", "=", "type_checkers", ".", "TYPE_TO_BYTE_SIZE_FN", "[", "field_type", "]", "return", "fn", "(", "field_number", ",", "value", ")", "except", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/python_message.py#L1041-L1058
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/websocket-client/websocket.py
python
WebSocket.recv
(self)
return data
Receive string data(byte array) from the server. return value: string(byte array) value.
Receive string data(byte array) from the server.
[ "Receive", "string", "data", "(", "byte", "array", ")", "from", "the", "server", "." ]
def recv(self): """ Receive string data(byte array) from the server. return value: string(byte array) value. """ opcode, data = self.recv_data() return data
[ "def", "recv", "(", "self", ")", ":", "opcode", ",", "data", "=", "self", ".", "recv_data", "(", ")", "return", "data" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/websocket-client/websocket.py#L590-L597
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/excel/_base.py
python
ExcelFile.parse
( self, sheet_name=0, header=0, names=None, index_col=None, usecols=None, squeeze=False, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, parse_dates=False, date_parser=None, thousands=None, comment=None, skipfooter=0, convert_float=True, mangle_dupe_cols=True, **kwds, )
return self._reader.parse( sheet_name=sheet_name, header=header, names=names, index_col=index_col, usecols=usecols, squeeze=squeeze, converters=converters, true_values=true_values, false_values=false_values, skiprows=skiprows, nrows=nrows, na_values=na_values, parse_dates=parse_dates, date_parser=date_parser, thousands=thousands, comment=comment, skipfooter=skipfooter, convert_float=convert_float, mangle_dupe_cols=mangle_dupe_cols, **kwds, )
Parse specified sheet(s) into a DataFrame. Equivalent to read_excel(ExcelFile, ...) See the read_excel docstring for more info on accepted parameters. Returns ------- DataFrame or dict of DataFrames DataFrame from the passed in Excel file.
Parse specified sheet(s) into a DataFrame.
[ "Parse", "specified", "sheet", "(", "s", ")", "into", "a", "DataFrame", "." ]
def parse( self, sheet_name=0, header=0, names=None, index_col=None, usecols=None, squeeze=False, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, parse_dates=False, date_parser=None, thousands=None, comment=None, skipfooter=0, convert_float=True, mangle_dupe_cols=True, **kwds, ): """ Parse specified sheet(s) into a DataFrame. Equivalent to read_excel(ExcelFile, ...) See the read_excel docstring for more info on accepted parameters. Returns ------- DataFrame or dict of DataFrames DataFrame from the passed in Excel file. """ if "chunksize" in kwds: raise NotImplementedError( "chunksize keyword of read_excel is not implemented" ) return self._reader.parse( sheet_name=sheet_name, header=header, names=names, index_col=index_col, usecols=usecols, squeeze=squeeze, converters=converters, true_values=true_values, false_values=false_values, skiprows=skiprows, nrows=nrows, na_values=na_values, parse_dates=parse_dates, date_parser=date_parser, thousands=thousands, comment=comment, skipfooter=skipfooter, convert_float=convert_float, mangle_dupe_cols=mangle_dupe_cols, **kwds, )
[ "def", "parse", "(", "self", ",", "sheet_name", "=", "0", ",", "header", "=", "0", ",", "names", "=", "None", ",", "index_col", "=", "None", ",", "usecols", "=", "None", ",", "squeeze", "=", "False", ",", "converters", "=", "None", ",", "true_values"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/excel/_base.py#L829-L889
VowpalWabbit/vowpal_wabbit
866b8fa88ff85a957c7eb72065ea44518b9ba416
python/vowpalwabbit/dftovw.py
python
_Col.check_col_type
(self, df: pd.DataFrame)
Check if the type of the column is valid. Args: df: The dataframe from which to check the column. Raises: TypeError: If the type of the column is not valid.
Check if the type of the column is valid.
[ "Check", "if", "the", "type", "of", "the", "column", "is", "valid", "." ]
def check_col_type(self, df: pd.DataFrame) -> None: """Check if the type of the column is valid. Args: df: The dataframe from which to check the column. Raises: TypeError: If the type of the column is not valid. """ expected_type = [ self.mapping_python_numpy[exp_type] for exp_type in self.expected_type ] col_type = df[self.colname].dtype if not any(np.issubdtype(col_type, exp_type) for exp_type in expected_type): raise TypeError( "column '{colname}' should be either of the following type(s): {type_name}.".format( colname=self.colname, type_name=str([x.__name__ for x in self.expected_type])[1:-1], ) )
[ "def", "check_col_type", "(", "self", ",", "df", ":", "pd", ".", "DataFrame", ")", "->", "None", ":", "expected_type", "=", "[", "self", ".", "mapping_python_numpy", "[", "exp_type", "]", "for", "exp_type", "in", "self", ".", "expected_type", "]", "col_typ...
https://github.com/VowpalWabbit/vowpal_wabbit/blob/866b8fa88ff85a957c7eb72065ea44518b9ba416/python/vowpalwabbit/dftovw.py#L90-L110
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/npyio.py
python
_getconv
(dtype)
Find the correct dtype converter. Adapted from matplotlib
Find the correct dtype converter. Adapted from matplotlib
[ "Find", "the", "correct", "dtype", "converter", ".", "Adapted", "from", "matplotlib" ]
def _getconv(dtype): """ Find the correct dtype converter. Adapted from matplotlib """ def floatconv(x): x.lower() if '0x' in x: return float.fromhex(x) return float(x) typ = dtype.type if issubclass(typ, np.bool_): return lambda x: bool(int(x)) if issubclass(typ, np.uint64): return np.uint64 if issubclass(typ, np.int64): return np.int64 if issubclass(typ, np.integer): return lambda x: int(float(x)) elif issubclass(typ, np.longdouble): return np.longdouble elif issubclass(typ, np.floating): return floatconv elif issubclass(typ, complex): return lambda x: complex(asstr(x).replace('+-', '-')) elif issubclass(typ, np.bytes_): return asbytes elif issubclass(typ, np.unicode_): return asunicode else: return asstr
[ "def", "_getconv", "(", "dtype", ")", ":", "def", "floatconv", "(", "x", ")", ":", "x", ".", "lower", "(", ")", "if", "'0x'", "in", "x", ":", "return", "float", ".", "fromhex", "(", "x", ")", "return", "float", "(", "x", ")", "typ", "=", "dtype...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/npyio.py#L787-L816
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
FileDropTarget._setCallbackInfo
(*args, **kwargs)
return _misc_.FileDropTarget__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 _misc_.FileDropTarget__setCallbackInfo(*args, **kwargs)
[ "def", "_setCallbackInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "FileDropTarget__setCallbackInfo", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L5706-L5708
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/ragged/ragged_map_ops.py
python
map_fn
(fn, elems, dtype=None, parallel_iterations=None, back_prop=True, swap_memory=False, infer_shape=True, name=None)
return map_fn_lib.map_fn(fn, elems, dtype, parallel_iterations, back_prop, swap_memory, infer_shape, name)
map on the list of tensors unpacked from `elems` on dimension 0. The simplest version of `map_fn` repeatedly applies the callable `fn` to a sequence of elements from first to last. The elements are made of the tensors unpacked from `elems`. `dtype` is the data type of the return value of `fn`. Users must provide `dtype` if it is different from the data type of `elems`. Suppose that `elems` is unpacked into `values`, a list of tensors. The shape of the result tensor is `[values.shape[0]] + fn(values[0]).shape`. This method also allows multi-arity `elems` and output of `fn`. If `elems` is a (possibly nested) list or tuple of tensors, then each of these tensors must have a matching first (unpack) dimension. The signature of `fn` may match the structure of `elems`. That is, if `elems` is `(t1, [t2, t3, [t4, t5]])`, then an appropriate signature for `fn` is: `fn = lambda (t1, [t2, t3, [t4, t5]]):`. Furthermore, `fn` may emit a different structure than its input. For example, `fn` may look like: `fn = lambda t1: return (t1 + 1, t1 - 1)`. In this case, the `dtype` parameter is not optional: `dtype` must be a type or (possibly nested) tuple of types matching the output of `fn`. To apply a functional operation to the nonzero elements of a SparseTensor one of the following methods is recommended. First, if the function is expressible as TensorFlow ops, use ```python result = SparseTensor(input.indices, fn(input.values), input.dense_shape) ``` If, however, the function is not expressible as a TensorFlow op, then use ```python result = SparseTensor( input.indices, map_fn(fn, input.values), input.dense_shape) ``` instead. When executing eagerly, map_fn does not execute in parallel even if `parallel_iterations` is set to a value > 1. You can still get the performance benefits of running a function in parallel by using the `tf.contrib.eager.defun` decorator, ```python # Assume the function being used in map_fn is fn. # To ensure map_fn calls fn in parallel, use the defun decorator. @tf.contrib.eager.defun def func(tensor): return tf.map_fn(fn, tensor) ``` Note that if you use the defun decorator, any non-TensorFlow Python code that you may have written in your function won't get executed. See `tf.contrib.eager.defun` for more details. The recommendation would be to debug without defun but switch to defun to get performance benefits of running map_fn in parallel. Args: fn: The callable to be performed. It accepts one argument, which will have the same (possibly nested) structure as `elems`. Its output must have the same structure as `dtype` if one is provided, otherwise it must have the same structure as `elems`. elems: A tensor or (possibly nested) sequence of tensors, each of which will be unpacked along their first dimension. The nested sequence of the resulting slices will be applied to `fn`. dtype: (optional) The output type(s) of `fn`. If `fn` returns a structure of Tensors differing from the structure of `elems`, then `dtype` is not optional and must have the same structure as the output of `fn`. Use `RaggedTensorType` to declare an output of type `RaggedTensor`. parallel_iterations: (optional) The number of iterations allowed to run in parallel. When graph building, the default value is 10. While executing eagerly, the default value is set to 1. back_prop: (optional) True enables support for back propagation. swap_memory: (optional) True enables GPU-CPU memory swapping. infer_shape: (optional) False disables tests for consistent output shapes. name: (optional) Name prefix for the returned tensors. Returns: A possibly nested sequence of potentially ragged tensors. Each tensor packs the results of applying `fn` to tensors unpacked from `elems` along the first dimension, from first to last. Raises: TypeError: if `fn` is not callable or the structure of the output of `fn` and `dtype` do not match, or if elems is a SparseTensor. ValueError: if the lengths of the output of `fn` and `dtype` do not match. #### Examples: ```python elems = np.array([1, 2, 3, 4, 5, 6]) squares = map_fn(lambda x: x * x, elems) # squares == [1, 4, 9, 16, 25, 36] ``` ```python elems = (np.array([1, 2, 3]), np.array([-1, 1, -1])) alternate = map_fn(lambda x: x[0] * x[1], elems, dtype=tf.int64) # alternate == [-1, 2, -3] ``` ```python elems = np.array([1, 2, 3]) alternates = map_fn(lambda x: (x, -x), elems, dtype=(tf.int64, tf.int64)) # alternates[0] == [1, 2, 3] # alternates[1] == [-1, -2, -3] ``` ```python elems=ragged.constant([[1, 2, 3], [4, 5], [6, 7]]) mean = map_fn(tf.reduce_mean, elems) # mean == [2, 4, 6] ``` ```python elems=ragged.constant([[1, 2, 3], [4, 5], [6, 7]], dtype=tf.int64) out = map_fn(fn=lambda x: x+1, elems, dtype=ragged.RaggedTensorType(type=tf.int64, ragged_rank=0)) # out = tf.ragged.constant([[2, 3, 4], [5, 6], [7, 8]]) ```
map on the list of tensors unpacked from `elems` on dimension 0.
[ "map", "on", "the", "list", "of", "tensors", "unpacked", "from", "elems", "on", "dimension", "0", "." ]
def map_fn(fn, elems, dtype=None, parallel_iterations=None, back_prop=True, swap_memory=False, infer_shape=True, name=None): """map on the list of tensors unpacked from `elems` on dimension 0. The simplest version of `map_fn` repeatedly applies the callable `fn` to a sequence of elements from first to last. The elements are made of the tensors unpacked from `elems`. `dtype` is the data type of the return value of `fn`. Users must provide `dtype` if it is different from the data type of `elems`. Suppose that `elems` is unpacked into `values`, a list of tensors. The shape of the result tensor is `[values.shape[0]] + fn(values[0]).shape`. This method also allows multi-arity `elems` and output of `fn`. If `elems` is a (possibly nested) list or tuple of tensors, then each of these tensors must have a matching first (unpack) dimension. The signature of `fn` may match the structure of `elems`. That is, if `elems` is `(t1, [t2, t3, [t4, t5]])`, then an appropriate signature for `fn` is: `fn = lambda (t1, [t2, t3, [t4, t5]]):`. Furthermore, `fn` may emit a different structure than its input. For example, `fn` may look like: `fn = lambda t1: return (t1 + 1, t1 - 1)`. In this case, the `dtype` parameter is not optional: `dtype` must be a type or (possibly nested) tuple of types matching the output of `fn`. To apply a functional operation to the nonzero elements of a SparseTensor one of the following methods is recommended. First, if the function is expressible as TensorFlow ops, use ```python result = SparseTensor(input.indices, fn(input.values), input.dense_shape) ``` If, however, the function is not expressible as a TensorFlow op, then use ```python result = SparseTensor( input.indices, map_fn(fn, input.values), input.dense_shape) ``` instead. When executing eagerly, map_fn does not execute in parallel even if `parallel_iterations` is set to a value > 1. You can still get the performance benefits of running a function in parallel by using the `tf.contrib.eager.defun` decorator, ```python # Assume the function being used in map_fn is fn. # To ensure map_fn calls fn in parallel, use the defun decorator. @tf.contrib.eager.defun def func(tensor): return tf.map_fn(fn, tensor) ``` Note that if you use the defun decorator, any non-TensorFlow Python code that you may have written in your function won't get executed. See `tf.contrib.eager.defun` for more details. The recommendation would be to debug without defun but switch to defun to get performance benefits of running map_fn in parallel. Args: fn: The callable to be performed. It accepts one argument, which will have the same (possibly nested) structure as `elems`. Its output must have the same structure as `dtype` if one is provided, otherwise it must have the same structure as `elems`. elems: A tensor or (possibly nested) sequence of tensors, each of which will be unpacked along their first dimension. The nested sequence of the resulting slices will be applied to `fn`. dtype: (optional) The output type(s) of `fn`. If `fn` returns a structure of Tensors differing from the structure of `elems`, then `dtype` is not optional and must have the same structure as the output of `fn`. Use `RaggedTensorType` to declare an output of type `RaggedTensor`. parallel_iterations: (optional) The number of iterations allowed to run in parallel. When graph building, the default value is 10. While executing eagerly, the default value is set to 1. back_prop: (optional) True enables support for back propagation. swap_memory: (optional) True enables GPU-CPU memory swapping. infer_shape: (optional) False disables tests for consistent output shapes. name: (optional) Name prefix for the returned tensors. Returns: A possibly nested sequence of potentially ragged tensors. Each tensor packs the results of applying `fn` to tensors unpacked from `elems` along the first dimension, from first to last. Raises: TypeError: if `fn` is not callable or the structure of the output of `fn` and `dtype` do not match, or if elems is a SparseTensor. ValueError: if the lengths of the output of `fn` and `dtype` do not match. #### Examples: ```python elems = np.array([1, 2, 3, 4, 5, 6]) squares = map_fn(lambda x: x * x, elems) # squares == [1, 4, 9, 16, 25, 36] ``` ```python elems = (np.array([1, 2, 3]), np.array([-1, 1, -1])) alternate = map_fn(lambda x: x[0] * x[1], elems, dtype=tf.int64) # alternate == [-1, 2, -3] ``` ```python elems = np.array([1, 2, 3]) alternates = map_fn(lambda x: (x, -x), elems, dtype=(tf.int64, tf.int64)) # alternates[0] == [1, 2, 3] # alternates[1] == [-1, -2, -3] ``` ```python elems=ragged.constant([[1, 2, 3], [4, 5], [6, 7]]) mean = map_fn(tf.reduce_mean, elems) # mean == [2, 4, 6] ``` ```python elems=ragged.constant([[1, 2, 3], [4, 5], [6, 7]], dtype=tf.int64) out = map_fn(fn=lambda x: x+1, elems, dtype=ragged.RaggedTensorType(type=tf.int64, ragged_rank=0)) # out = tf.ragged.constant([[2, 3, 4], [5, 6], [7, 8]]) ``` """ if dtype is None: dtype = nest.map_structure(lambda e: e.dtype, elems) dtype = nest.map_structure(_ragged_type_to_spec, dtype) return map_fn_lib.map_fn(fn, elems, dtype, parallel_iterations, back_prop, swap_memory, infer_shape, name)
[ "def", "map_fn", "(", "fn", ",", "elems", ",", "dtype", "=", "None", ",", "parallel_iterations", "=", "None", ",", "back_prop", "=", "True", ",", "swap_memory", "=", "False", ",", "infer_shape", "=", "True", ",", "name", "=", "None", ")", ":", "if", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_map_ops.py#L27-L168
memkind/memkind
cbbf843ba63d852914f665064b6bf74cdc07ac54
utils/qemu/main.py
python
QEMU._cpu_options
(self, tpg: TopologyCfg)
return tpg.cpu_options if tpg.cpu_options else '-smp 2'
CPU used by QEMU
CPU used by QEMU
[ "CPU", "used", "by", "QEMU" ]
def _cpu_options(self, tpg: TopologyCfg) -> str: """ CPU used by QEMU """ return tpg.cpu_options if tpg.cpu_options else '-smp 2'
[ "def", "_cpu_options", "(", "self", ",", "tpg", ":", "TopologyCfg", ")", "->", "str", ":", "return", "tpg", ".", "cpu_options", "if", "tpg", ".", "cpu_options", "else", "'-smp 2'" ]
https://github.com/memkind/memkind/blob/cbbf843ba63d852914f665064b6bf74cdc07ac54/utils/qemu/main.py#L292-L296
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Subst.py
python
ListSubber.add_to_current_word
(self, x)
Append the string x to the end of the current last word in the result. If that is not possible, then just add it as a new word. Make sure the entire concatenated string inherits the object attributes of x (in particular, the escape function) by wrapping it as CmdStringHolder.
Append the string x to the end of the current last word in the result. If that is not possible, then just add it as a new word. Make sure the entire concatenated string inherits the object attributes of x (in particular, the escape function) by wrapping it as CmdStringHolder.
[ "Append", "the", "string", "x", "to", "the", "end", "of", "the", "current", "last", "word", "in", "the", "result", ".", "If", "that", "is", "not", "possible", "then", "just", "add", "it", "as", "a", "new", "word", ".", "Make", "sure", "the", "entire"...
def add_to_current_word(self, x): """Append the string x to the end of the current last word in the result. If that is not possible, then just add it as a new word. Make sure the entire concatenated string inherits the object attributes of x (in particular, the escape function) by wrapping it as CmdStringHolder.""" if not self.in_strip or self.mode != SUBST_SIG: try: current_word = self[-1][-1] except IndexError: self.add_new_word(x) else: # All right, this is a hack and it should probably # be refactored out of existence in the future. # The issue is that we want to smoosh words together # and make one file name that gets escaped if # we're expanding something like foo$EXTENSION, # but we don't want to smoosh them together if # it's something like >$TARGET, because then we'll # treat the '>' like it's part of the file name. # So for now, just hard-code looking for the special # command-line redirection characters... try: last_char = str(current_word)[-1] except IndexError: last_char = '\0' if last_char in '<>|': self.add_new_word(x) else: y = current_word + x # We used to treat a word appended to a literal # as a literal itself, but this caused problems # with interpreting quotes around space-separated # targets on command lines. Removing this makes # none of the "substantive" end-to-end tests fail, # so we'll take this out but leave it commented # for now in case there's a problem not covered # by the test cases and we need to resurrect this. #literal1 = self.literal(self[-1][-1]) #literal2 = self.literal(x) y = self.conv(y) if is_String(y): #y = CmdStringHolder(y, literal1 or literal2) y = CmdStringHolder(y, None) self[-1][-1] = y
[ "def", "add_to_current_word", "(", "self", ",", "x", ")", ":", "if", "not", "self", ".", "in_strip", "or", "self", ".", "mode", "!=", "SUBST_SIG", ":", "try", ":", "current_word", "=", "self", "[", "-", "1", "]", "[", "-", "1", "]", "except", "Inde...
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Subst.py#L655-L701
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/utils/encoding.py
python
getdefaultencoding
(prefer_stream=True)
return enc
Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually UTF8 as of Python 3.
Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually UTF8 as of Python 3.
[ "Return", "IPython", "s", "guess", "for", "the", "default", "encoding", "for", "bytes", "as", "text", ".", "If", "prefer_stream", "is", "True", "(", "default", ")", "asks", "for", "stdin", ".", "encoding", "first", "to", "match", "the", "calling", "Termina...
def getdefaultencoding(prefer_stream=True): """Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually UTF8 as of Python 3. """ enc = None if prefer_stream: enc = get_stream_enc(sys.stdin) if not enc or enc=='ascii': try: # There are reports of getpreferredencoding raising errors # in some cases, which may well be fixed, but let's be conservative here. enc = locale.getpreferredencoding() except Exception: pass enc = enc or sys.getdefaultencoding() # On windows `cp0` can be returned to indicate that there is no code page. # Since cp0 is an invalid encoding return instead cp1252 which is the # Western European default. if enc == 'cp0': warnings.warn( "Invalid code page cp0 detected - using cp1252 instead." "If cp1252 is incorrect please ensure a valid code page " "is defined for the process.", RuntimeWarning) return 'cp1252' return enc
[ "def", "getdefaultencoding", "(", "prefer_stream", "=", "True", ")", ":", "enc", "=", "None", "if", "prefer_stream", ":", "enc", "=", "get_stream_enc", "(", "sys", ".", "stdin", ")", "if", "not", "enc", "or", "enc", "==", "'ascii'", ":", "try", ":", "#...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/utils/encoding.py#L38-L69
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py
python
TextDoc.docdata
(self, object, name=None, mod=None, cl=None)
return self._docdescriptor(name, object, mod)
Produce text documentation for a data descriptor.
Produce text documentation for a data descriptor.
[ "Produce", "text", "documentation", "for", "a", "data", "descriptor", "." ]
def docdata(self, object, name=None, mod=None, cl=None): """Produce text documentation for a data descriptor.""" return self._docdescriptor(name, object, mod)
[ "def", "docdata", "(", "self", ",", "object", ",", "name", "=", "None", ",", "mod", "=", "None", ",", "cl", "=", "None", ")", ":", "return", "self", ".", "_docdescriptor", "(", "name", ",", "object", ",", "mod", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/pydoc.py#L1315-L1317
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/logging/__init__.py
python
Filterer.addFilter
(self, filter)
Add the specified filter to this handler.
Add the specified filter to this handler.
[ "Add", "the", "specified", "filter", "to", "this", "handler", "." ]
def addFilter(self, filter): """ Add the specified filter to this handler. """ if not (filter in self.filters): self.filters.append(filter)
[ "def", "addFilter", "(", "self", ",", "filter", ")", ":", "if", "not", "(", "filter", "in", "self", ".", "filters", ")", ":", "self", ".", "filters", ".", "append", "(", "filter", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/logging/__init__.py#L584-L589
LLNL/lbann
26083e6c86050302ce33148aea70f62e61cacb92
python/lbann/models/subgraph/transformer.py
python
TransformerEncoderLayer.forward
(self, x, mask=None)
return z
Apply Transformer encoder layer. Args: x (lbann.Layer): Sequence of input vectors. mask (lbann.Layer, optional): Attention mask. Returns: lbann.Layer: Sequence of output vectors.
Apply Transformer encoder layer.
[ "Apply", "Transformer", "encoder", "layer", "." ]
def forward(self, x, mask=None): """Apply Transformer encoder layer. Args: x (lbann.Layer): Sequence of input vectors. mask (lbann.Layer, optional): Attention mask. Returns: lbann.Layer: Sequence of output vectors. """ self.instance += 1 name = f'{self.name}_instance{self.instance}' # Self-attention with residual connection y = self.attention(x, x, x, mask=mask) if self.dropout_prob > 0: y = lbann.Dropout( y, keep_prob=1-self.dropout_prob, name=f'{name}_drop1', ) z = lbann.Sum(x, y, name=f'{name}_sum1') z = lbann.InstanceNorm(z, name=f'{name}_norm1') x = z # Feedforward network with residual connection y = lbann.ChannelwiseFullyConnected( x, weights=self.fc1_weights, output_channel_dims=[self.feedforward_dim], name=f'{name}_fc1', ) y = lbann.Relu(y, name=f'{name}_relu1') if self.dropout_prob > 0: y = lbann.Dropout( y, keep_prob=1-self.dropout_prob, name=f'{name}_drop2', ) y = lbann.ChannelwiseFullyConnected( y, weights=self.fc2_weights, output_channel_dims=[self.embed_dim], name=f'{name}_fc2', ) if self.dropout_prob > 0: y = lbann.Dropout( y, keep_prob=1-self.dropout_prob, name=f'{name}_drop3', ) z = lbann.Sum(x, y, name=f'{name}_sum2') z = lbann.InstanceNorm(z, name=f'{name}_norm2') return z
[ "def", "forward", "(", "self", ",", "x", ",", "mask", "=", "None", ")", ":", "self", ".", "instance", "+=", "1", "name", "=", "f'{self.name}_instance{self.instance}'", "# Self-attention with residual connection", "y", "=", "self", ".", "attention", "(", "x", "...
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/python/lbann/models/subgraph/transformer.py#L82-L136
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/ndarray.py
python
NDArray.attach_grad
(self, grad_req='write', stype=None)
Attach a gradient buffer to this NDArray, so that `backward` can compute gradient with respect to it. The gradient is initialized to zeros. Parameters ---------- grad_req : {'write', 'add', 'null'} How gradient will be accumulated. - 'write': gradient will be overwritten on every backward. - 'add': gradient will be added to existing value on every backward. - 'null': do not compute gradient for this NDArray. stype : str, optional The storage type of the gradient array. Defaults to the same stype of this NDArray.
Attach a gradient buffer to this NDArray, so that `backward` can compute gradient with respect to it.
[ "Attach", "a", "gradient", "buffer", "to", "this", "NDArray", "so", "that", "backward", "can", "compute", "gradient", "with", "respect", "to", "it", "." ]
def attach_grad(self, grad_req='write', stype=None): """Attach a gradient buffer to this NDArray, so that `backward` can compute gradient with respect to it. The gradient is initialized to zeros. Parameters ---------- grad_req : {'write', 'add', 'null'} How gradient will be accumulated. - 'write': gradient will be overwritten on every backward. - 'add': gradient will be added to existing value on every backward. - 'null': do not compute gradient for this NDArray. stype : str, optional The storage type of the gradient array. Defaults to the same stype of this NDArray. """ from . import zeros as _zeros if stype is not None: grad = _zeros(self.shape, stype=stype, dtype=self.dtype) else: grad = op.zeros_like(self) # pylint: disable=undefined-variable grad_req = _GRAD_REQ_MAP[grad_req] check_call(_LIB.MXAutogradMarkVariables( 1, ctypes.pointer(self.handle), ctypes.pointer(mx_uint(grad_req)), ctypes.pointer(grad.handle)))
[ "def", "attach_grad", "(", "self", ",", "grad_req", "=", "'write'", ",", "stype", "=", "None", ")", ":", "from", ".", "import", "zeros", "as", "_zeros", "if", "stype", "is", "not", "None", ":", "grad", "=", "_zeros", "(", "self", ".", "shape", ",", ...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L2878-L2903
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/decorator/decorator.py
python
FunctionMaker.make
(self, src_templ, evaldict=None, addsource=False, **attrs)
return func
Make a new function from a given template and update the signature
Make a new function from a given template and update the signature
[ "Make", "a", "new", "function", "from", "a", "given", "template", "and", "update", "the", "signature" ]
def make(self, src_templ, evaldict=None, addsource=False, **attrs): "Make a new function from a given template and update the signature" src = src_templ % vars(self) # expand name and signature evaldict = evaldict or {} mo = DEF.search(src) if mo is None: raise SyntaxError('not a valid function template\n%s' % src) name = mo.group(1) # extract the function name names = set([name] + [arg.strip(' *') for arg in self.shortsignature.split(',')]) for n in names: if n in ('_func_', '_call_'): raise NameError('%s is overridden in\n%s' % (n, src)) if not src.endswith('\n'): # add a newline for old Pythons src += '\n' # Ensure each generated function has a unique filename for profilers # (such as cProfile) that depend on the tuple of (<filename>, # <definition line>, <function name>) being unique. filename = '<decorator-gen-%d>' % next(self._compile_count) try: code = compile(src, filename, 'single') exec(code, evaldict) except Exception: print('Error in generated code:', file=sys.stderr) print(src, file=sys.stderr) raise func = evaldict[name] if addsource: attrs['__source__'] = src self.update(func, **attrs) return func
[ "def", "make", "(", "self", ",", "src_templ", ",", "evaldict", "=", "None", ",", "addsource", "=", "False", ",", "*", "*", "attrs", ")", ":", "src", "=", "src_templ", "%", "vars", "(", "self", ")", "# expand name and signature", "evaldict", "=", "evaldic...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/decorator/decorator.py#L162-L194
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/genericpath.py
python
commonprefix
(m)
return s1
Given a list of pathnames, returns the longest common leading component
Given a list of pathnames, returns the longest common leading component
[ "Given", "a", "list", "of", "pathnames", "returns", "the", "longest", "common", "leading", "component" ]
def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' s1 = min(m) s2 = max(m) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1
[ "def", "commonprefix", "(", "m", ")", ":", "if", "not", "m", ":", "return", "''", "s1", "=", "min", "(", "m", ")", "s2", "=", "max", "(", "m", ")", "for", "i", ",", "c", "in", "enumerate", "(", "s1", ")", ":", "if", "c", "!=", "s2", "[", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/genericpath.py#L68-L76
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/keras/python/keras/backend.py
python
is_sparse
(tensor)
return isinstance(tensor, sparse_tensor.SparseTensor)
Returns whether a tensor is a sparse tensor. Arguments: tensor: A tensor instance. Returns: A boolean. Example: ```python >>> from keras import backend as K >>> a = K.placeholder((2, 2), sparse=False) >>> print(K.is_sparse(a)) False >>> b = K.placeholder((2, 2), sparse=True) >>> print(K.is_sparse(b)) True ```
Returns whether a tensor is a sparse tensor.
[ "Returns", "whether", "a", "tensor", "is", "a", "sparse", "tensor", "." ]
def is_sparse(tensor): """Returns whether a tensor is a sparse tensor. Arguments: tensor: A tensor instance. Returns: A boolean. Example: ```python >>> from keras import backend as K >>> a = K.placeholder((2, 2), sparse=False) >>> print(K.is_sparse(a)) False >>> b = K.placeholder((2, 2), sparse=True) >>> print(K.is_sparse(b)) True ``` """ return isinstance(tensor, sparse_tensor.SparseTensor)
[ "def", "is_sparse", "(", "tensor", ")", ":", "return", "isinstance", "(", "tensor", ",", "sparse_tensor", ".", "SparseTensor", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/backend.py#L441-L461
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/__init__.py
python
Process.wait
(self, timeout=None)
return self._proc.wait(timeout)
Wait for process to terminate and, if process is a children of os.getpid(), also return its exit code, else None. On Windows there's no such limitation (exit code is always returned). If the process is already terminated immediately return None instead of raising NoSuchProcess. If *timeout* (in seconds) is specified and process is still alive raise TimeoutExpired. To wait for multiple Process(es) use psutil.wait_procs().
Wait for process to terminate and, if process is a children of os.getpid(), also return its exit code, else None. On Windows there's no such limitation (exit code is always returned).
[ "Wait", "for", "process", "to", "terminate", "and", "if", "process", "is", "a", "children", "of", "os", ".", "getpid", "()", "also", "return", "its", "exit", "code", "else", "None", ".", "On", "Windows", "there", "s", "no", "such", "limitation", "(", "...
def wait(self, timeout=None): """Wait for process to terminate and, if process is a children of os.getpid(), also return its exit code, else None. On Windows there's no such limitation (exit code is always returned). If the process is already terminated immediately return None instead of raising NoSuchProcess. If *timeout* (in seconds) is specified and process is still alive raise TimeoutExpired. To wait for multiple Process(es) use psutil.wait_procs(). """ if timeout is not None and not timeout >= 0: raise ValueError("timeout must be a positive integer") return self._proc.wait(timeout)
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "not", "None", "and", "not", "timeout", ">=", "0", ":", "raise", "ValueError", "(", "\"timeout must be a positive integer\"", ")", "return", "self", ".", "_proc", "."...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/__init__.py#L1259-L1275
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/ValidationKit/common/webutils.py
python
downloadFile
(sUrlFile, sDstFile, sLocalPrefix, fnLog, fnError = None, fNoProxies=True)
return True
Downloads the given file if an URL is given, otherwise assume it's something on the build share and copy it from there. Raises no exceptions, returns log + success indicator instead. Note! This method may use proxies configured on the system and the http_proxy, ftp_proxy, no_proxy environment variables. @todo Fixed build burn here. Please set default value for fNoProxies to appropriate one.
Downloads the given file if an URL is given, otherwise assume it's something on the build share and copy it from there.
[ "Downloads", "the", "given", "file", "if", "an", "URL", "is", "given", "otherwise", "assume", "it", "s", "something", "on", "the", "build", "share", "and", "copy", "it", "from", "there", "." ]
def downloadFile(sUrlFile, sDstFile, sLocalPrefix, fnLog, fnError = None, fNoProxies=True): """ Downloads the given file if an URL is given, otherwise assume it's something on the build share and copy it from there. Raises no exceptions, returns log + success indicator instead. Note! This method may use proxies configured on the system and the http_proxy, ftp_proxy, no_proxy environment variables. @todo Fixed build burn here. Please set default value for fNoProxies to appropriate one. """ if fnError is None: fnError = fnLog; if sUrlFile.startswith('http://') \ or sUrlFile.startswith('https://') \ or sUrlFile.startswith('ftp://'): # Download the file. fnLog('Downloading "%s" to "%s"...' % (sUrlFile, sDstFile)); try: ## @todo We get 404.html content instead of exceptions here, which is confusing and should be addressed. if fNoProxies: oSrc = urllib_urlopen(sUrlFile); else: oSrc = urllib_urlopen(sUrlFile, proxies = dict()); oDst = utils.openNoInherit(sDstFile, 'wb'); oDst.write(oSrc.read()); oDst.close(); oSrc.close(); except Exception as oXcpt: fnError('Error downloading "%s" to "%s": %s' % (sUrlFile, sDstFile, oXcpt)); return False; else: # Assumes file from the build share. sSrcPath = os.path.join(sLocalPrefix, sUrlFile); fnLog('Copying "%s" to "%s"...' % (sSrcPath, sDstFile)); try: utils.copyFileSimple(sSrcPath, sDstFile); except Exception as oXcpt: fnError('Error copying "%s" to "%s": %s' % (sSrcPath, sDstFile, oXcpt)); return False; return True;
[ "def", "downloadFile", "(", "sUrlFile", ",", "sDstFile", ",", "sLocalPrefix", ",", "fnLog", ",", "fnError", "=", "None", ",", "fNoProxies", "=", "True", ")", ":", "if", "fnError", "is", "None", ":", "fnError", "=", "fnLog", "if", "sUrlFile", ".", "starts...
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/ValidationKit/common/webutils.py#L139-L183
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/saved_model/builder_impl.py
python
SavedModelBuilder._tag_and_add_meta_graph
(self, meta_graph_def, tags, signature_def_map)
Tags the meta graph def and adds it to the SavedModel. Tags the meta graph def with the supplied tags, adds signature defs to it if provided and appends the meta graph def to the SavedModel proto. Args: meta_graph_def: The meta graph def to add to the SavedModel. tags: The set of tags to annotate the meta graph def with. signature_def_map: The map of signature defs to be added to the meta graph def.
Tags the meta graph def and adds it to the SavedModel.
[ "Tags", "the", "meta", "graph", "def", "and", "adds", "it", "to", "the", "SavedModel", "." ]
def _tag_and_add_meta_graph(self, meta_graph_def, tags, signature_def_map): """Tags the meta graph def and adds it to the SavedModel. Tags the meta graph def with the supplied tags, adds signature defs to it if provided and appends the meta graph def to the SavedModel proto. Args: meta_graph_def: The meta graph def to add to the SavedModel. tags: The set of tags to annotate the meta graph def with. signature_def_map: The map of signature defs to be added to the meta graph def. """ for tag in tags: meta_graph_def.meta_info_def.tags.append(tag) if signature_def_map is not None: for key in signature_def_map: meta_graph_def.signature_def[key].CopyFrom(signature_def_map[key]) proto_meta_graph_def = self._saved_model.meta_graphs.add() proto_meta_graph_def.CopyFrom(meta_graph_def)
[ "def", "_tag_and_add_meta_graph", "(", "self", ",", "meta_graph_def", ",", "tags", ",", "signature_def_map", ")", ":", "for", "tag", "in", "tags", ":", "meta_graph_def", ".", "meta_info_def", ".", "tags", ".", "append", "(", "tag", ")", "if", "signature_def_ma...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/saved_model/builder_impl.py#L164-L184
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/copy_helper.py
python
Manifest._ParseManifest
(self)
Load and parse a manifest file. This information will be used to skip any files that have a skip or OK status.
Load and parse a manifest file.
[ "Load", "and", "parse", "a", "manifest", "file", "." ]
def _ParseManifest(self): """Load and parse a manifest file. This information will be used to skip any files that have a skip or OK status. """ try: if os.path.exists(self.manifest_path): with open(self.manifest_path, 'rb') as f: first_row = True reader = csv.reader(f) for row in reader: if first_row: try: source_index = row.index('Source') result_index = row.index('Result') except ValueError: # No header and thus not a valid manifest file. raise CommandException( 'Missing headers in manifest file: %s' % self.manifest_path) first_row = False source = row[source_index] result = row[result_index] if result in ['OK', 'skip']: # We're always guaranteed to take the last result of a specific # source url. self.manifest_filter[source] = result except IOError: raise CommandException('Could not parse %s' % self.manifest_path)
[ "def", "_ParseManifest", "(", "self", ")", ":", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "manifest_path", ")", ":", "with", "open", "(", "self", ".", "manifest_path", ",", "'rb'", ")", "as", "f", ":", "first_row", "=", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/copy_helper.py#L2844-L2872
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Executor.py
python
Executor.get_timestamp
(self)
return 0
Fetch a time stamp for this Executor. We don't have one, of course (only files do), but this is the interface used by the timestamp module.
Fetch a time stamp for this Executor. We don't have one, of course (only files do), but this is the interface used by the timestamp module.
[ "Fetch", "a", "time", "stamp", "for", "this", "Executor", ".", "We", "don", "t", "have", "one", "of", "course", "(", "only", "files", "do", ")", "but", "this", "is", "the", "interface", "used", "by", "the", "timestamp", "module", "." ]
def get_timestamp(self): """Fetch a time stamp for this Executor. We don't have one, of course (only files do), but this is the interface used by the timestamp module. """ return 0
[ "def", "get_timestamp", "(", "self", ")", ":", "return", "0" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Executor.py#L472-L477
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/image_processing/screen_finder.py
python
ScreenFinder._FindCorners
(self, intersections, grey_frame)
return real_corners, missing_corners
Finds the screen corners in the image. Given the set of intersections in the image, finds the intersections most likely to be corners. Args: intersections: The array of intersections in the image. grey_frame: The greyscale frame we're processing. Returns: An array of length 4 containing the positions of the corners, or nan for each index where a corner could not be found, and a count of the number of missing corners. The corners are ordered as follows: 1 | 0 ----- 2 | 3 Ex. 3 corners are found from a square of width 2 centered at the origin, the output would look like: '[[1, 1], [np.nan, np.nan], [-1, -1], [1, -1]], 1
Finds the screen corners in the image.
[ "Finds", "the", "screen", "corners", "in", "the", "image", "." ]
def _FindCorners(self, intersections, grey_frame): """Finds the screen corners in the image. Given the set of intersections in the image, finds the intersections most likely to be corners. Args: intersections: The array of intersections in the image. grey_frame: The greyscale frame we're processing. Returns: An array of length 4 containing the positions of the corners, or nan for each index where a corner could not be found, and a count of the number of missing corners. The corners are ordered as follows: 1 | 0 ----- 2 | 3 Ex. 3 corners are found from a square of width 2 centered at the origin, the output would look like: '[[1, 1], [np.nan, np.nan], [-1, -1], [1, -1]], 1'""" filtered = [] corners = np.empty((0, 2), np.float32) for corner_pos, score, point, line1, line2 in \ self._LooksLikeCorner(intersections, grey_frame): if self.DEBUG: center = (int(point[0] + 0.5), int(point[1] + 0.5)) cv2.circle(self._frame_debug, center, 5, (0, 255, 0), 1) point.resize(1, 2) corners = np.append(corners, point, axis=0) point.resize(2,) corner_data = self.CornerData(corner_pos, point, score, line1, line2) filtered.append(corner_data) # De-duplicate corners because we may have found many false positives, or # near-misses. self._DeDupCorners(filtered, corners) # Strip everything but the corner location. filtered_corners = np.array( [corner_data.corner_location for corner_data in filtered]) corner_indices = [corner_data.corner_index for corner_data in filtered] # If we have found a corner to replace a lost corner, we want to check # that the corner is not erroneous by ensuring it makes a rectangle with # the 3 known good corners. if len(filtered) == 4: for i in xrange(4): point_info = (filtered[i].corner_location, filtered[i].line1, filtered[i].line2) if (self._lost_corners[i] and not self._PointConnectsToCorners(filtered_corners, point_info)): filtered_corners = np.delete(filtered_corners, i, 0) corner_indices = np.delete(corner_indices, i, 0) break # Ensure corners are sorted properly, inserting nans for missing corners. sorted_corners = np.empty((4, 2), np.float32) sorted_corners[:] = np.nan for i in xrange(len(filtered_corners)): sorted_corners[corner_indices[i]] = filtered_corners[i] # From this point on, our corners arrays are guaranteed to have 4 # elements, though some may be nan. # Filter corners that have moved too far from the previous corner if we # are not resetting known corner information. reset_corners = ( (self._lost_corner_frames > self.RESET_AFTER_N_BAD_FRAMES) and len(filtered_corners) == 4) if self._prev_corners is not None and not reset_corners: sqdists = cv_util.SqDistances(self._prev_corners, sorted_corners) for i in xrange(4): if np.isnan(sorted_corners[i][0]): continue if sqdists[i] > self.MAX_INTERFRAME_MOTION: sorted_corners[i] = np.nan real_corners = self._FindExactCorners(sorted_corners) missing_corners = np.count_nonzero(np.isnan(real_corners)) / 2 return real_corners, missing_corners
[ "def", "_FindCorners", "(", "self", ",", "intersections", ",", "grey_frame", ")", ":", "filtered", "=", "[", "]", "corners", "=", "np", ".", "empty", "(", "(", "0", ",", "2", ")", ",", "np", ".", "float32", ")", "for", "corner_pos", ",", "score", "...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/image_processing/screen_finder.py#L304-L385
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py
python
Bits._getoct
(self)
return self._readoct(self.len, 0)
Return interpretation as an octal string.
Return interpretation as an octal string.
[ "Return", "interpretation", "as", "an", "octal", "string", "." ]
def _getoct(self): """Return interpretation as an octal string.""" return self._readoct(self.len, 0)
[ "def", "_getoct", "(", "self", ")", ":", "return", "self", ".", "_readoct", "(", "self", ".", "len", ",", "0", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L1891-L1893
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_extended_env.py
python
MinitaurExtendedEnv.reset
(self)
return np.array(super(MinitaurExtendedEnv, self).reset())
Resets the time and history buffer.
Resets the time and history buffer.
[ "Resets", "the", "time", "and", "history", "buffer", "." ]
def reset(self): """Resets the time and history buffer.""" self._counter = 0 self._signal(self._counter) # This sets the current phase self._past_parent_observations = np.zeros((self.MAX_BUFFER_SIZE + 1, self.PARENT_OBSERVATION_DIM)) self._past_motor_angles = np.zeros((self.MAX_BUFFER_SIZE + 1, 8)) self._past_actions = np.zeros((self.MAX_BUFFER_SIZE, self.ACTION_DIM)) self._counter = 0 return np.array(super(MinitaurExtendedEnv, self).reset())
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_counter", "=", "0", "self", ".", "_signal", "(", "self", ".", "_counter", ")", "# This sets the current phase", "self", ".", "_past_parent_observations", "=", "np", ".", "zeros", "(", "(", "self", ".", ...
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_extended_env.py#L135-L145
deepmodeling/deepmd-kit
159e45d248b0429844fb6a8cb3b3a201987c8d79
deepmd/infer/model_devi.py
python
_check_tmaps
(tmaps, ref_tmap=None)
return flag
Check whether type maps are identical
Check whether type maps are identical
[ "Check", "whether", "type", "maps", "are", "identical" ]
def _check_tmaps(tmaps, ref_tmap=None): ''' Check whether type maps are identical ''' assert isinstance(tmaps, list) if ref_tmap is None: ref_tmap = tmaps[0] assert isinstance(ref_tmap, list) flag = True for tmap in tmaps: if tmap != ref_tmap: flag = False break return flag
[ "def", "_check_tmaps", "(", "tmaps", ",", "ref_tmap", "=", "None", ")", ":", "assert", "isinstance", "(", "tmaps", ",", "list", ")", "if", "ref_tmap", "is", "None", ":", "ref_tmap", "=", "tmaps", "[", "0", "]", "assert", "isinstance", "(", "ref_tmap", ...
https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/infer/model_devi.py#L66-L80
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/actor/Actor.py
python
Actor.pingpong
(self, animName, restart=1, partName=None, fromFrame=None, toFrame=None)
pingpong(self, string, int=1, string=None) Loop the given animation on the given part of the actor, restarting at zero frame if requested. If no part name is given then try to loop on all parts. NOTE: loops on all LOD's
pingpong(self, string, int=1, string=None) Loop the given animation on the given part of the actor, restarting at zero frame if requested. If no part name is given then try to loop on all parts. NOTE: loops on all LOD's
[ "pingpong", "(", "self", "string", "int", "=", "1", "string", "=", "None", ")", "Loop", "the", "given", "animation", "on", "the", "given", "part", "of", "the", "actor", "restarting", "at", "zero", "frame", "if", "requested", ".", "If", "no", "part", "n...
def pingpong(self, animName, restart=1, partName=None, fromFrame=None, toFrame=None): """pingpong(self, string, int=1, string=None) Loop the given animation on the given part of the actor, restarting at zero frame if requested. If no part name is given then try to loop on all parts. NOTE: loops on all LOD's""" if fromFrame is None: fromFrame = 0 for control in self.getAnimControls(animName, partName): if toFrame is None: control.pingpong(restart, fromFrame, control.getNumFrames() - 1) else: control.pingpong(restart, fromFrame, toFrame)
[ "def", "pingpong", "(", "self", ",", "animName", ",", "restart", "=", "1", ",", "partName", "=", "None", ",", "fromFrame", "=", "None", ",", "toFrame", "=", "None", ")", ":", "if", "fromFrame", "is", "None", ":", "fromFrame", "=", "0", "for", "contro...
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/actor/Actor.py#L1570-L1584
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextEvent.GetAnnotationsLinesAdded
(*args, **kwargs)
return _stc.StyledTextEvent_GetAnnotationsLinesAdded(*args, **kwargs)
GetAnnotationsLinesAdded(self) -> int
GetAnnotationsLinesAdded(self) -> int
[ "GetAnnotationsLinesAdded", "(", "self", ")", "-", ">", "int" ]
def GetAnnotationsLinesAdded(*args, **kwargs): """GetAnnotationsLinesAdded(self) -> int""" return _stc.StyledTextEvent_GetAnnotationsLinesAdded(*args, **kwargs)
[ "def", "GetAnnotationsLinesAdded", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextEvent_GetAnnotationsLinesAdded", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L7194-L7196
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_presenter.py
python
BasicFittingPresenter.handle_ads_clear_or_remove_workspace_event
(self, _: str = None)
Handle when there is a clear or remove workspace event in the ADS.
Handle when there is a clear or remove workspace event in the ADS.
[ "Handle", "when", "there", "is", "a", "clear", "or", "remove", "workspace", "event", "in", "the", "ADS", "." ]
def handle_ads_clear_or_remove_workspace_event(self, _: str = None) -> None: """Handle when there is a clear or remove workspace event in the ADS.""" self.update_and_reset_all_data() if self.model.number_of_datasets == 0: self.view.disable_view() else: self.enable_editing_notifier.notify_subscribers()
[ "def", "handle_ads_clear_or_remove_workspace_event", "(", "self", ",", "_", ":", "str", "=", "None", ")", "->", "None", ":", "self", ".", "update_and_reset_all_data", "(", ")", "if", "self", ".", "model", ".", "number_of_datasets", "==", "0", ":", "self", "....
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_presenter.py#L95-L102
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/losses/python/losses/loss_ops.py
python
_scale_losses
(losses, weights)
return math_ops.reduce_sum(reduced_losses)
Computes the scaled loss. Args: losses: A `Tensor` of size [batch_size, d1, ... dN]. weights: A `Tensor` of size [1], [batch_size] or [batch_size, d1, ... dN]. The `losses` are reduced (tf.reduce_sum) until its dimension matches that of `weights` at which point the reduced `losses` are element-wise multiplied by `weights` and a final reduce_sum is computed on the result. Conceptually, this operation is equivalent to broadcasting (tiling) `weights` to be the same size as `losses`, performing an element-wise multiplication, and summing the result. Returns: A scalar tf.float32 `Tensor` whose value represents the sum of the scaled `losses`.
Computes the scaled loss.
[ "Computes", "the", "scaled", "loss", "." ]
def _scale_losses(losses, weights): """Computes the scaled loss. Args: losses: A `Tensor` of size [batch_size, d1, ... dN]. weights: A `Tensor` of size [1], [batch_size] or [batch_size, d1, ... dN]. The `losses` are reduced (tf.reduce_sum) until its dimension matches that of `weights` at which point the reduced `losses` are element-wise multiplied by `weights` and a final reduce_sum is computed on the result. Conceptually, this operation is equivalent to broadcasting (tiling) `weights` to be the same size as `losses`, performing an element-wise multiplication, and summing the result. Returns: A scalar tf.float32 `Tensor` whose value represents the sum of the scaled `losses`. """ # First, compute the sum of the losses over all elements: start_index = max(0, weights.get_shape().ndims) reduction_indices = list(range(start_index, losses.get_shape().ndims)) reduced_losses = math_ops.reduce_sum(losses, reduction_indices=reduction_indices) reduced_losses = math_ops.multiply(reduced_losses, weights) return math_ops.reduce_sum(reduced_losses)
[ "def", "_scale_losses", "(", "losses", ",", "weights", ")", ":", "# First, compute the sum of the losses over all elements:", "start_index", "=", "max", "(", "0", ",", "weights", ".", "get_shape", "(", ")", ".", "ndims", ")", "reduction_indices", "=", "list", "(",...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/losses/python/losses/loss_ops.py#L48-L71
devsisters/libquic
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
src/third_party/protobuf/python/google/protobuf/internal/decoder.py
python
_VarintDecoder
(mask, result_type)
return DecodeVarint
Return an encoder for a basic varint value (does not include tag). Decoded values will be bitwise-anded with the given mask before being returned, e.g. to limit them to 32 bits. The returned decoder does not take the usual "end" parameter -- the caller is expected to do bounds checking after the fact (often the caller can defer such checking until later). The decoder returns a (value, new_pos) pair.
Return an encoder for a basic varint value (does not include tag).
[ "Return", "an", "encoder", "for", "a", "basic", "varint", "value", "(", "does", "not", "include", "tag", ")", "." ]
def _VarintDecoder(mask, result_type): """Return an encoder for a basic varint value (does not include tag). Decoded values will be bitwise-anded with the given mask before being returned, e.g. to limit them to 32 bits. The returned decoder does not take the usual "end" parameter -- the caller is expected to do bounds checking after the fact (often the caller can defer such checking until later). The decoder returns a (value, new_pos) pair. """ def DecodeVarint(buffer, pos): result = 0 shift = 0 while 1: b = six.indexbytes(buffer, pos) result |= ((b & 0x7f) << shift) pos += 1 if not (b & 0x80): result &= mask result = result_type(result) return (result, pos) shift += 7 if shift >= 64: raise _DecodeError('Too many bytes when decoding varint.') return DecodeVarint
[ "def", "_VarintDecoder", "(", "mask", ",", "result_type", ")", ":", "def", "DecodeVarint", "(", "buffer", ",", "pos", ")", ":", "result", "=", "0", "shift", "=", "0", "while", "1", ":", "b", "=", "six", ".", "indexbytes", "(", "buffer", ",", "pos", ...
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/internal/decoder.py#L107-L131
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
linked_list/rotate.py
python
LinkedList.insert_head
(self, data)
inserts node at the start of linked list
inserts node at the start of linked list
[ "inserts", "node", "at", "the", "start", "of", "linked", "list" ]
def insert_head(self, data): """ inserts node at the start of linked list """ node = Node(data) node.next = self.head self.head = node
[ "def", "insert_head", "(", "self", ",", "data", ")", ":", "node", "=", "Node", "(", "data", ")", "node", ".", "next", "=", "self", ".", "head", "self", ".", "head", "=", "node" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/linked_list/rotate.py#L20-L24
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/fft/fftpack.py
python
irfft
(a, n=None, axis=-1)
return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftb, _real_fft_cache) / n
Compute the inverse of the n-point DFT for real input. This function computes the inverse of the one-dimensional *n*-point discrete Fourier Transform of real input computed by `rfft`. In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical accuracy. (See Notes below for why ``len(a)`` is necessary here.) The input is expected to be in the form returned by `rfft`, i.e. the real zero-frequency term followed by the complex positive frequency terms in order of increasing frequency. Since the discrete Fourier Transform of real input is Hermite-symmetric, the negative frequency terms are taken to be the complex conjugates of the corresponding positive frequency terms. Parameters ---------- a : array_like The input array. n : int, optional Length of the transformed axis of the output. For `n` output points, ``n//2+1`` input points are necessary. If the input is longer than this, it is cropped. If it is shorter than this, it is padded with zeros. If `n` is not given, it is determined from the length of the input (along the axis specified by `axis`). axis : int, optional Axis over which to compute the inverse FFT. Returns ------- out : ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. The length of the transformed axis is `n`, or, if `n` is not given, ``2*(m-1)`` where `m` is the length of the transformed axis of the input. To get an odd number of output points, `n` must be specified. Raises ------ IndexError If `axis` is larger than the last axis of `a`. See Also -------- numpy.fft : For definition of the DFT and conventions used. rfft : The one-dimensional FFT of real input, of which `irfft` is inverse. fft : The one-dimensional FFT. irfft2 : The inverse of the two-dimensional FFT of real input. irfftn : The inverse of the *n*-dimensional FFT of real input. Notes ----- Returns the real valued `n`-point inverse discrete Fourier transform of `a`, where `a` contains the non-negative frequency terms of a Hermite-symmetric sequence. `n` is the length of the result, not the input. If you specify an `n` such that `a` must be zero-padded or truncated, the extra/removed values will be added/removed at high frequencies. One can thus resample a series to `m` points via Fourier interpolation by: ``a_resamp = irfft(rfft(a), m)``. Examples -------- >>> np.fft.ifft([1, -1j, -1, 1j]) array([ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) >>> np.fft.irfft([1, -1j, -1]) array([ 0., 1., 0., 0.]) Notice how the last term in the input to the ordinary `ifft` is the complex conjugate of the second term, and the output has zero imaginary part everywhere. When calling `irfft`, the negative frequencies are not specified, and the output array is purely real.
Compute the inverse of the n-point DFT for real input.
[ "Compute", "the", "inverse", "of", "the", "n", "-", "point", "DFT", "for", "real", "input", "." ]
def irfft(a, n=None, axis=-1): """ Compute the inverse of the n-point DFT for real input. This function computes the inverse of the one-dimensional *n*-point discrete Fourier Transform of real input computed by `rfft`. In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical accuracy. (See Notes below for why ``len(a)`` is necessary here.) The input is expected to be in the form returned by `rfft`, i.e. the real zero-frequency term followed by the complex positive frequency terms in order of increasing frequency. Since the discrete Fourier Transform of real input is Hermite-symmetric, the negative frequency terms are taken to be the complex conjugates of the corresponding positive frequency terms. Parameters ---------- a : array_like The input array. n : int, optional Length of the transformed axis of the output. For `n` output points, ``n//2+1`` input points are necessary. If the input is longer than this, it is cropped. If it is shorter than this, it is padded with zeros. If `n` is not given, it is determined from the length of the input (along the axis specified by `axis`). axis : int, optional Axis over which to compute the inverse FFT. Returns ------- out : ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. The length of the transformed axis is `n`, or, if `n` is not given, ``2*(m-1)`` where `m` is the length of the transformed axis of the input. To get an odd number of output points, `n` must be specified. Raises ------ IndexError If `axis` is larger than the last axis of `a`. See Also -------- numpy.fft : For definition of the DFT and conventions used. rfft : The one-dimensional FFT of real input, of which `irfft` is inverse. fft : The one-dimensional FFT. irfft2 : The inverse of the two-dimensional FFT of real input. irfftn : The inverse of the *n*-dimensional FFT of real input. Notes ----- Returns the real valued `n`-point inverse discrete Fourier transform of `a`, where `a` contains the non-negative frequency terms of a Hermite-symmetric sequence. `n` is the length of the result, not the input. If you specify an `n` such that `a` must be zero-padded or truncated, the extra/removed values will be added/removed at high frequencies. One can thus resample a series to `m` points via Fourier interpolation by: ``a_resamp = irfft(rfft(a), m)``. Examples -------- >>> np.fft.ifft([1, -1j, -1, 1j]) array([ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) >>> np.fft.irfft([1, -1j, -1]) array([ 0., 1., 0., 0.]) Notice how the last term in the input to the ordinary `ifft` is the complex conjugate of the second term, and the output has zero imaginary part everywhere. When calling `irfft`, the negative frequencies are not specified, and the output array is purely real. """ a = asarray(a).astype(complex) if n is None: n = (shape(a)[axis] - 1) * 2 return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftb, _real_fft_cache) / n
[ "def", "irfft", "(", "a", ",", "n", "=", "None", ",", "axis", "=", "-", "1", ")", ":", "a", "=", "asarray", "(", "a", ")", ".", "astype", "(", "complex", ")", "if", "n", "is", "None", ":", "n", "=", "(", "shape", "(", "a", ")", "[", "axis...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/fft/fftpack.py#L337-L418
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/mixture/gmm.py
python
_GMMBase._fit
(self, X, y=None, do_prediction=False)
return responsibilities
Estimate model parameters with the EM algorithm. A initialization step is performed before entering the expectation-maximization (EM) algorithm. If you want to avoid this step, set the keyword argument init_params to the empty string '' when creating the GMM object. Likewise, if you would like just to do an initialization, set n_iter=0. Parameters ---------- X : array_like, shape (n, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- responsibilities : array, shape (n_samples, n_components) Posterior probabilities of each mixture component for each observation.
Estimate model parameters with the EM algorithm.
[ "Estimate", "model", "parameters", "with", "the", "EM", "algorithm", "." ]
def _fit(self, X, y=None, do_prediction=False): """Estimate model parameters with the EM algorithm. A initialization step is performed before entering the expectation-maximization (EM) algorithm. If you want to avoid this step, set the keyword argument init_params to the empty string '' when creating the GMM object. Likewise, if you would like just to do an initialization, set n_iter=0. Parameters ---------- X : array_like, shape (n, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- responsibilities : array, shape (n_samples, n_components) Posterior probabilities of each mixture component for each observation. """ # initialization step X = check_array(X, dtype=np.float64, ensure_min_samples=2, estimator=self) if X.shape[0] < self.n_components: raise ValueError( 'GMM estimation with %s components, but got only %s samples' % (self.n_components, X.shape[0])) max_log_prob = -np.infty if self.verbose > 0: print('Expectation-maximization algorithm started.') for init in range(self.n_init): if self.verbose > 0: print('Initialization ' + str(init + 1)) start_init_time = time() if 'm' in self.init_params or not hasattr(self, 'means_'): self.means_ = cluster.KMeans( n_clusters=self.n_components, random_state=self.random_state).fit(X).cluster_centers_ if self.verbose > 1: print('\tMeans have been initialized.') if 'w' in self.init_params or not hasattr(self, 'weights_'): self.weights_ = np.tile(1.0 / self.n_components, self.n_components) if self.verbose > 1: print('\tWeights have been initialized.') if 'c' in self.init_params or not hasattr(self, 'covars_'): cv = np.cov(X.T) + self.min_covar * np.eye(X.shape[1]) if not cv.shape: cv.shape = (1, 1) self.covars_ = \ distribute_covar_matrix_to_match_covariance_type( cv, self.covariance_type, self.n_components) if self.verbose > 1: print('\tCovariance matrices have been initialized.') # EM algorithms current_log_likelihood = None # reset self.converged_ to False self.converged_ = False for i in range(self.n_iter): if self.verbose > 0: print('\tEM iteration ' + str(i + 1)) start_iter_time = time() prev_log_likelihood = current_log_likelihood # Expectation step log_likelihoods, responsibilities = self.score_samples(X) current_log_likelihood = log_likelihoods.mean() # Check for convergence. if prev_log_likelihood is not None: change = abs(current_log_likelihood - prev_log_likelihood) if self.verbose > 1: print('\t\tChange: ' + str(change)) if change < self.tol: self.converged_ = True if self.verbose > 0: print('\t\tEM algorithm converged.') break # Maximization step self._do_mstep(X, responsibilities, self.params, self.min_covar) if self.verbose > 1: print('\t\tEM iteration ' + str(i + 1) + ' took {0:.5f}s'.format( time() - start_iter_time)) # if the results are better, keep it if self.n_iter: if current_log_likelihood > max_log_prob: max_log_prob = current_log_likelihood best_params = {'weights': self.weights_, 'means': self.means_, 'covars': self.covars_} if self.verbose > 1: print('\tBetter parameters were found.') if self.verbose > 1: print('\tInitialization ' + str(init + 1) + ' took {0:.5f}s'.format( time() - start_init_time)) # check the existence of an init param that was not subject to # likelihood computation issue. if np.isneginf(max_log_prob) and self.n_iter: raise RuntimeError( "EM algorithm was never able to compute a valid likelihood " + "given initial parameters. Try different init parameters " + "(or increasing n_init) or check for degenerate data.") if self.n_iter: self.covars_ = best_params['covars'] self.means_ = best_params['means'] self.weights_ = best_params['weights'] else: # self.n_iter == 0 occurs when using GMM within HMM # Need to make sure that there are responsibilities to output # Output zeros because it was just a quick initialization responsibilities = np.zeros((X.shape[0], self.n_components)) return responsibilities
[ "def", "_fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "do_prediction", "=", "False", ")", ":", "# initialization step", "X", "=", "check_array", "(", "X", ",", "dtype", "=", "np", ".", "float64", ",", "ensure_min_samples", "=", "2", ",", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/mixture/gmm.py#L450-L576
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/preprocessing/imputation.py
python
Imputer.fit
(self, X, y=None)
return self
Fit the imputer on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Input data, where ``n_samples`` is the number of samples and ``n_features`` is the number of features. Returns ------- self : object Returns self.
Fit the imputer on X.
[ "Fit", "the", "imputer", "on", "X", "." ]
def fit(self, X, y=None): """Fit the imputer on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Input data, where ``n_samples`` is the number of samples and ``n_features`` is the number of features. Returns ------- self : object Returns self. """ # Check parameters allowed_strategies = ["mean", "median", "most_frequent"] if self.strategy not in allowed_strategies: raise ValueError("Can only use these strategies: {0} " " got strategy={1}".format(allowed_strategies, self.strategy)) if self.axis not in [0, 1]: raise ValueError("Can only impute missing values on axis 0 and 1, " " got axis={0}".format(self.axis)) # Since two different arrays can be provided in fit(X) and # transform(X), the imputation data will be computed in transform() # when the imputation is done per sample (i.e., when axis=1). if self.axis == 0: X = check_array(X, accept_sparse='csc', dtype=np.float64, force_all_finite=False) if sparse.issparse(X): self.statistics_ = self._sparse_fit(X, self.strategy, self.missing_values, self.axis) else: self.statistics_ = self._dense_fit(X, self.strategy, self.missing_values, self.axis) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "# Check parameters", "allowed_strategies", "=", "[", "\"mean\"", ",", "\"median\"", ",", "\"most_frequent\"", "]", "if", "self", ".", "strategy", "not", "in", "allowed_strategies", ":", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/preprocessing/imputation.py#L126-L169
Manu343726/siplasplas
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
reference/cindex.py
python
Type.argument_types
(self)
return ArgumentsIterator(self)
Retrieve a container for the non-variadic arguments for this type. The returned object is iterable and indexable. Each item in the container is a Type instance.
Retrieve a container for the non-variadic arguments for this type.
[ "Retrieve", "a", "container", "for", "the", "non", "-", "variadic", "arguments", "for", "this", "type", "." ]
def argument_types(self): """Retrieve a container for the non-variadic arguments for this type. The returned object is iterable and indexable. Each item in the container is a Type instance. """ class ArgumentsIterator(collections.Sequence): def __init__(self, parent): self.parent = parent self.length = None def __len__(self): if self.length is None: self.length = conf.lib.clang_getNumArgTypes(self.parent) return self.length def __getitem__(self, key): # FIXME Support slice objects. if not isinstance(key, int): raise TypeError("Must supply a non-negative int.") if key < 0: raise IndexError("Only non-negative indexes are accepted.") if key >= len(self): raise IndexError("Index greater than container length: " "%d > %d" % ( key, len(self) )) result = conf.lib.clang_getArgType(self.parent, key) if result.kind == TypeKind.INVALID: raise IndexError("Argument could not be retrieved.") return result assert self.kind == TypeKind.FUNCTIONPROTO return ArgumentsIterator(self)
[ "def", "argument_types", "(", "self", ")", ":", "class", "ArgumentsIterator", "(", "collections", ".", "Sequence", ")", ":", "def", "__init__", "(", "self", ",", "parent", ")", ":", "self", ".", "parent", "=", "parent", "self", ".", "length", "=", "None"...
https://github.com/Manu343726/siplasplas/blob/9fae7559f87087cf8ef34f04bd1e774b84b2ea9c/reference/cindex.py#L1762-L1798
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/debugger_r.py
python
wrap_info
(info)
replace info[2], a traceback instance, by its ID
replace info[2], a traceback instance, by its ID
[ "replace", "info", "[", "2", "]", "a", "traceback", "instance", "by", "its", "ID" ]
def wrap_info(info): "replace info[2], a traceback instance, by its ID" if info is None: return None else: traceback = info[2] assert isinstance(traceback, types.TracebackType) traceback_id = id(traceback) tracebacktable[traceback_id] = traceback modified_info = (info[0], info[1], traceback_id) return modified_info
[ "def", "wrap_info", "(", "info", ")", ":", "if", "info", "is", "None", ":", "return", "None", "else", ":", "traceback", "=", "info", "[", "2", "]", "assert", "isinstance", "(", "traceback", ",", "types", ".", "TracebackType", ")", "traceback_id", "=", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/debugger_r.py#L45-L55