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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/__init__.py | python | TransformSpec.get_transforms | (self) | return [] | Transforms required by this class. Override in subclasses. | Transforms required by this class. Override in subclasses. | [
"Transforms",
"required",
"by",
"this",
"class",
".",
"Override",
"in",
"subclasses",
"."
] | def get_transforms(self):
"""Transforms required by this class. Override in subclasses."""
if self.default_transforms != ():
import warnings
warnings.warn('default_transforms attribute deprecated.\n'
'Use get_transforms() method instead.',
DeprecationWarning)
return list(self.default_transforms)
return [] | [
"def",
"get_transforms",
"(",
"self",
")",
":",
"if",
"self",
".",
"default_transforms",
"!=",
"(",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"'default_transforms attribute deprecated.\\n'",
"'Use get_transforms() method instead.'",
",",
"Deprecation... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/__init__.py#L206-L214 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/_abcoll.py | python | MutableSequence.pop | (self, index=-1) | return v | S.pop([index]) -> item -- remove and return item at index (default last).
Raise IndexError if list is empty or index is out of range. | S.pop([index]) -> item -- remove and return item at index (default last).
Raise IndexError if list is empty or index is out of range. | [
"S",
".",
"pop",
"(",
"[",
"index",
"]",
")",
"-",
">",
"item",
"--",
"remove",
"and",
"return",
"item",
"at",
"index",
"(",
"default",
"last",
")",
".",
"Raise",
"IndexError",
"if",
"list",
"is",
"empty",
"or",
"index",
"is",
"out",
"of",
"range",... | def pop(self, index=-1):
'''S.pop([index]) -> item -- remove and return item at index (default last).
Raise IndexError if list is empty or index is out of range.
'''
v = self[index]
del self[index]
return v | [
"def",
"pop",
"(",
"self",
",",
"index",
"=",
"-",
"1",
")",
":",
"v",
"=",
"self",
"[",
"index",
"]",
"del",
"self",
"[",
"index",
"]",
"return",
"v"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/_abcoll.py#L653-L659 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | FontFromNativeInfoString | (*args, **kwargs) | return val | FontFromNativeInfoString(String info) -> Font
Construct a `wx.Font` from the string representation of a
`wx.NativeFontInfo` object. | FontFromNativeInfoString(String info) -> Font | [
"FontFromNativeInfoString",
"(",
"String",
"info",
")",
"-",
">",
"Font"
] | def FontFromNativeInfoString(*args, **kwargs):
"""
FontFromNativeInfoString(String info) -> Font
Construct a `wx.Font` from the string representation of a
`wx.NativeFontInfo` object.
"""
if kwargs.has_key('faceName'): kwargs['face'] = kwargs['faceName'];del kwargs['faceName']
val = _gdi_.new_FontFromNativeInfoString(*args, **kwargs)
return val | [
"def",
"FontFromNativeInfoString",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"has_key",
"(",
"'faceName'",
")",
":",
"kwargs",
"[",
"'face'",
"]",
"=",
"kwargs",
"[",
"'faceName'",
"]",
"del",
"kwargs",
"[",
"'faceName'",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L2545-L2554 | |
cmu-db/bustub | fe1b9e984bd2967997b52df872c873d80f71cf7d | build_support/cpplint.py | python | _CppLintState.BackupFilters | (self) | Saves the current filter list to backup storage. | Saves the current filter list to backup storage. | [
"Saves",
"the",
"current",
"filter",
"list",
"to",
"backup",
"storage",
"."
] | def BackupFilters(self):
""" Saves the current filter list to backup storage."""
self._filters_backup = self.filters[:] | [
"def",
"BackupFilters",
"(",
"self",
")",
":",
"self",
".",
"_filters_backup",
"=",
"self",
".",
"filters",
"[",
":",
"]"
] | https://github.com/cmu-db/bustub/blob/fe1b9e984bd2967997b52df872c873d80f71cf7d/build_support/cpplint.py#L1079-L1081 | ||
eProsima/Fast-DDS | 6639a84b7855e8fda66a4afb541326ef22f8c727 | tools/fastdds/shm/clean.py | python | Clean.__remove_file | (self, file) | Delete a file.
Always return void, even if the function fails.
param file str:
The complete file_path | Delete a file. | [
"Delete",
"a",
"file",
"."
] | def __remove_file(self, file):
"""
Delete a file.
Always return void, even if the function fails.
param file str:
The complete file_path
"""
try:
os.remove(file)
except BaseException:
pass | [
"def",
"__remove_file",
"(",
"self",
",",
"file",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"file",
")",
"except",
"BaseException",
":",
"pass"
] | https://github.com/eProsima/Fast-DDS/blob/6639a84b7855e8fda66a4afb541326ef22f8c727/tools/fastdds/shm/clean.py#L169-L182 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/models/rnn/translate/data_utils.py | python | gunzip_file | (gz_path, new_path) | Unzips from gz_path into new_path. | Unzips from gz_path into new_path. | [
"Unzips",
"from",
"gz_path",
"into",
"new_path",
"."
] | def gunzip_file(gz_path, new_path):
"""Unzips from gz_path into new_path."""
print("Unpacking %s to %s" % (gz_path, new_path))
with gzip.open(gz_path, "rb") as gz_file:
with open(new_path, "wb") as new_file:
for line in gz_file:
new_file.write(line) | [
"def",
"gunzip_file",
"(",
"gz_path",
",",
"new_path",
")",
":",
"print",
"(",
"\"Unpacking %s to %s\"",
"%",
"(",
"gz_path",
",",
"new_path",
")",
")",
"with",
"gzip",
".",
"open",
"(",
"gz_path",
",",
"\"rb\"",
")",
"as",
"gz_file",
":",
"with",
"open"... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/models/rnn/translate/data_utils.py#L65-L71 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | PRESUBMIT.py | python | _CheckIncludeOrderForScope | (scope, input_api, file_path, changed_linenums) | return warnings | Checks that the lines in scope occur in the right order.
1. C system files in alphabetical order
2. C++ system files in alphabetical order
3. Project's .h files | Checks that the lines in scope occur in the right order. | [
"Checks",
"that",
"the",
"lines",
"in",
"scope",
"occur",
"in",
"the",
"right",
"order",
"."
] | def _CheckIncludeOrderForScope(scope, input_api, file_path, changed_linenums):
"""Checks that the lines in scope occur in the right order.
1. C system files in alphabetical order
2. C++ system files in alphabetical order
3. Project's .h files
"""
c_system_include_pattern = input_api.re.compile(r'\s*#include <.*\.h>')
cpp_system_include_pattern = input_api.re.compile(r'\s*#include <.*>')
custom_include_pattern = input_api.re.compile(r'\s*#include ".*')
C_SYSTEM_INCLUDES, CPP_SYSTEM_INCLUDES, CUSTOM_INCLUDES = range(3)
state = C_SYSTEM_INCLUDES
previous_line = ''
previous_line_num = 0
problem_linenums = []
for line_num, line in scope:
if c_system_include_pattern.match(line):
if state != C_SYSTEM_INCLUDES:
problem_linenums.append((line_num, previous_line_num))
elif previous_line and previous_line > line:
problem_linenums.append((line_num, previous_line_num))
elif cpp_system_include_pattern.match(line):
if state == C_SYSTEM_INCLUDES:
state = CPP_SYSTEM_INCLUDES
elif state == CUSTOM_INCLUDES:
problem_linenums.append((line_num, previous_line_num))
elif previous_line and previous_line > line:
problem_linenums.append((line_num, previous_line_num))
elif custom_include_pattern.match(line):
if state != CUSTOM_INCLUDES:
state = CUSTOM_INCLUDES
elif previous_line and previous_line > line:
problem_linenums.append((line_num, previous_line_num))
else:
problem_linenums.append(line_num)
previous_line = line
previous_line_num = line_num
warnings = []
for (line_num, previous_line_num) in problem_linenums:
if line_num in changed_linenums or previous_line_num in changed_linenums:
warnings.append(' %s:%d' % (file_path, line_num))
return warnings | [
"def",
"_CheckIncludeOrderForScope",
"(",
"scope",
",",
"input_api",
",",
"file_path",
",",
"changed_linenums",
")",
":",
"c_system_include_pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'\\s*#include <.*\\.h>'",
")",
"cpp_system_include_pattern",
"=",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/PRESUBMIT.py#L562-L608 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/quickcpplint.py | python | lint_all | (file_names: List[str]) | Lint files command entry point based on working tree. | Lint files command entry point based on working tree. | [
"Lint",
"files",
"command",
"entry",
"point",
"based",
"on",
"working",
"tree",
"."
] | def lint_all(file_names: List[str]) -> None:
# pylint: disable=unused-argument
"""Lint files command entry point based on working tree."""
all_file_names = git.get_files_to_check_working_tree(is_interesting_file)
_lint_files(all_file_names) | [
"def",
"lint_all",
"(",
"file_names",
":",
"List",
"[",
"str",
"]",
")",
"->",
"None",
":",
"# pylint: disable=unused-argument",
"all_file_names",
"=",
"git",
".",
"get_files_to_check_working_tree",
"(",
"is_interesting_file",
")",
"_lint_files",
"(",
"all_file_names"... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/quickcpplint.py#L57-L62 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pdb.py | python | Pdb.do_commands | (self, arg) | Defines a list of commands associated to a breakpoint.
Those commands will be executed whenever the breakpoint causes
the program to stop execution. | Defines a list of commands associated to a breakpoint. | [
"Defines",
"a",
"list",
"of",
"commands",
"associated",
"to",
"a",
"breakpoint",
"."
] | def do_commands(self, arg):
"""Defines a list of commands associated to a breakpoint.
Those commands will be executed whenever the breakpoint causes
the program to stop execution."""
if not arg:
bnum = len(bdb.Breakpoint.bpbynumber)-1
else:
try:
bnum = int(arg)
except:
print >>self.stdout, "Usage : commands [bnum]\n ..." \
"\n end"
return
self.commands_bnum = bnum
self.commands[bnum] = []
self.commands_doprompt[bnum] = True
self.commands_silent[bnum] = False
prompt_back = self.prompt
self.prompt = '(com) '
self.commands_defining = True
try:
self.cmdloop()
finally:
self.commands_defining = False
self.prompt = prompt_back | [
"def",
"do_commands",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"arg",
":",
"bnum",
"=",
"len",
"(",
"bdb",
".",
"Breakpoint",
".",
"bpbynumber",
")",
"-",
"1",
"else",
":",
"try",
":",
"bnum",
"=",
"int",
"(",
"arg",
")",
"except",
":",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pdb.py#L317-L342 | ||
etotheipi/BitcoinArmory | 2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98 | armoryengine/CoinSelection.py | python | calcMinSuggestedFeesHackMS | (selectCoinsResult, targetOutVal, preSelectedFee,
numRecipients) | return suggestedFee | This is a hack, because the calcMinSuggestedFees below assumes standard
P2PKH inputs and outputs, not allowing us a way to modify it if we ne know
that the inputs will be much larger, or the outputs.
we just copy the original method with an update to the computation | This is a hack, because the calcMinSuggestedFees below assumes standard
P2PKH inputs and outputs, not allowing us a way to modify it if we ne know
that the inputs will be much larger, or the outputs. | [
"This",
"is",
"a",
"hack",
"because",
"the",
"calcMinSuggestedFees",
"below",
"assumes",
"standard",
"P2PKH",
"inputs",
"and",
"outputs",
"not",
"allowing",
"us",
"a",
"way",
"to",
"modify",
"it",
"if",
"we",
"ne",
"know",
"that",
"the",
"inputs",
"will",
... | def calcMinSuggestedFeesHackMS(selectCoinsResult, targetOutVal, preSelectedFee,
numRecipients):
"""
This is a hack, because the calcMinSuggestedFees below assumes standard
P2PKH inputs and outputs, not allowing us a way to modify it if we ne know
that the inputs will be much larger, or the outputs.
we just copy the original method with an update to the computation
"""
numBytes = 0
msInfo = [getMultisigScriptInfo(utxo.getScript()) for utxo in selectCoinsResult]
for m,n,As,Ps in msInfo:
numBytes += m*70 + 40
numBytes += 200*numRecipients # assume large lockbox outputs
numKb = int(numBytes / 1000)
suggestedFee = (1+numKb)*estimateFee()
if numKb>10:
return suggestedFee
# Compute raw priority of tx
prioritySum = 0
for utxo in selectCoinsResult:
prioritySum += utxo.getValue() * utxo.getNumConfirm()
prioritySum = prioritySum / numBytes
if(prioritySum >= estimatePriority() and numBytes < 10000):
return 0
return suggestedFee | [
"def",
"calcMinSuggestedFeesHackMS",
"(",
"selectCoinsResult",
",",
"targetOutVal",
",",
"preSelectedFee",
",",
"numRecipients",
")",
":",
"numBytes",
"=",
"0",
"msInfo",
"=",
"[",
"getMultisigScriptInfo",
"(",
"utxo",
".",
"getScript",
"(",
")",
")",
"for",
"ut... | https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/CoinSelection.py#L762-L792 | |
OpenGenus/quark | 225ad96efdfcc66cb6584a756c17eb3871e6eb62 | code/code/data_structures/src/list/circular_linked_list/operations/has_loop.py | python | LinkedList.add | (self, data) | return new | add new node to head of list | add new node to head of list | [
"add",
"new",
"node",
"to",
"head",
"of",
"list"
] | def add(self, data):
"""add new node to head of list"""
new = LinkedList.Node(data, self.head)
self.head = new
return new | [
"def",
"add",
"(",
"self",
",",
"data",
")",
":",
"new",
"=",
"LinkedList",
".",
"Node",
"(",
"data",
",",
"self",
".",
"head",
")",
"self",
".",
"head",
"=",
"new",
"return",
"new"
] | https://github.com/OpenGenus/quark/blob/225ad96efdfcc66cb6584a756c17eb3871e6eb62/code/code/data_structures/src/list/circular_linked_list/operations/has_loop.py#L35-L39 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/main.py | python | StdoutRefactoringTool.__init__ | (self, fixers, options, explicit, nobackups, show_diffs,
input_base_dir='', output_dir='', append_suffix='') | Args:
fixers: A list of fixers to import.
options: A dict with RefactoringTool configuration.
explicit: A list of fixers to run even if they are explicit.
nobackups: If true no backup '.bak' files will be created for those
files that are being refactored.
show_diffs: Should diffs of the refactoring be printed to stdout?
input_base_dir: The base directory for all input files. This class
will strip this path prefix off of filenames before substituting
it with output_dir. Only meaningful if output_dir is supplied.
All files processed by refactor() must start with this path.
output_dir: If supplied, all converted files will be written into
this directory tree instead of input_base_dir.
append_suffix: If supplied, all files output by this tool will have
this appended to their filename. Useful for changing .py to
.py3 for example by passing append_suffix='3'. | Args:
fixers: A list of fixers to import.
options: A dict with RefactoringTool configuration.
explicit: A list of fixers to run even if they are explicit.
nobackups: If true no backup '.bak' files will be created for those
files that are being refactored.
show_diffs: Should diffs of the refactoring be printed to stdout?
input_base_dir: The base directory for all input files. This class
will strip this path prefix off of filenames before substituting
it with output_dir. Only meaningful if output_dir is supplied.
All files processed by refactor() must start with this path.
output_dir: If supplied, all converted files will be written into
this directory tree instead of input_base_dir.
append_suffix: If supplied, all files output by this tool will have
this appended to their filename. Useful for changing .py to
.py3 for example by passing append_suffix='3'. | [
"Args",
":",
"fixers",
":",
"A",
"list",
"of",
"fixers",
"to",
"import",
".",
"options",
":",
"A",
"dict",
"with",
"RefactoringTool",
"configuration",
".",
"explicit",
":",
"A",
"list",
"of",
"fixers",
"to",
"run",
"even",
"if",
"they",
"are",
"explicit"... | def __init__(self, fixers, options, explicit, nobackups, show_diffs,
input_base_dir='', output_dir='', append_suffix=''):
"""
Args:
fixers: A list of fixers to import.
options: A dict with RefactoringTool configuration.
explicit: A list of fixers to run even if they are explicit.
nobackups: If true no backup '.bak' files will be created for those
files that are being refactored.
show_diffs: Should diffs of the refactoring be printed to stdout?
input_base_dir: The base directory for all input files. This class
will strip this path prefix off of filenames before substituting
it with output_dir. Only meaningful if output_dir is supplied.
All files processed by refactor() must start with this path.
output_dir: If supplied, all converted files will be written into
this directory tree instead of input_base_dir.
append_suffix: If supplied, all files output by this tool will have
this appended to their filename. Useful for changing .py to
.py3 for example by passing append_suffix='3'.
"""
self.nobackups = nobackups
self.show_diffs = show_diffs
if input_base_dir and not input_base_dir.endswith(os.sep):
input_base_dir += os.sep
self._input_base_dir = input_base_dir
self._output_dir = output_dir
self._append_suffix = append_suffix
super(StdoutRefactoringTool, self).__init__(fixers, options, explicit) | [
"def",
"__init__",
"(",
"self",
",",
"fixers",
",",
"options",
",",
"explicit",
",",
"nobackups",
",",
"show_diffs",
",",
"input_base_dir",
"=",
"''",
",",
"output_dir",
"=",
"''",
",",
"append_suffix",
"=",
"''",
")",
":",
"self",
".",
"nobackups",
"=",... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/main.py#L36-L63 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/codecs.py | python | IncrementalEncoder.getstate | (self) | return 0 | Return the current state of the encoder. | Return the current state of the encoder. | [
"Return",
"the",
"current",
"state",
"of",
"the",
"encoder",
"."
] | def getstate(self):
"""
Return the current state of the encoder.
"""
return 0 | [
"def",
"getstate",
"(",
"self",
")",
":",
"return",
"0"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/codecs.py#L184-L188 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/engine/datasets.py | python | TransferDataset.send | (self, num_epochs=-1) | Send to device | Send to device | [
"Send",
"to",
"device"
] | def send(self, num_epochs=-1):
"""
Send to device
"""
if Dataset._noop_mode():
return
if self._to_device is not None:
del self._to_device
self._to_device = _ToDevice(self, num_epochs)
self._to_device.send() | [
"def",
"send",
"(",
"self",
",",
"num_epochs",
"=",
"-",
"1",
")",
":",
"if",
"Dataset",
".",
"_noop_mode",
"(",
")",
":",
"return",
"if",
"self",
".",
"_to_device",
"is",
"not",
"None",
":",
"del",
"self",
".",
"_to_device",
"self",
".",
"_to_device... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/datasets.py#L3352-L3361 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/stats/morestats.py | python | _parse_dist_kw | (dist, enforce_subclass=True) | return dist | Parse `dist` keyword.
Parameters
----------
dist : str or stats.distributions instance.
Several functions take `dist` as a keyword, hence this utility
function.
enforce_subclass : bool, optional
If True (default), `dist` needs to be a
`_distn_infrastructure.rv_generic` instance.
It can sometimes be useful to set this keyword to False, if a function
wants to accept objects that just look somewhat like such an instance
(for example, they have a ``ppf`` method). | Parse `dist` keyword. | [
"Parse",
"dist",
"keyword",
"."
] | def _parse_dist_kw(dist, enforce_subclass=True):
"""Parse `dist` keyword.
Parameters
----------
dist : str or stats.distributions instance.
Several functions take `dist` as a keyword, hence this utility
function.
enforce_subclass : bool, optional
If True (default), `dist` needs to be a
`_distn_infrastructure.rv_generic` instance.
It can sometimes be useful to set this keyword to False, if a function
wants to accept objects that just look somewhat like such an instance
(for example, they have a ``ppf`` method).
"""
if isinstance(dist, rv_generic):
pass
elif isinstance(dist, string_types):
try:
dist = getattr(distributions, dist)
except AttributeError:
raise ValueError("%s is not a valid distribution name" % dist)
elif enforce_subclass:
msg = ("`dist` should be a stats.distributions instance or a string "
"with the name of such a distribution.")
raise ValueError(msg)
return dist | [
"def",
"_parse_dist_kw",
"(",
"dist",
",",
"enforce_subclass",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"dist",
",",
"rv_generic",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"dist",
",",
"string_types",
")",
":",
"try",
":",
"dist",
"=",
"getatt... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/morestats.py#L424-L452 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/buttonpanel.py | python | Control.__init__ | (self, parent, size=wx.Size(-1, -1), id=wx.ID_ANY) | Default class constructor.
:param Window `parent`: the control parent object. Must not be ``None``;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:type `size`: tuple or :class:`Size`
:param integer `id`: window identifier. A value of -1 indicates a default value. | Default class constructor.
:param Window `parent`: the control parent object. Must not be ``None``;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:type `size`: tuple or :class:`Size`
:param integer `id`: window identifier. A value of -1 indicates a default value. | [
"Default",
"class",
"constructor",
".",
":",
"param",
"Window",
"parent",
":",
"the",
"control",
"parent",
"object",
".",
"Must",
"not",
"be",
"None",
";",
":",
"param",
"size",
":",
"the",
"control",
"size",
".",
"A",
"value",
"of",
"(",
"-",
"1",
"... | def __init__(self, parent, size=wx.Size(-1, -1), id=wx.ID_ANY):
"""
Default class constructor.
:param Window `parent`: the control parent object. Must not be ``None``;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:type `size`: tuple or :class:`Size`
:param integer `id`: window identifier. A value of -1 indicates a default value.
"""
wx.EvtHandler.__init__(self)
self._parent = parent
if id == wx.ID_ANY:
self._id = wx.NewId()
else:
self._id = id
self._size = size
self._isshown = True
self._focus = False | [
"def",
"__init__",
"(",
"self",
",",
"parent",
",",
"size",
"=",
"wx",
".",
"Size",
"(",
"-",
"1",
",",
"-",
"1",
")",
",",
"id",
"=",
"wx",
".",
"ID_ANY",
")",
":",
"wx",
".",
"EvtHandler",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"_p... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/buttonpanel.py#L839-L861 | ||
francinexue/xuefu | b6ff79747a42e020588c0c0a921048e08fe4680c | cnx/tickfeed.py | python | BaseBarFeed.getNextBars | (self) | Override to return the next :class:`pyalgotrade.bar.Bars` in the feed or None if there are no bars.
.. note::
This is for BaseBarFeed subclasses and it should not be called directly. | Override to return the next :class:`pyalgotrade.bar.Bars` in the feed or None if there are no bars. | [
"Override",
"to",
"return",
"the",
"next",
":",
"class",
":",
"pyalgotrade",
".",
"bar",
".",
"Bars",
"in",
"the",
"feed",
"or",
"None",
"if",
"there",
"are",
"no",
"bars",
"."
] | def getNextBars(self):
"""Override to return the next :class:`pyalgotrade.bar.Bars` in the feed or None if there are no bars.
.. note::
This is for BaseBarFeed subclasses and it should not be called directly.
"""
raise NotImplementedError() | [
"def",
"getNextBars",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/cnx/tickfeed.py#L84-L90 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/lexers.py | python | PygmentsLexer.lex_document | (self, cli, document) | return get_line | Create a lexer function that takes a line number and returns the list
of (Token, text) tuples as the Pygments lexer returns for that line. | Create a lexer function that takes a line number and returns the list
of (Token, text) tuples as the Pygments lexer returns for that line. | [
"Create",
"a",
"lexer",
"function",
"that",
"takes",
"a",
"line",
"number",
"and",
"returns",
"the",
"list",
"of",
"(",
"Token",
"text",
")",
"tuples",
"as",
"the",
"Pygments",
"lexer",
"returns",
"for",
"that",
"line",
"."
] | def lex_document(self, cli, document):
"""
Create a lexer function that takes a line number and returns the list
of (Token, text) tuples as the Pygments lexer returns for that line.
"""
# Cache of already lexed lines.
cache = {}
# Pygments generators that are currently lexing.
line_generators = {} # Map lexer generator to the line number.
def get_syntax_sync():
" The Syntax synchronisation objcet that we currently use. "
if self.sync_from_start(cli):
return SyncFromStart()
else:
return self.syntax_sync
def find_closest_generator(i):
" Return a generator close to line 'i', or None if none was fonud. "
for generator, lineno in line_generators.items():
if lineno < i and i - lineno < self.REUSE_GENERATOR_MAX_DISTANCE:
return generator
def create_line_generator(start_lineno, column=0):
"""
Create a generator that yields the lexed lines.
Each iteration it yields a (line_number, [(token, text), ...]) tuple.
"""
def get_tokens():
text = '\n'.join(document.lines[start_lineno:])[column:]
# We call `get_tokens_unprocessed`, because `get_tokens` will
# still replace \r\n and \r by \n. (We don't want that,
# Pygments should return exactly the same amount of text, as we
# have given as input.)
for _, t, v in self.pygments_lexer.get_tokens_unprocessed(text):
yield t, v
return enumerate(split_lines(get_tokens()), start_lineno)
def get_generator(i):
"""
Find an already started generator that is close, or create a new one.
"""
# Find closest line generator.
generator = find_closest_generator(i)
if generator:
return generator
# No generator found. Determine starting point for the syntax
# synchronisation first.
# Go at least x lines back. (Make scrolling upwards more
# efficient.)
i = max(0, i - self.MIN_LINES_BACKWARDS)
if i == 0:
row = 0
column = 0
else:
row, column = get_syntax_sync().get_sync_start_position(document, i)
# Find generator close to this point, or otherwise create a new one.
generator = find_closest_generator(i)
if generator:
return generator
else:
generator = create_line_generator(row, column)
# If the column is not 0, ignore the first line. (Which is
# incomplete. This happens when the synchronisation algorithm tells
# us to start parsing in the middle of a line.)
if column:
next(generator)
row += 1
line_generators[generator] = row
return generator
def get_line(i):
" Return the tokens for a given line number. "
try:
return cache[i]
except KeyError:
generator = get_generator(i)
# Exhaust the generator, until we find the requested line.
for num, line in generator:
cache[num] = line
if num == i:
line_generators[generator] = i
# Remove the next item from the cache.
# (It could happen that it's already there, because of
# another generator that started filling these lines,
# but we want to synchronise these lines with the
# current lexer's state.)
if num + 1 in cache:
del cache[num + 1]
return cache[num]
return []
return get_line | [
"def",
"lex_document",
"(",
"self",
",",
"cli",
",",
"document",
")",
":",
"# Cache of already lexed lines.",
"cache",
"=",
"{",
"}",
"# Pygments generators that are currently lexing.",
"line_generators",
"=",
"{",
"}",
"# Map lexer generator to the line number.",
"def",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/lexers.py#L216-L320 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/fusion/portableglobe/servers/local_server.py | python | LocalServer.JStoJson | (self, js_string) | return json.dumps(json.loads(out_string)) | Converts a JS server definition string to valid JSON. | Converts a JS server definition string to valid JSON. | [
"Converts",
"a",
"JS",
"server",
"definition",
"string",
"to",
"valid",
"JSON",
"."
] | def JStoJson(self, js_string):
"""Converts a JS server definition string to valid JSON."""
# Remove "var geeServerDefs = " or similar from start.
# Then add quotes to JSON keys that don't have them.
# Strip out the trailing ';'
# Finally, push it through json.dumps to ensure consistently-formatted output.
out_string = re.sub(r"^var \w+ ?= ?", "", js_string)
out_string = re.sub(r"([,{]\s+)(\w+):", r'\1"\2":', out_string)
out_string = out_string.strip(";")
return json.dumps(json.loads(out_string)) | [
"def",
"JStoJson",
"(",
"self",
",",
"js_string",
")",
":",
"# Remove \"var geeServerDefs = \" or similar from start.",
"# Then add quotes to JSON keys that don't have them.",
"# Strip out the trailing ';'",
"# Finally, push it through json.dumps to ensure consistently-formatted output.",
"o... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/local_server.py#L414-L423 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/showbase/Audio3DManager.py | python | Audio3DManager.getDistanceFactor | (self) | return self.audio_manager.audio3dGetDistanceFactor() | Control the scale that sets the distance units for 3D spacialized audio.
Default is 1.0 which is adjust in panda to be meters. | Control the scale that sets the distance units for 3D spacialized audio.
Default is 1.0 which is adjust in panda to be meters. | [
"Control",
"the",
"scale",
"that",
"sets",
"the",
"distance",
"units",
"for",
"3D",
"spacialized",
"audio",
".",
"Default",
"is",
"1",
".",
"0",
"which",
"is",
"adjust",
"in",
"panda",
"to",
"be",
"meters",
"."
] | def getDistanceFactor(self):
"""
Control the scale that sets the distance units for 3D spacialized audio.
Default is 1.0 which is adjust in panda to be meters.
"""
return self.audio_manager.audio3dGetDistanceFactor() | [
"def",
"getDistanceFactor",
"(",
"self",
")",
":",
"return",
"self",
".",
"audio_manager",
".",
"audio3dGetDistanceFactor",
"(",
")"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/Audio3DManager.py#L44-L49 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/credentials.py | python | AssumeRoleProvider._get_role_config | (self, profile_name) | return role_config | Retrieves and validates the role configuration for the profile. | Retrieves and validates the role configuration for the profile. | [
"Retrieves",
"and",
"validates",
"the",
"role",
"configuration",
"for",
"the",
"profile",
"."
] | def _get_role_config(self, profile_name):
"""Retrieves and validates the role configuration for the profile."""
profiles = self._loaded_config.get('profiles', {})
profile = profiles[profile_name]
source_profile = profile.get('source_profile')
role_arn = profile['role_arn']
credential_source = profile.get('credential_source')
mfa_serial = profile.get('mfa_serial')
external_id = profile.get('external_id')
role_session_name = profile.get('role_session_name')
duration_seconds = profile.get('duration_seconds')
role_config = {
'role_arn': role_arn,
'external_id': external_id,
'mfa_serial': mfa_serial,
'role_session_name': role_session_name,
'source_profile': source_profile,
'credential_source': credential_source
}
if duration_seconds is not None:
try:
role_config['duration_seconds'] = int(duration_seconds)
except ValueError:
pass
# Either the credential source or the source profile must be
# specified, but not both.
if credential_source is not None and source_profile is not None:
raise InvalidConfigError(
error_msg=(
'The profile "%s" contains both source_profile and '
'credential_source.' % profile_name
)
)
elif credential_source is None and source_profile is None:
raise PartialCredentialsError(
provider=self.METHOD,
cred_var='source_profile or credential_source'
)
elif credential_source is not None:
self._validate_credential_source(
profile_name, credential_source)
else:
self._validate_source_profile(profile_name, source_profile)
return role_config | [
"def",
"_get_role_config",
"(",
"self",
",",
"profile_name",
")",
":",
"profiles",
"=",
"self",
".",
"_loaded_config",
".",
"get",
"(",
"'profiles'",
",",
"{",
"}",
")",
"profile",
"=",
"profiles",
"[",
"profile_name",
"]",
"source_profile",
"=",
"profile",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/credentials.py#L1437-L1485 | |
anestisb/oatdump_plus | ba858c1596598f0d9ae79c14d08c708cecc50af3 | tools/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/anestisb/oatdump_plus/blob/ba858c1596598f0d9ae79c14d08c708cecc50af3/tools/cpplint.py#L1038-L1040 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/mws/connection.py | python | MWSConnection.create_inbound_shipment_plan | (self, request, response, **kw) | return self._post_request(request, kw, response) | Returns the information required to create an inbound shipment. | Returns the information required to create an inbound shipment. | [
"Returns",
"the",
"information",
"required",
"to",
"create",
"an",
"inbound",
"shipment",
"."
] | def create_inbound_shipment_plan(self, request, response, **kw):
"""Returns the information required to create an inbound shipment.
"""
return self._post_request(request, kw, response) | [
"def",
"create_inbound_shipment_plan",
"(",
"self",
",",
"request",
",",
"response",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"_post_request",
"(",
"request",
",",
"kw",
",",
"response",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/mws/connection.py#L551-L554 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/elastic/rendezvous/api.py | python | RendezvousHandler.get_run_id | (self) | Returns the run id of the rendezvous.
The run id is a user-defined id that uniquely identifies an instance of
a distributed application. It typically maps to a job id and is used to
allow nodes to join the correct distributed application. | Returns the run id of the rendezvous. | [
"Returns",
"the",
"run",
"id",
"of",
"the",
"rendezvous",
"."
] | def get_run_id(self) -> str:
"""Returns the run id of the rendezvous.
The run id is a user-defined id that uniquely identifies an instance of
a distributed application. It typically maps to a job id and is used to
allow nodes to join the correct distributed application.
""" | [
"def",
"get_run_id",
"(",
"self",
")",
"->",
"str",
":"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/rendezvous/api.py#L100-L106 | ||
DaehwanKimLab/hisat2 | c4419f9884c43295b141fe7ec5aeecc032427d42 | scripts/sa.py | python | loadFasta | (fns) | return ''.join(falist) | Load the concatenation of all the A/C/G/T characters | Load the concatenation of all the A/C/G/T characters | [
"Load",
"the",
"concatenation",
"of",
"all",
"the",
"A",
"/",
"C",
"/",
"G",
"/",
"T",
"characters"
] | def loadFasta(fns):
""" Load the concatenation of all the A/C/G/T characters """
falist = []
dna = set(['A', 'C', 'G', 'T', 'a', 'c', 'g', 't'])
for fn in fns:
with open(fn, 'r') as fh:
for line in fh:
if line[0] == '>':
continue
for c in line:
if c in dna:
falist.append(c)
return ''.join(falist) | [
"def",
"loadFasta",
"(",
"fns",
")",
":",
"falist",
"=",
"[",
"]",
"dna",
"=",
"set",
"(",
"[",
"'A'",
",",
"'C'",
",",
"'G'",
",",
"'T'",
",",
"'a'",
",",
"'c'",
",",
"'g'",
",",
"'t'",
"]",
")",
"for",
"fn",
"in",
"fns",
":",
"with",
"ope... | https://github.com/DaehwanKimLab/hisat2/blob/c4419f9884c43295b141fe7ec5aeecc032427d42/scripts/sa.py#L25-L37 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | tools/update-packaging/make_incremental_updates.py | python | copy_file | (src_file_abs_path, dst_file_abs_path) | Copies src to dst creating any parent dirs required in dst first | Copies src to dst creating any parent dirs required in dst first | [
"Copies",
"src",
"to",
"dst",
"creating",
"any",
"parent",
"dirs",
"required",
"in",
"dst",
"first"
] | def copy_file(src_file_abs_path, dst_file_abs_path):
""" Copies src to dst creating any parent dirs required in dst first """
dst_file_dir=os.path.dirname(dst_file_abs_path)
if not os.path.exists(dst_file_dir):
os.makedirs(dst_file_dir)
# Copy the file over
shutil.copy2(src_file_abs_path, dst_file_abs_path) | [
"def",
"copy_file",
"(",
"src_file_abs_path",
",",
"dst_file_abs_path",
")",
":",
"dst_file_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dst_file_abs_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dst_file_dir",
")",
":",
"os",
"."... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/tools/update-packaging/make_incremental_updates.py#L194-L200 | ||
NVIDIA/thrust | 627dccb359a635afdd69e95a6cc59698f23f70e2 | internal/benchmark/combine_benchmark_results.py | python | find_significant_digit | (x) | return -int(floor(log10(abs(x)))) | Return the significant digit of the number x. The result is the number of
digits after the decimal place to round to (negative numbers indicate rounding
before the decimal place). | Return the significant digit of the number x. The result is the number of
digits after the decimal place to round to (negative numbers indicate rounding
before the decimal place). | [
"Return",
"the",
"significant",
"digit",
"of",
"the",
"number",
"x",
".",
"The",
"result",
"is",
"the",
"number",
"of",
"digits",
"after",
"the",
"decimal",
"place",
"to",
"round",
"to",
"(",
"negative",
"numbers",
"indicate",
"rounding",
"before",
"the",
... | def find_significant_digit(x):
"""Return the significant digit of the number x. The result is the number of
digits after the decimal place to round to (negative numbers indicate rounding
before the decimal place)."""
if x == 0: return 0
return -int(floor(log10(abs(x)))) | [
"def",
"find_significant_digit",
"(",
"x",
")",
":",
"if",
"x",
"==",
"0",
":",
"return",
"0",
"return",
"-",
"int",
"(",
"floor",
"(",
"log10",
"(",
"abs",
"(",
"x",
")",
")",
")",
")"
] | https://github.com/NVIDIA/thrust/blob/627dccb359a635afdd69e95a6cc59698f23f70e2/internal/benchmark/combine_benchmark_results.py#L92-L97 | |
GXYM/DRRG | 9e074fa9052de8d131f55ca1f6ae6673c1bfeca4 | dataset/icdar15/Evaluation_Protocol/rrc_evaluation_funcs.py | python | load_zip_file_keys | (file,fileNameRegExp='') | return pairs | Returns an array with the entries of the ZIP file that match with the regular expression.
The key's are the names or the file or the capturing group definied in the fileNameRegExp | Returns an array with the entries of the ZIP file that match with the regular expression.
The key's are the names or the file or the capturing group definied in the fileNameRegExp | [
"Returns",
"an",
"array",
"with",
"the",
"entries",
"of",
"the",
"ZIP",
"file",
"that",
"match",
"with",
"the",
"regular",
"expression",
".",
"The",
"key",
"s",
"are",
"the",
"names",
"or",
"the",
"file",
"or",
"the",
"capturing",
"group",
"definied",
"i... | def load_zip_file_keys(file,fileNameRegExp=''):
"""
Returns an array with the entries of the ZIP file that match with the regular expression.
The key's are the names or the file or the capturing group definied in the fileNameRegExp
"""
try:
archive=zipfile.ZipFile(file, mode='r', allowZip64=True)
except :
raise Exception('Error loading the ZIP archive.')
pairs = []
for name in archive.namelist():
addFile = True
keyName = name
if fileNameRegExp!="":
m = re.match(fileNameRegExp,name)
if m == None:
addFile = False
else:
if len(m.groups())>0:
keyName = m.group(1)
if addFile:
pairs.append( keyName )
return pairs | [
"def",
"load_zip_file_keys",
"(",
"file",
",",
"fileNameRegExp",
"=",
"''",
")",
":",
"try",
":",
"archive",
"=",
"zipfile",
".",
"ZipFile",
"(",
"file",
",",
"mode",
"=",
"'r'",
",",
"allowZip64",
"=",
"True",
")",
"except",
":",
"raise",
"Exception",
... | https://github.com/GXYM/DRRG/blob/9e074fa9052de8d131f55ca1f6ae6673c1bfeca4/dataset/icdar15/Evaluation_Protocol/rrc_evaluation_funcs.py#L17-L43 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py | python | StateTracker.DocFlagPass | (self, start_token, error_handler) | Parses doc flags.
This pass needs to be executed before the aliaspass and we don't want to do
a full-blown statetracker dry run for these.
Args:
start_token: The token at which to start iterating
error_handler: An error handler for error reporting. | Parses doc flags. | [
"Parses",
"doc",
"flags",
"."
] | def DocFlagPass(self, start_token, error_handler):
"""Parses doc flags.
This pass needs to be executed before the aliaspass and we don't want to do
a full-blown statetracker dry run for these.
Args:
start_token: The token at which to start iterating
error_handler: An error handler for error reporting.
"""
if not start_token:
return
doc_flag_types = (Type.DOC_FLAG, Type.DOC_INLINE_FLAG)
for token in start_token:
if token.type in doc_flag_types:
token.attached_object = self._doc_flag(token, error_handler) | [
"def",
"DocFlagPass",
"(",
"self",
",",
"start_token",
",",
"error_handler",
")",
":",
"if",
"not",
"start_token",
":",
"return",
"doc_flag_types",
"=",
"(",
"Type",
".",
"DOC_FLAG",
",",
"Type",
".",
"DOC_INLINE_FLAG",
")",
"for",
"token",
"in",
"start_toke... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/statetracker.py#L782-L797 | ||
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py | python | quantized_matmul | (
A=TensorDef(T1, S.M, S.K),
B=TensorDef(T2, S.K, S.N),
AZp=ScalarDef(I32),
BZp=ScalarDef(I32),
C=TensorDef(U, S.M, S.N, output=True)) | Performs a matrix multiplication of two 2D inputs.
Numeric casting is performed on the operands to the inner multiply, promoting
them to the same data type as the accumulator/output. The quantized variant
includes zero-point adjustments for the left and right operands of the
matmul. | Performs a matrix multiplication of two 2D inputs. | [
"Performs",
"a",
"matrix",
"multiplication",
"of",
"two",
"2D",
"inputs",
"."
] | def quantized_matmul(
A=TensorDef(T1, S.M, S.K),
B=TensorDef(T2, S.K, S.N),
AZp=ScalarDef(I32),
BZp=ScalarDef(I32),
C=TensorDef(U, S.M, S.N, output=True)):
"""Performs a matrix multiplication of two 2D inputs.
Numeric casting is performed on the operands to the inner multiply, promoting
them to the same data type as the accumulator/output. The quantized variant
includes zero-point adjustments for the left and right operands of the
matmul.
"""
domain(D.m, D.n, D.k)
C[D.m, D.n] += (TypeFn.cast(U, A[D.m, D.k]) - TypeFn.cast(U, AZp)) * (
TypeFn.cast(U, B[D.k, D.n]) - TypeFn.cast(U, BZp)) | [
"def",
"quantized_matmul",
"(",
"A",
"=",
"TensorDef",
"(",
"T1",
",",
"S",
".",
"M",
",",
"S",
".",
"K",
")",
",",
"B",
"=",
"TensorDef",
"(",
"T2",
",",
"S",
".",
"K",
",",
"S",
".",
"N",
")",
",",
"AZp",
"=",
"ScalarDef",
"(",
"I32",
")"... | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py#L41-L56 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | chrome/common/extensions/docs/server2/link_error_detector.py | python | LinkErrorDetector._RenderAllPages | (self) | Traverses the public templates directory rendering each URL and
processing the resultant html to pull out all links and anchors. | Traverses the public templates directory rendering each URL and
processing the resultant html to pull out all links and anchors. | [
"Traverses",
"the",
"public",
"templates",
"directory",
"rendering",
"each",
"URL",
"and",
"processing",
"the",
"resultant",
"html",
"to",
"pull",
"out",
"all",
"links",
"and",
"anchors",
"."
] | def _RenderAllPages(self):
'''Traverses the public templates directory rendering each URL and
processing the resultant html to pull out all links and anchors.
'''
top_level_directories = (
('docs/templates/public/', ''),
('docs/static/', 'static/'),
('docs/examples/', 'extensions/examples/'),
)
for dirpath, urlprefix in top_level_directories:
files = CreateURLsFromPaths(self._file_system, dirpath, urlprefix)
for url, path in files:
self._pages[url] = _Process(url, self._renderer)
if self._pages[url].status != 200:
print(url, ', a url derived from the path', dirpath +
', resulted in a', self._pages[url].status) | [
"def",
"_RenderAllPages",
"(",
"self",
")",
":",
"top_level_directories",
"=",
"(",
"(",
"'docs/templates/public/'",
",",
"''",
")",
",",
"(",
"'docs/static/'",
",",
"'static/'",
")",
",",
"(",
"'docs/examples/'",
",",
"'extensions/examples/'",
")",
",",
")",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/link_error_detector.py#L141-L158 | ||
scribusproject/scribus | 41ec7c775a060912cf251682a8b1437f753f80f4 | scribus/plugins/scripter/python/scripter_runtime.py | python | cleanup | () | delete every child which is not marked as keep | delete every child which is not marked as keep | [
"delete",
"every",
"child",
"which",
"is",
"not",
"marked",
"as",
"keep"
] | def cleanup():
"""
delete every child which is not marked as keep
"""
for child in Scripter.collector.children():
if hasattr(child, "qt"): child = child.qt
v = child.property("keep")
if v and v.toBool() == True:
#print "Keeping", child
continue
print "* deleting collected", child
sip.delete(child) | [
"def",
"cleanup",
"(",
")",
":",
"for",
"child",
"in",
"Scripter",
".",
"collector",
".",
"children",
"(",
")",
":",
"if",
"hasattr",
"(",
"child",
",",
"\"qt\"",
")",
":",
"child",
"=",
"child",
".",
"qt",
"v",
"=",
"child",
".",
"property",
"(",
... | https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/scribus/plugins/scripter/python/scripter_runtime.py#L237-L248 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/utils/misc/grep-svn-log.py | python | Log.finish | (self) | Call this when you're finished with populating content. | Call this when you're finished with populating content. | [
"Call",
"this",
"when",
"you",
"re",
"finished",
"with",
"populating",
"content",
"."
] | def finish(self):
"""Call this when you're finished with populating content."""
if self.prev_line is not None:
print >> self, self.prev_line
self.prev_line = None | [
"def",
"finish",
"(",
"self",
")",
":",
"if",
"self",
".",
"prev_line",
"is",
"not",
"None",
":",
"print",
">>",
"self",
",",
"self",
".",
"prev_line",
"self",
".",
"prev_line",
"=",
"None"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/utils/misc/grep-svn-log.py#L48-L52 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/descriptor_pool.py | python | DescriptorPool._GetDeps | (self, dependencies) | Recursively finds dependencies for file protos.
Args:
dependencies: The names of the files being depended on.
Yields:
Each direct and indirect dependency. | Recursively finds dependencies for file protos. | [
"Recursively",
"finds",
"dependencies",
"for",
"file",
"protos",
"."
] | def _GetDeps(self, dependencies):
"""Recursively finds dependencies for file protos.
Args:
dependencies: The names of the files being depended on.
Yields:
Each direct and indirect dependency.
"""
for dependency in dependencies:
dep_desc = self.FindFileByName(dependency)
yield dep_desc
for parent_dep in dep_desc.dependencies:
yield parent_dep | [
"def",
"_GetDeps",
"(",
"self",
",",
"dependencies",
")",
":",
"for",
"dependency",
"in",
"dependencies",
":",
"dep_desc",
"=",
"self",
".",
"FindFileByName",
"(",
"dependency",
")",
"yield",
"dep_desc",
"for",
"parent_dep",
"in",
"dep_desc",
".",
"dependencie... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/descriptor_pool.py#L1218-L1232 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/distribution/logistic.py | python | Logistic._sd | (self, loc=None, scale=None) | return scale * self.consttensor(self.sd_const, self.dtypeop(scale)) | The standard deviation of the distribution. | The standard deviation of the distribution. | [
"The",
"standard",
"deviation",
"of",
"the",
"distribution",
"."
] | def _sd(self, loc=None, scale=None):
"""
The standard deviation of the distribution.
"""
_, scale = self._check_param_type(loc, scale)
return scale * self.consttensor(self.sd_const, self.dtypeop(scale)) | [
"def",
"_sd",
"(",
"self",
",",
"loc",
"=",
"None",
",",
"scale",
"=",
"None",
")",
":",
"_",
",",
"scale",
"=",
"self",
".",
"_check_param_type",
"(",
"loc",
",",
"scale",
")",
"return",
"scale",
"*",
"self",
".",
"consttensor",
"(",
"self",
".",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/logistic.py#L255-L260 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/motionplanning.py | python | CSpaceInterface.setVisibilityPrior | (self, name, costPrior=0.0, visibilityProbability=0.0, evidenceStrength=1.0) | return _motionplanning.CSpaceInterface_setVisibilityPrior(self, name, costPrior, visibilityProbability, evidenceStrength) | setVisibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double visibilityProbability=0.0, double evidenceStrength=1.0)
setVisibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double visibilityProbability=0.0)
setVisibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0)
setVisibilityPrior(CSpaceInterface self, char const * name)
Resets the data for a certain visibility test. Default values give a data-
gathering behavior. | setVisibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double visibilityProbability=0.0, double evidenceStrength=1.0)
setVisibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double visibilityProbability=0.0)
setVisibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0)
setVisibilityPrior(CSpaceInterface self, char const * name) | [
"setVisibilityPrior",
"(",
"CSpaceInterface",
"self",
"char",
"const",
"*",
"name",
"double",
"costPrior",
"=",
"0",
".",
"0",
"double",
"visibilityProbability",
"=",
"0",
".",
"0",
"double",
"evidenceStrength",
"=",
"1",
".",
"0",
")",
"setVisibilityPrior",
"... | def setVisibilityPrior(self, name, costPrior=0.0, visibilityProbability=0.0, evidenceStrength=1.0):
"""
setVisibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double visibilityProbability=0.0, double evidenceStrength=1.0)
setVisibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0, double visibilityProbability=0.0)
setVisibilityPrior(CSpaceInterface self, char const * name, double costPrior=0.0)
setVisibilityPrior(CSpaceInterface self, char const * name)
Resets the data for a certain visibility test. Default values give a data-
gathering behavior.
"""
return _motionplanning.CSpaceInterface_setVisibilityPrior(self, name, costPrior, visibilityProbability, evidenceStrength) | [
"def",
"setVisibilityPrior",
"(",
"self",
",",
"name",
",",
"costPrior",
"=",
"0.0",
",",
"visibilityProbability",
"=",
"0.0",
",",
"evidenceStrength",
"=",
"1.0",
")",
":",
"return",
"_motionplanning",
".",
"CSpaceInterface_setVisibilityPrior",
"(",
"self",
",",
... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/motionplanning.py#L634-L647 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | WhileContext._MaybeAddControlDependency | (self, op) | Add a control input to the op if it only depends on loop invariants. | Add a control input to the op if it only depends on loop invariants. | [
"Add",
"a",
"control",
"input",
"to",
"the",
"op",
"if",
"it",
"only",
"depends",
"on",
"loop",
"invariants",
"."
] | def _MaybeAddControlDependency(self, op):
"""Add a control input to the op if it only depends on loop invariants."""
def _IsOpFree(op):
if op.control_inputs:
return False
for x in op.inputs:
if not _IsLoopConstantEnter(x.op):
return False
return True
if _IsOpFree(op):
# pylint: disable=protected-access
op._add_control_input(self.GetControlPivot().op) | [
"def",
"_MaybeAddControlDependency",
"(",
"self",
",",
"op",
")",
":",
"def",
"_IsOpFree",
"(",
"op",
")",
":",
"if",
"op",
".",
"control_inputs",
":",
"return",
"False",
"for",
"x",
"in",
"op",
".",
"inputs",
":",
"if",
"not",
"_IsLoopConstantEnter",
"(... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L1544-L1555 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | chrome/common/extensions/docs/server2/api_data_source.py | python | _JSCModel._GetIntroTableList | (self) | return intro_rows | Create a generic data structure that can be traversed by the templates
to create an API intro table. | Create a generic data structure that can be traversed by the templates
to create an API intro table. | [
"Create",
"a",
"generic",
"data",
"structure",
"that",
"can",
"be",
"traversed",
"by",
"the",
"templates",
"to",
"create",
"an",
"API",
"intro",
"table",
"."
] | def _GetIntroTableList(self):
'''Create a generic data structure that can be traversed by the templates
to create an API intro table.
'''
intro_rows = [
self._GetIntroDescriptionRow(),
self._GetIntroAvailabilityRow()
] + self._GetIntroDependencyRows()
# Add rows using data from intro_tables.json, overriding any existing rows
# if they share the same 'title' attribute.
row_titles = [row['title'] for row in intro_rows]
for misc_row in self._GetMiscIntroRows():
if misc_row['title'] in row_titles:
intro_rows[row_titles.index(misc_row['title'])] = misc_row
else:
intro_rows.append(misc_row)
return intro_rows | [
"def",
"_GetIntroTableList",
"(",
"self",
")",
":",
"intro_rows",
"=",
"[",
"self",
".",
"_GetIntroDescriptionRow",
"(",
")",
",",
"self",
".",
"_GetIntroAvailabilityRow",
"(",
")",
"]",
"+",
"self",
".",
"_GetIntroDependencyRows",
"(",
")",
"# Add rows using da... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/api_data_source.py#L334-L352 | |
wujixiu/helmet-detection | 8eff5c59ddfba5a29e0b76aeb48babcb49246178 | hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py | python | CheckComment | (comment, filename, linenum, error) | Checks for common mistakes in TODO comments.
Args:
comment: The text of the comment from the line in question.
filename: The name of the current file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for common mistakes in TODO comments. | [
"Checks",
"for",
"common",
"mistakes",
"in",
"TODO",
"comments",
"."
] | def CheckComment(comment, filename, linenum, error):
"""Checks for common mistakes in TODO comments.
Args:
comment: The text of the comment from the line in question.
filename: The name of the current file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
match = _RE_PATTERN_TODO.match(comment)
if match:
# One whitespace is correct; zero whitespace is handled elsewhere.
leading_whitespace = match.group(1)
if len(leading_whitespace) > 1:
error(filename, linenum, 'whitespace/todo', 2,
'Too many spaces before TODO')
username = match.group(2)
if not username:
error(filename, linenum, 'readability/todo', 2,
'Missing username in TODO; it should look like '
'"// TODO(my_username): Stuff."')
middle_whitespace = match.group(3)
# Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
if middle_whitespace != ' ' and middle_whitespace != '':
error(filename, linenum, 'whitespace/todo', 2,
'TODO(my_username) should be followed by a space') | [
"def",
"CheckComment",
"(",
"comment",
",",
"filename",
",",
"linenum",
",",
"error",
")",
":",
"match",
"=",
"_RE_PATTERN_TODO",
".",
"match",
"(",
"comment",
")",
"if",
"match",
":",
"# One whitespace is correct; zero whitespace is handled elsewhere.",
"leading_whit... | https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py#L2461-L2488 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/math_ops.py | python | cumsum | (x, axis=0, exclusive=False, reverse=False, name=None) | Compute the cumulative sum of the tensor `x` along `axis`.
By default, this op performs an inclusive cumsum, which means that the first
element of the input is identical to the first element of the output:
```prettyprint
tf.cumsum([a, b, c]) ==> [a, a + b, a + b + c]
```
By setting the `exclusive` kwarg to `True`, an exclusive cumsum is performed
instead:
```prettyprint
tf.cumsum([a, b, c], exclusive=True) ==> [0, a, a + b]
```
By setting the `reverse` kwarg to `True`, the cumsum is performed in the
opposite direction:
```prettyprint
tf.cumsum([a, b, c], reverse=True) ==> [a + b + c, b + c, c]
```
This is more efficient than using separate `tf.reverse` ops.
The `reverse` and `exclusive` kwargs can also be combined:
```prettyprint
tf.cumsum([a, b, c], exclusive=True, reverse=True) ==> [b + c, c, 0]
```
Args:
x: A `Tensor`. Must be one of the following types: `float32`, `float64`,
`int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,
`complex128`, `qint8`, `quint8`, `qint32`, `half`.
axis: A `Tensor` of type `int32` (default: 0).
reverse: A `bool` (default: False).
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `x`. | Compute the cumulative sum of the tensor `x` along `axis`. | [
"Compute",
"the",
"cumulative",
"sum",
"of",
"the",
"tensor",
"x",
"along",
"axis",
"."
] | def cumsum(x, axis=0, exclusive=False, reverse=False, name=None):
"""Compute the cumulative sum of the tensor `x` along `axis`.
By default, this op performs an inclusive cumsum, which means that the first
element of the input is identical to the first element of the output:
```prettyprint
tf.cumsum([a, b, c]) ==> [a, a + b, a + b + c]
```
By setting the `exclusive` kwarg to `True`, an exclusive cumsum is performed
instead:
```prettyprint
tf.cumsum([a, b, c], exclusive=True) ==> [0, a, a + b]
```
By setting the `reverse` kwarg to `True`, the cumsum is performed in the
opposite direction:
```prettyprint
tf.cumsum([a, b, c], reverse=True) ==> [a + b + c, b + c, c]
```
This is more efficient than using separate `tf.reverse` ops.
The `reverse` and `exclusive` kwargs can also be combined:
```prettyprint
tf.cumsum([a, b, c], exclusive=True, reverse=True) ==> [b + c, c, 0]
```
Args:
x: A `Tensor`. Must be one of the following types: `float32`, `float64`,
`int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,
`complex128`, `qint8`, `quint8`, `qint32`, `half`.
axis: A `Tensor` of type `int32` (default: 0).
reverse: A `bool` (default: False).
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `x`.
"""
with ops.op_scope([x], name, "Cumsum") as name:
x = ops.convert_to_tensor(x, name="x")
return gen_math_ops.cumsum(
x, axis, exclusive=exclusive, reverse=reverse, name=name) | [
"def",
"cumsum",
"(",
"x",
",",
"axis",
"=",
"0",
",",
"exclusive",
"=",
"False",
",",
"reverse",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"x",
"]",
",",
"name",
",",
"\"Cumsum\"",
")",
"as",
"... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L1605-L1646 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/difflib.py | python | Differ._fancy_replace | (self, a, alo, ahi, b, blo, bhi) | r"""
When replacing one block of lines with another, search the blocks
for *similar* lines; the best-matching pair (if any) is used as a
synch point, and intraline difference marking is done on the
similar pair. Lots of work, but often worth it.
Example:
>>> d = Differ()
>>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
... ['abcdefGhijkl\n'], 0, 1)
>>> print(''.join(results), end="")
- abcDefghiJkl
? ^ ^ ^
+ abcdefGhijkl
? ^ ^ ^ | r"""
When replacing one block of lines with another, search the blocks
for *similar* lines; the best-matching pair (if any) is used as a
synch point, and intraline difference marking is done on the
similar pair. Lots of work, but often worth it. | [
"r",
"When",
"replacing",
"one",
"block",
"of",
"lines",
"with",
"another",
"search",
"the",
"blocks",
"for",
"*",
"similar",
"*",
"lines",
";",
"the",
"best",
"-",
"matching",
"pair",
"(",
"if",
"any",
")",
"is",
"used",
"as",
"a",
"synch",
"point",
... | def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
r"""
When replacing one block of lines with another, search the blocks
for *similar* lines; the best-matching pair (if any) is used as a
synch point, and intraline difference marking is done on the
similar pair. Lots of work, but often worth it.
Example:
>>> d = Differ()
>>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
... ['abcdefGhijkl\n'], 0, 1)
>>> print(''.join(results), end="")
- abcDefghiJkl
? ^ ^ ^
+ abcdefGhijkl
? ^ ^ ^
"""
# don't synch up unless the lines have a similarity score of at
# least cutoff; best_ratio tracks the best score seen so far
best_ratio, cutoff = 0.74, 0.75
cruncher = SequenceMatcher(self.charjunk)
eqi, eqj = None, None # 1st indices of equal lines (if any)
# search for the pair that matches best without being identical
# (identical lines must be junk lines, & we don't want to synch up
# on junk -- unless we have to)
for j in range(blo, bhi):
bj = b[j]
cruncher.set_seq2(bj)
for i in range(alo, ahi):
ai = a[i]
if ai == bj:
if eqi is None:
eqi, eqj = i, j
continue
cruncher.set_seq1(ai)
# computing similarity is expensive, so use the quick
# upper bounds first -- have seen this speed up messy
# compares by a factor of 3.
# note that ratio() is only expensive to compute the first
# time it's called on a sequence pair; the expensive part
# of the computation is cached by cruncher
if cruncher.real_quick_ratio() > best_ratio and \
cruncher.quick_ratio() > best_ratio and \
cruncher.ratio() > best_ratio:
best_ratio, best_i, best_j = cruncher.ratio(), i, j
if best_ratio < cutoff:
# no non-identical "pretty close" pair
if eqi is None:
# no identical pair either -- treat it as a straight replace
yield from self._plain_replace(a, alo, ahi, b, blo, bhi)
return
# no close pair, but an identical pair -- synch up on that
best_i, best_j, best_ratio = eqi, eqj, 1.0
else:
# there's a close pair, so forget the identical pair (if any)
eqi = None
# a[best_i] very similar to b[best_j]; eqi is None iff they're not
# identical
# pump out diffs from before the synch point
yield from self._fancy_helper(a, alo, best_i, b, blo, best_j)
# do intraline marking on the synch pair
aelt, belt = a[best_i], b[best_j]
if eqi is None:
# pump out a '-', '?', '+', '?' quad for the synched lines
atags = btags = ""
cruncher.set_seqs(aelt, belt)
for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
la, lb = ai2 - ai1, bj2 - bj1
if tag == 'replace':
atags += '^' * la
btags += '^' * lb
elif tag == 'delete':
atags += '-' * la
elif tag == 'insert':
btags += '+' * lb
elif tag == 'equal':
atags += ' ' * la
btags += ' ' * lb
else:
raise ValueError('unknown tag %r' % (tag,))
yield from self._qformat(aelt, belt, atags, btags)
else:
# the synch pair is identical
yield ' ' + aelt
# pump out diffs from after the synch point
yield from self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi) | [
"def",
"_fancy_replace",
"(",
"self",
",",
"a",
",",
"alo",
",",
"ahi",
",",
"b",
",",
"blo",
",",
"bhi",
")",
":",
"# don't synch up unless the lines have a similarity score of at",
"# least cutoff; best_ratio tracks the best score seen so far",
"best_ratio",
",",
"cutof... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/difflib.py#L928-L1020 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/stats/_continuous_distns.py | python | crystalball_gen._munp | (self, n, beta, m) | return N * _lazywhere(n + 1 < m, (n, beta, m),
np.vectorize(n_th_moment, otypes=[np.float]),
np.inf) | Returns the n-th non-central moment of the crystalball function. | Returns the n-th non-central moment of the crystalball function. | [
"Returns",
"the",
"n",
"-",
"th",
"non",
"-",
"central",
"moment",
"of",
"the",
"crystalball",
"function",
"."
] | def _munp(self, n, beta, m):
"""
Returns the n-th non-central moment of the crystalball function.
"""
N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) +
_norm_pdf_C * _norm_cdf(beta))
def n_th_moment(n, beta, m):
"""
Returns n-th moment. Defined only if n+1 < m
Function cannot broadcast due to the loop over n
"""
A = (m/beta)**m * np.exp(-beta**2 / 2.0)
B = m/beta - beta
rhs = (2**((n-1)/2.0) * sc.gamma((n+1)/2) *
(1.0 + (-1)**n * sc.gammainc((n+1)/2, beta**2 / 2)))
lhs = np.zeros(rhs.shape)
for k in range(n + 1):
lhs += (sc.binom(n, k) * B**(n-k) * (-1)**k / (m - k - 1) *
(m/beta)**(-m + k + 1))
return A * lhs + rhs
return N * _lazywhere(n + 1 < m, (n, beta, m),
np.vectorize(n_th_moment, otypes=[np.float]),
np.inf) | [
"def",
"_munp",
"(",
"self",
",",
"n",
",",
"beta",
",",
"m",
")",
":",
"N",
"=",
"1.0",
"/",
"(",
"m",
"/",
"beta",
"/",
"(",
"m",
"-",
"1",
")",
"*",
"np",
".",
"exp",
"(",
"-",
"beta",
"**",
"2",
"/",
"2.0",
")",
"+",
"_norm_pdf_C",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/_continuous_distns.py#L7025-L7049 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py | python | _GetPdbPath | (target_dict, config_name, vars) | return pdb_path | Returns the path to the PDB file that will be generated by a given
configuration.
The lookup proceeds as follows:
- Look for an explicit path in the VCLinkerTool configuration block.
- Look for an 'msvs_large_pdb_path' variable.
- Use '<(PRODUCT_DIR)/<(product_name).(exe|dll).pdb' if 'product_name' is
specified.
- Use '<(PRODUCT_DIR)/<(target_name).(exe|dll).pdb'.
Arguments:
target_dict: The target dictionary to be searched.
config_name: The name of the configuration of interest.
vars: A dictionary of common GYP variables with generator-specific values.
Returns:
The path of the corresponding PDB file. | Returns the path to the PDB file that will be generated by a given
configuration. | [
"Returns",
"the",
"path",
"to",
"the",
"PDB",
"file",
"that",
"will",
"be",
"generated",
"by",
"a",
"given",
"configuration",
"."
] | def _GetPdbPath(target_dict, config_name, vars):
"""Returns the path to the PDB file that will be generated by a given
configuration.
The lookup proceeds as follows:
- Look for an explicit path in the VCLinkerTool configuration block.
- Look for an 'msvs_large_pdb_path' variable.
- Use '<(PRODUCT_DIR)/<(product_name).(exe|dll).pdb' if 'product_name' is
specified.
- Use '<(PRODUCT_DIR)/<(target_name).(exe|dll).pdb'.
Arguments:
target_dict: The target dictionary to be searched.
config_name: The name of the configuration of interest.
vars: A dictionary of common GYP variables with generator-specific values.
Returns:
The path of the corresponding PDB file.
"""
config = target_dict['configurations'][config_name]
msvs = config.setdefault('msvs_settings', {})
linker = msvs.get('VCLinkerTool', {})
pdb_path = linker.get('ProgramDatabaseFile')
if pdb_path:
return pdb_path
variables = target_dict.get('variables', {})
pdb_path = variables.get('msvs_large_pdb_path', None)
if pdb_path:
return pdb_path
pdb_base = target_dict.get('product_name', target_dict['target_name'])
pdb_base = '%s.%s.pdb' % (pdb_base, TARGET_TYPE_EXT[target_dict['type']])
pdb_path = vars['PRODUCT_DIR'] + '/' + pdb_base
return pdb_path | [
"def",
"_GetPdbPath",
"(",
"target_dict",
",",
"config_name",
",",
"vars",
")",
":",
"config",
"=",
"target_dict",
"[",
"'configurations'",
"]",
"[",
"config_name",
"]",
"msvs",
"=",
"config",
".",
"setdefault",
"(",
"'msvs_settings'",
",",
"{",
"}",
")",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py#L128-L165 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_distutils/ccompiler.py | python | gen_lib_options | (compiler, library_dirs, runtime_library_dirs, libraries) | return lib_opts | Generate linker options for searching library directories and
linking with specific libraries. 'libraries' and 'library_dirs' are,
respectively, lists of library names (not filenames!) and search
directories. Returns a list of command-line options suitable for use
with some compiler (depending on the two format strings passed in). | Generate linker options for searching library directories and
linking with specific libraries. 'libraries' and 'library_dirs' are,
respectively, lists of library names (not filenames!) and search
directories. Returns a list of command-line options suitable for use
with some compiler (depending on the two format strings passed in). | [
"Generate",
"linker",
"options",
"for",
"searching",
"library",
"directories",
"and",
"linking",
"with",
"specific",
"libraries",
".",
"libraries",
"and",
"library_dirs",
"are",
"respectively",
"lists",
"of",
"library",
"names",
"(",
"not",
"filenames!",
")",
"and... | def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries):
"""Generate linker options for searching library directories and
linking with specific libraries. 'libraries' and 'library_dirs' are,
respectively, lists of library names (not filenames!) and search
directories. Returns a list of command-line options suitable for use
with some compiler (depending on the two format strings passed in).
"""
lib_opts = []
for dir in library_dirs:
lib_opts.append(compiler.library_dir_option(dir))
for dir in runtime_library_dirs:
opt = compiler.runtime_library_dir_option(dir)
if isinstance(opt, list):
lib_opts = lib_opts + opt
else:
lib_opts.append(opt)
# XXX it's important that we *not* remove redundant library mentions!
# sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
# resolve all symbols. I just hope we never have to say "-lfoo obj.o
# -lbar" to get things to work -- that's certainly a possibility, but a
# pretty nasty way to arrange your C code.
for lib in libraries:
(lib_dir, lib_name) = os.path.split(lib)
if lib_dir:
lib_file = compiler.find_library_file([lib_dir], lib_name)
if lib_file:
lib_opts.append(lib_file)
else:
compiler.warn("no library file corresponding to "
"'%s' found (skipping)" % lib)
else:
lib_opts.append(compiler.library_option (lib))
return lib_opts | [
"def",
"gen_lib_options",
"(",
"compiler",
",",
"library_dirs",
",",
"runtime_library_dirs",
",",
"libraries",
")",
":",
"lib_opts",
"=",
"[",
"]",
"for",
"dir",
"in",
"library_dirs",
":",
"lib_opts",
".",
"append",
"(",
"compiler",
".",
"library_dir_option",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/ccompiler.py#L1087-L1123 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_SelfTest_REQUEST.initFromTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def initFromTpm(self, buf):
""" TpmMarshaller method """
self.fullTest = buf.readByte() | [
"def",
"initFromTpm",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"fullTest",
"=",
"buf",
".",
"readByte",
"(",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L9140-L9142 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/ttk.py | python | Progressbar.__init__ | (self, master=None, **kw) | Construct a Ttk Progressbar with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
orient, length, mode, maximum, value, variable, phase | Construct a Ttk Progressbar with parent master. | [
"Construct",
"a",
"Ttk",
"Progressbar",
"with",
"parent",
"master",
"."
] | def __init__(self, master=None, **kw):
"""Construct a Ttk Progressbar with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
orient, length, mode, maximum, value, variable, phase
"""
Widget.__init__(self, master, "ttk::progressbar", kw) | [
"def",
"__init__",
"(",
"self",
",",
"master",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"Widget",
".",
"__init__",
"(",
"self",
",",
"master",
",",
"\"ttk::progressbar\"",
",",
"kw",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/ttk.py#L999-L1010 | ||
shader-slang/slang | b8982fcf43b86c1e39dcc3dd19bff2821633eda6 | external/vulkan/registry/reg.py | python | Registry.checkForCorrectionAliases | (self, alias, require, tag) | return False | Check for an alias in the same require block.
- alias - String name of the alias
- require - `<require>` block from the registry
- tag - tag to look for in the require block | Check for an alias in the same require block. | [
"Check",
"for",
"an",
"alias",
"in",
"the",
"same",
"require",
"block",
"."
] | def checkForCorrectionAliases(self, alias, require, tag):
"""Check for an alias in the same require block.
- alias - String name of the alias
- require - `<require>` block from the registry
- tag - tag to look for in the require block"""
if alias and require.findall(tag + "[@name='" + alias + "']"):
return True
return False | [
"def",
"checkForCorrectionAliases",
"(",
"self",
",",
"alias",
",",
"require",
",",
"tag",
")",
":",
"if",
"alias",
"and",
"require",
".",
"findall",
"(",
"tag",
"+",
"\"[@name='\"",
"+",
"alias",
"+",
"\"']\"",
")",
":",
"return",
"True",
"return",
"Fal... | https://github.com/shader-slang/slang/blob/b8982fcf43b86c1e39dcc3dd19bff2821633eda6/external/vulkan/registry/reg.py#L810-L820 | |
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | examples/pycaffe/layers/pascal_multilabel_datalayers.py | python | BatchLoader.load_next_image | (self) | return self.transformer.preprocess(im), multilabel | Load the next image in a batch. | Load the next image in a batch. | [
"Load",
"the",
"next",
"image",
"in",
"a",
"batch",
"."
] | def load_next_image(self):
"""
Load the next image in a batch.
"""
# Did we finish an epoch?
if self._cur == len(self.indexlist):
self._cur = 0
shuffle(self.indexlist)
# Load an image
index = self.indexlist[self._cur] # Get the image index
image_file_name = index + '.jpg'
im = np.asarray(Image.open(
osp.join(self.pascal_root, 'JPEGImages', image_file_name)))
im = scipy.misc.imresize(im, self.im_shape) # resize
# do a simple horizontal flip as data augmentation
flip = np.random.choice(2)*2-1
im = im[:, ::flip, :]
# Load and prepare ground truth
multilabel = np.zeros(20).astype(np.float32)
anns = load_pascal_annotation(index, self.pascal_root)
for label in anns['gt_classes']:
# in the multilabel problem we don't care how MANY instances
# there are of each class. Only if they are present.
# The "-1" is b/c we are not interested in the background
# class.
multilabel[label - 1] = 1
self._cur += 1
return self.transformer.preprocess(im), multilabel | [
"def",
"load_next_image",
"(",
"self",
")",
":",
"# Did we finish an epoch?",
"if",
"self",
".",
"_cur",
"==",
"len",
"(",
"self",
".",
"indexlist",
")",
":",
"self",
".",
"_cur",
"=",
"0",
"shuffle",
"(",
"self",
".",
"indexlist",
")",
"# Load an image",
... | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L142-L173 | |
JarveeLee/SynthText_Chinese_version | 4b2cbc7d14741f21d0bb17966a339ab3574b09a8 | synthgen.py | python | RendererV3.render_text | (self,rgb,depth,seg,area,label,ninstance=1,viz=False) | return res | rgb : HxWx3 image rgb values (uint8)
depth : HxW depth values (float)
seg : HxW segmentation region masks
area : number of pixels in each region
label : region labels == unique(seg) / {0}
i.e., indices of pixels in SEG which
constitute a region mask
ninstance : no of times image should be
used to place text.
@return:
res : a list of dictionaries, one for each of
the image instances.
Each dictionary has the following structure:
'img' : rgb-image with text on it.
'bb' : 2x4xn matrix of bounding-boxes
for each character in the image.
'txt' : a list of strings.
The correspondence b/w bb and txt is that
i-th non-space white-character in txt is at bb[:,:,i].
If there's an error in pre-text placement, for e.g. if there's
no suitable region for text placement, an empty list is returned. | rgb : HxWx3 image rgb values (uint8)
depth : HxW depth values (float)
seg : HxW segmentation region masks
area : number of pixels in each region
label : region labels == unique(seg) / {0}
i.e., indices of pixels in SEG which
constitute a region mask
ninstance : no of times image should be
used to place text. | [
"rgb",
":",
"HxWx3",
"image",
"rgb",
"values",
"(",
"uint8",
")",
"depth",
":",
"HxW",
"depth",
"values",
"(",
"float",
")",
"seg",
":",
"HxW",
"segmentation",
"region",
"masks",
"area",
":",
"number",
"of",
"pixels",
"in",
"each",
"region",
"label",
"... | def render_text(self,rgb,depth,seg,area,label,ninstance=1,viz=False):
"""
rgb : HxWx3 image rgb values (uint8)
depth : HxW depth values (float)
seg : HxW segmentation region masks
area : number of pixels in each region
label : region labels == unique(seg) / {0}
i.e., indices of pixels in SEG which
constitute a region mask
ninstance : no of times image should be
used to place text.
@return:
res : a list of dictionaries, one for each of
the image instances.
Each dictionary has the following structure:
'img' : rgb-image with text on it.
'bb' : 2x4xn matrix of bounding-boxes
for each character in the image.
'txt' : a list of strings.
The correspondence b/w bb and txt is that
i-th non-space white-character in txt is at bb[:,:,i].
If there's an error in pre-text placement, for e.g. if there's
no suitable region for text placement, an empty list is returned.
"""
try:
# depth -> xyz
xyz = su.DepthCamera.depth2xyz(depth)
# find text-regions:
regions = TextRegions.get_regions(xyz,seg,area,label)
# find the placement mask and homographies:
regions = self.filter_for_placement(xyz,seg,regions)
# finally place some text:
nregions = len(regions['place_mask'])
if nregions < 1: # no good region to place text on
return []
except:
# failure in pre-text placement
#import traceback
traceback.print_exc()
return []
res = []
for i in xrange(ninstance):
place_masks = copy.deepcopy(regions['place_mask'])
print colorize(Color.CYAN, " ** instance # : %d"%i)
idict = {'img':[], 'charBB':None, 'wordBB':None, 'txt':None}
m = self.get_num_text_regions(nregions)#np.arange(nregions)#min(nregions, 5*ninstance*self.max_text_regions))
reg_idx = np.arange(min(2*m,nregions))
#np.random.shuffle(reg_idx)
reg_idx = reg_idx[:m]
placed = False
img = rgb.copy()
itext = []
ibb = []
# process regions:
num_txt_regions = len(reg_idx)
NUM_REP = 5 # re-use each region three times:
reg_range = np.arange(NUM_REP * num_txt_regions) % num_txt_regions
for idx in reg_range:
ireg = reg_idx[idx]
try:
if self.max_time is None:
txt_render_res = self.place_text(img,place_masks[ireg],
regions['homography'][ireg],
regions['homography_inv'][ireg])
else:
with time_limit(self.max_time):
txt_render_res = self.place_text(img,place_masks[ireg],
regions['homography'][ireg],
regions['homography_inv'][ireg])
except TimeoutException, msg:
print msg
continue
except:
traceback.print_exc()
# some error in placing text on the region
continue
if txt_render_res is not None:
placed = True
img,text,bb,collision_mask = txt_render_res
# update the region collision mask:
place_masks[ireg] = collision_mask
# store the result:
itext.append(text)
ibb.append(bb)
print colorize(Color.GREEN, 'text in synthgen.py/render_text append into itext '+text)
if placed:
# at least 1 word was placed in this instance:
idict['img'] = img
idict['txt'] = itext
idict['charBB'] = np.concatenate(ibb, axis=2)
idict['wordBB'] = self.char2wordBB(idict['charBB'].copy(), ' '.join(itext))
print colorize(Color.GREEN, itext)
res.append(idict.copy())
if viz:
viz_textbb(1,img, [idict['wordBB']], alpha=1.0)
viz_masks(2,img,seg,depth,regions['label'])
# viz_regions(rgb.copy(),xyz,seg,regions['coeff'],regions['label'])
if i < ninstance-1:
raw_input(colorize(Color.BLUE,'continue?',True))
return res | [
"def",
"render_text",
"(",
"self",
",",
"rgb",
",",
"depth",
",",
"seg",
",",
"area",
",",
"label",
",",
"ninstance",
"=",
"1",
",",
"viz",
"=",
"False",
")",
":",
"try",
":",
"# depth -> xyz",
"xyz",
"=",
"su",
".",
"DepthCamera",
".",
"depth2xyz",
... | https://github.com/JarveeLee/SynthText_Chinese_version/blob/4b2cbc7d14741f21d0bb17966a339ab3574b09a8/synthgen.py#L585-L698 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/ensemble/_gb.py | python | VerboseReporter.update | (self, j, est) | Update reporter with new iteration.
Parameters
----------
j : int
The new iteration
est : Estimator
The estimator | Update reporter with new iteration. | [
"Update",
"reporter",
"with",
"new",
"iteration",
"."
] | def update(self, j, est):
"""Update reporter with new iteration.
Parameters
----------
j : int
The new iteration
est : Estimator
The estimator
"""
do_oob = est.subsample < 1
# we need to take into account if we fit additional estimators.
i = j - self.begin_at_stage # iteration relative to the start iter
if (i + 1) % self.verbose_mod == 0:
oob_impr = est.oob_improvement_[j] if do_oob else 0
remaining_time = ((est.n_estimators - (j + 1)) *
(time() - self.start_time) / float(i + 1))
if remaining_time > 60:
remaining_time = '{0:.2f}m'.format(remaining_time / 60.0)
else:
remaining_time = '{0:.2f}s'.format(remaining_time)
print(self.verbose_fmt.format(iter=j + 1,
train_score=est.train_score_[j],
oob_impr=oob_impr,
remaining_time=remaining_time))
if self.verbose == 1 and ((i + 1) // (self.verbose_mod * 10) > 0):
# adjust verbose frequency (powers of 10)
self.verbose_mod *= 10 | [
"def",
"update",
"(",
"self",
",",
"j",
",",
"est",
")",
":",
"do_oob",
"=",
"est",
".",
"subsample",
"<",
"1",
"# we need to take into account if we fit additional estimators.",
"i",
"=",
"j",
"-",
"self",
".",
"begin_at_stage",
"# iteration relative to the start i... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/ensemble/_gb.py#L1136-L1163 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/rcode.py | python | from_text | (text) | return v | Convert text into an rcode.
@param text: the texual rcode
@type text: string
@raises UnknownRcode: the rcode is unknown
@rtype: int | Convert text into an rcode. | [
"Convert",
"text",
"into",
"an",
"rcode",
"."
] | def from_text(text):
"""Convert text into an rcode.
@param text: the texual rcode
@type text: string
@raises UnknownRcode: the rcode is unknown
@rtype: int
"""
if text.isdigit():
v = int(text)
if v >= 0 and v <= 4095:
return v
v = _by_text.get(text.upper())
if v is None:
raise UnknownRcode
return v | [
"def",
"from_text",
"(",
"text",
")",
":",
"if",
"text",
".",
"isdigit",
"(",
")",
":",
"v",
"=",
"int",
"(",
"text",
")",
"if",
"v",
">=",
"0",
"and",
"v",
"<=",
"4095",
":",
"return",
"v",
"v",
"=",
"_by_text",
".",
"get",
"(",
"text",
".",... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/rcode.py#L59-L75 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py | python | pooling_nchw_max | (
I=TensorDef(T1, S.N, S.C, S.OH * S.SH + S.KH * S.DH,
S.OW * S.SW + S.KW * S.DW),
K=TensorDef(T2, S.KH, S.KW, index_dims=[D.kh, D.kw]),
O=TensorDef(U, S.N, S.C, S.OH, S.OW, output=True),
strides=IndexAttrDef(S.SH, S.SW),
dilations=IndexAttrDef(S.DH, S.DW)) | Performs max pooling.
Numeric casting is performed on the input operand, promoting it to the same
data type as the accumulator/output. | Performs max pooling. | [
"Performs",
"max",
"pooling",
"."
] | def pooling_nchw_max(
I=TensorDef(T1, S.N, S.C, S.OH * S.SH + S.KH * S.DH,
S.OW * S.SW + S.KW * S.DW),
K=TensorDef(T2, S.KH, S.KW, index_dims=[D.kh, D.kw]),
O=TensorDef(U, S.N, S.C, S.OH, S.OW, output=True),
strides=IndexAttrDef(S.SH, S.SW),
dilations=IndexAttrDef(S.DH, S.DW)):
"""Performs max pooling.
Numeric casting is performed on the input operand, promoting it to the same
data type as the accumulator/output.
"""
implements(ConvolutionOpInterface)
domain(D.n, D.c, D.oh, D.ow, D.kh, D.kw)
O[D.n, D.c, D.oh, D.ow] = ReduceFn.max[D.kh, D.kw](
TypeFn.cast(
U, I[D.n, D.c, D.oh * S.SH + D.kh * S.DH,
D.ow * S.SW + D.kw * S.DW,])) | [
"def",
"pooling_nchw_max",
"(",
"I",
"=",
"TensorDef",
"(",
"T1",
",",
"S",
".",
"N",
",",
"S",
".",
"C",
",",
"S",
".",
"OH",
"*",
"S",
".",
"SH",
"+",
"S",
".",
"KH",
"*",
"S",
".",
"DH",
",",
"S",
".",
"OW",
"*",
"S",
".",
"SW",
"+",... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py#L508-L525 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/profiler/internal/flops_registry.py | python | _equal_flops | (graph, node) | return _binary_per_element_op_flops(graph, node) | Compute flops for Equal operation. | Compute flops for Equal operation. | [
"Compute",
"flops",
"for",
"Equal",
"operation",
"."
] | def _equal_flops(graph, node):
"""Compute flops for Equal operation."""
return _binary_per_element_op_flops(graph, node) | [
"def",
"_equal_flops",
"(",
"graph",
",",
"node",
")",
":",
"return",
"_binary_per_element_op_flops",
"(",
"graph",
",",
"node",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/profiler/internal/flops_registry.py#L220-L222 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListMainWindow.PaintWaterMark | (self, dc) | Draws a watermark at the bottom right of :class:`UltimateListCtrl`.
:param `dc`: an instance of :class:`DC`.
.. todo:: Better support for this is needed. | Draws a watermark at the bottom right of :class:`UltimateListCtrl`. | [
"Draws",
"a",
"watermark",
"at",
"the",
"bottom",
"right",
"of",
":",
"class",
":",
"UltimateListCtrl",
"."
] | def PaintWaterMark(self, dc):
"""
Draws a watermark at the bottom right of :class:`UltimateListCtrl`.
:param `dc`: an instance of :class:`DC`.
.. todo:: Better support for this is needed.
"""
if not self._waterMark:
return
width, height = self.CalcUnscrolledPosition(*self.GetClientSize())
bitmapW = self._waterMark.GetWidth()
bitmapH = self._waterMark.GetHeight()
x = width - bitmapW - 5
y = height - bitmapH - 5
dc.DrawBitmap(self._waterMark, x, y, True) | [
"def",
"PaintWaterMark",
"(",
"self",
",",
"dc",
")",
":",
"if",
"not",
"self",
".",
"_waterMark",
":",
"return",
"width",
",",
"height",
"=",
"self",
".",
"CalcUnscrolledPosition",
"(",
"*",
"self",
".",
"GetClientSize",
"(",
")",
")",
"bitmapW",
"=",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L7236-L7256 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/feature_column/feature_column_v2.py | python | EmbeddingColumn._get_dense_tensor_internal | (self, sparse_tensors, state_manager) | return self._get_dense_tensor_internal_helper(sparse_tensors,
embedding_weights) | Private method that follows the signature of get_dense_tensor. | Private method that follows the signature of get_dense_tensor. | [
"Private",
"method",
"that",
"follows",
"the",
"signature",
"of",
"get_dense_tensor",
"."
] | def _get_dense_tensor_internal(self, sparse_tensors, state_manager):
"""Private method that follows the signature of get_dense_tensor."""
embedding_weights = state_manager.get_variable(
self, name='embedding_weights')
return self._get_dense_tensor_internal_helper(sparse_tensors,
embedding_weights) | [
"def",
"_get_dense_tensor_internal",
"(",
"self",
",",
"sparse_tensors",
",",
"state_manager",
")",
":",
"embedding_weights",
"=",
"state_manager",
".",
"get_variable",
"(",
"self",
",",
"name",
"=",
"'embedding_weights'",
")",
"return",
"self",
".",
"_get_dense_ten... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/feature_column_v2.py#L3004-L3009 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/multiprocessing/__init__.py | python | Manager | () | return m | Returns a manager associated with a running server process
The managers methods such as `Lock()`, `Condition()` and `Queue()`
can be used to create shared objects. | Returns a manager associated with a running server process | [
"Returns",
"a",
"manager",
"associated",
"with",
"a",
"running",
"server",
"process"
] | def Manager():
'''
Returns a manager associated with a running server process
The managers methods such as `Lock()`, `Condition()` and `Queue()`
can be used to create shared objects.
'''
from multiprocessing.managers import SyncManager
m = SyncManager()
m.start()
return m | [
"def",
"Manager",
"(",
")",
":",
"from",
"multiprocessing",
".",
"managers",
"import",
"SyncManager",
"m",
"=",
"SyncManager",
"(",
")",
"m",
".",
"start",
"(",
")",
"return",
"m"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/multiprocessing/__init__.py#L89-L99 | |
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | prj/app/prj.py | python | System.image | (self) | return os.path.join(self.output, 'system') | The image of this system once built.
The system image is currently represented as the path to the linked executable.
In the future, more complex, class-based representations of system images might be introduced. | The image of this system once built.
The system image is currently represented as the path to the linked executable.
In the future, more complex, class-based representations of system images might be introduced. | [
"The",
"image",
"of",
"this",
"system",
"once",
"built",
".",
"The",
"system",
"image",
"is",
"currently",
"represented",
"as",
"the",
"path",
"to",
"the",
"linked",
"executable",
".",
"In",
"the",
"future",
"more",
"complex",
"class",
"-",
"based",
"repre... | def image(self):
"""The image of this system once built.
The system image is currently represented as the path to the linked executable.
In the future, more complex, class-based representations of system images might be introduced.
"""
return os.path.join(self.output, 'system') | [
"def",
"image",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"output",
",",
"'system'",
")"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/prj/app/prj.py#L670-L677 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | GraphicsContext.SetPen | (*args) | return _gdi_.GraphicsContext_SetPen(*args) | SetPen(self, GraphicsPen pen)
SetPen(self, Pen pen)
Sets the stroke pen | SetPen(self, GraphicsPen pen)
SetPen(self, Pen pen) | [
"SetPen",
"(",
"self",
"GraphicsPen",
"pen",
")",
"SetPen",
"(",
"self",
"Pen",
"pen",
")"
] | def SetPen(*args):
"""
SetPen(self, GraphicsPen pen)
SetPen(self, Pen pen)
Sets the stroke pen
"""
return _gdi_.GraphicsContext_SetPen(*args) | [
"def",
"SetPen",
"(",
"*",
"args",
")",
":",
"return",
"_gdi_",
".",
"GraphicsContext_SetPen",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L6310-L6317 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftobjects/pointarray.py | python | PointArray.onDocumentRestored | (self, obj) | return super(PointArray, self).onDocumentRestored(obj) | Execute code when the document is restored.
Add properties that don't exist and migrate old properties. | Execute code when the document is restored. | [
"Execute",
"code",
"when",
"the",
"document",
"is",
"restored",
"."
] | def onDocumentRestored(self, obj):
"""Execute code when the document is restored.
Add properties that don't exist and migrate old properties.
"""
# If the ExtraPlacement property has never been added before
# it will add it first, and set it to the base object's position
# in order to produce the same displacement as before.
# Then all the other properties will be processed.
properties = obj.PropertiesList
if "ExtraPlacement" not in properties:
_tip = QT_TRANSLATE_NOOP("App::Property", "Additional placement, shift and rotation, that will be applied to each copy")
obj.addProperty("App::PropertyPlacement",
"ExtraPlacement",
"Objects",
_tip)
obj.ExtraPlacement.Base = obj.Base.Placement.Base
_wrn("v0.19, " + obj.Label + ", " + translate("draft","added property 'ExtraPlacement'"))
self.set_properties(obj)
self.migrate_properties_0v19(obj)
return super(PointArray, self).onDocumentRestored(obj) | [
"def",
"onDocumentRestored",
"(",
"self",
",",
"obj",
")",
":",
"# If the ExtraPlacement property has never been added before",
"# it will add it first, and set it to the base object's position",
"# in order to produce the same displacement as before.",
"# Then all the other properties will be... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftobjects/pointarray.py#L127-L149 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/ragged/ragged_math_ops.py | python | reduce_min | (input_tensor: ragged_tensor.Ragged,
axis=None,
keepdims=None,
name=None) | return ragged_reduce_aggregate(
reduce_op=math_ops.reduce_min,
unsorted_segment_op=math_ops.unsorted_segment_min,
rt_input=input_tensor,
axis=axis,
keepdims=keepdims,
name=(name or 'RaggedReduceMin')) | For docs, see: _RAGGED_REDUCE_DOCSTRING. | For docs, see: _RAGGED_REDUCE_DOCSTRING. | [
"For",
"docs",
"see",
":",
"_RAGGED_REDUCE_DOCSTRING",
"."
] | def reduce_min(input_tensor: ragged_tensor.Ragged,
axis=None,
keepdims=None,
name=None):
"""For docs, see: _RAGGED_REDUCE_DOCSTRING."""
return ragged_reduce_aggregate(
reduce_op=math_ops.reduce_min,
unsorted_segment_op=math_ops.unsorted_segment_min,
rt_input=input_tensor,
axis=axis,
keepdims=keepdims,
name=(name or 'RaggedReduceMin')) | [
"def",
"reduce_min",
"(",
"input_tensor",
":",
"ragged_tensor",
".",
"Ragged",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"return",
"ragged_reduce_aggregate",
"(",
"reduce_op",
"=",
"math_ops",
".",
"reduce_mi... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_math_ops.py#L639-L650 | |
gklz1982/caffe-yolov2 | ebb27029db4ddc0d40e520634633b0fa9cdcc10d | scripts/cpp_lint.py | python | _IncludeState.CheckNextIncludeOrder | (self, header_type) | return '' | Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong. | Returns a non-empty error message if the next header is out of order. | [
"Returns",
"a",
"non",
"-",
"empty",
"error",
"message",
"if",
"the",
"next",
"header",
"is",
"out",
"of",
"order",
"."
] | def CheckNextIncludeOrder(self, header_type):
"""Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong.
"""
error_message = ('Found %s after %s' %
(self._TYPE_NAMES[header_type],
self._SECTION_NAMES[self._section]))
last_section = self._section
if header_type == _C_SYS_HEADER:
if self._section <= self._C_SECTION:
self._section = self._C_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _CPP_SYS_HEADER:
if self._section <= self._CPP_SECTION:
self._section = self._CPP_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _LIKELY_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
self._section = self._OTHER_H_SECTION
elif header_type == _POSSIBLE_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
# This will always be the fallback because we're not sure
# enough that the header is associated with this file.
self._section = self._OTHER_H_SECTION
else:
assert header_type == _OTHER_HEADER
self._section = self._OTHER_H_SECTION
if last_section != self._section:
self._last_header = ''
return '' | [
"def",
"CheckNextIncludeOrder",
"(",
"self",
",",
"header_type",
")",
":",
"error_message",
"=",
"(",
"'Found %s after %s'",
"%",
"(",
"self",
".",
"_TYPE_NAMES",
"[",
"header_type",
"]",
",",
"self",
".",
"_SECTION_NAMES",
"[",
"self",
".",
"_section",
"]",
... | https://github.com/gklz1982/caffe-yolov2/blob/ebb27029db4ddc0d40e520634633b0fa9cdcc10d/scripts/cpp_lint.py#L633-L684 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | StandardPaths_Get | (*args) | return _misc_.StandardPaths_Get(*args) | StandardPaths_Get() -> StandardPaths
Return the global standard paths singleton | StandardPaths_Get() -> StandardPaths | [
"StandardPaths_Get",
"()",
"-",
">",
"StandardPaths"
] | def StandardPaths_Get(*args):
"""
StandardPaths_Get() -> StandardPaths
Return the global standard paths singleton
"""
return _misc_.StandardPaths_Get(*args) | [
"def",
"StandardPaths_Get",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"StandardPaths_Get",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L6472-L6478 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/appController.py | python | AppController._getPrimsFromPaths | (self, paths) | return prims | Get all prims from a list of paths. | Get all prims from a list of paths. | [
"Get",
"all",
"prims",
"from",
"a",
"list",
"of",
"paths",
"."
] | def _getPrimsFromPaths(self, paths):
"""Get all prims from a list of paths."""
prims = []
for path in paths:
# Ensure we have an Sdf.Path, not a string.
sdfPath = Sdf.Path(str(path))
prim = self._dataModel.stage.GetPrimAtPath(
sdfPath.GetAbsoluteRootOrPrimPath())
if not prim:
raise PrimNotFoundException(sdfPath)
prims.append(prim)
return prims | [
"def",
"_getPrimsFromPaths",
"(",
"self",
",",
"paths",
")",
":",
"prims",
"=",
"[",
"]",
"for",
"path",
"in",
"paths",
":",
"# Ensure we have an Sdf.Path, not a string.",
"sdfPath",
"=",
"Sdf",
".",
"Path",
"(",
"str",
"(",
"path",
")",
")",
"prim",
"=",
... | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/appController.py#L3257-L3273 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/types.py | python | prepare_class | (name, bases=(), kwds=None) | return meta, ns, kwds | Call the __prepare__ method of the appropriate metaclass.
Returns (metaclass, namespace, kwds) as a 3-tuple
*metaclass* is the appropriate metaclass
*namespace* is the prepared class namespace
*kwds* is an updated copy of the passed in kwds argument with any
'metaclass' entry removed. If no kwds argument is passed in, this will
be an empty dict. | Call the __prepare__ method of the appropriate metaclass. | [
"Call",
"the",
"__prepare__",
"method",
"of",
"the",
"appropriate",
"metaclass",
"."
] | def prepare_class(name, bases=(), kwds=None):
"""Call the __prepare__ method of the appropriate metaclass.
Returns (metaclass, namespace, kwds) as a 3-tuple
*metaclass* is the appropriate metaclass
*namespace* is the prepared class namespace
*kwds* is an updated copy of the passed in kwds argument with any
'metaclass' entry removed. If no kwds argument is passed in, this will
be an empty dict.
"""
if kwds is None:
kwds = {}
else:
kwds = dict(kwds) # Don't alter the provided mapping
if 'metaclass' in kwds:
meta = kwds.pop('metaclass')
else:
if bases:
meta = type(bases[0])
else:
meta = type
if isinstance(meta, type):
# when meta is a type, we first determine the most-derived metaclass
# instead of invoking the initial candidate directly
meta = _calculate_meta(meta, bases)
if hasattr(meta, '__prepare__'):
ns = meta.__prepare__(name, bases, **kwds)
else:
ns = {}
return meta, ns, kwds | [
"def",
"prepare_class",
"(",
"name",
",",
"bases",
"=",
"(",
")",
",",
"kwds",
"=",
"None",
")",
":",
"if",
"kwds",
"is",
"None",
":",
"kwds",
"=",
"{",
"}",
"else",
":",
"kwds",
"=",
"dict",
"(",
"kwds",
")",
"# Don't alter the provided mapping",
"i... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/types.py#L93-L123 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | Grid_GetClassDefaultAttributes | (*args, **kwargs) | return _grid.Grid_GetClassDefaultAttributes(*args, **kwargs) | Grid_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this. | Grid_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes | [
"Grid_GetClassDefaultAttributes",
"(",
"int",
"variant",
"=",
"WINDOW_VARIANT_NORMAL",
")",
"-",
">",
"VisualAttributes"
] | def Grid_GetClassDefaultAttributes(*args, **kwargs):
"""
Grid_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _grid.Grid_GetClassDefaultAttributes(*args, **kwargs) | [
"def",
"Grid_GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L2261-L2276 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/thrift/TMultiplexedProcessor.py | python | TMultiplexedProcessor.registerDefault | (self, processor) | If a non-multiplexed processor connects to the server and wants to
communicate, use the given processor to handle it. This mechanism
allows servers to upgrade from non-multiplexed to multiplexed in a
backwards-compatible way and still handle old clients. | If a non-multiplexed processor connects to the server and wants to
communicate, use the given processor to handle it. This mechanism
allows servers to upgrade from non-multiplexed to multiplexed in a
backwards-compatible way and still handle old clients. | [
"If",
"a",
"non",
"-",
"multiplexed",
"processor",
"connects",
"to",
"the",
"server",
"and",
"wants",
"to",
"communicate",
"use",
"the",
"given",
"processor",
"to",
"handle",
"it",
".",
"This",
"mechanism",
"allows",
"servers",
"to",
"upgrade",
"from",
"non"... | def registerDefault(self, processor):
"""
If a non-multiplexed processor connects to the server and wants to
communicate, use the given processor to handle it. This mechanism
allows servers to upgrade from non-multiplexed to multiplexed in a
backwards-compatible way and still handle old clients.
"""
self.defaultProcessor = processor | [
"def",
"registerDefault",
"(",
"self",
",",
"processor",
")",
":",
"self",
".",
"defaultProcessor",
"=",
"processor"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/thrift/TMultiplexedProcessor.py#L30-L37 | ||
fengbingchun/NN_Test | d6305825d5273e4569ccd1eda9ffa2a9c72e18d2 | src/tiny-dnn/third_party/gemmlowp/meta/generators/qnt_Nx8_neon.py | python | GenerateMultiQuantize | (emitter, aligned, rows) | Emit main quantization code that switches between optimized versions. | Emit main quantization code that switches between optimized versions. | [
"Emit",
"main",
"quantization",
"code",
"that",
"switches",
"between",
"optimized",
"versions",
"."
] | def GenerateMultiQuantize(emitter, aligned, rows):
"""Emit main quantization code that switches between optimized versions."""
name = BuildMultiQuantizeName(aligned, rows)
emitter.EmitFunctionBeginA(name, [['const std::int32_t*', 'source'],
['std::int32_t', 'count'],
['std::int32_t', 'stride'],
['const std::int32_t*', 'offsets'],
['std::uint8_t*', 'destination'],
['std::int32_t', 'destination_stride'],
['std::int32_t', 'multiplicative_offset'],
['std::int32_t', 'rounding_offset'],
['std::int32_t', 'shift']], 'void')
emitter.EmitSwitch('count % 8')
for leftovers in range(8):
emitter.EmitCase(leftovers)
emitter.PushIndent()
emitter.EmitCall(
BuildName(rows, leftovers, aligned),
['source', 'count', 'stride', 'offsets', 'destination',
'destination_stride', 'multiplicative_offset', 'rounding_offset',
'shift'])
emitter.EmitBreak()
emitter.PopIndent()
emitter.EmitSwitchEnd()
emitter.EmitFunctionEnd() | [
"def",
"GenerateMultiQuantize",
"(",
"emitter",
",",
"aligned",
",",
"rows",
")",
":",
"name",
"=",
"BuildMultiQuantizeName",
"(",
"aligned",
",",
"rows",
")",
"emitter",
".",
"EmitFunctionBeginA",
"(",
"name",
",",
"[",
"[",
"'const std::int32_t*'",
",",
"'so... | https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/gemmlowp/meta/generators/qnt_Nx8_neon.py#L221-L247 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py | python | Decimal.__mul__ | (self, other, context=None) | return ans | Return self * other.
(+-) INF * 0 (or its reverse) raise InvalidOperation. | Return self * other. | [
"Return",
"self",
"*",
"other",
"."
] | def __mul__(self, other, context=None):
"""Return self * other.
(+-) INF * 0 (or its reverse) raise InvalidOperation.
"""
other = _convert_other(other)
if other is NotImplemented:
return other
if context is None:
context = getcontext()
resultsign = self._sign ^ other._sign
if self._is_special or other._is_special:
ans = self._check_nans(other, context)
if ans:
return ans
if self._isinfinity():
if not other:
return context._raise_error(InvalidOperation, '(+-)INF * 0')
return _SignedInfinity[resultsign]
if other._isinfinity():
if not self:
return context._raise_error(InvalidOperation, '0 * (+-)INF')
return _SignedInfinity[resultsign]
resultexp = self._exp + other._exp
# Special case for multiplying by zero
if not self or not other:
ans = _dec_from_triple(resultsign, '0', resultexp)
# Fixing in case the exponent is out of bounds
ans = ans._fix(context)
return ans
# Special case for multiplying by power of 10
if self._int == '1':
ans = _dec_from_triple(resultsign, other._int, resultexp)
ans = ans._fix(context)
return ans
if other._int == '1':
ans = _dec_from_triple(resultsign, self._int, resultexp)
ans = ans._fix(context)
return ans
op1 = _WorkRep(self)
op2 = _WorkRep(other)
ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
ans = ans._fix(context)
return ans | [
"def",
"__mul__",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
")",
"if",
"other",
"is",
"NotImplemented",
":",
"return",
"other",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"g... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py#L1236-L1290 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/polynomial/polyutils.py | python | mapparms | (old, new) | return off, scl | Linear map parameters between domains.
Return the parameters of the linear map ``offset + scale*x`` that maps
`old` to `new` such that ``old[i] -> new[i]``, ``i = 0, 1``.
Parameters
----------
old, new : array_like
Domains. Each domain must (successfully) convert to a 1-d array
containing precisely two values.
Returns
-------
offset, scale : scalars
The map ``L(x) = offset + scale*x`` maps the first domain to the
second.
See Also
--------
getdomain, mapdomain
Notes
-----
Also works for complex numbers, and thus can be used to calculate the
parameters required to map any line in the complex plane to any other
line therein.
Examples
--------
>>> from numpy import polynomial as P
>>> P.mapparms((-1,1),(-1,1))
(0.0, 1.0)
>>> P.mapparms((1,-1),(-1,1))
(0.0, -1.0)
>>> i = complex(0,1)
>>> P.mapparms((-i,-1),(1,i))
((1+1j), (1+0j)) | Linear map parameters between domains. | [
"Linear",
"map",
"parameters",
"between",
"domains",
"."
] | def mapparms(old, new) :
"""
Linear map parameters between domains.
Return the parameters of the linear map ``offset + scale*x`` that maps
`old` to `new` such that ``old[i] -> new[i]``, ``i = 0, 1``.
Parameters
----------
old, new : array_like
Domains. Each domain must (successfully) convert to a 1-d array
containing precisely two values.
Returns
-------
offset, scale : scalars
The map ``L(x) = offset + scale*x`` maps the first domain to the
second.
See Also
--------
getdomain, mapdomain
Notes
-----
Also works for complex numbers, and thus can be used to calculate the
parameters required to map any line in the complex plane to any other
line therein.
Examples
--------
>>> from numpy import polynomial as P
>>> P.mapparms((-1,1),(-1,1))
(0.0, 1.0)
>>> P.mapparms((1,-1),(-1,1))
(0.0, -1.0)
>>> i = complex(0,1)
>>> P.mapparms((-i,-1),(1,i))
((1+1j), (1+0j))
"""
oldlen = old[1] - old[0]
newlen = new[1] - new[0]
off = (old[1]*new[0] - old[0]*new[1])/oldlen
scl = newlen/oldlen
return off, scl | [
"def",
"mapparms",
"(",
"old",
",",
"new",
")",
":",
"oldlen",
"=",
"old",
"[",
"1",
"]",
"-",
"old",
"[",
"0",
"]",
"newlen",
"=",
"new",
"[",
"1",
"]",
"-",
"new",
"[",
"0",
"]",
"off",
"=",
"(",
"old",
"[",
"1",
"]",
"*",
"new",
"[",
... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/polynomial/polyutils.py#L282-L327 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/framework/convert_to_constants.py | python | _ConverterData.graph_def | (self) | return self._graph_def | The graph to be converted. | The graph to be converted. | [
"The",
"graph",
"to",
"be",
"converted",
"."
] | def graph_def(self):
"""The graph to be converted."""
return self._graph_def | [
"def",
"graph_def",
"(",
"self",
")",
":",
"return",
"self",
".",
"_graph_def"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/convert_to_constants.py#L730-L732 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/sslproto.py | python | SSLProtocol.connection_lost | (self, exc) | Called when the low-level connection is lost or closed.
The argument is an exception object or None (the latter
meaning a regular EOF is received or the connection was
aborted or closed). | Called when the low-level connection is lost or closed. | [
"Called",
"when",
"the",
"low",
"-",
"level",
"connection",
"is",
"lost",
"or",
"closed",
"."
] | def connection_lost(self, exc):
"""Called when the low-level connection is lost or closed.
The argument is an exception object or None (the latter
meaning a regular EOF is received or the connection was
aborted or closed).
"""
if self._session_established:
self._session_established = False
self._loop.call_soon(self._app_protocol.connection_lost, exc)
else:
# Most likely an exception occurred while in SSL handshake.
# Just mark the app transport as closed so that its __del__
# doesn't complain.
if self._app_transport is not None:
self._app_transport._closed = True
self._transport = None
self._app_transport = None
if getattr(self, '_handshake_timeout_handle', None):
self._handshake_timeout_handle.cancel()
self._wakeup_waiter(exc)
self._app_protocol = None
self._sslpipe = None | [
"def",
"connection_lost",
"(",
"self",
",",
"exc",
")",
":",
"if",
"self",
".",
"_session_established",
":",
"self",
".",
"_session_established",
"=",
"False",
"self",
".",
"_loop",
".",
"call_soon",
"(",
"self",
".",
"_app_protocol",
".",
"connection_lost",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/sslproto.py#L484-L506 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/DraftVecUtils.py | python | isColinear | (vlist) | return True | Check if the vectors in the list are colinear.
Colinear vectors are those whose angle between them is zero.
This function tests for colinearity between the difference
of the first two vectors, and the difference of the nth vector with
the first vector.
::
vlist = [a, b, c, d, ..., n]
k = b - a
k2 = c - a
k3 = d - a
kn = n - a
Then test
::
angle(k2, k) == 0
angle(k3, k) == 0
angle(kn, k) == 0
Parameters
----------
vlist : list
List of Base::Vector3 vectors.
At least three elements must be present.
Returns
-------
bool
`True` if the vector differences are colinear,
or if the list only has two vectors.
`False` otherwise.
Notes
-----
Due to rounding errors, the angle may not be exactly zero;
therefore, it rounds the angle by the number
of decimals specified in the `precision` parameter
in the parameter database, and then compares the value to zero. | Check if the vectors in the list are colinear. | [
"Check",
"if",
"the",
"vectors",
"in",
"the",
"list",
"are",
"colinear",
"."
] | def isColinear(vlist):
"""Check if the vectors in the list are colinear.
Colinear vectors are those whose angle between them is zero.
This function tests for colinearity between the difference
of the first two vectors, and the difference of the nth vector with
the first vector.
::
vlist = [a, b, c, d, ..., n]
k = b - a
k2 = c - a
k3 = d - a
kn = n - a
Then test
::
angle(k2, k) == 0
angle(k3, k) == 0
angle(kn, k) == 0
Parameters
----------
vlist : list
List of Base::Vector3 vectors.
At least three elements must be present.
Returns
-------
bool
`True` if the vector differences are colinear,
or if the list only has two vectors.
`False` otherwise.
Notes
-----
Due to rounding errors, the angle may not be exactly zero;
therefore, it rounds the angle by the number
of decimals specified in the `precision` parameter
in the parameter database, and then compares the value to zero.
"""
typecheck([(vlist, list)], "isColinear")
# Return True if the list only has two vectors, why?
# This doesn't test for colinearity between the first two vectors.
if len(vlist) < 3:
return True
p = precision()
# Difference between the second vector and the first one
first = vlist[1].sub(vlist[0])
# Start testing from the third vector and onward
for i in range(2, len(vlist)):
# Difference between the 3rd vector and onward, and the first one.
diff = vlist[i].sub(vlist[0])
# The angle between the difference and the first difference.
_angle = angle(diff, first)
if round(_angle, p) != 0:
return False
return True | [
"def",
"isColinear",
"(",
"vlist",
")",
":",
"typecheck",
"(",
"[",
"(",
"vlist",
",",
"list",
")",
"]",
",",
"\"isColinear\"",
")",
"# Return True if the list only has two vectors, why?",
"# This doesn't test for colinearity between the first two vectors.",
"if",
"len",
... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/DraftVecUtils.py#L651-L716 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | GridTableBase.GetNumberRows | (*args, **kwargs) | return _grid.GridTableBase_GetNumberRows(*args, **kwargs) | GetNumberRows(self) -> int | GetNumberRows(self) -> int | [
"GetNumberRows",
"(",
"self",
")",
"-",
">",
"int"
] | def GetNumberRows(*args, **kwargs):
"""GetNumberRows(self) -> int"""
return _grid.GridTableBase_GetNumberRows(*args, **kwargs) | [
"def",
"GetNumberRows",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridTableBase_GetNumberRows",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L802-L804 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/lockfile/__init__.py | python | MkdirFileLock | (*args, **kwds) | return _fl_helper(mkdirlockfile.MkdirLockFile, "lockfile.mkdirlockfile",
*args, **kwds) | Factory function provided for backwards compatibility.
Do not use in new code. Instead, import MkdirLockFile from the
lockfile.mkdirlockfile module. | Factory function provided for backwards compatibility. | [
"Factory",
"function",
"provided",
"for",
"backwards",
"compatibility",
"."
] | def MkdirFileLock(*args, **kwds):
"""Factory function provided for backwards compatibility.
Do not use in new code. Instead, import MkdirLockFile from the
lockfile.mkdirlockfile module.
"""
from . import mkdirlockfile
return _fl_helper(mkdirlockfile.MkdirLockFile, "lockfile.mkdirlockfile",
*args, **kwds) | [
"def",
"MkdirFileLock",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"from",
".",
"import",
"mkdirlockfile",
"return",
"_fl_helper",
"(",
"mkdirlockfile",
".",
"MkdirLockFile",
",",
"\"lockfile.mkdirlockfile\"",
",",
"*",
"args",
",",
"*",
"*",
"kwds",... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/lockfile/__init__.py#L293-L301 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/cross_device_utils.py | python | sum_grad_and_var_all_reduce | (grad_and_vars,
num_workers,
alg,
gpu_indices,
aux_devices=None,
num_shards=1) | return result | Apply all-reduce algorithm over specified gradient tensors. | Apply all-reduce algorithm over specified gradient tensors. | [
"Apply",
"all",
"-",
"reduce",
"algorithm",
"over",
"specified",
"gradient",
"tensors",
"."
] | def sum_grad_and_var_all_reduce(grad_and_vars,
num_workers,
alg,
gpu_indices,
aux_devices=None,
num_shards=1):
"""Apply all-reduce algorithm over specified gradient tensors."""
with ops.name_scope('allreduce'):
# Note that each grad_and_vars looks like the following:
# ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))
scaled_grads = [g for g, _ in grad_and_vars]
if alg == 'nccl':
summed_grads = nccl_ops.all_sum(scaled_grads)
elif alg == 'xring':
summed_grads = all_reduce.build_ring_all_reduce(
scaled_grads, num_workers, num_shards, gpu_indices, math_ops.add)
elif alg == 'nccl/xring':
summed_grads = all_reduce.build_nccl_then_ring(scaled_grads, num_shards,
math_ops.add)
elif alg == 'nccl/rechd':
summed_grads = all_reduce.build_nccl_then_recursive_hd(
scaled_grads, math_ops.add)
elif alg == 'nccl/pscpu':
summed_grads = all_reduce.build_nccl_then_shuffle(
scaled_grads, aux_devices, math_ops.add, math_ops.add_n)
elif alg == 'pscpu/pscpu':
second_gather_devices = aux_devices[:num_shards]
summed_grads = all_reduce.build_shuffle_then_shuffle(
scaled_grads, aux_devices, second_gather_devices, math_ops.add_n)
elif alg in ['pscpu', 'psgpu']:
summed_grads = all_reduce.build_shuffle_all_reduce(
scaled_grads, aux_devices, math_ops.add_n)
else:
raise ValueError('unsupported all_reduce alg: ', alg)
result = []
for (_, v), g in zip(grad_and_vars, summed_grads):
result.append([g, v])
return result | [
"def",
"sum_grad_and_var_all_reduce",
"(",
"grad_and_vars",
",",
"num_workers",
",",
"alg",
",",
"gpu_indices",
",",
"aux_devices",
"=",
"None",
",",
"num_shards",
"=",
"1",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"'allreduce'",
")",
":",
"# Note that... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/cross_device_utils.py#L411-L449 | |
GoSSIP-SJTU/Armariris | ad5d868482956b2194a77b39c8d543c7c2318200 | utils/llvm-build/llvmbuild/main.py | python | add_magic_target_components | (parser, project, opts) | add_magic_target_components(project, opts) -> None
Add the "magic" target based components to the project, which can only be
determined based on the target configuration options.
This currently is responsible for populating the required_libraries list of
the "all-targets", "Native", "NativeCodeGen", and "Engine" components. | add_magic_target_components(project, opts) -> None | [
"add_magic_target_components",
"(",
"project",
"opts",
")",
"-",
">",
"None"
] | def add_magic_target_components(parser, project, opts):
"""add_magic_target_components(project, opts) -> None
Add the "magic" target based components to the project, which can only be
determined based on the target configuration options.
This currently is responsible for populating the required_libraries list of
the "all-targets", "Native", "NativeCodeGen", and "Engine" components.
"""
# Determine the available targets.
available_targets = dict((ci.name,ci)
for ci in project.component_infos
if ci.type_name == 'TargetGroup')
# Find the configured native target.
# We handle a few special cases of target names here for historical
# reasons, as these are the names configure currently comes up with.
native_target_name = { 'x86' : 'X86',
'x86_64' : 'X86',
'Unknown' : None }.get(opts.native_target,
opts.native_target)
if native_target_name is None:
native_target = None
else:
native_target = available_targets.get(native_target_name)
if native_target is None:
parser.error("invalid native target: %r (not in project)" % (
opts.native_target,))
if native_target.type_name != 'TargetGroup':
parser.error("invalid native target: %r (not a target)" % (
opts.native_target,))
# Find the list of targets to enable.
if opts.enable_targets is None:
enable_targets = available_targets.values()
else:
# We support both space separated and semi-colon separated lists.
if opts.enable_targets == '':
enable_target_names = []
elif ' ' in opts.enable_targets:
enable_target_names = opts.enable_targets.split()
else:
enable_target_names = opts.enable_targets.split(';')
enable_targets = []
for name in enable_target_names:
target = available_targets.get(name)
if target is None:
parser.error("invalid target to enable: %r (not in project)" % (
name,))
if target.type_name != 'TargetGroup':
parser.error("invalid target to enable: %r (not a target)" % (
name,))
enable_targets.append(target)
# Find the special library groups we are going to populate. We enforce that
# these appear in the project (instead of just adding them) so that they at
# least have an explicit representation in the project LLVMBuild files (and
# comments explaining how they are populated).
def find_special_group(name):
info = info_map.get(name)
if info is None:
fatal("expected project to contain special %r component" % (
name,))
if info.type_name != 'LibraryGroup':
fatal("special component %r should be a LibraryGroup" % (
name,))
if info.required_libraries:
fatal("special component %r must have empty %r list" % (
name, 'required_libraries'))
if info.add_to_library_groups:
fatal("special component %r must have empty %r list" % (
name, 'add_to_library_groups'))
info._is_special_group = True
return info
info_map = dict((ci.name, ci) for ci in project.component_infos)
all_targets = find_special_group('all-targets')
native_group = find_special_group('Native')
native_codegen_group = find_special_group('NativeCodeGen')
engine_group = find_special_group('Engine')
# Set the enabled bit in all the target groups, and append to the
# all-targets list.
for ci in enable_targets:
all_targets.required_libraries.append(ci.name)
ci.enabled = True
# If we have a native target, then that defines the native and
# native_codegen libraries.
if native_target and native_target.enabled:
native_group.required_libraries.append(native_target.name)
native_codegen_group.required_libraries.append(
'%sCodeGen' % native_target.name)
# If we have a native target with a JIT, use that for the engine. Otherwise,
# use the interpreter.
if native_target and native_target.enabled and native_target.has_jit:
engine_group.required_libraries.append('MCJIT')
engine_group.required_libraries.append(native_group.name)
else:
engine_group.required_libraries.append('Interpreter') | [
"def",
"add_magic_target_components",
"(",
"parser",
",",
"project",
",",
"opts",
")",
":",
"# Determine the available targets.",
"available_targets",
"=",
"dict",
"(",
"(",
"ci",
".",
"name",
",",
"ci",
")",
"for",
"ci",
"in",
"project",
".",
"component_infos",... | https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/utils/llvm-build/llvmbuild/main.py#L735-L841 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/graph_util.py | python | set_cpu0 | (device_string) | return parsed_device.to_string() | Creates a new device string based on `device_string' but using /CPU:0.
If the device is already on /CPU:0, this is a no-op.
Args:
device_string: A device string.
Returns:
A device string. | Creates a new device string based on `device_string' but using /CPU:0. | [
"Creates",
"a",
"new",
"device",
"string",
"based",
"on",
"device_string",
"but",
"using",
"/",
"CPU",
":",
"0",
"."
] | def set_cpu0(device_string):
"""Creates a new device string based on `device_string' but using /CPU:0.
If the device is already on /CPU:0, this is a no-op.
Args:
device_string: A device string.
Returns:
A device string.
"""
parsed_device = pydev.DeviceSpec.from_string(device_string)
parsed_device.device_type = "CPU"
parsed_device.device_index = 0
return parsed_device.to_string() | [
"def",
"set_cpu0",
"(",
"device_string",
")",
":",
"parsed_device",
"=",
"pydev",
".",
"DeviceSpec",
".",
"from_string",
"(",
"device_string",
")",
"parsed_device",
".",
"device_type",
"=",
"\"CPU\"",
"parsed_device",
".",
"device_index",
"=",
"0",
"return",
"pa... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/graph_util.py#L50-L64 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/SimpleHTTPServer.py | python | SimpleHTTPRequestHandler.do_HEAD | (self) | Serve a HEAD request. | Serve a HEAD request. | [
"Serve",
"a",
"HEAD",
"request",
"."
] | def do_HEAD(self):
"""Serve a HEAD request."""
f = self.send_head()
if f:
f.close() | [
"def",
"do_HEAD",
"(",
"self",
")",
":",
"f",
"=",
"self",
".",
"send_head",
"(",
")",
"if",
"f",
":",
"f",
".",
"close",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/SimpleHTTPServer.py#L49-L53 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/ogl/_composit.py | python | DivisionShape.ResizeAdjoining | (self, side, newPos, test) | return True | Resize adjoining divisions at the given side.
If test is TRUE, just see whether it's possible for each adjoining
region, returning FALSE if it's not.
side can be one of:
* DIVISION_SIDE_NONE
* DIVISION_SIDE_LEFT
* DIVISION_SIDE_TOP
* DIVISION_SIDE_RIGHT
* DIVISION_SIDE_BOTTOM | Resize adjoining divisions at the given side. | [
"Resize",
"adjoining",
"divisions",
"at",
"the",
"given",
"side",
"."
] | def ResizeAdjoining(self, side, newPos, test):
"""Resize adjoining divisions at the given side.
If test is TRUE, just see whether it's possible for each adjoining
region, returning FALSE if it's not.
side can be one of:
* DIVISION_SIDE_NONE
* DIVISION_SIDE_LEFT
* DIVISION_SIDE_TOP
* DIVISION_SIDE_RIGHT
* DIVISION_SIDE_BOTTOM
"""
divisionParent = self.GetParent()
for division in divisionParent.GetDivisions():
if side == DIVISION_SIDE_LEFT:
if division._rightSide == self:
success = division.AdjustRight(newPos, test)
if not success and test:
return false
elif side == DIVISION_SIDE_TOP:
if division._bottomSide == self:
success = division.AdjustBottom(newPos, test)
if not success and test:
return False
elif side == DIVISION_SIDE_RIGHT:
if division._leftSide == self:
success = division.AdjustLeft(newPos, test)
if not success and test:
return False
elif side == DIVISION_SIDE_BOTTOM:
if division._topSide == self:
success = division.AdjustTop(newPos, test)
if not success and test:
return False
return True | [
"def",
"ResizeAdjoining",
"(",
"self",
",",
"side",
",",
"newPos",
",",
"test",
")",
":",
"divisionParent",
"=",
"self",
".",
"GetParent",
"(",
")",
"for",
"division",
"in",
"divisionParent",
".",
"GetDivisions",
"(",
")",
":",
"if",
"side",
"==",
"DIVIS... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_composit.py#L1378-L1414 | |
tensorflow/ngraph-bridge | ea6422491ec75504e78a63db029e7f74ec3479a5 | examples/mnist/mnist_deep_simplified.py | python | conv2d | (x, W) | return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') | conv2d returns a 2d convolution layer with full stride. | conv2d returns a 2d convolution layer with full stride. | [
"conv2d",
"returns",
"a",
"2d",
"convolution",
"layer",
"with",
"full",
"stride",
"."
] | def conv2d(x, W):
"""conv2d returns a 2d convolution layer with full stride."""
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') | [
"def",
"conv2d",
"(",
"x",
",",
"W",
")",
":",
"return",
"tf",
".",
"nn",
".",
"conv2d",
"(",
"x",
",",
"W",
",",
"strides",
"=",
"[",
"1",
",",
"1",
",",
"1",
",",
"1",
"]",
",",
"padding",
"=",
"'SAME'",
")"
] | https://github.com/tensorflow/ngraph-bridge/blob/ea6422491ec75504e78a63db029e7f74ec3479a5/examples/mnist/mnist_deep_simplified.py#L106-L108 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | modules/freetype2/src/tools/docmaker/content.py | python | DocBlock.get_markup | ( self, tag_name ) | return None | return the DocMarkup corresponding to a given tag in a block | return the DocMarkup corresponding to a given tag in a block | [
"return",
"the",
"DocMarkup",
"corresponding",
"to",
"a",
"given",
"tag",
"in",
"a",
"block"
] | def get_markup( self, tag_name ):
"""return the DocMarkup corresponding to a given tag in a block"""
for m in self.markups:
if m.tag == string.lower( tag_name ):
return m
return None | [
"def",
"get_markup",
"(",
"self",
",",
"tag_name",
")",
":",
"for",
"m",
"in",
"self",
".",
"markups",
":",
"if",
"m",
".",
"tag",
"==",
"string",
".",
"lower",
"(",
"tag_name",
")",
":",
"return",
"m",
"return",
"None"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/modules/freetype2/src/tools/docmaker/content.py#L542-L547 | |
CanalTP/navitia | cb84ce9859070187e708818b058e6a7e0b7f891b | source/tyr/tyr/external_service.py | python | ExternalService.delete | (self, id=None, version=0) | Delete an external service in db, i.e. set parameter DISCARDED to TRUE | Delete an external service in db, i.e. set parameter DISCARDED to TRUE | [
"Delete",
"an",
"external",
"service",
"in",
"db",
"i",
".",
"e",
".",
"set",
"parameter",
"DISCARDED",
"to",
"TRUE"
] | def delete(self, id=None, version=0):
"""
Delete an external service in db, i.e. set parameter DISCARDED to TRUE
"""
if not id:
abort(400, status="error", message='id is required')
try:
provider = models.ExternalService.find_by_id(id)
provider.discarded = True
models.db.session.commit()
return None, 204
except sqlalchemy.orm.exc.NoResultFound:
abort(404, status="error", message='object not found') | [
"def",
"delete",
"(",
"self",
",",
"id",
"=",
"None",
",",
"version",
"=",
"0",
")",
":",
"if",
"not",
"id",
":",
"abort",
"(",
"400",
",",
"status",
"=",
"\"error\"",
",",
"message",
"=",
"'id is required'",
")",
"try",
":",
"provider",
"=",
"mode... | https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/tyr/tyr/external_service.py#L77-L89 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/linalg/basic.py | python | pinvh | (a, cond=None, rcond=None, lower=True, return_rank=False,
check_finite=True) | Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix.
Calculate a generalized inverse of a Hermitian or real symmetric matrix
using its eigenvalue decomposition and including all eigenvalues with
'large' absolute value.
Parameters
----------
a : (N, N) array_like
Real symmetric or complex hermetian matrix to be pseudo-inverted
cond, rcond : float or None
Cutoff for 'small' eigenvalues.
Singular values smaller than rcond * largest_eigenvalue are considered
zero.
If None or -1, suitable machine precision is used.
lower : bool, optional
Whether the pertinent array data is taken from the lower or upper
triangle of a. (Default: lower)
return_rank : bool, optional
if True, return the effective rank of the matrix
check_finite : bool, optional
Whether to check that the input matrix contains only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Returns
-------
B : (N, N) ndarray
The pseudo-inverse of matrix `a`.
rank : int
The effective rank of the matrix. Returned if return_rank == True
Raises
------
LinAlgError
If eigenvalue does not converge
Examples
--------
>>> from scipy.linalg import pinvh
>>> a = np.random.randn(9, 6)
>>> a = np.dot(a, a.T)
>>> B = pinvh(a)
>>> np.allclose(a, np.dot(a, np.dot(B, a)))
True
>>> np.allclose(B, np.dot(B, np.dot(a, B)))
True | Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix. | [
"Compute",
"the",
"(",
"Moore",
"-",
"Penrose",
")",
"pseudo",
"-",
"inverse",
"of",
"a",
"Hermitian",
"matrix",
"."
] | def pinvh(a, cond=None, rcond=None, lower=True, return_rank=False,
check_finite=True):
"""
Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix.
Calculate a generalized inverse of a Hermitian or real symmetric matrix
using its eigenvalue decomposition and including all eigenvalues with
'large' absolute value.
Parameters
----------
a : (N, N) array_like
Real symmetric or complex hermetian matrix to be pseudo-inverted
cond, rcond : float or None
Cutoff for 'small' eigenvalues.
Singular values smaller than rcond * largest_eigenvalue are considered
zero.
If None or -1, suitable machine precision is used.
lower : bool, optional
Whether the pertinent array data is taken from the lower or upper
triangle of a. (Default: lower)
return_rank : bool, optional
if True, return the effective rank of the matrix
check_finite : bool, optional
Whether to check that the input matrix contains only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Returns
-------
B : (N, N) ndarray
The pseudo-inverse of matrix `a`.
rank : int
The effective rank of the matrix. Returned if return_rank == True
Raises
------
LinAlgError
If eigenvalue does not converge
Examples
--------
>>> from scipy.linalg import pinvh
>>> a = np.random.randn(9, 6)
>>> a = np.dot(a, a.T)
>>> B = pinvh(a)
>>> np.allclose(a, np.dot(a, np.dot(B, a)))
True
>>> np.allclose(B, np.dot(B, np.dot(a, B)))
True
"""
a = _asarray_validated(a, check_finite=check_finite)
s, u = decomp.eigh(a, lower=lower, check_finite=False)
if rcond is not None:
cond = rcond
if cond in [None, -1]:
t = u.dtype.char.lower()
factor = {'f': 1E3, 'd': 1E6}
cond = factor[t] * np.finfo(t).eps
# For Hermitian matrices, singular values equal abs(eigenvalues)
above_cutoff = (abs(s) > cond * np.max(abs(s)))
psigma_diag = 1.0 / s[above_cutoff]
u = u[:, above_cutoff]
B = np.dot(u * psigma_diag, np.conjugate(u).T)
if return_rank:
return B, len(psigma_diag)
else:
return B | [
"def",
"pinvh",
"(",
"a",
",",
"cond",
"=",
"None",
",",
"rcond",
"=",
"None",
",",
"lower",
"=",
"True",
",",
"return_rank",
"=",
"False",
",",
"check_finite",
"=",
"True",
")",
":",
"a",
"=",
"_asarray_validated",
"(",
"a",
",",
"check_finite",
"="... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/linalg/basic.py#L1397-L1470 | ||
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | clang/bindings/python/clang/cindex.py | python | Type.spelling | (self) | return conf.lib.clang_getTypeSpelling(self) | Retrieve the spelling of this Type. | Retrieve the spelling of this Type. | [
"Retrieve",
"the",
"spelling",
"of",
"this",
"Type",
"."
] | def spelling(self):
"""Retrieve the spelling of this Type."""
return conf.lib.clang_getTypeSpelling(self) | [
"def",
"spelling",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTypeSpelling",
"(",
"self",
")"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/bindings/python/clang/cindex.py#L2427-L2429 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | Globable.popending | (self, expected = None) | return ending | Pop the ending found at the current position | Pop the ending found at the current position | [
"Pop",
"the",
"ending",
"found",
"at",
"the",
"current",
"position"
] | def popending(self, expected = None):
"Pop the ending found at the current position"
if self.isout() and self.leavepending:
return expected
ending = self.endinglist.pop(self)
if expected and expected != ending:
Trace.error('Expected ending ' + expected + ', got ' + ending)
self.skip(ending)
return ending | [
"def",
"popending",
"(",
"self",
",",
"expected",
"=",
"None",
")",
":",
"if",
"self",
".",
"isout",
"(",
")",
"and",
"self",
".",
"leavepending",
":",
"return",
"expected",
"ending",
"=",
"self",
".",
"endinglist",
".",
"pop",
"(",
"self",
")",
"if"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L1920-L1928 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/examples/python/gdbremote.py | python | TerminalColors.reset | (self) | return '' | Reset all terminal colors and formatting. | Reset all terminal colors and formatting. | [
"Reset",
"all",
"terminal",
"colors",
"and",
"formatting",
"."
] | def reset(self):
'''Reset all terminal colors and formatting.'''
if self.enabled:
return "\x1b[0m"
return '' | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"enabled",
":",
"return",
"\"\\x1b[0m\"",
"return",
"''"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/examples/python/gdbremote.py#L50-L54 | |
casadi/casadi | 8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff | misc/cpplint.py | python | CheckSpacingForFunctionCall | (filename, line, linenum, error) | Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for the correctness of various spacing around function calls. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"around",
"function",
"calls",
"."
] | def CheckSpacingForFunctionCall(filename, line, linenum, error):
"""Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Since function calls often occur inside if/for/while/switch
# expressions - which have their own, more liberal conventions - we
# first see if we should be looking inside such an expression for a
# function call, to which we can apply more strict standards.
fncall = line # if there's no control flow construct, look at whole line
for pattern in (r'\bif\s*\((.*)\)\s*{',
r'\bfor\s*\((.*)\)\s*{',
r'\bwhile\s*\((.*)\)\s*[{;]',
r'\bswitch\s*\((.*)\)\s*{'):
match = Search(pattern, line)
if match:
fncall = match.group(1) # look inside the parens for function calls
break
# Except in if/for/while/switch, there should never be space
# immediately inside parens (eg "f( 3, 4 )"). We make an exception
# for nested parens ( (a+b) + c ). Likewise, there should never be
# a space before a ( when it's a function argument. I assume it's a
# function argument when the char before the whitespace is legal in
# a function name (alnum + _) and we're not starting a macro. Also ignore
# pointers and references to arrays and functions coz they're too tricky:
# we use a very simple way to recognize these:
# " (something)(maybe-something)" or
# " (something)(maybe-something," or
# " (something)[something]"
# Note that we assume the contents of [] to be short enough that
# they'll never need to wrap.
if ( # Ignore control structures.
not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
fncall) and
# Ignore pointers/references to functions.
not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
# Ignore pointers/references to arrays.
not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
error(filename, linenum, 'whitespace/parens', 4,
'Extra space after ( in function call')
elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Extra space after (')
if (Search(r'\w\s+\(', fncall) and
not Search(r'#\s*define|typedef', fncall) and
not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)):
error(filename, linenum, 'whitespace/parens', 4,
'Extra space before ( in function call')
# If the ) is followed only by a newline or a { + newline, assume it's
# part of a control statement (if/while/etc), and don't complain
if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
# If the closing parenthesis is preceded by only whitespaces,
# try to give a more descriptive error message.
if Search(r'^\s+\)', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Closing ) should be moved to the previous line')
else:
error(filename, linenum, 'whitespace/parens', 2,
'Extra space before )') | [
"def",
"CheckSpacingForFunctionCall",
"(",
"filename",
",",
"line",
",",
"linenum",
",",
"error",
")",
":",
"# Since function calls often occur inside if/for/while/switch",
"# expressions - which have their own, more liberal conventions - we",
"# first see if we should be looking inside ... | https://github.com/casadi/casadi/blob/8d0f80a4d0fe2054384bfb9748f7a0f6bae540ff/misc/cpplint.py#L2194-L2259 | ||
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/clang/bindings/python/clang/cindex.py | python | Type.get_declaration | (self) | return conf.lib.clang_getTypeDeclaration(self) | Return the cursor for the declaration of the given type. | Return the cursor for the declaration of the given type. | [
"Return",
"the",
"cursor",
"for",
"the",
"declaration",
"of",
"the",
"given",
"type",
"."
] | def get_declaration(self):
"""
Return the cursor for the declaration of the given type.
"""
return conf.lib.clang_getTypeDeclaration(self) | [
"def",
"get_declaration",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTypeDeclaration",
"(",
"self",
")"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/bindings/python/clang/cindex.py#L2342-L2346 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py | python | _Stream.__read | (self, size) | return t[:size] | Return size bytes from stream. If internal buffer is empty,
read another block from the stream. | Return size bytes from stream. If internal buffer is empty,
read another block from the stream. | [
"Return",
"size",
"bytes",
"from",
"stream",
".",
"If",
"internal",
"buffer",
"is",
"empty",
"read",
"another",
"block",
"from",
"the",
"stream",
"."
] | def __read(self, size):
"""Return size bytes from stream. If internal buffer is empty,
read another block from the stream.
"""
c = len(self.buf)
t = [self.buf]
while c < size:
buf = self.fileobj.read(self.bufsize)
if not buf:
break
t.append(buf)
c += len(buf)
t = b"".join(t)
self.buf = t[size:]
return t[:size] | [
"def",
"__read",
"(",
"self",
",",
"size",
")",
":",
"c",
"=",
"len",
"(",
"self",
".",
"buf",
")",
"t",
"=",
"[",
"self",
".",
"buf",
"]",
"while",
"c",
"<",
"size",
":",
"buf",
"=",
"self",
".",
"fileobj",
".",
"read",
"(",
"self",
".",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py#L563-L577 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/mindrecord/tools/tfrecord_to_mr.py | python | TFRecordToMR.tfrecord_iterator | (self) | Yield a dictionary whose keys are fields in schema.
Yields:
dict, data dictionary whose keys are the same as columns. | Yield a dictionary whose keys are fields in schema. | [
"Yield",
"a",
"dictionary",
"whose",
"keys",
"are",
"fields",
"in",
"schema",
"."
] | def tfrecord_iterator(self):
"""
Yield a dictionary whose keys are fields in schema.
Yields:
dict, data dictionary whose keys are the same as columns.
"""
dataset = self.tf.data.TFRecordDataset(self.source)
dataset = dataset.map(self._parse_record)
iterator = dataset.__iter__()
while True:
try:
yield self._get_data_from_tfrecord_sample(iterator)
except self.tf.errors.OutOfRangeError:
break
except self.tf.errors.InvalidArgumentError:
raise ValueError("TFRecord feature_dict parameter error.") | [
"def",
"tfrecord_iterator",
"(",
"self",
")",
":",
"dataset",
"=",
"self",
".",
"tf",
".",
"data",
".",
"TFRecordDataset",
"(",
"self",
".",
"source",
")",
"dataset",
"=",
"dataset",
".",
"map",
"(",
"self",
".",
"_parse_record",
")",
"iterator",
"=",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/mindrecord/tools/tfrecord_to_mr.py#L262-L278 | ||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/google/protobuf-py/google/protobuf/internal/python_message.py | python | _AddEnumValues | (descriptor, cls) | Sets class-level attributes for all enum fields defined in this message.
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.
Args:
descriptor: Descriptor object for this message type.
cls: Class we're constructing for this message type.
"""
for enum_type in descriptor.enum_types:
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",
":",
"for",
"enum_value",
"in",
"enum_type",
".",
"values",
":",
"setattr",
"(",
"cls",
",",
"enum_value",
".",
"name",
",",
"enum_... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/internal/python_message.py#L223-L232 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | DateTime.MakeFromUTC | (*args, **kwargs) | return _misc_.DateTime_MakeFromUTC(*args, **kwargs) | MakeFromUTC(self, bool noDST=False) -> DateTime | MakeFromUTC(self, bool noDST=False) -> DateTime | [
"MakeFromUTC",
"(",
"self",
"bool",
"noDST",
"=",
"False",
")",
"-",
">",
"DateTime"
] | def MakeFromUTC(*args, **kwargs):
"""MakeFromUTC(self, bool noDST=False) -> DateTime"""
return _misc_.DateTime_MakeFromUTC(*args, **kwargs) | [
"def",
"MakeFromUTC",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_MakeFromUTC",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L3958-L3960 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibook.py | python | AuiNotebook.RemoveControlFromPage | (self, page_idx) | return True | Removes a control from a tab (not from the tab area).
:param integer `page_idx`: the page index. | Removes a control from a tab (not from the tab area). | [
"Removes",
"a",
"control",
"from",
"a",
"tab",
"(",
"not",
"from",
"the",
"tab",
"area",
")",
"."
] | def RemoveControlFromPage(self, page_idx):
"""
Removes a control from a tab (not from the tab area).
:param integer `page_idx`: the page index.
"""
if page_idx >= self._tabs.GetPageCount():
return False
page_info = self._tabs.GetPage(page_idx)
if page_info.control is None:
return False
page_info.control.Destroy()
page_info.control = None
# tab height might have changed
self.UpdateTabCtrlHeight(force=True)
# update what's on screen
ctrl, ctrl_idx = self.FindTab(page_info.window)
if not ctrl:
return False
info = ctrl.GetPage(ctrl_idx)
info.control = None
ctrl.Refresh()
ctrl.Update()
return True | [
"def",
"RemoveControlFromPage",
"(",
"self",
",",
"page_idx",
")",
":",
"if",
"page_idx",
">=",
"self",
".",
"_tabs",
".",
"GetPageCount",
"(",
")",
":",
"return",
"False",
"page_info",
"=",
"self",
".",
"_tabs",
".",
"GetPage",
"(",
"page_idx",
")",
"if... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L3859-L3889 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/nn/parallel/scatter_gather.py | python | scatter_kwargs | (inputs, kwargs, target_gpus, dim=0) | return inputs, kwargs | r"""Scatter with support for kwargs dictionary | r"""Scatter with support for kwargs dictionary | [
"r",
"Scatter",
"with",
"support",
"for",
"kwargs",
"dictionary"
] | def scatter_kwargs(inputs, kwargs, target_gpus, dim=0):
r"""Scatter with support for kwargs dictionary"""
inputs = scatter(inputs, target_gpus, dim) if inputs else []
kwargs = scatter(kwargs, target_gpus, dim) if kwargs else []
if len(inputs) < len(kwargs):
inputs.extend(() for _ in range(len(kwargs) - len(inputs)))
elif len(kwargs) < len(inputs):
kwargs.extend({} for _ in range(len(inputs) - len(kwargs)))
inputs = tuple(inputs)
kwargs = tuple(kwargs)
return inputs, kwargs | [
"def",
"scatter_kwargs",
"(",
"inputs",
",",
"kwargs",
",",
"target_gpus",
",",
"dim",
"=",
"0",
")",
":",
"inputs",
"=",
"scatter",
"(",
"inputs",
",",
"target_gpus",
",",
"dim",
")",
"if",
"inputs",
"else",
"[",
"]",
"kwargs",
"=",
"scatter",
"(",
... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/parallel/scatter_gather.py#L42-L52 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | tools/coverage/coverage_diff.py | python | get_info_file_lines | (info_file, diff_file) | Args:
info_file (str): File generated by lcov.
diff_file (str): File to get modified lines.
Returns:
None | Args:
info_file (str): File generated by lcov.
diff_file (str): File to get modified lines. | [
"Args",
":",
"info_file",
"(",
"str",
")",
":",
"File",
"generated",
"by",
"lcov",
".",
"diff_file",
"(",
"str",
")",
":",
"File",
"to",
"get",
"modified",
"lines",
"."
] | def get_info_file_lines(info_file, diff_file):
"""
Args:
info_file (str): File generated by lcov.
diff_file (str): File to get modified lines.
Returns:
None
"""
diff_file_lines = get_diff_file_lines(diff_file)
current_lines = []
current_lf = 0
current_lh = 0
with open(info_file) as info_file:
for line in info_file:
line = line.strip()
if line.startswith('SF:'):
current_file = line.lstrip('SF:')
if current_file.startswith('/paddle/'):
current_file = current_file[len('/paddle/'):]
current_lines = diff_file_lines.get(current_file, [])
elif line.startswith('DA:'):
da = line.lstrip('DA:').split(',')
if int(da[0]) in current_lines:
current_lf += 1
if not line.endswith(',0'):
current_lh += 1
print(line)
continue
elif line.startswith('LF:'):
print('LF:{}'.format(current_lf))
continue
elif line.startswith('LH:'):
print('LH:{}'.format(current_lh))
continue
print(line) | [
"def",
"get_info_file_lines",
"(",
"info_file",
",",
"diff_file",
")",
":",
"diff_file_lines",
"=",
"get_diff_file_lines",
"(",
"diff_file",
")",
"current_lines",
"=",
"[",
"]",
"current_lf",
"=",
"0",
"current_lh",
"=",
"0",
"with",
"open",
"(",
"info_file",
... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/tools/coverage/coverage_diff.py#L66-L116 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/main.py | python | StdoutRefactoringTool.__init__ | (self, fixers, options, explicit, nobackups, show_diffs,
input_base_dir='', output_dir='', append_suffix='') | Args:
fixers: A list of fixers to import.
options: A dict with RefactoringTool configuration.
explicit: A list of fixers to run even if they are explicit.
nobackups: If true no backup '.bak' files will be created for those
files that are being refactored.
show_diffs: Should diffs of the refactoring be printed to stdout?
input_base_dir: The base directory for all input files. This class
will strip this path prefix off of filenames before substituting
it with output_dir. Only meaningful if output_dir is supplied.
All files processed by refactor() must start with this path.
output_dir: If supplied, all converted files will be written into
this directory tree instead of input_base_dir.
append_suffix: If supplied, all files output by this tool will have
this appended to their filename. Useful for changing .py to
.py3 for example by passing append_suffix='3'. | Args:
fixers: A list of fixers to import.
options: A dict with RefactoringTool configuration.
explicit: A list of fixers to run even if they are explicit.
nobackups: If true no backup '.bak' files will be created for those
files that are being refactored.
show_diffs: Should diffs of the refactoring be printed to stdout?
input_base_dir: The base directory for all input files. This class
will strip this path prefix off of filenames before substituting
it with output_dir. Only meaningful if output_dir is supplied.
All files processed by refactor() must start with this path.
output_dir: If supplied, all converted files will be written into
this directory tree instead of input_base_dir.
append_suffix: If supplied, all files output by this tool will have
this appended to their filename. Useful for changing .py to
.py3 for example by passing append_suffix='3'. | [
"Args",
":",
"fixers",
":",
"A",
"list",
"of",
"fixers",
"to",
"import",
".",
"options",
":",
"A",
"dict",
"with",
"RefactoringTool",
"configuration",
".",
"explicit",
":",
"A",
"list",
"of",
"fixers",
"to",
"run",
"even",
"if",
"they",
"are",
"explicit"... | def __init__(self, fixers, options, explicit, nobackups, show_diffs,
input_base_dir='', output_dir='', append_suffix=''):
"""
Args:
fixers: A list of fixers to import.
options: A dict with RefactoringTool configuration.
explicit: A list of fixers to run even if they are explicit.
nobackups: If true no backup '.bak' files will be created for those
files that are being refactored.
show_diffs: Should diffs of the refactoring be printed to stdout?
input_base_dir: The base directory for all input files. This class
will strip this path prefix off of filenames before substituting
it with output_dir. Only meaningful if output_dir is supplied.
All files processed by refactor() must start with this path.
output_dir: If supplied, all converted files will be written into
this directory tree instead of input_base_dir.
append_suffix: If supplied, all files output by this tool will have
this appended to their filename. Useful for changing .py to
.py3 for example by passing append_suffix='3'.
"""
self.nobackups = nobackups
self.show_diffs = show_diffs
if input_base_dir and not input_base_dir.endswith(os.sep):
input_base_dir += os.sep
self._input_base_dir = input_base_dir
self._output_dir = output_dir
self._append_suffix = append_suffix
super(StdoutRefactoringTool, self).__init__(fixers, options, explicit) | [
"def",
"__init__",
"(",
"self",
",",
"fixers",
",",
"options",
",",
"explicit",
",",
"nobackups",
",",
"show_diffs",
",",
"input_base_dir",
"=",
"''",
",",
"output_dir",
"=",
"''",
",",
"append_suffix",
"=",
"''",
")",
":",
"self",
".",
"nobackups",
"=",... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/main.py#L36-L63 | ||
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | ThirdParty/cinema/paraview/tpl/cinema_python/database/vti_store.py | python | VTIFileStore.create | (self) | creates a new file store | creates a new file store | [
"creates",
"a",
"new",
"file",
"store"
] | def create(self):
"""creates a new file store"""
super(VTIFileStore, self).create()
self.save() | [
"def",
"create",
"(",
"self",
")",
":",
"super",
"(",
"VTIFileStore",
",",
"self",
")",
".",
"create",
"(",
")",
"self",
".",
"save",
"(",
")"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/database/vti_store.py#L40-L43 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/IndirectCommon.py | python | convertToElasticQ | (input_ws, output_ws=None) | Helper function to convert the spectrum axis of a sample to ElasticQ.
@param input_ws - the name of the workspace to convert from
@param output_ws - the name to call the converted workspace | Helper function to convert the spectrum axis of a sample to ElasticQ. | [
"Helper",
"function",
"to",
"convert",
"the",
"spectrum",
"axis",
"of",
"a",
"sample",
"to",
"ElasticQ",
"."
] | def convertToElasticQ(input_ws, output_ws=None):
"""
Helper function to convert the spectrum axis of a sample to ElasticQ.
@param input_ws - the name of the workspace to convert from
@param output_ws - the name to call the converted workspace
"""
if output_ws is None:
output_ws = input_ws
axis = s_api.mtd[input_ws].getAxis(1)
if axis.isSpectra():
e_fixed = getEfixed(input_ws)
s_api.ConvertSpectrumAxis(input_ws, Target='ElasticQ', EMode='Indirect', EFixed=e_fixed,
OutputWorkspace=output_ws)
elif axis.isNumeric():
# Check that units are Momentum Transfer
if axis.getUnit().unitID() != 'MomentumTransfer':
raise RuntimeError('Input must have axis values of Q')
s_api.CloneWorkspace(input_ws, OutputWorkspace=output_ws)
else:
raise RuntimeError('Input workspace must have either spectra or numeric axis.') | [
"def",
"convertToElasticQ",
"(",
"input_ws",
",",
"output_ws",
"=",
"None",
")",
":",
"if",
"output_ws",
"is",
"None",
":",
"output_ws",
"=",
"input_ws",
"axis",
"=",
"s_api",
".",
"mtd",
"[",
"input_ws",
"]",
".",
"getAxis",
"(",
"1",
")",
"if",
"axis... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/IndirectCommon.py#L456-L481 | ||
pichenettes/eurorack | 11cc3a80f2c6d67ee024091c711dfce59a58cb59 | elements/resources/audio_io.py | python | AudioIoException.__init__ | (self, message) | Initializes an AudioIoException object. | Initializes an AudioIoException object. | [
"Initializes",
"an",
"AudioIoException",
"object",
"."
] | def __init__(self, message):
"""Initializes an AudioIoException object."""
Exception.__init__(self, 'Audio IO error: %s' % message) | [
"def",
"__init__",
"(",
"self",
",",
"message",
")",
":",
"Exception",
".",
"__init__",
"(",
"self",
",",
"'Audio IO error: %s'",
"%",
"message",
")"
] | https://github.com/pichenettes/eurorack/blob/11cc3a80f2c6d67ee024091c711dfce59a58cb59/elements/resources/audio_io.py#L30-L32 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/lexer.py | python | TokenStream.close | (self) | Close the stream. | Close the stream. | [
"Close",
"the",
"stream",
"."
] | def close(self) -> None:
"""Close the stream."""
self.current = Token(self.current.lineno, TOKEN_EOF, "")
self._iter = iter(())
self.closed = True | [
"def",
"close",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"current",
"=",
"Token",
"(",
"self",
".",
"current",
".",
"lineno",
",",
"TOKEN_EOF",
",",
"\"\"",
")",
"self",
".",
"_iter",
"=",
"iter",
"(",
"(",
")",
")",
"self",
".",
"closed... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/lexer.py#L395-L399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.