docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Zip together multiple columns.
Args:
columns (WeldObject / Numpy.ndarray): lust of columns
Returns:
A WeldObject representing this computation | def unzip_columns(expr, column_types):
weld_obj = WeldObject(encoder_, decoder_)
column_appenders = []
struct_fields = []
result_fields = []
for i, column_type in enumerate(column_types):
column_appenders.append("appender[%s]" % column_type)
struct_fields.append("merge(b.$%s, e.... | 168,147 |
Sorts the vector.
If the field parameter is provided then the sort
operators on a vector of structs where the sort key
is the field of the struct.
Args:
expr (WeldObject)
field (Int) | def sort(expr, field = None, keytype=None, ascending=True):
weld_obj = WeldObject(encoder_, decoder_)
expr_var = weld_obj.update(expr)
if isinstance(expr, WeldObject):
expr_var = expr.obj_id
weld_obj.dependencies[expr_var] = expr
if field is not None:
key_str = "x.$%s" % f... | 168,148 |
Slices the vector.
Args:
expr (WeldObject)
start (Long)
stop (Long) | def slice_vec(expr, start, stop):
weld_obj = WeldObject(encoder_, decoder_)
expr_var = weld_obj.update(expr)
if isinstance(expr, WeldObject):
expr_var = expr.obj_id
weld_obj.dependencies[expr_var] = expr
weld_template =
weld_obj.weld_code = weld_template % {"expr":expr_var,
... | 168,149 |
Zip together multiple columns.
Args:
columns (WeldObject / Numpy.ndarray): lust of columns
Returns:
A WeldObject representing this computation | def zip_columns(columns):
weld_obj = WeldObject(encoder_, decoder_)
column_vars = []
for column in columns:
col_var = weld_obj.update(column)
if isinstance(column, WeldObject):
col_var = column.obj_id
weld_obj.dependencies[col_var] = column
column_vars.ap... | 168,150 |
Performs passed-in comparison op between every element in the passed-in
array and other, and returns an array of booleans.
Args:
array (WeldObject / Numpy.ndarray): Input array
other (WeldObject / Numpy.ndarray): Second input array
op (str): Op string used for element-wise comparison (=... | def compare(array, other, op, ty_str):
weld_obj = WeldObject(encoder_, decoder_)
array_var = weld_obj.update(array)
if isinstance(array, WeldObject):
array_var = array.obj_id
weld_obj.dependencies[array_var] = array
# Strings need to be encoded into vec[char] array.
# Constant... | 168,151 |
Returns a new array-of-arrays with each array truncated, starting at
index `start` for `length` characters.
Args:
array (WeldObject / Numpy.ndarray): Input array
start (int): starting index
size (int): length to truncate at
ty (WeldType): Type of each element in the input array
... | def slice(array, start, size, ty):
weld_obj = WeldObject(encoder_, decoder_)
array_var = weld_obj.update(array)
if isinstance(array, WeldObject):
array_var = array.obj_id
weld_obj.dependencies[array_var] = array
weld_template =
weld_obj.weld_code = weld_template % {"array": a... | 168,152 |
Checks if given string is contained in each string in the array.
Output is a vec of booleans.
Args:
array (WeldObject / Numpy.ndarray): Input array
start (int): starting index
size (int): length to truncate at
ty (WeldType): Type of each element in the input array
Returns:
... | def contains(array, ty, string):
weld_obj = WeldObject(encoder_, decoder_)
string_obj = weld_obj.update(string)
if isinstance(string, WeldObject):
string_obj = string.obj_id
weld_obj.dependencies[string_obj] = string
array_var = weld_obj.update(array)
if isinstance(array, Wel... | 168,153 |
Groups the given columns by the corresponding grouping column
value, and aggregate by summing values.
Args:
columns (List<WeldObject>): List of columns as WeldObjects
column_tys (List<str>): List of each column data ty
grouping_column (WeldObject): Column to group rest of columns by
... | def groupby_size(columns, column_tys, grouping_columns, grouping_column_tys):
weld_obj = WeldObject(encoder_, decoder_)
if len(grouping_columns) == 1 and len(grouping_column_tys) == 1:
grouping_column_var = weld_obj.update(grouping_columns[0])
if isinstance(grouping_columns[0], WeldObject)... | 168,161 |
Groups the given columns by the corresponding grouping column
value, and aggregate by summing values.
Args:
columns (List<WeldObject>): List of columns as WeldObjects
column_tys (List<str>): List of each column data ty
grouping_column (WeldObject): Column to group rest of columns by
... | def groupby_sort(columns, column_tys, grouping_columns, grouping_column_tys, key_index, ascending):
weld_obj = WeldObject(encoder_, decoder_)
if len(grouping_columns) == 1 and len(grouping_column_tys) == 1:
grouping_column_var = weld_obj.update(grouping_columns[0])
if isinstance(grouping_co... | 168,162 |
Groups the given columns by the corresponding grouping column
value, and aggregate by summing values.
Args:
columns (List<WeldObject>): List of columns as WeldObjects
column_tys (List<str>): List of each column data ty
grouping_column (WeldObject): Column to group rest of columns by
... | def flatten_group(expr, column_tys, grouping_column_tys):
weld_obj = WeldObject(encoder_, decoder_)
group_var = weld_obj.update(expr)
num_group_cols = len(grouping_column_tys)
if num_group_cols == 1:
grouping_column_ty_str = "%s" % grouping_column_tys[0]
grouping_column_key_str = ... | 168,163 |
Groups the given columns by the corresponding grouping column
value, and aggregate by summing values.
Args:
columns (List<WeldObject>): List of columns as WeldObjects
column_tys (List<str>): List of each column data ty
grouping_column (WeldObject): Column to group rest of columns by
... | def grouped_slice(expr, type, start, size):
weld_obj = WeldObject(encoder_, decoder_)
weld_obj.update(expr)
weld_template =
weld_obj.weld_code = weld_template % {"vec": expr.weld_code,
"type": type,
"start": str(s... | 168,164 |
Get column corresponding to passed-in index from ptr returned
by groupBySum.
Args:
columns (List<WeldObject>): List of columns as WeldObjects
column_tys (List<str>): List of each column data ty
index (int): index of selected column
Returns:
A WeldObject representing this co... | def get_column(columns, column_tys, index):
weld_obj = WeldObject(encoder_, decoder_)
columns_var = weld_obj.update(columns, tys=WeldVec(column_tys), override=False)
if isinstance(columns, WeldObject):
columns_var = columns.obj_id
weld_obj.dependencies[columns_var] = columns
weld_t... | 168,165 |
Computes the dot product between a matrix and a vector.
TODO: Make this more generic
Args:
matrix (TYPE): Description
vector (TYPE): Description | def dot(matrix, vector):
matrix_weld_type = None
vector_weld_type = None
if isinstance(matrix, LazyOpResult):
matrix_weld_type = matrix.weld_type
matrix = matrix.expr
elif isinstance(matrix, np.ndarray):
matrix_weld_type = numpy_weld_impl.numpy_to_weld_type_mapping[
... | 168,170 |
Computes a per-element exponent of the passed-in vector.
Args:
vector (TYPE): Description | def exp(vector):
weld_type = None
if isinstance(vector, LazyOpResult):
weld_type = vector.weld_type
vector = vector.expr
elif isinstance(vector, np.ndarray):
weld_type = numpy_weld_impl.numpy_to_weld_type_mapping[
str(vector.dtype)]
return NumpyArrayWeld(numpy_we... | 168,171 |
Summary
Args:
other (TYPE): Description
Returns:
TYPE: Description | def __div__(self, other):
if isinstance(other, LazyOpResult):
other = other.expr
return NumpyArrayWeld(
numpy_weld_impl.div(
self.expr,
other,
self.weld_type
),
self.weld_type
) | 168,172 |
Summary
Args:
obj (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description | def py_to_weld_type(self, obj):
if isinstance(obj, np.ndarray):
dtype = str(obj.dtype)
if dtype == 'int16':
base = WeldInt16()
elif dtype == 'int32':
base = WeldInt()
elif dtype == 'int64':
base = WeldLong()... | 168,176 |
Converts Python object to Weld object.
Args:
obj: Python object that needs to be converted to Weld format
Returns:
Weld formatted object | def encode(self, obj):
if isinstance(obj, np.ndarray):
if obj.ndim == 1 and obj.dtype == 'int16':
numpy_to_weld = self.utils.numpy_to_weld_int16_arr
elif obj.ndim == 1 and obj.dtype == 'int32':
numpy_to_weld = self.utils.numpy_to_weld_int_arr
... | 168,177 |
Converts Weld object to Python object.
Args:
obj: Result of Weld computation that needs to be decoded
restype: Type of Weld computation result
raw_ptr: Boolean indicating whether obj needs to be extracted
from WeldValue or not
Returns:
... | def decode(self, obj, restype, raw_ptr=False):
if raw_ptr:
data = obj
else:
data = cweld.WeldValue(obj).data()
result = ctypes.cast(data, ctypes.POINTER(restype.ctype_class)).contents
if restype == WeldInt16():
data = cweld.WeldValue(obj).dat... | 168,178 |
Updates the global list of line error-suppressions.
Parses any NOLINT comments on the current line, updating the global
error_suppressions store. Reports an error if the NOLINT comment
was malformed.
Args:
filename: str, the name of the input file.
raw_line: str, the line of input text, with comments... | def ParseNolintSuppressions(filename, raw_line, linenum, error):
matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
if matched:
if matched.group(1):
suppressed_line = linenum + 1
else:
suppressed_line = linenum
category = matched.group(2)
if category in (None, '(*)'): #... | 170,130 |
Updates the list of global error suppressions.
Parses any lint directives in the file that have global effect.
Args:
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline. | def ProcessGlobalSuppresions(lines):
for line in lines:
if _SEARCH_C_FILE.search(line):
for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
_global_error_suppressions[category] = True
if _SEARCH_KERNEL_FILE.search(line):
for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
_glob... | 170,131 |
Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
... | def IsErrorSuppressedByNolint(category, linenum):
return (_global_error_suppressions.get(category, False) or
linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | 170,132 |
Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements) | def ReplaceAll(pattern, rep, s):
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].sub(rep, s) | 170,134 |
Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant. | def IsCppString(line):
line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 | 170,137 |
Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw str... | def CleanseRawStrings(raw_lines):
delimiter = None
lines_without_raw_strings = []
for line in raw_lines:
if delimiter:
# Inside a raw string, look for the end
end = line.find(delimiter)
if end >= 0:
# Found the end of the string, match leading space for this
# line and re... | 170,138 |
Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed. | def CleanseComments(line):
commentpos = line.find('//')
if commentpos != -1 and not IsCppString(line[:commentpos]):
line = line[:commentpos].rstrip()
# get rid of /* ... */
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | 170,143 |
Find the position just after the end of current parenthesized expression.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
stack: nesting stack at startpos.
Returns:
On finding matching end: (index just after matching end, None)
On finding an unclosed expression: (... | def FindEndOfExpressionInLine(line, startpos, stack):
for i in xrange(startpos, len(line)):
char = line[i]
if char in '([{':
# Found start of parenthesized expression, push to expression stack
stack.append(char)
elif char == '<':
# Found potential start of template argument list
... | 170,144 |
Find position at the matching start of current expression.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
stack: nesting stack at endpos.
Retu... | def FindStartOfExpressionInLine(line, endpos, stack):
i = endpos
while i >= 0:
char = line[i]
if char in ')]}':
# Found end of expression, push to expression stack
stack.append(char)
elif char == '>':
# Found potential end of template argument list.
#
# Ignore it if it's... | 170,146 |
Return the number of leading spaces in line.
Args:
line: A string to check.
Returns:
An integer count of leading spaces, possibly zero. | def GetIndentLevel(line):
indent = Match(r'^( *)\S', line)
if indent:
return len(indent.group(1))
else:
return 0 | 170,149 |
Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file. | def GetHeaderGuardCPPVariable(filename):
# Restores original filename in case that cpplint is invoked from Emacs's
# flymake.
filename = re.sub(r'_flymake\.h$', '.h', filename)
filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
# Replace 'c++' with 'cpp'.
filename = filename.replace('C++', 'cpp... | 170,150 |
Checks that the file contains a header guard.
Logs an error if no #ifndef header guard is present. For other
headers, checks that the full pathname is used.
Args:
filename: The name of the C++ header file.
clean_lines: A CleansedLines instance containing the file.
error: The function to call with a... | def CheckForHeaderGuard(filename, clean_lines, error):
# Don't check for header guards if there are error suppression
# comments somewhere in this file.
#
# Because this is silencing a warning for a nonexistent line, we
# only support the very specific NOLINT(build/header_guard) syntax,
# and not the ge... | 170,151 |
Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | def CheckForNewlineAtEOF(filename, lines, error):
# The array lines() was created by adding two newlines to the
# original file (go figure), then splitting on \n.
# To verify that the file ends in \n, we just have to make sure the
# last-but-two element of lines() exists and is empty.
if len(lines) < 3 or... | 170,154 |
Checks that VLOG() is only used for defining a logging level.
For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
VLOG(FATAL) are not.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to ... | def CheckVlogArguments(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
error(filename, linenum, 'runtime/vlog', 5,
'VLOG() should be used with numeric verbosity level. '
'Use LOG() if you want sym... | 170,157 |
Checks for invalid increment *count++.
For example following function:
void increment_counter(int* count) {
*count++;
}
is invalid, because it effectively does count++, moving pointer, and should
be replaced with ++*count, (*count)++ or *count += 1.
Args:
filename: The name of the current file.
... | def CheckInvalidIncrement(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
if _RE_PATTERN_INVALID_INCREMENT.match(line):
error(filename, linenum, 'runtime/invalid_increment', 5,
'Changing pointer instead of value (or unused value of operator*).') | 170,158 |
Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# 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
#... | 170,160 |
Checks for common mistakes in comments.
Args:
line: The line in question.
filename: The name of the current file.
linenum: The number of the line to check.
next_line_start: The first non-whitespace column of the next line.
error: The function to call with any errors found. | def CheckComment(line, filename, linenum, next_line_start, error):
commentpos = line.find('//')
if commentpos != -1:
# Check if the // may be in quotes. If so, ignore it
if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
# Allow one space for new scopes, two spaces otherwise:
if ... | 170,163 |
Checks for improper use of DISALLOW* macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack... | def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
line = clean_lines.elided[linenum] # get rid of comments and strings
matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
if not matched:
return
if nesting_state.stack and i... | 170,164 |
Checks for horizontal spacing around parentheses.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# No spaces after an if, while, switch, or for
match = Search(r' (if\(|for\(|while\(|switch\()', line)
if match:
error(filename, linenum, 'whitespace/parens', 5,
'Missing space before ( in %s... | 170,166 |
Checks for horizontal spacing near commas and semicolons.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckCommaSpacing(filename, clean_lines, linenum, error):
raw = clean_lines.lines_without_raw_strings
line = clean_lines.elided[linenum]
# You should always have a space after a comma (either as fn arg or operator)
#
# This does not apply when the non-space character following the
# comma is another... | 170,167 |
Check if expression looks like a type name, returns true if so.
Args:
clean_lines: A CleansedLines instance containing the file.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
expr: The expression to check.
Re... | def _IsType(clean_lines, nesting_state, expr):
# Keep only the last token in the expression
last_word = Match(r'^.*(\b\S+)$', expr)
if last_word:
token = last_word.group(1)
else:
token = expr
# Match native types and stdint types
if _TYPES.match(token):
return True
# Try a bit harder to m... | 170,168 |
Checks for horizontal spacing near commas.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack o... | def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
line = clean_lines.elided[linenum]
# Except after an opening paren, or after another opening brace (in case of
# an initializer list, for instance), you should have spaces before your
# braces when they are delimiting blocks, clas... | 170,169 |
Check if the token ending on (linenum, column) is decltype().
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: the number of the line to check.
column: end column of the token to check.
Returns:
True if this token is decltype() expression, False otherwise. | def IsDecltype(clean_lines, linenum, column):
(text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
if start_col < 0:
return False
if Search(r'\bdecltype\s*$', text[0:start_col]):
return True
return False | 170,170 |
Checks for additional blank line issues related to sections.
Currently the only thing checked here is blank line before protected/private.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
class_info: A _ClassInfo objects.
linenum: The number ... | def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
# Skip checks if the class is small, where small means 25 lines or less.
# 25 lines seems like a good cutoff since that's the usual height of
# terminals, and any class that can't fit in one screen can't really
# be considered "small... | 170,171 |
Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, ... | def GetPreviousNonBlankLine(clean_lines, linenum):
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline): # if not a blank line...
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1) | 170,172 |
Looks for redundant trailing semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# Block bodies should not be followed by a semicolon. Due to C++11
# brace initialization, there are more places where semicolons are
# required than not, so we use a whitelist approach to check these
#... | 170,173 |
Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
# Search for loop keywords at the beginning of the line. Because only
# whitespaces are allowed before the keywords, this will also ignore most
# do-while-loops, since those lines should start with closing brace.
#
# We also check "if" block... | 170,174 |
Find a replaceable CHECK-like macro.
Args:
line: line to search on.
Returns:
(macro name, start position), or (None, -1) if no replaceable
macro is found. | def FindCheckMacro(line):
for macro in _CHECK_MACROS:
i = line.find(macro)
if i >= 0:
# Find opening parenthesis. Do a regular expression match here
# to make sure that we are matching the expected CHECK macro, as
# opposed to some other macro that happens to contain the CHECK
# su... | 170,175 |
Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckCheck(filename, clean_lines, linenum, error):
# Decide the set of replacement macros that should be suggested
lines = clean_lines.elided
(check_macro, start_pos) = FindCheckMacro(lines[linenum])
if not check_macro:
return
# Find end of the boolean expression by matching parentheses
(last_l... | 170,176 |
Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckAltTokens(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# Avoid preprocessor lines
if Match(r'^\s*#', line):
return
# Last ditch effort to avoid multi-line comments. This will not help
# if the comment started before the current line or ended after the
# curre... | 170,177 |
Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters. | def GetLineWidth(line):
if isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if unicodedata.east_asian_width(uc) in ('W', 'F'):
width += 2
elif not unicodedata.combining(uc):
width += 1
return width
else:
return len(line) | 170,178 |
Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')... | def _DropCommonSuffixes(filename):
for suffix in itertools.chain(
('%s.%s' % (test_suffix.lstrip('_'), ext)
for test_suffix, ext in itertools.product(_test_suffixes, GetNonHeaderExtensions())),
('%s.%s' % (suffix, ext)
for suffix, ext in itertools.product(['inl', 'imp', 'internal'], GetHe... | 170,179 |
Check for unsafe global or static objects.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckGlobalStatic(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# Match two lines at a time to support multiline declarations
if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
line += clean_lines.elided[linenum + 1].strip()
# Check for people decla... | 170,184 |
Check for printf related issues.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckPrintf(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# When snprintf is used, the second argument shouldn't be a literal.
match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
if match and match.group(2) != '0':
# If 2nd arg is zero, snprintf is used to calc... | 170,185 |
Check if current line contains an inherited function.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains a function with "override"
virt-specifier. | def IsDerivedFunction(clean_lines, linenum):
# Scan back a few lines for start of current function
for i in xrange(linenum, max(-1, linenum - 10), -1):
match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
if match:
# Look for "override" after the matching closing parenthesis
line, _, closi... | 170,186 |
Check if current line contains an out-of-line method definition.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains an out-of-line method definition. | def IsOutOfLineMethodDefinition(clean_lines, linenum):
# Scan back a few lines for start of current function
for i in xrange(linenum, max(-1, linenum - 10), -1):
if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
return False | 170,187 |
Check if current line is inside constructor initializer list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line appears to be inside constructor initializer
list, False otherwise. | def IsInitializerList(clean_lines, linenum):
for i in xrange(linenum, 1, -1):
line = clean_lines.elided[i]
if i == linenum:
remove_function_body = Match(r'^(.*)\{\s*$', line)
if remove_function_body:
line = remove_function_body.group(1)
if Search(r'\s:\s*\w+[({]', line):
# A ... | 170,188 |
Check for non-const references.
Separate from CheckLanguage since it scans backwards from current
line, instead of scanning forward.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A... | def CheckForNonConstReference(filename, clean_lines, linenum,
nesting_state, error):
# Do nothing if there is no '&' on current line.
line = clean_lines.elided[linenum]
if '&' not in line:
return
# If a function is inherited, current function doesn't have much of
# a choi... | 170,189 |
Various cast related checks.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckCasts(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# Check to see if they're using an conversion function cast.
# I just try to capture the most common basic types, though there are more.
# Parameterless conversion functions, such as bool(), are allowed as they are
#... | 170,190 |
Checks whether where function type arguments are expected.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if the line at 'linenum' is inside something that expects arguments
of function types. | def ExpectingFunctionArgs(clean_lines, linenum):
line = clean_lines.elided[linenum]
return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
(linenum >= 2 and
(Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
clean_lines.elided[linenum - 1]) or
... | 170,192 |
Fill up the include_dict with new includes found from the file.
Args:
filename: the name of the header to read.
include_dict: a dictionary in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was successfully added. Fals... | def UpdateIncludeState(filename, include_dict, io=codecs):
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _RE_PATTERN_INCLUDE.search(cl... | 170,194 |
Check that make_pair's template arguments are deduced.
G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linen... | def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair',
4, # 4 = high confidence
'For C++11-compatibility, omit template a... | 170,195 |
Check if line contains a redundant "virtual" function-specifier.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckRedundantVirtual(filename, clean_lines, linenum, error):
# Look for "virtual" on current line.
line = clean_lines.elided[linenum]
virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
if not virtual: return
# Ignore "virtual" keywords that are near access-specifiers. These
# are only used in class... | 170,196 |
Check if line contains a redundant "override" or "final" virt-specifier.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
# Look for closing parenthesis nearby. We need one to confirm where
# the declarator ends and where the virt-specifier starts to avoid
# false positives.
line = clean_lines.elided[linenum]
declarator_end = line.rfind(')')
if decla... | 170,197 |
Checks that the new block is directly in a namespace.
Args:
nesting_state: The _NestingState object that contains info about our state.
is_forward_declaration: If the class is a forward declared class.
Returns:
Whether or not the new block is directly in a namespace. | def IsBlockInNameSpace(nesting_state, is_forward_declaration):
if is_forward_declaration:
return len(nesting_state.stack) >= 1 and (
isinstance(nesting_state.stack[-1], _NamespaceInfo))
return (len(nesting_state.stack) > 1 and
nesting_state.stack[-1].check_namespace_indentation and
... | 170,198 |
Flag those C++14 features that we restrict.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def FlagCxx14Features(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
# Flag unapproved C++14 headers.
if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
error(filename, linenum, 'build/c++14', ... | 170,201 |
Loads the configuration files and processes the config overrides.
Args:
filename: The name of the file being processed by the linter.
Returns:
False if the current |filename| should not be processed further. | def ProcessConfigOverrides(filename):
abs_filename = os.path.abspath(filename)
cfg_filters = []
keep_looking = True
while keep_looking:
abs_path, base_name = os.path.split(abs_filename)
if not base_name:
break # Reached the root directory.
cfg_file = os.path.join(abs_path, "CPPLINT.cfg")... | 170,203 |
Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
... | def ProcessFile(filename, vlevel, extra_check_functions=None):
_SetVerboseLevel(vlevel)
_BackupFilters()
if not ProcessConfigOverrides(filename):
_RestoreFilters()
return
lf_lines = []
crlf_lines = []
try:
# Support the UNIX convention of using "-" for stdin. Note that
# we are not op... | 170,204 |
Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint. | def ParseArguments(args):
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
'counting=',
'filter=',
'root=',
... | 170,206 |
Searches a list of filenames and replaces directories in the list with
all files descending from those directories. Files with extensions not in
the valid extensions list are excluded.
Args:
filenames: A list of files or directories
Returns:
A list of all files that are members of filenames or descend... | def _ExpandDirectories(filenames):
expanded = set()
for filename in filenames:
if not os.path.isdir(filename):
expanded.add(filename)
continue
for root, _, files in os.walk(filename):
for loopfile in files:
fullname = os.path.join(root, loopfile)
if fullna... | 170,207 |
Check if a header has already been included.
Args:
header: header to check.
Returns:
Line number of previous occurrence, or -1 if the header has not
been seen before. | def FindHeader(self, header):
for section_list in self.include_list:
for f in section_list:
if f[0] == header:
return f[1]
return -1 | 170,211 |
Reset section checking for preprocessor directive.
Args:
directive: preprocessor directive (e.g. "if", "else"). | def ResetSection(self, directive):
# The name of the current section.
self._section = self._INITIAL_SECTION
# The path of last found header.
self._last_header = ''
# Update list of includes. Note that we never pop from the
# include list.
if directive in ('if', 'ifdef', 'ifndef'):
... | 170,212 |
Check if a header is in alphabetical order with the previous header.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
header_path: Canonicalized header to be checked.
Returns:
Returns true if the header is in alphabetical order. | def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
# If previous section is different from current section, _last_header will
# be reset to empty string, so it's always less than current header.
#
# If previous line was a blank line, assume that the headers are
# intentionally ... | 170,213 |
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 a... | def CheckNextIncludeOrder(self, header_type):
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:... | 170,214 |
Start analyzing function body.
Args:
function_name: The name of the function being tracked. | def Begin(self, function_name):
self.in_a_function = True
self.lines_in_function = 0
self.current_function = function_name | 170,224 |
Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings. | def _CollapseStrings(elided):
if _RE_PATTERN_INCLUDE.match(elided):
return elided
# Remove escaped characters first to make quote/single quote collapsing
# basic. Things that look like escaped characters shouldn't occur
# outside of strings and chars.
elided = _RE_PATTERN_CLEANSE_LINE_E... | 170,228 |
Check if current position is inside template argument list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: position just after the suspected template argument.
Returns:
True if (linenum, pos) is inside template arguments. | def InTemplateArgumentList(self, clean_lines, linenum, pos):
while linenum < clean_lines.NumLines():
# Find the earliest character that might indicate a template argument
line = clean_lines.elided[linenum]
match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
if not match:
linenum ... | 170,235 |
Update nesting state with current line.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def Update(self, filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# Remember top of the previous nesting stack.
#
# The stack is always pushed/popped and not modified in place, so
# we can just do a shallow copy instead of copy.deepcopy. Using
# deepcopy would sl... | 170,237 |
Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found. | def CheckCompletedBlocks(self, filename, error):
# Note: This test can result in false positives if #ifdef constructs
# get in the way of brace matching. See the testBuildClass test in
# cpplint_unittest.py for an example of this.
for obj in self.stack:
if isinstance(obj, _ClassInfo):
... | 170,239 |
Make sympy symbols q0, q1, ...
Args:
n(int), m(int, optional):
If specified both n and m, returns [qn, q(n+1), ..., qm],
Only n is specified, returns[q0, q1, ..., qn].
Return:
tuple(Symbol): Tuple of sympy symbols. | def make_qs(n, m=None):
try:
import sympy
except ImportError:
raise ImportError("This function requires sympy. Please install it.")
if m is None:
syms = sympy.symbols(" ".join(f"q{i}" for i in range(n)))
if isinstance(syms, tuple):
return syms
else:
... | 170,324 |
Convert Sympy's expr to QUBO.
Args:
expr: Sympy's quadratic expression with variable `q0`, `q1`, ...
Returns:
[[float]]: Returns QUBO matrix. | def qn_to_qubo(expr):
try:
import sympy
except ImportError:
raise ImportError("This function requires sympy. Please install it.")
assert type(expr) == sympy.Add
to_i = lambda s: int(str(s)[1:])
max_i = max(map(to_i, expr.free_symbols)) + 1
qubo = [[0.] * max_i for _ in range... | 170,326 |
Register new macro to Circuit.
Args:
name (str): The name of macro.
func (callable): The function to be called.
allow_overwrite (bool, optional): If True, allow to overwrite the existing macro.
Otherwise, raise the ValueError.
Raises:
Val... | def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None:
if hasattr(Circuit, name):
if allow_overwrite:
warnings.warn(f"Circuit has attribute `{name}`.")
else:
raise ValueError(f"Circuit has attribute `{name}`.")
... | 170,455 |
Register new gate to gate set.
Args:
name (str): The name of gate.
gateclass (type): The type object of gate.
allow_overwrite (bool, optional): If True, allow to overwrite the existing gate.
Otherwise, raise the ValueError.
Raises:
ValueE... | def register_gate(name, gateclass, allow_overwrite=False):
if hasattr(Circuit, name):
if allow_overwrite:
warnings.warn(f"Circuit has attribute `{name}`.")
else:
raise ValueError(f"Circuit has attribute `{name}`.")
if name.startswith("run_... | 170,456 |
Register new backend.
Args:
name (str): The name of backend.
gateclass (type): The type object of backend
allow_overwrite (bool, optional): If True, allow to overwrite the existing backend.
Otherwise, raise the ValueError.
Raises:
ValueEr... | def register_backend(name, backend, allow_overwrite=False):
if hasattr(Circuit, "run_with_" + name):
if allow_overwrite:
warnings.warn(f"Circuit has attribute `run_with_{name}`.")
else:
raise ValueError(f"Circuit has attribute `run_with_{name}`.")... | 170,457 |
Make Pauli matrix from an character.
Args:
ch (str): "X" or "Y" or "Z" or "I".
n (int, optional): Make Pauli matrix as n-th qubits.
Returns:
If ch is "X" => X, "Y" => Y, "Z" => Z, "I" => I
Raises:
ValueError: When ch is not "X", "Y", "Z" nor "I". | def pauli_from_char(ch, n=0):
ch = ch.upper()
if ch == "I":
return I
if ch == "X":
return X(n)
if ch == "Y":
return Y(n)
if ch == "Z":
return Z(n)
raise ValueError("ch shall be X, Y, Z or I") | 170,459 |
Returns [expr1, expr2] = expr1 * expr2 - expr2 * expr1.
Args:
expr1 (Expr, Term or Pauli operator): Pauli's expression.
expr2 (Expr, Term or Pauli operator): Pauli's expression.
Returns:
Expr: expr1 * expr2 - expr2 * expr1. | def commutator(expr1, expr2):
expr1 = expr1.to_expr().simplify()
expr2 = expr2.to_expr().simplify()
return (expr1 * expr2 - expr2 * expr1).simplify() | 170,460 |
Test whether expr1 and expr2 are commutable.
Args:
expr1 (Expr, Term or Pauli operator): Pauli's expression.
expr2 (Expr, Term or Pauli operator): Pauli's expression.
eps (float, optional): Machine epsilon.
If |[expr1, expr2]| < eps, consider it is commutable.
Returns:
... | def is_commutable(expr1, expr2, eps=0.00000001):
return sum((x * x.conjugate()).real for x in commutator(expr1, expr2).coeffs()) < eps | 170,461 |
Make Pauli's Term from chars which is written by "X", "Y", "Z" or "I".
e.g. "XZIY" => X(0) * Z(1) * Y(3)
Args:
chars (str): Written in "X", "Y", "Z" or "I".
Returns:
Term: A `Term` object.
Raises:
ValueError: When chars conteins the character which ... | def from_chars(chars):
paulis = [pauli_from_char(c, n) for n, c in enumerate(chars) if c != "I"]
if not paulis:
return 1.0 * I
if len(paulis) == 1:
return 1.0 * paulis[0]
return reduce(lambda a, b: a * b, paulis) | 170,468 |
Sets the stroke properties.
Args:
width (int): stroke width
color (str): stroke color | def set_stroke(self, width=1, color='black'):
self.attributes['stroke'] = color
self.attributes['stroke-width'] = str(width) | 170,514 |
setup a method as an event, adding also javascript code to generate
Args:
js_code (str): javascript code to generate the event client-side.
js_code is added to the widget html as
widget.attributes['onclick'] = js_code%{'emitter_identifier':widget.identifier, 'event_name':'onclick'} | def decorate_event_js(js_code):
def add_annotation(method):
setattr(method, "__is_event", True )
setattr(method, "_js_code", js_code )
return method
return add_annotation | 170,611 |
Private decorator for use in the editor.
Allows the Editor to create listener methods.
Args:
params (str): The list of parameters for the listener
method (es. "(self, new_value)") | def decorate_set_on_listener(prototype):
# noinspection PyDictCreation,PyProtectedMember
def add_annotation(method):
method._event_info = {}
method._event_info['name'] = method.__name__
method._event_info['prototype'] = prototype
return method
return add_annotation | 170,612 |
It is used to automatically represent the object to HTML format
packs all the attributes, children and so on.
Args:
changed_widgets (dict): A dictionary containing a collection of tags that have to be updated.
The tag that have to be updated is the key, and the value is its ... | def repr(self, changed_widgets=None):
if changed_widgets is None:
changed_widgets = {}
local_changed_widgets = {}
_innerHTML = self.innerHTML(local_changed_widgets)
if self._ischanged() or ( len(local_changed_widgets) > 0 ):
self._backup_repr = ''.join((... | 170,625 |
Adds a child to the Tag
To retrieve the child call get_child or access to the Tag.children[key] dictionary.
Args:
key (str): Unique child's identifier, or iterable of keys
value (Tag, str): can be a Tag, an iterable of Tag or a str. In case of iterable
of Tag i... | def add_child(self, key, value):
if type(value) in (list, tuple, dict):
if type(value)==dict:
for k in value.keys():
self.add_child(k, value[k])
return
i = 0
for child in value:
self.add_child(key[i]... | 170,631 |
Removes a child instance from the Tag's children.
Args:
child (Tag): The child to be removed. | def remove_child(self, child):
if child in self.children.values() and hasattr(child, 'identifier'):
for k in self.children.keys():
if hasattr(self.children[k], 'identifier'):
if self.children[k].identifier == child.identifier:
if k... | 170,633 |
Allows to set style properties for the widget.
Args:
style (str or dict): The style property dictionary or json string. | def set_style(self, style):
if style is not None:
try:
self.style.update(style)
except ValueError:
for s in style.split(';'):
k, v = s.split(':', 1)
self.style[k.strip()] = v.strip() | 170,635 |
Set the widget size.
Args:
width (int or str): An optional width for the widget (es. width=10 or width='10px' or width='10%').
height (int or str): An optional height for the widget (es. height=10 or height='10px' or height='10%'). | def set_size(self, width, height):
if width is not None:
try:
width = to_pix(int(width))
except ValueError:
# now we know w has 'px or % in it'
pass
self.style['width'] = width
if height is not None:
... | 170,636 |
Represents the widget as HTML format, packs all the attributes, children and so on.
Args:
client (App): Client instance.
changed_widgets (dict): A dictionary containing a collection of widgets that have to be updated.
The Widget that have to be updated is the key, and th... | def repr(self, changed_widgets=None):
if changed_widgets is None:
changed_widgets={}
return super(Widget, self).repr(changed_widgets) | 170,637 |
Called when user types and releases a key.
The widget should be able to receive the focus in order to emit the event.
Assign a 'tabindex' attribute to make it focusable.
Args:
key (str): the character value
keycode (str): the numeric char code | def onkeyup(self, key, keycode, ctrl, shift, alt):
return (key, keycode, ctrl, shift, alt) | 170,638 |
Called when user types and releases a key.
The widget should be able to receive the focus in order to emit the event.
Assign a 'tabindex' attribute to make it focusable.
Args:
key (str): the character value
keycode (str): the numeric char code | def onkeydown(self, key, keycode, ctrl, shift, alt):
return (key, keycode, ctrl, shift, alt) | 170,639 |
It is used to automatically represent the object to HTML format
packs all the attributes, children and so on.
Args:
changed_widgets (dict): A dictionary containing a collection of tags that have to be updated.
The tag that have to be updated is the key, and the value is its ... | def repr(self, changed_widgets=None):
if changed_widgets is None:
changed_widgets={}
local_changed_widgets = {}
self._set_updated()
return ''.join(('<', self.type, '>\n', self.innerHTML(local_changed_widgets), '\n</', self.type, '>')) | 170,641 |
Allows to define an icon for the App
Args:
filename (str): the resource file name (ie. "/res:myicon.png")
rel (str): leave it unchanged (standard "icon") | def set_icon_file(self, filename, rel="icon"):
mimetype, encoding = mimetypes.guess_type(filename)
self.add_child("favicon", '<link rel="%s" href="%s" type="%s" />'%(rel, filename, mimetype)) | 170,643 |
Allows to define an icon for the App
Args:
base64_data (str): base64 encoded image data (ie. "data:image/x-icon;base64,AAABAAEAEBA....")
mimetype (str): mimetype of the image ("image/png" or "image/x-icon"...)
rel (str): leave it unchanged (standard ... | def set_icon_data(self, base64_data, mimetype="image/png", rel="icon"):
self.add_child("favicon", '<link rel="%s" href="%s" type="%s" />'%(rel, base64_data, mimetype)) | 170,644 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.