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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
xenia-project/xenia | 9b1fdac98665ac091b9660a5d0fbb259ed79e578 | third_party/google-styleguide/cpplint/cpplint.py | python | CheckAltTokens | (filename, clean_lines, linenum, error) | 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. | Check alternative keywords being used in boolean expressions. | [
"Check",
"alternative",
"keywords",
"being",
"used",
"in",
"boolean",
"expressions",
"."
] | def CheckAltTokens(filename, clean_lines, linenum, error):
"""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.
"""
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
# current line, but it catches most of the false positives. At least,
# it provides a way to workaround this warning for people who use
# multi-line comments in preprocessor macros.
#
# TODO(unknown): remove this once cpplint has better support for
# multi-line comments.
if line.find('/*') >= 0 or line.find('*/') >= 0:
return
for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
error(filename, linenum, 'readability/alt_tokens', 2,
'Use operator %s instead of %s' % (
_ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) | [
"def",
"CheckAltTokens",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Avoid preprocessor lines",
"if",
"Match",
"(",
"r'^\\s*#'",
",",
"line",
")",
":",
"retur... | https://github.com/xenia-project/xenia/blob/9b1fdac98665ac091b9660a5d0fbb259ed79e578/third_party/google-styleguide/cpplint/cpplint.py#L3904-L3933 | ||
cmu-db/noisepage | 79276e68fe83322f1249e8a8be96bd63c583ae56 | build-support/cpplint.py | python | FlagCxx11Features | (filename, clean_lines, linenum, error) | Flag those c++11 features that we only allow in certain places.
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. | Flag those c++11 features that we only allow in certain places. | [
"Flag",
"those",
"c",
"++",
"11",
"features",
"that",
"we",
"only",
"allow",
"in",
"certain",
"places",
"."
] | def FlagCxx11Features(filename, clean_lines, linenum, error):
"""Flag those c++11 features that we only allow in certain places.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
# Flag unapproved C++ TR1 headers.
if include and include.group(1).startswith('tr1/'):
error(filename, linenum, 'build/c++tr1', 5,
('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
# Flag unapproved C++11 headers.
if include and include.group(1) in ('cfenv',
'condition_variable',
'fenv.h',
'future',
'mutex',
'thread',
'chrono',
'ratio',
'regex',
'system_error',
):
error(filename, linenum, 'build/c++11', 5,
('<%s> is an unapproved C++11 header.') % include.group(1))
# The only place where we need to worry about C++11 keywords and library
# features in preprocessor directives is in macro definitions.
if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
# These are classes and free functions. The classes are always
# mentioned as std::*, but we only catch the free functions if
# they're not found by ADL. They're alphabetical by header.
for top_name in (
# type_traits
'alignment_of',
'aligned_union',
):
if Search(r'\bstd::%s\b' % top_name, line):
error(filename, linenum, 'build/c++11', 5,
('std::%s is an unapproved C++11 class or function. Send c-style '
'an example of where it would make your code more readable, and '
'they may let you use it.') % top_name) | [
"def",
"FlagCxx11Features",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"include",
"=",
"Match",
"(",
"r'\\s*#\\s*include\\s+[<\"]([^<\"]+)[\">]'",
",",
"line",
")",... | https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/build-support/cpplint.py#L6109-L6158 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/graphics.py | python | GraphicsContext.SetCompositingOperator | (self, op) | return self._context.set_operator(op) | Sets the compositin operator to be used for all drawing
operations. The default operator is OPERATOR_OVER. | Sets the compositin operator to be used for all drawing
operations. The default operator is OPERATOR_OVER. | [
"Sets",
"the",
"compositin",
"operator",
"to",
"be",
"used",
"for",
"all",
"drawing",
"operations",
".",
"The",
"default",
"operator",
"is",
"OPERATOR_OVER",
"."
] | def SetCompositingOperator(self, op):
"""
Sets the compositin operator to be used for all drawing
operations. The default operator is OPERATOR_OVER.
"""
return self._context.set_operator(op) | [
"def",
"SetCompositingOperator",
"(",
"self",
",",
"op",
")",
":",
"return",
"self",
".",
"_context",
".",
"set_operator",
"(",
"op",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/graphics.py#L1562-L1567 | |
floooh/oryol | eb08cffe1b1cb6b05ed14ec692bca9372cef064e | fips-files/generators/util/png.py | python | read_pam_header | (infile) | return 'P7', width, height, depth, maxval | Read (the rest of a) PAM header. `infile` should be positioned
immediately after the initial 'P7' line (at the beginning of the
second line). Returns are as for `read_pnm_header`. | Read (the rest of a) PAM header. `infile` should be positioned
immediately after the initial 'P7' line (at the beginning of the
second line). Returns are as for `read_pnm_header`. | [
"Read",
"(",
"the",
"rest",
"of",
"a",
")",
"PAM",
"header",
".",
"infile",
"should",
"be",
"positioned",
"immediately",
"after",
"the",
"initial",
"P7",
"line",
"(",
"at",
"the",
"beginning",
"of",
"the",
"second",
"line",
")",
".",
"Returns",
"are",
... | def read_pam_header(infile):
"""
Read (the rest of a) PAM header. `infile` should be positioned
immediately after the initial 'P7' line (at the beginning of the
second line). Returns are as for `read_pnm_header`.
"""
# Unlike PBM, PGM, and PPM, we can read the header a line at a time.
header = dict()
while True:
l = infile.readline().strip()
if l == strtobytes('ENDHDR'):
break
if not l:
raise EOFError('PAM ended prematurely')
if l[0] == strtobytes('#'):
continue
l = l.split(None, 1)
if l[0] not in header:
header[l[0]] = l[1]
else:
header[l[0]] += strtobytes(' ') + l[1]
required = ['WIDTH', 'HEIGHT', 'DEPTH', 'MAXVAL']
required = [strtobytes(x) for x in required]
WIDTH,HEIGHT,DEPTH,MAXVAL = required
present = [x for x in required if x in header]
if len(present) != len(required):
raise Error('PAM file must specify WIDTH, HEIGHT, DEPTH, and MAXVAL')
width = int(header[WIDTH])
height = int(header[HEIGHT])
depth = int(header[DEPTH])
maxval = int(header[MAXVAL])
if (width <= 0 or
height <= 0 or
depth <= 0 or
maxval <= 0):
raise Error(
'WIDTH, HEIGHT, DEPTH, MAXVAL must all be positive integers')
return 'P7', width, height, depth, maxval | [
"def",
"read_pam_header",
"(",
"infile",
")",
":",
"# Unlike PBM, PGM, and PPM, we can read the header a line at a time.",
"header",
"=",
"dict",
"(",
")",
"while",
"True",
":",
"l",
"=",
"infile",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"if",
"l",
... | https://github.com/floooh/oryol/blob/eb08cffe1b1cb6b05ed14ec692bca9372cef064e/fips-files/generators/util/png.py#L3470-L3509 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/ndimage/interpolation.py | python | map_coordinates | (input, coordinates, output=None, order=3,
mode='constant', cval=0.0, prefilter=True) | return output | Map the input array to new coordinates by interpolation.
The array of coordinates is used to find, for each point in the output,
the corresponding coordinates in the input. The value of the input at
those coordinates is determined by spline interpolation of the
requested order.
The shape of the output is derived from that of the coordinate
array by dropping the first axis. The values of the array along
the first axis are the coordinates in the input array at which the
output value is found.
Parameters
----------
%(input)s
coordinates : array_like
The coordinates at which `input` is evaluated.
%(output)s
order : int, optional
The order of the spline interpolation, default is 3.
The order has to be in the range 0-5.
%(mode)s
%(cval)s
%(prefilter)s
Returns
-------
map_coordinates : ndarray
The result of transforming the input. The shape of the output is
derived from that of `coordinates` by dropping the first axis.
See Also
--------
spline_filter, geometric_transform, scipy.interpolate
Examples
--------
>>> from scipy import ndimage
>>> a = np.arange(12.).reshape((4, 3))
>>> a
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.],
[ 9., 10., 11.]])
>>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1)
array([ 2., 7.])
Above, the interpolated value of a[0.5, 0.5] gives output[0], while
a[2, 1] is output[1].
>>> inds = np.array([[0.5, 2], [0.5, 4]])
>>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3)
array([ 2. , -33.3])
>>> ndimage.map_coordinates(a, inds, order=1, mode='nearest')
array([ 2., 8.])
>>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool)
array([ True, False], dtype=bool) | Map the input array to new coordinates by interpolation. | [
"Map",
"the",
"input",
"array",
"to",
"new",
"coordinates",
"by",
"interpolation",
"."
] | def map_coordinates(input, coordinates, output=None, order=3,
mode='constant', cval=0.0, prefilter=True):
"""
Map the input array to new coordinates by interpolation.
The array of coordinates is used to find, for each point in the output,
the corresponding coordinates in the input. The value of the input at
those coordinates is determined by spline interpolation of the
requested order.
The shape of the output is derived from that of the coordinate
array by dropping the first axis. The values of the array along
the first axis are the coordinates in the input array at which the
output value is found.
Parameters
----------
%(input)s
coordinates : array_like
The coordinates at which `input` is evaluated.
%(output)s
order : int, optional
The order of the spline interpolation, default is 3.
The order has to be in the range 0-5.
%(mode)s
%(cval)s
%(prefilter)s
Returns
-------
map_coordinates : ndarray
The result of transforming the input. The shape of the output is
derived from that of `coordinates` by dropping the first axis.
See Also
--------
spline_filter, geometric_transform, scipy.interpolate
Examples
--------
>>> from scipy import ndimage
>>> a = np.arange(12.).reshape((4, 3))
>>> a
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.],
[ 9., 10., 11.]])
>>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1)
array([ 2., 7.])
Above, the interpolated value of a[0.5, 0.5] gives output[0], while
a[2, 1] is output[1].
>>> inds = np.array([[0.5, 2], [0.5, 4]])
>>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3)
array([ 2. , -33.3])
>>> ndimage.map_coordinates(a, inds, order=1, mode='nearest')
array([ 2., 8.])
>>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool)
array([ True, False], dtype=bool)
"""
if order < 0 or order > 5:
raise RuntimeError('spline order not supported')
input = numpy.asarray(input)
if numpy.iscomplexobj(input):
raise TypeError('Complex type not supported')
coordinates = numpy.asarray(coordinates)
if numpy.iscomplexobj(coordinates):
raise TypeError('Complex type not supported')
output_shape = coordinates.shape[1:]
if input.ndim < 1 or len(output_shape) < 1:
raise RuntimeError('input and output rank must be > 0')
if coordinates.shape[0] != input.ndim:
raise RuntimeError('invalid shape for coordinate array')
mode = _ni_support._extend_mode_to_code(mode)
if prefilter and order > 1:
filtered = spline_filter(input, order, output=numpy.float64)
else:
filtered = input
output = _ni_support._get_output(output, input,
shape=output_shape)
_nd_image.geometric_transform(filtered, None, coordinates, None, None,
output, order, mode, cval, None, None)
return output | [
"def",
"map_coordinates",
"(",
"input",
",",
"coordinates",
",",
"output",
"=",
"None",
",",
"order",
"=",
"3",
",",
"mode",
"=",
"'constant'",
",",
"cval",
"=",
"0.0",
",",
"prefilter",
"=",
"True",
")",
":",
"if",
"order",
"<",
"0",
"or",
"order",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/ndimage/interpolation.py#L267-L351 | |
tinyobjloader/tinyobjloader | 8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93 | deps/cpplint.py | python | GetHeaderGuardCPPVariable | (filename) | return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_' | 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. | Returns the CPP variable that should be used as a header guard. | [
"Returns",
"the",
"CPP",
"variable",
"that",
"should",
"be",
"used",
"as",
"a",
"header",
"guard",
"."
] | def GetHeaderGuardCPPVariable(filename):
"""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.
"""
# 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').replace('c++', 'cpp')
fileinfo = FileInfo(filename)
file_path_from_root = fileinfo.RepositoryName()
if _root:
file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_' | [
"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",
... | https://github.com/tinyobjloader/tinyobjloader/blob/8322e00ae685ea623ab6ac5a6cebcfa2d22fbf93/deps/cpplint.py#L1651-L1674 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pyio.py | python | BufferedIOBase.readinto1 | (self, b) | return self._readinto(b, read1=True) | Read bytes into buffer *b*, using at most one system call
Returns an int representing the number of bytes read (0 for EOF).
Raises BlockingIOError if the underlying raw stream has no
data at the moment. | Read bytes into buffer *b*, using at most one system call | [
"Read",
"bytes",
"into",
"buffer",
"*",
"b",
"*",
"using",
"at",
"most",
"one",
"system",
"call"
] | def readinto1(self, b):
"""Read bytes into buffer *b*, using at most one system call
Returns an int representing the number of bytes read (0 for EOF).
Raises BlockingIOError if the underlying raw stream has no
data at the moment.
"""
return self._readinto(b, read1=True) | [
"def",
"readinto1",
"(",
"self",
",",
"b",
")",
":",
"return",
"self",
".",
"_readinto",
"(",
"b",
",",
"read1",
"=",
"True",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pyio.py#L684-L693 | |
libornovax/master_thesis_code | 6eca474ed3cae673afde010caef338cf7349f839 | caffe/scripts/cpp_lint.py | python | ResetNolintSuppressions | () | Resets the set of NOLINT suppressions to empty. | Resets the set of NOLINT suppressions to empty. | [
"Resets",
"the",
"set",
"of",
"NOLINT",
"suppressions",
"to",
"empty",
"."
] | def ResetNolintSuppressions():
"Resets the set of NOLINT suppressions to empty."
_error_suppressions.clear() | [
"def",
"ResetNolintSuppressions",
"(",
")",
":",
"_error_suppressions",
".",
"clear",
"(",
")"
] | https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/caffe/scripts/cpp_lint.py#L495-L497 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pyedbglib/protocols/cmsisdap.py | python | CmsisDapDebugger.init_swj | (self) | Magic sequence to execute on pins to enable SWD in case of JTAG-default parts | Magic sequence to execute on pins to enable SWD in case of JTAG-default parts | [
"Magic",
"sequence",
"to",
"execute",
"on",
"pins",
"to",
"enable",
"SWD",
"in",
"case",
"of",
"JTAG",
"-",
"default",
"parts"
] | def init_swj(self):
"""Magic sequence to execute on pins to enable SWD in case of JTAG-default parts"""
self.logger.debug("SWJ init sequence")
# According to ARM manuals:
# Send at least 50 cycles with TMS=1
self._send_flush_tms()
# Send 16-bit switching code
cmd = bytearray(2)
cmd[0] = self.ID_DAP_SWJ_Sequence
cmd[1] = 16
cmd.extend(binary.pack_le16(0xE79E))
rsp = self.dap_command_response(cmd)
self._check_response(cmd, rsp)
if rsp[1] != self.DAP_OK:
raise PyedbglibError("SWJ sequence failed (0x{0:02X})".format(rsp[1]))
# Flush TMS again
self._send_flush_tms()
# Set data low again
cmd = bytearray(3)
cmd[0] = self.ID_DAP_SWJ_Sequence
cmd[1] = 1
cmd[2] = 0x00
rsp = self.dap_command_response(cmd)
self._check_response(cmd, rsp)
if rsp[1] != self.DAP_OK:
raise PyedbglibError("SWJ sequence failed (0x{0:02X})".format(rsp[1]))
# Now read the ID to check that it has switched
dap_id = self.dap_read_idcode()
if dap_id != self.CM0P_DAPID:
raise PyedbglibError("Invalid SWD DAP ID code! Only M0+ is currently supported.") | [
"def",
"init_swj",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"SWJ init sequence\"",
")",
"# According to ARM manuals:",
"# Send at least 50 cycles with TMS=1",
"self",
".",
"_send_flush_tms",
"(",
")",
"# Send 16-bit switching code",
"cmd",
"=",... | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/protocols/cmsisdap.py#L453-L486 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | LayoutConstraints.AreSatisfied | (*args, **kwargs) | return _core_.LayoutConstraints_AreSatisfied(*args, **kwargs) | AreSatisfied(self) -> bool | AreSatisfied(self) -> bool | [
"AreSatisfied",
"(",
"self",
")",
"-",
">",
"bool"
] | def AreSatisfied(*args, **kwargs):
"""AreSatisfied(self) -> bool"""
return _core_.LayoutConstraints_AreSatisfied(*args, **kwargs) | [
"def",
"AreSatisfied",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"LayoutConstraints_AreSatisfied",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L16362-L16364 | |
eomahony/Numberjack | 53fa9e994a36f881ffd320d8d04158097190aad8 | Numberjack/__init__.py | python | NBJ_STD_Solver.load_gmpl | (self, filename, data=None) | Asks the underlying MIP solver to load a GMPL file, possibly with a
separate data file.
:param filename: the path to the file.
:param data: optional path to a data file.
:raises UnsupportedSolverFunction: if called on a non MIP solver. | Asks the underlying MIP solver to load a GMPL file, possibly with a
separate data file. | [
"Asks",
"the",
"underlying",
"MIP",
"solver",
"to",
"load",
"a",
"GMPL",
"file",
"possibly",
"with",
"a",
"separate",
"data",
"file",
"."
] | def load_gmpl(self, filename, data=None):
"""
Asks the underlying MIP solver to load a GMPL file, possibly with a
separate data file.
:param filename: the path to the file.
:param data: optional path to a data file.
:raises UnsupportedSolverFunction: if called on a non MIP solver.
"""
if not hasattr(self.solver, 'load_gmpl'):
raise UnsupportedSolverFunction(
str(type(self)), "load_gmpl", "Please load the model using a "
"MIP solver to use this functionality.")
if data == None:
self.solver.load_gmpl(filename)
else:
self.solver.load_gmpl(filename, data) | [
"def",
"load_gmpl",
"(",
"self",
",",
"filename",
",",
"data",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"solver",
",",
"'load_gmpl'",
")",
":",
"raise",
"UnsupportedSolverFunction",
"(",
"str",
"(",
"type",
"(",
"self",
")",
")"... | https://github.com/eomahony/Numberjack/blob/53fa9e994a36f881ffd320d8d04158097190aad8/Numberjack/__init__.py#L3859-L3875 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/tools/freeze_graph.py | python | _parse_input_meta_graph_proto | (input_graph, input_binary) | return input_meta_graph_def | Parses input tensorflow graph into MetaGraphDef proto. | Parses input tensorflow graph into MetaGraphDef proto. | [
"Parses",
"input",
"tensorflow",
"graph",
"into",
"MetaGraphDef",
"proto",
"."
] | def _parse_input_meta_graph_proto(input_graph, input_binary):
"""Parses input tensorflow graph into MetaGraphDef proto."""
if not gfile.Exists(input_graph):
raise IOError("Input meta graph file '" + input_graph + "' does not exist!")
input_meta_graph_def = MetaGraphDef()
mode = "rb" if input_binary else "r"
with gfile.GFile(input_graph, mode) as f:
if input_binary:
input_meta_graph_def.ParseFromString(f.read())
else:
text_format.Merge(f.read(), input_meta_graph_def)
print("Loaded meta graph file '" + input_graph)
return input_meta_graph_def | [
"def",
"_parse_input_meta_graph_proto",
"(",
"input_graph",
",",
"input_binary",
")",
":",
"if",
"not",
"gfile",
".",
"Exists",
"(",
"input_graph",
")",
":",
"raise",
"IOError",
"(",
"\"Input meta graph file '\"",
"+",
"input_graph",
"+",
"\"' does not exist!\"",
")... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tools/freeze_graph.py#L253-L265 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextCtrl.MoveCaretForward | (*args, **kwargs) | return _richtext.RichTextCtrl_MoveCaretForward(*args, **kwargs) | MoveCaretForward(self, long oldPosition) | MoveCaretForward(self, long oldPosition) | [
"MoveCaretForward",
"(",
"self",
"long",
"oldPosition",
")"
] | def MoveCaretForward(*args, **kwargs):
"""MoveCaretForward(self, long oldPosition)"""
return _richtext.RichTextCtrl_MoveCaretForward(*args, **kwargs) | [
"def",
"MoveCaretForward",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_MoveCaretForward",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L4080-L4082 | |
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/toolset.py | python | __set_target_variables_aux | (manager, rule_or_module, ps) | return result | Given a rule name and a property set, returns a list of tuples of
variables names and values, which must be set on targets for that
rule/properties combination. | Given a rule name and a property set, returns a list of tuples of
variables names and values, which must be set on targets for that
rule/properties combination. | [
"Given",
"a",
"rule",
"name",
"and",
"a",
"property",
"set",
"returns",
"a",
"list",
"of",
"tuples",
"of",
"variables",
"names",
"and",
"values",
"which",
"must",
"be",
"set",
"on",
"targets",
"for",
"that",
"rule",
"/",
"properties",
"combination",
"."
] | def __set_target_variables_aux (manager, rule_or_module, ps):
""" Given a rule name and a property set, returns a list of tuples of
variables names and values, which must be set on targets for that
rule/properties combination.
"""
assert isinstance(rule_or_module, basestring)
assert isinstance(ps, property_set.PropertySet)
result = []
for f in __flags.get(rule_or_module, []):
if not f.condition or find_satisfied_condition (f.condition, ps):
processed = []
for v in f.values:
# The value might be <feature-name> so needs special
# treatment.
processed += __handle_flag_value (manager, v, ps)
for r in processed:
result.append ((f.variable_name, r))
# strip away last dot separated part and recurse.
next = __re_split_last_segment.match(rule_or_module)
if next:
result.extend(__set_target_variables_aux(
manager, next.group(1), ps))
return result | [
"def",
"__set_target_variables_aux",
"(",
"manager",
",",
"rule_or_module",
",",
"ps",
")",
":",
"assert",
"isinstance",
"(",
"rule_or_module",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"ps",
",",
"property_set",
".",
"PropertySet",
")",
"result",
"="... | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/toolset.py#L301-L329 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathSlot.py | python | Create | (name, obj=None, parentJob=None) | return obj | Create(name) ... Creates and returns a Slot operation. | Create(name) ... Creates and returns a Slot operation. | [
"Create",
"(",
"name",
")",
"...",
"Creates",
"and",
"returns",
"a",
"Slot",
"operation",
"."
] | def Create(name, obj=None, parentJob=None):
'''Create(name) ... Creates and returns a Slot operation.'''
if obj is None:
obj = FreeCAD.ActiveDocument.addObject("Path::FeaturePython", name)
obj.Proxy = ObjectSlot(obj, name, parentJob)
return obj | [
"def",
"Create",
"(",
"name",
",",
"obj",
"=",
"None",
",",
"parentJob",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"None",
":",
"obj",
"=",
"FreeCAD",
".",
"ActiveDocument",
".",
"addObject",
"(",
"\"Path::FeaturePython\"",
",",
"name",
")",
"obj",
"."... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathSlot.py#L1770-L1775 | |
arkenthera/electron-vibrancy | 383153ef9ccb23a6c7517150d6bb0794dff3115e | scripts/cpplint.py | python | CheckCommaSpacing | (filename, clean_lines, linenum, error) | 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. | Checks for horizontal spacing near commas and semicolons. | [
"Checks",
"for",
"horizontal",
"spacing",
"near",
"commas",
"and",
"semicolons",
"."
] | def CheckCommaSpacing(filename, clean_lines, linenum, error):
"""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.
"""
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 comma, since the only time when that happens is
# for empty macro arguments.
#
# We run this check in two passes: first pass on elided lines to
# verify that lines contain missing whitespaces, second pass on raw
# lines to confirm that those missing whitespaces are not due to
# elided comments.
if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]):
error(filename, linenum, 'whitespace/comma', 3,
'Missing space after ,')
# You should always have a space after a semicolon
# except for few corner cases
# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
# space after ;
if Search(r';[^\s};\\)/]', line):
error(filename, linenum, 'whitespace/semicolon', 3,
'Missing space after ;') | [
"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 af... | https://github.com/arkenthera/electron-vibrancy/blob/383153ef9ccb23a6c7517150d6bb0794dff3115e/scripts/cpplint.py#L2940-L2972 | ||
cornell-zhang/heterocl | 6d9e4b4acc2ee2707b2d25b27298c0335bccedfd | python/heterocl/visitor.py | python | HalideIRVisitor.visit_Lambda | (self, node) | return self.visit(body), indices | Visit lambda x, y: expr
Returns
-------
Stmt, Expr | Visit lambda x, y: expr | [
"Visit",
"lambda",
"x",
"y",
":",
"expr"
] | def visit_Lambda(self, node):
"""Visit lambda x, y: expr
Returns
-------
Stmt, Expr
"""
args = node.args.args
body = node.body
indices = []
for arg in args:
assert isinstance(arg, ast.Name), "Argument to the lambda function must be a name"
name = arg.id
tvm_var = tvm.var(arg.id, dtype = "int32") #must be a for loop index
var = {'var': tvm_var, 'type': 'for', 'allocated': True}
self.insert_var(name, var)
indices.append(tvm_var)
return self.visit(body), indices | [
"def",
"visit_Lambda",
"(",
"self",
",",
"node",
")",
":",
"args",
"=",
"node",
".",
"args",
".",
"args",
"body",
"=",
"node",
".",
"body",
"indices",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"ast",
... | https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/visitor.py#L631-L648 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | ToolBarBase.FindById | (*args, **kwargs) | return _controls_.ToolBarBase_FindById(*args, **kwargs) | FindById(self, int toolid) -> ToolBarToolBase | FindById(self, int toolid) -> ToolBarToolBase | [
"FindById",
"(",
"self",
"int",
"toolid",
")",
"-",
">",
"ToolBarToolBase"
] | def FindById(*args, **kwargs):
"""FindById(self, int toolid) -> ToolBarToolBase"""
return _controls_.ToolBarBase_FindById(*args, **kwargs) | [
"def",
"FindById",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ToolBarBase_FindById",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L3903-L3905 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/factorization/python/ops/gmm_ops.py | python | GmmAlgorithm._create_variables | (self) | Initializes GMM algorithm. | Initializes GMM algorithm. | [
"Initializes",
"GMM",
"algorithm",
"."
] | def _create_variables(self):
"""Initializes GMM algorithm."""
init_value = array_ops.constant([], dtype=dtypes.float32)
self._means = variables.Variable(init_value,
name=self.CLUSTERS_VARIABLE,
validate_shape=False)
self._covs = variables.Variable(
init_value, name=self.CLUSTERS_COVS_VARIABLE, validate_shape=False)
# Mixture weights, representing the probability that a randomly
# selected unobservable data (in EM terms) was generated by component k.
self._alpha = variable_scope.variable(
array_ops.tile([1.0 / self._num_classes], [self._num_classes]),
name=self.CLUSTERS_WEIGHT,
validate_shape=False)
self._cluster_centers_initialized = variables.Variable(False,
dtype=dtypes.bool,
name='initialized') | [
"def",
"_create_variables",
"(",
"self",
")",
":",
"init_value",
"=",
"array_ops",
".",
"constant",
"(",
"[",
"]",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
")",
"self",
".",
"_means",
"=",
"variables",
".",
"Variable",
"(",
"init_value",
",",
"name",... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L156-L172 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/data_flow_ops.py | python | BaseStagingArea.names | (self) | return self._names | The list of names for each component of a staging area element. | The list of names for each component of a staging area element. | [
"The",
"list",
"of",
"names",
"for",
"each",
"component",
"of",
"a",
"staging",
"area",
"element",
"."
] | def names(self):
"""The list of names for each component of a staging area element."""
return self._names | [
"def",
"names",
"(",
"self",
")",
":",
"return",
"self",
".",
"_names"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/data_flow_ops.py#L1666-L1668 | |
dmlc/treelite | df56babb6a4a2d7c29d719c28ce53acfa7dbab3c | python/treelite/util.py | python | py_str | (string) | return string.decode('utf-8') | Convert C string back to Python string | Convert C string back to Python string | [
"Convert",
"C",
"string",
"back",
"to",
"Python",
"string"
] | def py_str(string):
"""Convert C string back to Python string"""
return string.decode('utf-8') | [
"def",
"py_str",
"(",
"string",
")",
":",
"return",
"string",
".",
"decode",
"(",
"'utf-8'",
")"
] | https://github.com/dmlc/treelite/blob/df56babb6a4a2d7c29d719c28ce53acfa7dbab3c/python/treelite/util.py#L46-L48 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/optimize/_trustregion_ncg.py | python | CGSteihaugSubproblem.solve | (self, trust_radius) | Solve the subproblem using a conjugate gradient method.
Parameters
----------
trust_radius : float
We are allowed to wander only this far away from the origin.
Returns
-------
p : ndarray
The proposed step.
hits_boundary : bool
True if the proposed step is on the boundary of the trust region.
Notes
-----
This is algorithm (7.2) of Nocedal and Wright 2nd edition.
Only the function that computes the Hessian-vector product is required.
The Hessian itself is not required, and the Hessian does
not need to be positive semidefinite. | Solve the subproblem using a conjugate gradient method. | [
"Solve",
"the",
"subproblem",
"using",
"a",
"conjugate",
"gradient",
"method",
"."
] | def solve(self, trust_radius):
"""
Solve the subproblem using a conjugate gradient method.
Parameters
----------
trust_radius : float
We are allowed to wander only this far away from the origin.
Returns
-------
p : ndarray
The proposed step.
hits_boundary : bool
True if the proposed step is on the boundary of the trust region.
Notes
-----
This is algorithm (7.2) of Nocedal and Wright 2nd edition.
Only the function that computes the Hessian-vector product is required.
The Hessian itself is not required, and the Hessian does
not need to be positive semidefinite.
"""
# get the norm of jacobian and define the origin
p_origin = np.zeros_like(self.jac)
# define a default tolerance
tolerance = min(0.5, math.sqrt(self.jac_mag)) * self.jac_mag
# Stop the method if the search direction
# is a direction of nonpositive curvature.
if self.jac_mag < tolerance:
hits_boundary = False
return p_origin, hits_boundary
# init the state for the first iteration
z = p_origin
r = self.jac
d = -r
# Search for the min of the approximation of the objective function.
while True:
# do an iteration
Bd = self.hessp(d)
dBd = np.dot(d, Bd)
if dBd <= 0:
# Look at the two boundary points.
# Find both values of t to get the boundary points such that
# ||z + t d|| == trust_radius
# and then choose the one with the predicted min value.
ta, tb = self.get_boundaries_intersections(z, d, trust_radius)
pa = z + ta * d
pb = z + tb * d
if self(pa) < self(pb):
p_boundary = pa
else:
p_boundary = pb
hits_boundary = True
return p_boundary, hits_boundary
r_squared = np.dot(r, r)
alpha = r_squared / dBd
z_next = z + alpha * d
if scipy.linalg.norm(z_next) >= trust_radius:
# Find t >= 0 to get the boundary point such that
# ||z + t d|| == trust_radius
ta, tb = self.get_boundaries_intersections(z, d, trust_radius)
p_boundary = z + tb * d
hits_boundary = True
return p_boundary, hits_boundary
r_next = r + alpha * Bd
r_next_squared = np.dot(r_next, r_next)
if math.sqrt(r_next_squared) < tolerance:
hits_boundary = False
return z_next, hits_boundary
beta_next = r_next_squared / r_squared
d_next = -r_next + beta_next * d
# update the state for the next iteration
z = z_next
r = r_next
d = d_next | [
"def",
"solve",
"(",
"self",
",",
"trust_radius",
")",
":",
"# get the norm of jacobian and define the origin",
"p_origin",
"=",
"np",
".",
"zeros_like",
"(",
"self",
".",
"jac",
")",
"# define a default tolerance",
"tolerance",
"=",
"min",
"(",
"0.5",
",",
"math"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/_trustregion_ncg.py#L46-L128 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/image/python/ops/sparse_image_warp.py | python | sparse_image_warp | (image,
source_control_point_locations,
dest_control_point_locations,
interpolation_order=2,
regularization_weight=0.0,
num_boundary_points=0,
name='sparse_image_warp') | Image warping using correspondences between sparse control points.
Apply a non-linear warp to the image, where the warp is specified by
the source and destination locations of a (potentially small) number of
control points. First, we use a polyharmonic spline
(`tf.contrib.image.interpolate_spline`) to interpolate the displacements
between the corresponding control points to a dense flow field.
Then, we warp the image using this dense flow field
(`tf.contrib.image.dense_image_warp`).
Let t index our control points. For regularization_weight=0, we have:
warped_image[b, dest_control_point_locations[b, t, 0],
dest_control_point_locations[b, t, 1], :] =
image[b, source_control_point_locations[b, t, 0],
source_control_point_locations[b, t, 1], :].
For regularization_weight > 0, this condition is met approximately, since
regularized interpolation trades off smoothness of the interpolant vs.
reconstruction of the interpolant at the control points.
See `tf.contrib.image.interpolate_spline` for further documentation of the
interpolation_order and regularization_weight arguments.
Args:
image: `[batch, height, width, channels]` float `Tensor`
source_control_point_locations: `[batch, num_control_points, 2]` float
`Tensor`
dest_control_point_locations: `[batch, num_control_points, 2]` float
`Tensor`
interpolation_order: polynomial order used by the spline interpolation
regularization_weight: weight on smoothness regularizer in interpolation
num_boundary_points: How many zero-flow boundary points to include at
each image edge.Usage:
num_boundary_points=0: don't add zero-flow points
num_boundary_points=1: 4 corners of the image
num_boundary_points=2: 4 corners and one in the middle of each edge
(8 points total)
num_boundary_points=n: 4 corners and n-1 along each edge
name: A name for the operation (optional).
Note that image and offsets can be of type tf.half, tf.float32, or
tf.float64, and do not necessarily have to be the same type.
Returns:
warped_image: `[batch, height, width, channels]` float `Tensor` with same
type as input image.
flow_field: `[batch, height, width, 2]` float `Tensor` containing the dense
flow field produced by the interpolation. | Image warping using correspondences between sparse control points. | [
"Image",
"warping",
"using",
"correspondences",
"between",
"sparse",
"control",
"points",
"."
] | def sparse_image_warp(image,
source_control_point_locations,
dest_control_point_locations,
interpolation_order=2,
regularization_weight=0.0,
num_boundary_points=0,
name='sparse_image_warp'):
"""Image warping using correspondences between sparse control points.
Apply a non-linear warp to the image, where the warp is specified by
the source and destination locations of a (potentially small) number of
control points. First, we use a polyharmonic spline
(`tf.contrib.image.interpolate_spline`) to interpolate the displacements
between the corresponding control points to a dense flow field.
Then, we warp the image using this dense flow field
(`tf.contrib.image.dense_image_warp`).
Let t index our control points. For regularization_weight=0, we have:
warped_image[b, dest_control_point_locations[b, t, 0],
dest_control_point_locations[b, t, 1], :] =
image[b, source_control_point_locations[b, t, 0],
source_control_point_locations[b, t, 1], :].
For regularization_weight > 0, this condition is met approximately, since
regularized interpolation trades off smoothness of the interpolant vs.
reconstruction of the interpolant at the control points.
See `tf.contrib.image.interpolate_spline` for further documentation of the
interpolation_order and regularization_weight arguments.
Args:
image: `[batch, height, width, channels]` float `Tensor`
source_control_point_locations: `[batch, num_control_points, 2]` float
`Tensor`
dest_control_point_locations: `[batch, num_control_points, 2]` float
`Tensor`
interpolation_order: polynomial order used by the spline interpolation
regularization_weight: weight on smoothness regularizer in interpolation
num_boundary_points: How many zero-flow boundary points to include at
each image edge.Usage:
num_boundary_points=0: don't add zero-flow points
num_boundary_points=1: 4 corners of the image
num_boundary_points=2: 4 corners and one in the middle of each edge
(8 points total)
num_boundary_points=n: 4 corners and n-1 along each edge
name: A name for the operation (optional).
Note that image and offsets can be of type tf.half, tf.float32, or
tf.float64, and do not necessarily have to be the same type.
Returns:
warped_image: `[batch, height, width, channels]` float `Tensor` with same
type as input image.
flow_field: `[batch, height, width, 2]` float `Tensor` containing the dense
flow field produced by the interpolation.
"""
image = ops.convert_to_tensor(image)
source_control_point_locations = ops.convert_to_tensor(
source_control_point_locations)
dest_control_point_locations = ops.convert_to_tensor(
dest_control_point_locations)
control_point_flows = (
dest_control_point_locations - source_control_point_locations)
clamp_boundaries = num_boundary_points > 0
boundary_points_per_edge = num_boundary_points - 1
with ops.name_scope(name):
batch_size, image_height, image_width, _ = image.get_shape().as_list()
# This generates the dense locations where the interpolant
# will be evaluated.
grid_locations = _get_grid_locations(image_height, image_width)
flattened_grid_locations = np.reshape(grid_locations,
[image_height * image_width, 2])
flattened_grid_locations = constant_op.constant(
_expand_to_minibatch(flattened_grid_locations, batch_size), image.dtype)
if clamp_boundaries:
(dest_control_point_locations,
control_point_flows) = _add_zero_flow_controls_at_boundary(
dest_control_point_locations, control_point_flows, image_height,
image_width, boundary_points_per_edge)
flattened_flows = interpolate_spline.interpolate_spline(
dest_control_point_locations, control_point_flows,
flattened_grid_locations, interpolation_order, regularization_weight)
dense_flows = array_ops.reshape(flattened_flows,
[batch_size, image_height, image_width, 2])
warped_image = dense_image_warp.dense_image_warp(image, dense_flows)
return warped_image, dense_flows | [
"def",
"sparse_image_warp",
"(",
"image",
",",
"source_control_point_locations",
",",
"dest_control_point_locations",
",",
"interpolation_order",
"=",
"2",
",",
"regularization_weight",
"=",
"0.0",
",",
"num_boundary_points",
"=",
"0",
",",
"name",
"=",
"'sparse_image_w... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/image/python/ops/sparse_image_warp.py#L104-L202 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.SetMarginMask | (*args, **kwargs) | return _stc.StyledTextCtrl_SetMarginMask(*args, **kwargs) | SetMarginMask(self, int margin, int mask)
Set a mask that determines which markers are displayed in a margin. | SetMarginMask(self, int margin, int mask) | [
"SetMarginMask",
"(",
"self",
"int",
"margin",
"int",
"mask",
")"
] | def SetMarginMask(*args, **kwargs):
"""
SetMarginMask(self, int margin, int mask)
Set a mask that determines which markers are displayed in a margin.
"""
return _stc.StyledTextCtrl_SetMarginMask(*args, **kwargs) | [
"def",
"SetMarginMask",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetMarginMask",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L2466-L2472 | |
JoseExposito/touchegg | 1f3fda214358d071c05da4bf17c070c33d67b5eb | cmake/cpplint.py | python | RemoveMultiLineCommentsFromRange | (lines, begin, end) | Clears a range of lines for multi-line comments. | Clears a range of lines for multi-line comments. | [
"Clears",
"a",
"range",
"of",
"lines",
"for",
"multi",
"-",
"line",
"comments",
"."
] | def RemoveMultiLineCommentsFromRange(lines, begin, end):
"""Clears a range of lines for multi-line comments."""
# Having // <empty> comments makes the lines non-empty, so we will not get
# unnecessary blank line warnings later in the code.
for i in range(begin, end):
lines[i] = '/**/' | [
"def",
"RemoveMultiLineCommentsFromRange",
"(",
"lines",
",",
"begin",
",",
"end",
")",
":",
"# Having // <empty> comments makes the lines non-empty, so we will not get",
"# unnecessary blank line warnings later in the code.",
"for",
"i",
"in",
"range",
"(",
"begin",
",",
"end"... | https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L1384-L1389 | ||
v8mips/v8mips | f0c9cc0bbfd461c7f516799d9a58e9a7395f737e | tools/stats-viewer.py | python | Counter.Name | (self) | return result | Return the ascii name of this counter. | Return the ascii name of this counter. | [
"Return",
"the",
"ascii",
"name",
"of",
"this",
"counter",
"."
] | def Name(self):
"""Return the ascii name of this counter."""
result = ""
index = self.offset + 4
current = self.data.ByteAt(index)
while current:
result += chr(current)
index += 1
current = self.data.ByteAt(index)
return result | [
"def",
"Name",
"(",
"self",
")",
":",
"result",
"=",
"\"\"",
"index",
"=",
"self",
".",
"offset",
"+",
"4",
"current",
"=",
"self",
".",
"data",
".",
"ByteAt",
"(",
"index",
")",
"while",
"current",
":",
"result",
"+=",
"chr",
"(",
"current",
")",
... | https://github.com/v8mips/v8mips/blob/f0c9cc0bbfd461c7f516799d9a58e9a7395f737e/tools/stats-viewer.py#L344-L353 | |
freesurfer/freesurfer | 6dbe527d43ffa611acb2cd112e9469f9bfec8e36 | python/freesurfer/lookups.py | python | LookupTable.copy_colors | (self, source_lut) | Copies colors of matching label indices from a source LookupTable. | Copies colors of matching label indices from a source LookupTable. | [
"Copies",
"colors",
"of",
"matching",
"label",
"indices",
"from",
"a",
"source",
"LookupTable",
"."
] | def copy_colors(self, source_lut):
"""
Copies colors of matching label indices from a source LookupTable.
"""
for label in self.keys():
elt = source_lut.get(label)
if elt is not None and elt.color is not None:
self[label].color = elt.color | [
"def",
"copy_colors",
"(",
"self",
",",
"source_lut",
")",
":",
"for",
"label",
"in",
"self",
".",
"keys",
"(",
")",
":",
"elt",
"=",
"source_lut",
".",
"get",
"(",
"label",
")",
"if",
"elt",
"is",
"not",
"None",
"and",
"elt",
".",
"color",
"is",
... | https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/python/freesurfer/lookups.py#L87-L94 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/flatnotebook.py | python | FlatNotebookEvent.SetSelection | (self, nSel) | Sets event selection. | Sets event selection. | [
"Sets",
"event",
"selection",
"."
] | def SetSelection(self, nSel):
""" Sets event selection. """
self._selection = nSel | [
"def",
"SetSelection",
"(",
"self",
",",
"nSel",
")",
":",
"self",
".",
"_selection",
"=",
"nSel"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/flatnotebook.py#L1065-L1068 | ||
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/tools/clang/bindings/python/clang/cindex.py | python | Type.element_type | (self) | return result | Retrieve the Type of elements within this Type.
If accessed on a type that is not an array, complex, or vector type, an
exception will be raised. | Retrieve the Type of elements within this Type. | [
"Retrieve",
"the",
"Type",
"of",
"elements",
"within",
"this",
"Type",
"."
] | def element_type(self):
"""Retrieve the Type of elements within this Type.
If accessed on a type that is not an array, complex, or vector type, an
exception will be raised.
"""
result = conf.lib.clang_getElementType(self)
if result.kind == TypeKind.INVALID:
raise Exception('Element type not available on this type.')
return result | [
"def",
"element_type",
"(",
"self",
")",
":",
"result",
"=",
"conf",
".",
"lib",
".",
"clang_getElementType",
"(",
"self",
")",
"if",
"result",
".",
"kind",
"==",
"TypeKind",
".",
"INVALID",
":",
"raise",
"Exception",
"(",
"'Element type not available on this ... | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/bindings/python/clang/cindex.py#L2224-L2234 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py | python | NDFrame._construct_axes_dict | (self, axes=None, **kwargs) | return d | Return an axes dictionary for myself. | Return an axes dictionary for myself. | [
"Return",
"an",
"axes",
"dictionary",
"for",
"myself",
"."
] | def _construct_axes_dict(self, axes=None, **kwargs):
"""Return an axes dictionary for myself."""
d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}
d.update(kwargs)
return d | [
"def",
"_construct_axes_dict",
"(",
"self",
",",
"axes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"a",
":",
"self",
".",
"_get_axis",
"(",
"a",
")",
"for",
"a",
"in",
"(",
"axes",
"or",
"self",
".",
"_AXIS_ORDERS",
")",
"}",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py#L343-L347 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/liquidation.py | python | Liquidation.order_id | (self) | return self._order_id | Gets the order_id of this Liquidation. # noqa: E501
:return: The order_id of this Liquidation. # noqa: E501
:rtype: str | Gets the order_id of this Liquidation. # noqa: E501 | [
"Gets",
"the",
"order_id",
"of",
"this",
"Liquidation",
".",
"#",
"noqa",
":",
"E501"
] | def order_id(self):
"""Gets the order_id of this Liquidation. # noqa: E501
:return: The order_id of this Liquidation. # noqa: E501
:rtype: str
"""
return self._order_id | [
"def",
"order_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_order_id"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/liquidation.py#L70-L77 | |
nasa/astrobee | 9241e67e6692810d6e275abb3165b6d02f4ca5ef | scripts/git/cpplint.py | python | Search | (pattern, s) | return _regexp_compile_cache[pattern].search(s) | Searches the string for the pattern, caching the compiled regexp. | Searches the string for the pattern, caching the compiled regexp. | [
"Searches",
"the",
"string",
"for",
"the",
"pattern",
"caching",
"the",
"compiled",
"regexp",
"."
] | def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s) | [
"def",
"Search",
"(",
"pattern",
",",
"s",
")",
":",
"if",
"pattern",
"not",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_cache",
"[",
"pat... | https://github.com/nasa/astrobee/blob/9241e67e6692810d6e275abb3165b6d02f4ca5ef/scripts/git/cpplint.py#L611-L615 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | ClipboardEvent.__init__ | (self, *args, **kwargs) | __init__(self, EventType evtType=wxEVT_NULL) -> ClipboardEvent | __init__(self, EventType evtType=wxEVT_NULL) -> ClipboardEvent | [
"__init__",
"(",
"self",
"EventType",
"evtType",
"=",
"wxEVT_NULL",
")",
"-",
">",
"ClipboardEvent"
] | def __init__(self, *args, **kwargs):
"""__init__(self, EventType evtType=wxEVT_NULL) -> ClipboardEvent"""
_misc_.ClipboardEvent_swiginit(self,_misc_.new_ClipboardEvent(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_misc_",
".",
"ClipboardEvent_swiginit",
"(",
"self",
",",
"_misc_",
".",
"new_ClipboardEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L5980-L5982 | ||
cybermaggedon/cyberprobe | f826dbc35ad3a79019cb871c0bc3fb1236130b3e | indicators/cyberprobe/indicators.py | python | Indicators.dumps | (self) | return json.dumps(self.dump(), indent=4) | Dumps an indicator set to JSON string. | Dumps an indicator set to JSON string. | [
"Dumps",
"an",
"indicator",
"set",
"to",
"JSON",
"string",
"."
] | def dumps(self):
""" Dumps an indicator set to JSON string. """
return json.dumps(self.dump(), indent=4) | [
"def",
"dumps",
"(",
"self",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"dump",
"(",
")",
",",
"indent",
"=",
"4",
")"
] | https://github.com/cybermaggedon/cyberprobe/blob/f826dbc35ad3a79019cb871c0bc3fb1236130b3e/indicators/cyberprobe/indicators.py#L47-L49 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py | python | FindQualifiedTargets | (target, qualified_list) | return [t for t in qualified_list if ParseQualifiedTarget(t)[1] == target] | Given a list of qualified targets, return the qualified targets for the
specified |target|. | Given a list of qualified targets, return the qualified targets for the
specified |target|. | [
"Given",
"a",
"list",
"of",
"qualified",
"targets",
"return",
"the",
"qualified",
"targets",
"for",
"the",
"specified",
"|target|",
"."
] | def FindQualifiedTargets(target, qualified_list):
"""
Given a list of qualified targets, return the qualified targets for the
specified |target|.
"""
return [t for t in qualified_list if ParseQualifiedTarget(t)[1] == target] | [
"def",
"FindQualifiedTargets",
"(",
"target",
",",
"qualified_list",
")",
":",
"return",
"[",
"t",
"for",
"t",
"in",
"qualified_list",
"if",
"ParseQualifiedTarget",
"(",
"t",
")",
"[",
"1",
"]",
"==",
"target",
"]"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py#L48-L53 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/layers/python/layers/utils.py | python | constant_value | (value_or_tensor_or_var, dtype=None) | return value | Returns value if value_or_tensor_or_var has a constant value.
Args:
value_or_tensor_or_var: A value, a `Tensor` or a `Variable`.
dtype: Optional `tf.dtype`, if set it would check it has the right
dtype.
Returns:
The constant value or None if it not constant.
Raises:
ValueError: if value_or_tensor_or_var is None or the tensor_variable has the
wrong dtype. | Returns value if value_or_tensor_or_var has a constant value. | [
"Returns",
"value",
"if",
"value_or_tensor_or_var",
"has",
"a",
"constant",
"value",
"."
] | def constant_value(value_or_tensor_or_var, dtype=None):
"""Returns value if value_or_tensor_or_var has a constant value.
Args:
value_or_tensor_or_var: A value, a `Tensor` or a `Variable`.
dtype: Optional `tf.dtype`, if set it would check it has the right
dtype.
Returns:
The constant value or None if it not constant.
Raises:
ValueError: if value_or_tensor_or_var is None or the tensor_variable has the
wrong dtype.
"""
if value_or_tensor_or_var is None:
raise ValueError('value_or_tensor_or_var cannot be None')
value = value_or_tensor_or_var
if isinstance(value_or_tensor_or_var, (ops.Tensor, variables.Variable)):
if dtype and value_or_tensor_or_var.dtype != dtype:
raise ValueError('It has the wrong type %s instead of %s' % (
value_or_tensor_or_var.dtype, dtype))
if isinstance(value_or_tensor_or_var, variables.Variable):
value = None
else:
value = tensor_util.constant_value(value_or_tensor_or_var)
return value | [
"def",
"constant_value",
"(",
"value_or_tensor_or_var",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"value_or_tensor_or_var",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'value_or_tensor_or_var cannot be None'",
")",
"value",
"=",
"value_or_tensor_or_var",
"if",
"i... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/layers/python/layers/utils.py#L137-L163 | |
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | deps/boost/tools/build/src/build/generators.py | python | __ensure_type | (targets) | Ensures all 'targets' have types. If this is not so, exists with
error. | Ensures all 'targets' have types. If this is not so, exists with
error. | [
"Ensures",
"all",
"targets",
"have",
"types",
".",
"If",
"this",
"is",
"not",
"so",
"exists",
"with",
"error",
"."
] | def __ensure_type (targets):
""" Ensures all 'targets' have types. If this is not so, exists with
error.
"""
assert is_iterable_typed(targets, virtual_target.VirtualTarget)
for t in targets:
if not t.type ():
get_manager().errors()("target '%s' has no type" % str (t)) | [
"def",
"__ensure_type",
"(",
"targets",
")",
":",
"assert",
"is_iterable_typed",
"(",
"targets",
",",
"virtual_target",
".",
"VirtualTarget",
")",
"for",
"t",
"in",
"targets",
":",
"if",
"not",
"t",
".",
"type",
"(",
")",
":",
"get_manager",
"(",
")",
".... | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/generators.py#L978-L985 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/wrap/grad_reducer.py | python | _tensors_allreduce_post | (degree, mean, allreduce_filter, grad) | return grad | Apply allreduce on gradient in PyNative mode.
Args:
degree (int): The mean coefficient.
mean (bool): When mean is true, the mean coefficient (degree) would apply on gradients.
allgather (Primitive): The communication operator for sparse gradients.
allreduce (Primitive): The communication operator for gradients.
allreduce_filter (bool): When it is true, allreduce would apply.
grad (Tensor): The gradient tensor before operation.
Returns:
Tensor, the gradient tensor after operation. | Apply allreduce on gradient in PyNative mode. | [
"Apply",
"allreduce",
"on",
"gradient",
"in",
"PyNative",
"mode",
"."
] | def _tensors_allreduce_post(degree, mean, allreduce_filter, grad):
"""
Apply allreduce on gradient in PyNative mode.
Args:
degree (int): The mean coefficient.
mean (bool): When mean is true, the mean coefficient (degree) would apply on gradients.
allgather (Primitive): The communication operator for sparse gradients.
allreduce (Primitive): The communication operator for gradients.
allreduce_filter (bool): When it is true, allreduce would apply.
grad (Tensor): The gradient tensor before operation.
Returns:
Tensor, the gradient tensor after operation.
"""
if allreduce_filter:
if mean:
grad = F.tensor_mul(grad, F.cast(degree, F.dtype(grad)))
return grad
return grad | [
"def",
"_tensors_allreduce_post",
"(",
"degree",
",",
"mean",
",",
"allreduce_filter",
",",
"grad",
")",
":",
"if",
"allreduce_filter",
":",
"if",
"mean",
":",
"grad",
"=",
"F",
".",
"tensor_mul",
"(",
"grad",
",",
"F",
".",
"cast",
"(",
"degree",
",",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/wrap/grad_reducer.py#L107-L126 | |
devosoft/avida | c6179ffc617fdbc962b5a9c4de3e889e0ef2d94c | avida-core/support/utils/AvidaUtils/PysteTool.py | python | PysteRecursiveScanner | (node, env, path) | Recursively calls scanner corresponding to type of file being scanned, if
scanner is available. If file is a .pyste file, calls PysteScanner
instance. | Recursively calls scanner corresponding to type of file being scanned, if
scanner is available. If file is a .pyste file, calls PysteScanner
instance. | [
"Recursively",
"calls",
"scanner",
"corresponding",
"to",
"type",
"of",
"file",
"being",
"scanned",
"if",
"scanner",
"is",
"available",
".",
"If",
"file",
"is",
"a",
".",
"pyste",
"file",
"calls",
"PysteScanner",
"instance",
"."
] | def PysteRecursiveScanner(node, env, path):
"""
Recursively calls scanner corresponding to type of file being scanned, if
scanner is available. If file is a .pyste file, calls PysteScanner
instance.
"""
pyste_scanner = PysteScanner()
scanner_key = node.scanner_key()
if scanner_key in pyste_scanner.skeys: return pyste_scanner(node,env,path)
else:
scanner = env.get_scanner(scanner_key)
if scanner: return scanner(node,env,path)
else: return [] | [
"def",
"PysteRecursiveScanner",
"(",
"node",
",",
"env",
",",
"path",
")",
":",
"pyste_scanner",
"=",
"PysteScanner",
"(",
")",
"scanner_key",
"=",
"node",
".",
"scanner_key",
"(",
")",
"if",
"scanner_key",
"in",
"pyste_scanner",
".",
"skeys",
":",
"return",... | https://github.com/devosoft/avida/blob/c6179ffc617fdbc962b5a9c4de3e889e0ef2d94c/avida-core/support/utils/AvidaUtils/PysteTool.py#L49-L61 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_pytorch/pytorch_binding/pytorch_nndct/nn/modules/fix_ops.py | python | NndctScale | (Tinput, scale) | if Tinput.device == torch.device("cpu"):
Tinput.mul_(scale)
else:
nndct_kernels.Scale(Tinput, scale) | if Tinput.device == torch.device("cpu"):
Tinput.mul_(scale)
else:
nndct_kernels.Scale(Tinput, scale) | [
"if",
"Tinput",
".",
"device",
"==",
"torch",
".",
"device",
"(",
"cpu",
")",
":",
"Tinput",
".",
"mul_",
"(",
"scale",
")",
"else",
":",
"nndct_kernels",
".",
"Scale",
"(",
"Tinput",
"scale",
")"
] | def NndctScale(Tinput, scale):
device_id = 1 if Tinput.device == torch.device("cpu") else 0
nndct_kernels.Scale(Tinput, scale, device_id)
'''
if Tinput.device == torch.device("cpu"):
Tinput.mul_(scale)
else:
nndct_kernels.Scale(Tinput, scale)
''' | [
"def",
"NndctScale",
"(",
"Tinput",
",",
"scale",
")",
":",
"device_id",
"=",
"1",
"if",
"Tinput",
".",
"device",
"==",
"torch",
".",
"device",
"(",
"\"cpu\"",
")",
"else",
"0",
"nndct_kernels",
".",
"Scale",
"(",
"Tinput",
",",
"scale",
",",
"device_i... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_pytorch/pytorch_binding/pytorch_nndct/nn/modules/fix_ops.py#L55-L63 | ||
genn-team/genn | 75e1eb218cafa228bf36ae4613d1ce26e877b12c | pygenn/genn_groups.py | python | NeuronGroup.push_prev_spike_event_times_to_device | (self) | Helper to push previous spike event times to device | Helper to push previous spike event times to device | [
"Helper",
"to",
"push",
"previous",
"spike",
"event",
"times",
"to",
"device"
] | def push_prev_spike_event_times_to_device(self):
"""Helper to push previous spike event times to device"""
# **YUCK** these variables are named inconsistently
self._model.push_var_to_device("PreviousSpikeEventTimes", self.name) | [
"def",
"push_prev_spike_event_times_to_device",
"(",
"self",
")",
":",
"# **YUCK** these variables are named inconsistently",
"self",
".",
"_model",
".",
"push_var_to_device",
"(",
"\"PreviousSpikeEventTimes\"",
",",
"self",
".",
"name",
")"
] | https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/pygenn/genn_groups.py#L500-L503 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/options.py | python | OptionParser.parse_config_file | (self, path: str, final: bool = True) | Parses and loads the config file at the given path.
The config file contains Python code that will be executed (so
it is **not safe** to use untrusted config files). Anything in
the global namespace that matches a defined option will be
used to set that option's value.
Options may either be the specified type for the option or
strings (in which case they will be parsed the same way as in
`.parse_command_line`)
Example (using the options defined in the top-level docs of
this module)::
port = 80
mysql_host = 'mydb.example.com:3306'
# Both lists and comma-separated strings are allowed for
# multiple=True.
memcache_hosts = ['cache1.example.com:11011',
'cache2.example.com:11011']
memcache_hosts = 'cache1.example.com:11011,cache2.example.com:11011'
If ``final`` is ``False``, parse callbacks will not be run.
This is useful for applications that wish to combine configurations
from multiple sources.
.. note::
`tornado.options` is primarily a command-line library.
Config file support is provided for applications that wish
to use it, but applications that prefer config files may
wish to look at other libraries instead.
.. versionchanged:: 4.1
Config files are now always interpreted as utf-8 instead of
the system default encoding.
.. versionchanged:: 4.4
The special variable ``__file__`` is available inside config
files, specifying the absolute path to the config file itself.
.. versionchanged:: 5.1
Added the ability to set options via strings in config files. | Parses and loads the config file at the given path. | [
"Parses",
"and",
"loads",
"the",
"config",
"file",
"at",
"the",
"given",
"path",
"."
] | def parse_config_file(self, path: str, final: bool = True) -> None:
"""Parses and loads the config file at the given path.
The config file contains Python code that will be executed (so
it is **not safe** to use untrusted config files). Anything in
the global namespace that matches a defined option will be
used to set that option's value.
Options may either be the specified type for the option or
strings (in which case they will be parsed the same way as in
`.parse_command_line`)
Example (using the options defined in the top-level docs of
this module)::
port = 80
mysql_host = 'mydb.example.com:3306'
# Both lists and comma-separated strings are allowed for
# multiple=True.
memcache_hosts = ['cache1.example.com:11011',
'cache2.example.com:11011']
memcache_hosts = 'cache1.example.com:11011,cache2.example.com:11011'
If ``final`` is ``False``, parse callbacks will not be run.
This is useful for applications that wish to combine configurations
from multiple sources.
.. note::
`tornado.options` is primarily a command-line library.
Config file support is provided for applications that wish
to use it, but applications that prefer config files may
wish to look at other libraries instead.
.. versionchanged:: 4.1
Config files are now always interpreted as utf-8 instead of
the system default encoding.
.. versionchanged:: 4.4
The special variable ``__file__`` is available inside config
files, specifying the absolute path to the config file itself.
.. versionchanged:: 5.1
Added the ability to set options via strings in config files.
"""
config = {"__file__": os.path.abspath(path)}
with open(path, "rb") as f:
exec_in(native_str(f.read()), config, config)
for name in config:
normalized = self._normalize_name(name)
if normalized in self._options:
option = self._options[normalized]
if option.multiple:
if not isinstance(config[name], (list, str)):
raise Error(
"Option %r is required to be a list of %s "
"or a comma-separated string"
% (option.name, option.type.__name__)
)
if type(config[name]) == str and option.type != str:
option.parse(config[name])
else:
option.set(config[name])
if final:
self.run_parse_callbacks() | [
"def",
"parse_config_file",
"(",
"self",
",",
"path",
":",
"str",
",",
"final",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"config",
"=",
"{",
"\"__file__\"",
":",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"}",
"with",
"open",
"("... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/options.py#L358-L425 | ||
lagadic/visp | e14e125ccc2d7cf38f3353efa01187ef782fbd0b | modules/java/generator/gen_java.py | python | JavaWrapperGenerator.makeReport | (self) | return report.getvalue() | Returns string with generator report | Returns string with generator report | [
"Returns",
"string",
"with",
"generator",
"report"
] | def makeReport(self):
'''
Returns string with generator report
'''
report = StringIO()
total_count = len(self.ported_func_list) + len(self.skipped_func_list)
report.write("PORTED FUNCs LIST (%i of %i):\n\n" % (len(self.ported_func_list), total_count))
report.write("\n".join(self.ported_func_list))
report.write("\n\nSKIPPED FUNCs LIST (%i of %i):\n\n" % (len(self.skipped_func_list), total_count))
report.write("".join(self.skipped_func_list))
for i in self.def_args_hist.keys():
report.write("\n%i def args - %i funcs" % (i, self.def_args_hist[i]))
return report.getvalue() | [
"def",
"makeReport",
"(",
"self",
")",
":",
"report",
"=",
"StringIO",
"(",
")",
"total_count",
"=",
"len",
"(",
"self",
".",
"ported_func_list",
")",
"+",
"len",
"(",
"self",
".",
"skipped_func_list",
")",
"report",
".",
"write",
"(",
"\"PORTED FUNCs LIST... | https://github.com/lagadic/visp/blob/e14e125ccc2d7cf38f3353efa01187ef782fbd0b/modules/java/generator/gen_java.py#L609-L621 | |
Yelp/MOE | 5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c | moe/optimal_learning/python/cpp_wrappers/log_likelihood.py | python | GaussianProcessLogLikelihood.get_covariance_copy | (self) | return copy.deepcopy(self._covariance) | Return a copy of the covariance object specifying the Gaussian Process.
:return: covariance object encoding assumptions about the GP's behavior on our data
:rtype: interfaces.covariance_interface.CovarianceInterface subclass | Return a copy of the covariance object specifying the Gaussian Process. | [
"Return",
"a",
"copy",
"of",
"the",
"covariance",
"object",
"specifying",
"the",
"Gaussian",
"Process",
"."
] | def get_covariance_copy(self):
"""Return a copy of the covariance object specifying the Gaussian Process.
:return: covariance object encoding assumptions about the GP's behavior on our data
:rtype: interfaces.covariance_interface.CovarianceInterface subclass
"""
return copy.deepcopy(self._covariance) | [
"def",
"get_covariance_copy",
"(",
"self",
")",
":",
"return",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_covariance",
")"
] | https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/cpp_wrappers/log_likelihood.py#L285-L292 | |
zju3dv/clean-pvnet | 5870c509e3cc205e1bb28910a7b1a9a3c8add9a8 | lib/utils/renderer/render_utils.py | python | ViewpointSampler.sample_sphere | (num_samples) | return viewpoints | sample angles from the sphere
reference: https://zhuanlan.zhihu.com/p/25988652?group_id=828963677192491008 | sample angles from the sphere
reference: https://zhuanlan.zhihu.com/p/25988652?group_id=828963677192491008 | [
"sample",
"angles",
"from",
"the",
"sphere",
"reference",
":",
"https",
":",
"//",
"zhuanlan",
".",
"zhihu",
".",
"com",
"/",
"p",
"/",
"25988652?group_id",
"=",
"828963677192491008"
] | def sample_sphere(num_samples):
""" sample angles from the sphere
reference: https://zhuanlan.zhihu.com/p/25988652?group_id=828963677192491008
"""
begin_elevation = 0
ratio = (begin_elevation + 90) / 180
num_points = int(num_samples // (1 - ratio))
phi = (np.sqrt(5) - 1.0) / 2.
azimuths = []
elevations = []
for n in range(num_points - num_samples, num_points):
z = 2. * n / num_points - 1.
azimuths.append(np.rad2deg(2 * np.pi * n * phi % (2 * np.pi)))
elevations.append(np.rad2deg(np.arcsin(z)))
tilts = np.zeros_like(azimuths)
viewpoints = np.stack([azimuths, elevations, tilts], axis=-1)
inds = np.lexsort(
[viewpoints[:, 2], viewpoints[:, 1], viewpoints[:, 0]])
viewpoints = viewpoints[inds]
return viewpoints | [
"def",
"sample_sphere",
"(",
"num_samples",
")",
":",
"begin_elevation",
"=",
"0",
"ratio",
"=",
"(",
"begin_elevation",
"+",
"90",
")",
"/",
"180",
"num_points",
"=",
"int",
"(",
"num_samples",
"//",
"(",
"1",
"-",
"ratio",
")",
")",
"phi",
"=",
"(",
... | https://github.com/zju3dv/clean-pvnet/blob/5870c509e3cc205e1bb28910a7b1a9a3c8add9a8/lib/utils/renderer/render_utils.py#L88-L110 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/header.py | python | Header.append | (self, s, charset=None, errors='strict') | Append a string to the MIME header.
Optional charset, if given, should be a Charset instance or the name
of a character set (which will be converted to a Charset instance). A
value of None (the default) means that the charset given in the
constructor is used.
s may be a byte string or a Unicode string. If it is a byte string
(i.e. isinstance(s, str) is true), then charset is the encoding of
that byte string, and a UnicodeError will be raised if the string
cannot be decoded with that charset. If s is a Unicode string, then
charset is a hint specifying the character set of the characters in
the string. In this case, when producing an RFC 2822 compliant header
using RFC 2047 rules, the Unicode string will be encoded using the
following charsets in order: us-ascii, the charset hint, utf-8. The
first character set not to provoke a UnicodeError is used.
Optional `errors' is passed as the third argument to any unicode() or
ustr.encode() call. | Append a string to the MIME header. | [
"Append",
"a",
"string",
"to",
"the",
"MIME",
"header",
"."
] | def append(self, s, charset=None, errors='strict'):
"""Append a string to the MIME header.
Optional charset, if given, should be a Charset instance or the name
of a character set (which will be converted to a Charset instance). A
value of None (the default) means that the charset given in the
constructor is used.
s may be a byte string or a Unicode string. If it is a byte string
(i.e. isinstance(s, str) is true), then charset is the encoding of
that byte string, and a UnicodeError will be raised if the string
cannot be decoded with that charset. If s is a Unicode string, then
charset is a hint specifying the character set of the characters in
the string. In this case, when producing an RFC 2822 compliant header
using RFC 2047 rules, the Unicode string will be encoded using the
following charsets in order: us-ascii, the charset hint, utf-8. The
first character set not to provoke a UnicodeError is used.
Optional `errors' is passed as the third argument to any unicode() or
ustr.encode() call.
"""
if charset is None:
charset = self._charset
elif not isinstance(charset, Charset):
charset = Charset(charset)
# If the charset is our faux 8bit charset, leave the string unchanged
if charset != '8bit':
# We need to test that the string can be converted to unicode and
# back to a byte string, given the input and output codecs of the
# charset.
if isinstance(s, str):
# Possibly raise UnicodeError if the byte string can't be
# converted to a unicode with the input codec of the charset.
incodec = charset.input_codec or 'us-ascii'
ustr = unicode(s, incodec, errors)
# Now make sure that the unicode could be converted back to a
# byte string with the output codec, which may be different
# than the iput coded. Still, use the original byte string.
outcodec = charset.output_codec or 'us-ascii'
ustr.encode(outcodec, errors)
elif isinstance(s, unicode):
# Now we have to be sure the unicode string can be converted
# to a byte string with a reasonable output codec. We want to
# use the byte string in the chunk.
for charset in USASCII, charset, UTF8:
try:
outcodec = charset.output_codec or 'us-ascii'
s = s.encode(outcodec, errors)
break
except UnicodeError:
pass
else:
assert False, 'utf-8 conversion failed'
self._chunks.append((s, charset)) | [
"def",
"append",
"(",
"self",
",",
"s",
",",
"charset",
"=",
"None",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"charset",
"is",
"None",
":",
"charset",
"=",
"self",
".",
"_charset",
"elif",
"not",
"isinstance",
"(",
"charset",
",",
"Charset",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/header.py#L233-L286 | ||
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetCflags | (self, config) | return cflags | Returns the flags that need to be added to .c and .cc compilations. | Returns the flags that need to be added to .c and .cc compilations. | [
"Returns",
"the",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
".",
"c",
"and",
".",
"cc",
"compilations",
"."
] | def GetCflags(self, config):
"""Returns the flags that need to be added to .c and .cc compilations."""
config = self._TargetConfig(config)
cflags = []
cflags.extend(['/wd' + w for w in self.msvs_disabled_warnings[config]])
cl = self._GetWrapper(self, self.msvs_settings[config],
'VCCLCompilerTool', append=cflags)
cl('Optimization',
map={'0': 'd', '1': '1', '2': '2', '3': 'x'}, prefix='/O', default='2')
cl('InlineFunctionExpansion', prefix='/Ob')
cl('DisableSpecificWarnings', prefix='/wd')
cl('StringPooling', map={'true': '/GF'})
cl('EnableFiberSafeOptimizations', map={'true': '/GT'})
cl('OmitFramePointers', map={'false': '-', 'true': ''}, prefix='/Oy')
cl('EnableIntrinsicFunctions', map={'false': '-', 'true': ''}, prefix='/Oi')
cl('FavorSizeOrSpeed', map={'1': 't', '2': 's'}, prefix='/O')
cl('FloatingPointModel',
map={'0': 'precise', '1': 'strict', '2': 'fast'}, prefix='/fp:',
default='0')
cl('CompileAsManaged', map={'false': '', 'true': '/clr'})
cl('WholeProgramOptimization', map={'true': '/GL'})
cl('WarningLevel', prefix='/W')
cl('WarnAsError', map={'true': '/WX'})
cl('CallingConvention',
map={'0': 'd', '1': 'r', '2': 'z', '3': 'v'}, prefix='/G')
cl('DebugInformationFormat',
map={'1': '7', '3': 'i', '4': 'I'}, prefix='/Z')
cl('RuntimeTypeInfo', map={'true': '/GR', 'false': '/GR-'})
cl('EnableFunctionLevelLinking', map={'true': '/Gy', 'false': '/Gy-'})
cl('MinimalRebuild', map={'true': '/Gm'})
cl('BufferSecurityCheck', map={'true': '/GS', 'false': '/GS-'})
cl('BasicRuntimeChecks', map={'1': 's', '2': 'u', '3': '1'}, prefix='/RTC')
cl('RuntimeLibrary',
map={'0': 'T', '1': 'Td', '2': 'D', '3': 'Dd'}, prefix='/M')
cl('ExceptionHandling', map={'1': 'sc','2': 'a'}, prefix='/EH')
cl('DefaultCharIsUnsigned', map={'true': '/J'})
cl('TreatWChar_tAsBuiltInType',
map={'false': '-', 'true': ''}, prefix='/Zc:wchar_t')
cl('EnablePREfast', map={'true': '/analyze'})
cl('AdditionalOptions', prefix='')
cl('EnableEnhancedInstructionSet',
map={'1': 'SSE', '2': 'SSE2', '3': 'AVX', '4': 'IA32', '5': 'AVX2'},
prefix='/arch:')
cflags.extend(['/FI' + f for f in self._Setting(
('VCCLCompilerTool', 'ForcedIncludeFiles'), config, default=[])])
if self.vs_version.short_name in ('2013', '2013e', '2015'):
# New flag required in 2013 to maintain previous PDB behavior.
cflags.append('/FS')
# ninja handles parallelism by itself, don't have the compiler do it too.
cflags = filter(lambda x: not x.startswith('/MP'), cflags)
return cflags | [
"def",
"GetCflags",
"(",
"self",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"cflags",
"=",
"[",
"]",
"cflags",
".",
"extend",
"(",
"[",
"'/wd'",
"+",
"w",
"for",
"w",
"in",
"self",
".",
"msvs_disabled_wa... | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/msvs_emulation.py#L426-L476 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | build/android/pylib/results/flakiness_dashboard/json_results_generator.py | python | JSONResultsGeneratorBase.__init__ | (self, builder_name, build_name, build_number,
results_file_base_path, builder_base_url,
test_results_map, svn_repositories=None,
test_results_server=None,
test_type='',
master_name='') | Modifies the results.json file. Grabs it off the archive directory
if it is not found locally.
Args
builder_name: the builder name (e.g. Webkit).
build_name: the build name (e.g. webkit-rel).
build_number: the build number.
results_file_base_path: Absolute path to the directory containing the
results json file.
builder_base_url: the URL where we have the archived test results.
If this is None no archived results will be retrieved.
test_results_map: A dictionary that maps test_name to TestResult.
svn_repositories: A (json_field_name, svn_path) pair for SVN
repositories that tests rely on. The SVN revision will be
included in the JSON with the given json_field_name.
test_results_server: server that hosts test results json.
test_type: test type string (e.g. 'layout-tests').
master_name: the name of the buildbot master. | Modifies the results.json file. Grabs it off the archive directory
if it is not found locally. | [
"Modifies",
"the",
"results",
".",
"json",
"file",
".",
"Grabs",
"it",
"off",
"the",
"archive",
"directory",
"if",
"it",
"is",
"not",
"found",
"locally",
"."
] | def __init__(self, builder_name, build_name, build_number,
results_file_base_path, builder_base_url,
test_results_map, svn_repositories=None,
test_results_server=None,
test_type='',
master_name=''):
"""Modifies the results.json file. Grabs it off the archive directory
if it is not found locally.
Args
builder_name: the builder name (e.g. Webkit).
build_name: the build name (e.g. webkit-rel).
build_number: the build number.
results_file_base_path: Absolute path to the directory containing the
results json file.
builder_base_url: the URL where we have the archived test results.
If this is None no archived results will be retrieved.
test_results_map: A dictionary that maps test_name to TestResult.
svn_repositories: A (json_field_name, svn_path) pair for SVN
repositories that tests rely on. The SVN revision will be
included in the JSON with the given json_field_name.
test_results_server: server that hosts test results json.
test_type: test type string (e.g. 'layout-tests').
master_name: the name of the buildbot master.
"""
self._builder_name = builder_name
self._build_name = build_name
self._build_number = build_number
self._builder_base_url = builder_base_url
self._results_directory = results_file_base_path
self._test_results_map = test_results_map
self._test_results = test_results_map.values()
self._svn_repositories = svn_repositories
if not self._svn_repositories:
self._svn_repositories = {}
self._test_results_server = test_results_server
self._test_type = test_type
self._master_name = master_name
self._archived_results = None | [
"def",
"__init__",
"(",
"self",
",",
"builder_name",
",",
"build_name",
",",
"build_number",
",",
"results_file_base_path",
",",
"builder_base_url",
",",
"test_results_map",
",",
"svn_repositories",
"=",
"None",
",",
"test_results_server",
"=",
"None",
",",
"test_ty... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/pylib/results/flakiness_dashboard/json_results_generator.py#L165-L207 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/distributions/python/ops/conditional_transformed_distribution.py | python | ConditionalTransformedDistribution._finish_prob_for_one_fiber | (self, y, x, ildj, distribution_kwargs) | return math_ops.exp(ildj) * prob | Finish computation of prob on one element of the inverse image. | Finish computation of prob on one element of the inverse image. | [
"Finish",
"computation",
"of",
"prob",
"on",
"one",
"element",
"of",
"the",
"inverse",
"image",
"."
] | def _finish_prob_for_one_fiber(self, y, x, ildj, distribution_kwargs):
"""Finish computation of prob on one element of the inverse image."""
x = self._maybe_rotate_dims(x, rotate_right=True)
prob = self.distribution.prob(x, **distribution_kwargs)
if self._is_maybe_event_override:
prob = math_ops.reduce_prod(prob, self._reduce_event_indices)
return math_ops.exp(ildj) * prob | [
"def",
"_finish_prob_for_one_fiber",
"(",
"self",
",",
"y",
",",
"x",
",",
"ildj",
",",
"distribution_kwargs",
")",
":",
"x",
"=",
"self",
".",
"_maybe_rotate_dims",
"(",
"x",
",",
"rotate_right",
"=",
"True",
")",
"prob",
"=",
"self",
".",
"distribution",... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/conditional_transformed_distribution.py#L140-L146 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet_multinomial.py | python | DirichletMultinomial.mean | (self, name="mean") | Class means for every batch member. | Class means for every batch member. | [
"Class",
"means",
"for",
"every",
"batch",
"member",
"."
] | def mean(self, name="mean"):
"""Class means for every batch member."""
alpha = self._alpha
alpha_sum = self._alpha_sum
n = self._n
with ops.name_scope(self.name):
with ops.op_scope([alpha, alpha_sum, n], name):
mean_no_n = alpha / array_ops.expand_dims(alpha_sum, -1)
return array_ops.expand_dims(n, -1) * mean_no_n | [
"def",
"mean",
"(",
"self",
",",
"name",
"=",
"\"mean\"",
")",
":",
"alpha",
"=",
"self",
".",
"_alpha",
"alpha_sum",
"=",
"self",
".",
"_alpha_sum",
"n",
"=",
"self",
".",
"_n",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"name",
")",
":",... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet_multinomial.py#L200-L208 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/third_party/jinja2/parser.py | python | Parser.fail | (self, msg, lineno=None, exc=TemplateSyntaxError) | Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename. | Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename. | [
"Convenience",
"method",
"that",
"raises",
"exc",
"with",
"the",
"message",
"passed",
"line",
"number",
"or",
"last",
"line",
"number",
"as",
"well",
"as",
"the",
"current",
"name",
"and",
"filename",
"."
] | def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
"""Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename.
"""
if lineno is None:
lineno = self.stream.current.lineno
raise exc(msg, lineno, self.name, self.filename) | [
"def",
"fail",
"(",
"self",
",",
"msg",
",",
"lineno",
"=",
"None",
",",
"exc",
"=",
"TemplateSyntaxError",
")",
":",
"if",
"lineno",
"is",
"None",
":",
"lineno",
"=",
"self",
".",
"stream",
".",
"current",
".",
"lineno",
"raise",
"exc",
"(",
"msg",
... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/parser.py#L52-L59 | ||
yue/yue | 619d62c191b13c51c01be451dc48917c34a5aefc | building/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/yue/yue/blob/619d62c191b13c51c01be451dc48917c34a5aefc/building/tools/cpplint.py#L1441-L1443 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/learn/python/learn/datasets/base.py | python | load_csv_without_header | (filename,
target_dtype,
features_dtype,
target_column=-1) | return Dataset(data=np.array(data),
target=np.array(target).astype(target_dtype)) | Load dataset from CSV file without a header row. | Load dataset from CSV file without a header row. | [
"Load",
"dataset",
"from",
"CSV",
"file",
"without",
"a",
"header",
"row",
"."
] | def load_csv_without_header(filename,
target_dtype,
features_dtype,
target_column=-1):
"""Load dataset from CSV file without a header row."""
with gfile.Open(filename) as csv_file:
data_file = csv.reader(csv_file)
data, target = [], []
for row in data_file:
target.append(row.pop(target_column))
data.append(np.asarray(row, dtype=features_dtype))
target = np.array(target, dtype=target_dtype)
data = np.array(data)
return Dataset(data=np.array(data),
target=np.array(target).astype(target_dtype)) | [
"def",
"load_csv_without_header",
"(",
"filename",
",",
"target_dtype",
",",
"features_dtype",
",",
"target_column",
"=",
"-",
"1",
")",
":",
"with",
"gfile",
".",
"Open",
"(",
"filename",
")",
"as",
"csv_file",
":",
"data_file",
"=",
"csv",
".",
"reader",
... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/datasets/base.py#L72-L87 | |
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | lldb/third_party/Python/module/pexpect-4.6/pexpect/ANSI.py | python | ANSI.do_modecrap | (self, fsm) | Handler for \x1b[?<number>h and \x1b[?<number>l. If anyone
wanted to actually use these, they'd need to add more states to the
FSM rather than just improve or override this method. | Handler for \x1b[?<number>h and \x1b[?<number>l. If anyone
wanted to actually use these, they'd need to add more states to the
FSM rather than just improve or override this method. | [
"Handler",
"for",
"\\",
"x1b",
"[",
"?<number",
">",
"h",
"and",
"\\",
"x1b",
"[",
"?<number",
">",
"l",
".",
"If",
"anyone",
"wanted",
"to",
"actually",
"use",
"these",
"they",
"d",
"need",
"to",
"add",
"more",
"states",
"to",
"the",
"FSM",
"rather"... | def do_modecrap (self, fsm):
'''Handler for \x1b[?<number>h and \x1b[?<number>l. If anyone
wanted to actually use these, they'd need to add more states to the
FSM rather than just improve or override this method. '''
screen = fsm.memory[0]
fsm.memory = [screen] | [
"def",
"do_modecrap",
"(",
"self",
",",
"fsm",
")",
":",
"screen",
"=",
"fsm",
".",
"memory",
"[",
"0",
"]",
"fsm",
".",
"memory",
"=",
"[",
"screen",
"]"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/third_party/Python/module/pexpect-4.6/pexpect/ANSI.py#L346-L351 | ||
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/gravimetry/gravMagModelling.py | python | gradGZHalfPlateHoriz | (pnts, t, rho, pos=(0.0, 0.0)) | return gz | r"""TODO WRITEME.
.. math:: g = -\nabla u
Parameters
----------
pnts : array (:math:`n\times 2`)
n 2 dimensional measurement points
t : float
Plate thickness in :math:`[\text{m}]`
rho : float
Density in :math:`[\text{kg}/\text{m}^3]`
Returns
-------
gz : array
Gradient of z-component of g
:math:`\nabla(\frac{\partial u}{\partial\vec{r}}_z)` | r"""TODO WRITEME. | [
"r",
"TODO",
"WRITEME",
"."
] | def gradGZHalfPlateHoriz(pnts, t, rho, pos=(0.0, 0.0)):
r"""TODO WRITEME.
.. math:: g = -\nabla u
Parameters
----------
pnts : array (:math:`n\times 2`)
n 2 dimensional measurement points
t : float
Plate thickness in :math:`[\text{m}]`
rho : float
Density in :math:`[\text{kg}/\text{m}^3]`
Returns
-------
gz : array
Gradient of z-component of g
:math:`\nabla(\frac{\partial u}{\partial\vec{r}}_z)`
"""
gz = np.zeros((len(pnts), 2))
for i, q in enumerate(pnts):
zz1 = q[1] - pos[1]
xx1 = q[0] - pos[0]
gz[i, 0] = -2.0 * G * rho * t * (zz1 / (xx1 * xx1 + zz1 * zz1))
gz[i, 1] = +2.0 * G * rho * t * (xx1 / (xx1 * xx1 + zz1 * zz1))
return gz | [
"def",
"gradGZHalfPlateHoriz",
"(",
"pnts",
",",
"t",
",",
"rho",
",",
"pos",
"=",
"(",
"0.0",
",",
"0.0",
")",
")",
":",
"gz",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"pnts",
")",
",",
"2",
")",
")",
"for",
"i",
",",
"q",
"in",
"enu... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/gravimetry/gravMagModelling.py#L308-L340 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TSInOut.SetPos | (self, *args) | return _snap.TSInOut_SetPos(self, *args) | SetPos(TSInOut self, int const & Pos)
Parameters:
Pos: int const & | SetPos(TSInOut self, int const & Pos) | [
"SetPos",
"(",
"TSInOut",
"self",
"int",
"const",
"&",
"Pos",
")"
] | def SetPos(self, *args):
"""
SetPos(TSInOut self, int const & Pos)
Parameters:
Pos: int const &
"""
return _snap.TSInOut_SetPos(self, *args) | [
"def",
"SetPos",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TSInOut_SetPos",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L2614-L2622 | |
NVIDIA/DALI | bf16cc86ba8f091b145f91962f21fe1b6aff243d | third_party/cpplint.py | python | PathSplitToList | (path) | return lst | Returns the path split into a list by the separator.
Args:
path: An absolute or relative path (e.g. '/a/b/c/' or '../a')
Returns:
A list of path components (e.g. ['a', 'b', 'c]). | Returns the path split into a list by the separator. | [
"Returns",
"the",
"path",
"split",
"into",
"a",
"list",
"by",
"the",
"separator",
"."
] | def PathSplitToList(path):
"""Returns the path split into a list by the separator.
Args:
path: An absolute or relative path (e.g. '/a/b/c/' or '../a')
Returns:
A list of path components (e.g. ['a', 'b', 'c]).
"""
lst = []
while True:
(head, tail) = os.path.split(path)
if head == path: # absolute paths end
lst.append(head)
break
if tail == path: # relative paths end
lst.append(tail)
break
path = head
lst.append(tail)
lst.reverse()
return lst | [
"def",
"PathSplitToList",
"(",
"path",
")",
":",
"lst",
"=",
"[",
"]",
"while",
"True",
":",
"(",
"head",
",",
"tail",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"if",
"head",
"==",
"path",
":",
"# absolute paths end",
"lst",
".",... | https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/third_party/cpplint.py#L1781-L1804 | |
vmware/concord-bft | ec036a384b4c81be0423d4b429bd37900b13b864 | messages/compiler/visitor.py | python | Visitor.msg_start | (self, name, id) | A new message has been defined.
Message definitions are not nestable.
Args:
name (str): The name of the message
id (int): The numeric id of the message | A new message has been defined.
Message definitions are not nestable. | [
"A",
"new",
"message",
"has",
"been",
"defined",
".",
"Message",
"definitions",
"are",
"not",
"nestable",
"."
] | def msg_start(self, name, id):
"""
A new message has been defined.
Message definitions are not nestable.
Args:
name (str): The name of the message
id (int): The numeric id of the message
"""
pass | [
"def",
"msg_start",
"(",
"self",
",",
"name",
",",
"id",
")",
":",
"pass"
] | https://github.com/vmware/concord-bft/blob/ec036a384b4c81be0423d4b429bd37900b13b864/messages/compiler/visitor.py#L63-L72 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cef_parser.py | python | is_base_class | (clsname) | return clsname == 'CefBaseRefCounted' or clsname == 'CefBaseScoped' | Returns true if |clsname| is a known base (root) class in the object
hierarchy. | Returns true if |clsname| is a known base (root) class in the object
hierarchy. | [
"Returns",
"true",
"if",
"|clsname|",
"is",
"a",
"known",
"base",
"(",
"root",
")",
"class",
"in",
"the",
"object",
"hierarchy",
"."
] | def is_base_class(clsname):
""" Returns true if |clsname| is a known base (root) class in the object
hierarchy.
"""
return clsname == 'CefBaseRefCounted' or clsname == 'CefBaseScoped' | [
"def",
"is_base_class",
"(",
"clsname",
")",
":",
"return",
"clsname",
"==",
"'CefBaseRefCounted'",
"or",
"clsname",
"==",
"'CefBaseScoped'"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cef_parser.py#L97-L101 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/framemanager.py | python | AuiManager.RepositionPane | (self, pane, wnd_pos, wnd_size) | Repositions a pane after the main frame has been moved/resized.
:param `pane`: a :class:`AuiPaneInfo` instance;
:param Point `wnd_pos`: the main frame position;
:param Size `wnd_size`: the main frame size. | Repositions a pane after the main frame has been moved/resized. | [
"Repositions",
"a",
"pane",
"after",
"the",
"main",
"frame",
"has",
"been",
"moved",
"/",
"resized",
"."
] | def RepositionPane(self, pane, wnd_pos, wnd_size):
"""
Repositions a pane after the main frame has been moved/resized.
:param `pane`: a :class:`AuiPaneInfo` instance;
:param Point `wnd_pos`: the main frame position;
:param Size `wnd_size`: the main frame size.
"""
pane_pos = pane.floating_pos
pane_size = pane.floating_size
snap = pane.snapped
if snap == wx.LEFT:
floating_pos = wx.Point(wnd_pos.x - pane_size.x, pane_pos.y)
elif snap == wx.TOP:
floating_pos = wx.Point(pane_pos.x, wnd_pos.y - pane_size.y)
elif snap == wx.RIGHT:
floating_pos = wx.Point(wnd_pos.x + wnd_size.x, pane_pos.y)
elif snap == wx.BOTTOM:
floating_pos = wx.Point(pane_pos.x, wnd_pos.y + wnd_size.y)
if snap:
if pane_pos != floating_pos:
pane.floating_pos = floating_pos
self._from_move = True
pane.frame.SetPosition(pane.floating_pos)
self._from_move = False | [
"def",
"RepositionPane",
"(",
"self",
",",
"pane",
",",
"wnd_pos",
",",
"wnd_size",
")",
":",
"pane_pos",
"=",
"pane",
".",
"floating_pos",
"pane_size",
"=",
"pane",
".",
"floating_size",
"snap",
"=",
"pane",
".",
"snapped",
"if",
"snap",
"==",
"wx",
"."... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L8548-L8575 | ||
funnyzhou/Adaptive_Feeding | 9c78182331d8c0ea28de47226e805776c638d46f | lib/roi_data_layer/minibatch.py | python | get_minibatch | (roidb, num_classes) | return blobs | Given a roidb, construct a minibatch sampled from it. | Given a roidb, construct a minibatch sampled from it. | [
"Given",
"a",
"roidb",
"construct",
"a",
"minibatch",
"sampled",
"from",
"it",
"."
] | def get_minibatch(roidb, num_classes):
"""Given a roidb, construct a minibatch sampled from it."""
num_images = len(roidb)
num_reg_class = 2 if cfg.TRAIN.AGNOSTIC else num_classes
# Sample random scales to use for each image in this batch
random_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES),
size=num_images)
assert(cfg.TRAIN.BATCH_SIZE % num_images == 0) or (cfg.TRAIN.BATCH_SIZE == -1), \
'num_images ({}) must divide BATCH_SIZE ({})'. \
format(num_images, cfg.TRAIN.BATCH_SIZE)
rois_per_image = np.inf if cfg.TRAIN.BATCH_SIZE == -1 else cfg.TRAIN.BATCH_SIZE / num_images
fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)
# Get the input image blob, formatted for caffe
im_blob, im_scales = _get_image_blob(roidb, random_scale_inds)
blobs = {'data': im_blob}
if cfg.TRAIN.HAS_RPN:
assert len(im_scales) == 1, "Single batch only"
assert len(roidb) == 1, "Single batch only"
# gt boxes: (x1, y1, x2, y2, cls)
gt_inds = np.where(roidb[0]['gt_classes'] != 0)[0]
gt_boxes = np.empty((len(gt_inds), 5), dtype=np.float32)
gt_boxes[:, 0:4] = roidb[0]['boxes'][gt_inds, :] * im_scales[0]
gt_boxes[:, 4] = roidb[0]['gt_classes'][gt_inds]
blobs['gt_boxes'] = gt_boxes
blobs['im_info'] = np.array(
[[im_blob.shape[2], im_blob.shape[3], im_scales[0]]],
dtype=np.float32)
else: # not using RPN
# Now, build the region of interest and label blobs
rois_blob = np.zeros((0, 5), dtype=np.float32)
labels_blob = np.zeros((0), dtype=np.float32)
bbox_targets_blob = np.zeros((0, 4 * num_reg_class), dtype=np.float32)
bbox_inside_blob = np.zeros(bbox_targets_blob.shape, dtype=np.float32)
# all_overlaps = []
for im_i in xrange(num_images):
labels, overlaps, im_rois, bbox_targets, bbox_inside_weights \
= _sample_rois(roidb[im_i], fg_rois_per_image, rois_per_image,
num_classes)
# Add to RoIs blob
rois = _project_im_rois(im_rois, im_scales[im_i])
batch_ind = im_i * np.ones((rois.shape[0], 1))
rois_blob_this_image = np.hstack((batch_ind, rois))
rois_blob = np.vstack((rois_blob, rois_blob_this_image))
# Add to labels, bbox targets, and bbox loss blobs
labels_blob = np.hstack((labels_blob, labels))
bbox_targets_blob = np.vstack((bbox_targets_blob, bbox_targets))
bbox_inside_blob = np.vstack((bbox_inside_blob, bbox_inside_weights))
# all_overlaps = np.hstack((all_overlaps, overlaps))
# For debug visualizations
# _vis_minibatch(im_blob, rois_blob, labels_blob, all_overlaps)
blobs['rois'] = rois_blob
blobs['labels'] = labels_blob
if cfg.TRAIN.BBOX_REG:
blobs['bbox_targets'] = bbox_targets_blob
blobs['bbox_inside_weights'] = bbox_inside_blob
blobs['bbox_outside_weights'] = \
np.array(bbox_inside_blob > 0).astype(np.float32)
return blobs | [
"def",
"get_minibatch",
"(",
"roidb",
",",
"num_classes",
")",
":",
"num_images",
"=",
"len",
"(",
"roidb",
")",
"num_reg_class",
"=",
"2",
"if",
"cfg",
".",
"TRAIN",
".",
"AGNOSTIC",
"else",
"num_classes",
"# Sample random scales to use for each image in this batch... | https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/roi_data_layer/minibatch.py#L16-L82 | |
microsoft/AirSim | 8057725712c0cd46979135396381784075ffc0f3 | PythonClient/computer_vision/create_ir_segmentation_map.py | python | get_new_temp_emiss_from_radiance | (tempEmissivity, response) | return tempEmissivityNew | title::
get_new_temp_emiss_from_radiance
description::
Transform tempEmissivity from [objectName, temperature, emissivity]
to [objectName, "radiance"] using radiance calculation above.
input::
tempEmissivity
numpy array containing the temperature and emissivity of each
object (e.g., each row has: [objectName, temperature, emissivity])
response
camera response (same input as radiance, set to None if lacking
this information)
returns::
tempEmissivityNew
tempEmissivity, now with [objectName, "radiance"]; note that
integrated radiance (L) is divided by the maximum and multiplied
by 255 in order to simulate an 8 bit digital count observed by the
thermal sensor, since radiance and digital count are linearly
related, so it's [objectName, simulated thermal digital count]
author::
Elizabeth Bondi | title::
get_new_temp_emiss_from_radiance | [
"title",
"::",
"get_new_temp_emiss_from_radiance"
] | def get_new_temp_emiss_from_radiance(tempEmissivity, response):
"""
title::
get_new_temp_emiss_from_radiance
description::
Transform tempEmissivity from [objectName, temperature, emissivity]
to [objectName, "radiance"] using radiance calculation above.
input::
tempEmissivity
numpy array containing the temperature and emissivity of each
object (e.g., each row has: [objectName, temperature, emissivity])
response
camera response (same input as radiance, set to None if lacking
this information)
returns::
tempEmissivityNew
tempEmissivity, now with [objectName, "radiance"]; note that
integrated radiance (L) is divided by the maximum and multiplied
by 255 in order to simulate an 8 bit digital count observed by the
thermal sensor, since radiance and digital count are linearly
related, so it's [objectName, simulated thermal digital count]
author::
Elizabeth Bondi
"""
numObjects = tempEmissivity.shape[0]
L = radiance(tempEmissivity[:,1].reshape((-1,1)).astype(numpy.float64),
tempEmissivity[:,2].reshape((-1,1)).astype(numpy.float64),
response=response)[1].flatten()
L = ((L / L.max()) * 255).astype(numpy.uint8)
tempEmissivityNew = numpy.hstack((
tempEmissivity[:,0].reshape((numObjects,1)),
L.reshape((numObjects,1))))
return tempEmissivityNew | [
"def",
"get_new_temp_emiss_from_radiance",
"(",
"tempEmissivity",
",",
"response",
")",
":",
"numObjects",
"=",
"tempEmissivity",
".",
"shape",
"[",
"0",
"]",
"L",
"=",
"radiance",
"(",
"tempEmissivity",
"[",
":",
",",
"1",
"]",
".",
"reshape",
"(",
"(",
"... | https://github.com/microsoft/AirSim/blob/8057725712c0cd46979135396381784075ffc0f3/PythonClient/computer_vision/create_ir_segmentation_map.py#L65-L104 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | configure.py | python | set_tf_cuda_version | (environ_cp) | Set TF_CUDA_VERSION. | Set TF_CUDA_VERSION. | [
"Set",
"TF_CUDA_VERSION",
"."
] | def set_tf_cuda_version(environ_cp):
"""Set TF_CUDA_VERSION."""
ask_cuda_version = (
'Please specify the CUDA SDK version you want to use. '
'[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
tf_cuda_version = get_from_env_or_user_or_default(environ_cp,
'TF_CUDA_VERSION',
ask_cuda_version,
_DEFAULT_CUDA_VERSION)
environ_cp['TF_CUDA_VERSION'] = tf_cuda_version | [
"def",
"set_tf_cuda_version",
"(",
"environ_cp",
")",
":",
"ask_cuda_version",
"=",
"(",
"'Please specify the CUDA SDK version you want to use. '",
"'[Leave empty to default to CUDA %s]: '",
")",
"%",
"_DEFAULT_CUDA_VERSION",
"tf_cuda_version",
"=",
"get_from_env_or_user_or_default",... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/configure.py#L893-L902 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/httplib.py | python | HTTPMessage.addcontinue | (self, key, more) | Add more field data from a continuation line. | Add more field data from a continuation line. | [
"Add",
"more",
"field",
"data",
"from",
"a",
"continuation",
"line",
"."
] | def addcontinue(self, key, more):
"""Add more field data from a continuation line."""
prev = self.dict[key]
self.dict[key] = prev + "\n " + more | [
"def",
"addcontinue",
"(",
"self",
",",
"key",
",",
"more",
")",
":",
"prev",
"=",
"self",
".",
"dict",
"[",
"key",
"]",
"self",
".",
"dict",
"[",
"key",
"]",
"=",
"prev",
"+",
"\"\\n \"",
"+",
"more"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/httplib.py#L229-L232 | ||
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | util/gem5art/artifact/gem5art/artifact/_artifactdb.py | python | ArtifactDB.__init__ | (self, uri: str) | Initialize the database with a URI | Initialize the database with a URI | [
"Initialize",
"the",
"database",
"with",
"a",
"URI"
] | def __init__(self, uri: str) -> None:
"""Initialize the database with a URI"""
pass | [
"def",
"__init__",
"(",
"self",
",",
"uri",
":",
"str",
")",
"->",
"None",
":",
"pass"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/util/gem5art/artifact/gem5art/artifact/_artifactdb.py#L64-L66 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.GetTextRaw | (*args, **kwargs) | return _stc.StyledTextCtrl_GetTextRaw(*args, **kwargs) | GetTextRaw(self) -> wxCharBuffer
Retrieve all the text in the document. The returned value is a utf-8
encoded string in unicode builds of wxPython, or raw 8-bit text
otherwise. | GetTextRaw(self) -> wxCharBuffer | [
"GetTextRaw",
"(",
"self",
")",
"-",
">",
"wxCharBuffer"
] | def GetTextRaw(*args, **kwargs):
"""
GetTextRaw(self) -> wxCharBuffer
Retrieve all the text in the document. The returned value is a utf-8
encoded string in unicode builds of wxPython, or raw 8-bit text
otherwise.
"""
return _stc.StyledTextCtrl_GetTextRaw(*args, **kwargs) | [
"def",
"GetTextRaw",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetTextRaw",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L6758-L6766 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | caffe2/python/schema.py | python | RawTuple | (num_fields, name_prefix='field') | return NamedTuple(name_prefix, *([np.void] * num_fields)) | Creates a tuple of `num_field` untyped scalars. | Creates a tuple of `num_field` untyped scalars. | [
"Creates",
"a",
"tuple",
"of",
"num_field",
"untyped",
"scalars",
"."
] | def RawTuple(num_fields, name_prefix='field'):
"""
Creates a tuple of `num_field` untyped scalars.
"""
assert isinstance(num_fields, int)
assert num_fields >= 0
return NamedTuple(name_prefix, *([np.void] * num_fields)) | [
"def",
"RawTuple",
"(",
"num_fields",
",",
"name_prefix",
"=",
"'field'",
")",
":",
"assert",
"isinstance",
"(",
"num_fields",
",",
"int",
")",
"assert",
"num_fields",
">=",
"0",
"return",
"NamedTuple",
"(",
"name_prefix",
",",
"*",
"(",
"[",
"np",
".",
... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/schema.py#L945-L951 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/generator/cmake.py | python | CMakeStringEscape | (a) | return a.replace('\\', '\\\\').replace(';', '\\;').replace('"', '\\"') | Escapes the string 'a' for use inside a CMake string.
This means escaping
'\' otherwise it may be seen as modifying the next character
'"' otherwise it will end the string
';' otherwise the string becomes a list
The following do not need to be escaped
'#' when the lexer is in string state, this does not start a comment
The following are yet unknown
'$' generator variables (like ${obj}) must not be escaped,
but text $ should be escaped
what is wanted is to know which $ come from generator variables | Escapes the string 'a' for use inside a CMake string. | [
"Escapes",
"the",
"string",
"a",
"for",
"use",
"inside",
"a",
"CMake",
"string",
"."
] | def CMakeStringEscape(a):
"""Escapes the string 'a' for use inside a CMake string.
This means escaping
'\' otherwise it may be seen as modifying the next character
'"' otherwise it will end the string
';' otherwise the string becomes a list
The following do not need to be escaped
'#' when the lexer is in string state, this does not start a comment
The following are yet unknown
'$' generator variables (like ${obj}) must not be escaped,
but text $ should be escaped
what is wanted is to know which $ come from generator variables
"""
return a.replace('\\', '\\\\').replace(';', '\\;').replace('"', '\\"') | [
"def",
"CMakeStringEscape",
"(",
"a",
")",
":",
"return",
"a",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
".",
"replace",
"(",
"';'",
",",
"'\\\\;'",
")",
".",
"replace",
"(",
"'\"'",
",",
"'\\\\\"'",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/generator/cmake.py#L122-L138 | |
pristineio/webrtc-mirror | 7a5bcdffaab90a05bc1146b2b1ea71c004e54d71 | PRESUBMIT.py | python | _CheckUsageOfGoogleProtobufNamespace | (input_api, output_api) | return [] | Checks that the namespace google::protobuf has not been used. | Checks that the namespace google::protobuf has not been used. | [
"Checks",
"that",
"the",
"namespace",
"google",
"::",
"protobuf",
"has",
"not",
"been",
"used",
"."
] | def _CheckUsageOfGoogleProtobufNamespace(input_api, output_api):
"""Checks that the namespace google::protobuf has not been used."""
files = []
pattern = input_api.re.compile(r'google::protobuf')
proto_utils_path = os.path.join('webrtc', 'rtc_base', 'protobuf_utils.h')
for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
if f.LocalPath() in [proto_utils_path, 'PRESUBMIT.py']:
continue
contents = input_api.ReadFile(f)
if pattern.search(contents):
files.append(f)
if files:
return [output_api.PresubmitError(
'Please avoid to use namespace `google::protobuf` directly.\n'
'Add a using directive in `%s` and include that header instead.'
% proto_utils_path, files)]
return [] | [
"def",
"_CheckUsageOfGoogleProtobufNamespace",
"(",
"input_api",
",",
"output_api",
")",
":",
"files",
"=",
"[",
"]",
"pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'google::protobuf'",
")",
"proto_utils_path",
"=",
"os",
".",
"path",
".",
"joi... | https://github.com/pristineio/webrtc-mirror/blob/7a5bcdffaab90a05bc1146b2b1ea71c004e54d71/PRESUBMIT.py#L490-L507 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/urllib/parse.py | python | clear_cache | () | Clear the parse cache and the quoters cache. | Clear the parse cache and the quoters cache. | [
"Clear",
"the",
"parse",
"cache",
"and",
"the",
"quoters",
"cache",
"."
] | def clear_cache():
"""Clear the parse cache and the quoters cache."""
_parse_cache.clear()
_safe_quoters.clear() | [
"def",
"clear_cache",
"(",
")",
":",
"_parse_cache",
".",
"clear",
"(",
")",
"_safe_quoters",
".",
"clear",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/urllib/parse.py#L83-L86 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/checkpoint_utils.py | python | _set_variable_or_list_initializer | (variable_or_list, ckpt_file,
tensor_name) | Overrides initialization op of given variable or list of variables.
Calls `_set_checkpoint_initializer` for each variable in the given list of
variables.
Args:
variable_or_list: `tf.Variable` object or a list of `tf.Variable` objects.
ckpt_file: string, full path of the checkpoint.
tensor_name: Name of the tensor to load from the checkpoint.
Raises:
ValueError: if all objects in `variable_or_list` are not partitions of the
same large variable. | Overrides initialization op of given variable or list of variables. | [
"Overrides",
"initialization",
"op",
"of",
"given",
"variable",
"or",
"list",
"of",
"variables",
"."
] | def _set_variable_or_list_initializer(variable_or_list, ckpt_file,
tensor_name):
"""Overrides initialization op of given variable or list of variables.
Calls `_set_checkpoint_initializer` for each variable in the given list of
variables.
Args:
variable_or_list: `tf.Variable` object or a list of `tf.Variable` objects.
ckpt_file: string, full path of the checkpoint.
tensor_name: Name of the tensor to load from the checkpoint.
Raises:
ValueError: if all objects in `variable_or_list` are not partitions of the
same large variable.
"""
if isinstance(variable_or_list, (list, tuple)):
# A set of slices.
slice_name = None
for v in variable_or_list:
slice_info = v._save_slice_info # pylint:disable=protected-access
if slice_name is None:
slice_name = slice_info.full_name
elif slice_name != slice_info.full_name:
raise ValueError("Slices must all be from the same tensor: %s != %s" %
(slice_name, slice_info.full_name))
_set_checkpoint_initializer(v, ckpt_file, tensor_name, slice_info.spec)
else:
_set_checkpoint_initializer(variable_or_list, ckpt_file, tensor_name, "") | [
"def",
"_set_variable_or_list_initializer",
"(",
"variable_or_list",
",",
"ckpt_file",
",",
"tensor_name",
")",
":",
"if",
"isinstance",
"(",
"variable_or_list",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"# A set of slices.",
"slice_name",
"=",
"None",
"for",... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/checkpoint_utils.py#L430-L458 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/devtools_monitor.py | python | DevToolsConnection.ExecuteJavaScript | (self, expression) | return response['result']['result']['value'] | Run JavaScript expression.
Args:
expression: JavaScript expression to run.
Returns:
The return value from the JavaScript expression. | Run JavaScript expression. | [
"Run",
"JavaScript",
"expression",
"."
] | def ExecuteJavaScript(self, expression):
"""Run JavaScript expression.
Args:
expression: JavaScript expression to run.
Returns:
The return value from the JavaScript expression.
"""
response = self.SyncRequest('Runtime.evaluate', {
'expression': expression,
'returnByValue': True})
if 'error' in response:
raise Exception(response['error']['message'])
if 'wasThrown' in response['result'] and response['result']['wasThrown']:
raise Exception(response['error']['result']['description'])
if response['result']['result']['type'] == 'undefined':
return None
return response['result']['result']['value'] | [
"def",
"ExecuteJavaScript",
"(",
"self",
",",
"expression",
")",
":",
"response",
"=",
"self",
".",
"SyncRequest",
"(",
"'Runtime.evaluate'",
",",
"{",
"'expression'",
":",
"expression",
",",
"'returnByValue'",
":",
"True",
"}",
")",
"if",
"'error'",
"in",
"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/devtools_monitor.py#L280-L298 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/defchararray.py | python | startswith | (a, prefix, start=0, end=None) | return _vec_string(
a, bool_, 'startswith', [prefix, start] + _clean_args(end)) | Returns a boolean array which is `True` where the string element
in `a` starts with `prefix`, otherwise `False`.
Calls `str.startswith` element-wise.
Parameters
----------
a : array_like of str or unicode
prefix : str
start, end : int, optional
With optional `start`, test beginning at that position. With
optional `end`, stop comparing at that position.
Returns
-------
out : ndarray
Array of booleans
See also
--------
str.startswith | Returns a boolean array which is `True` where the string element
in `a` starts with `prefix`, otherwise `False`. | [
"Returns",
"a",
"boolean",
"array",
"which",
"is",
"True",
"where",
"the",
"string",
"element",
"in",
"a",
"starts",
"with",
"prefix",
"otherwise",
"False",
"."
] | def startswith(a, prefix, start=0, end=None):
"""
Returns a boolean array which is `True` where the string element
in `a` starts with `prefix`, otherwise `False`.
Calls `str.startswith` element-wise.
Parameters
----------
a : array_like of str or unicode
prefix : str
start, end : int, optional
With optional `start`, test beginning at that position. With
optional `end`, stop comparing at that position.
Returns
-------
out : ndarray
Array of booleans
See also
--------
str.startswith
"""
return _vec_string(
a, bool_, 'startswith', [prefix, start] + _clean_args(end)) | [
"def",
"startswith",
"(",
"a",
",",
"prefix",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"return",
"_vec_string",
"(",
"a",
",",
"bool_",
",",
"'startswith'",
",",
"[",
"prefix",
",",
"start",
"]",
"+",
"_clean_args",
"(",
"end",
")... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/defchararray.py#L1481-L1509 | |
OpenImageDenoise/oidn | 0a9bf27d41a4120a285b033ad743f48c1208a944 | training/ssim.py | python | ms_ssim | (X, Y, win_size=11, win_sigma=1.5, win=None, data_range=255, size_average=True, weights=None) | return msssim_val | r""" interface of ms-ssim
Args:
X (torch.Tensor): a batch of images, (N,C,H,W)
Y (torch.Tensor): a batch of images, (N,C,H,W)
win_size: (int, optional): the size of gauss kernel
win_sigma: (float, optional): sigma of normal distribution
win (torch.Tensor, optional): 1-D gauss kernel. if None, a new kernel will be created according to win_size and win_sigma
data_range (float or int, optional): value range of input images. (usually 1.0 or 255)
size_average (bool, optional): if size_average=True, ssim of all images will be averaged as a scalar
weights (list, optional): weights for different scales
Returns:
torch.Tensor: ms-ssim results | r""" interface of ms-ssim
Args:
X (torch.Tensor): a batch of images, (N,C,H,W)
Y (torch.Tensor): a batch of images, (N,C,H,W)
win_size: (int, optional): the size of gauss kernel
win_sigma: (float, optional): sigma of normal distribution
win (torch.Tensor, optional): 1-D gauss kernel. if None, a new kernel will be created according to win_size and win_sigma
data_range (float or int, optional): value range of input images. (usually 1.0 or 255)
size_average (bool, optional): if size_average=True, ssim of all images will be averaged as a scalar
weights (list, optional): weights for different scales | [
"r",
"interface",
"of",
"ms",
"-",
"ssim",
"Args",
":",
"X",
"(",
"torch",
".",
"Tensor",
")",
":",
"a",
"batch",
"of",
"images",
"(",
"N",
"C",
"H",
"W",
")",
"Y",
"(",
"torch",
".",
"Tensor",
")",
":",
"a",
"batch",
"of",
"images",
"(",
"N"... | def ms_ssim(X, Y, win_size=11, win_sigma=1.5, win=None, data_range=255, size_average=True, weights=None):
r""" interface of ms-ssim
Args:
X (torch.Tensor): a batch of images, (N,C,H,W)
Y (torch.Tensor): a batch of images, (N,C,H,W)
win_size: (int, optional): the size of gauss kernel
win_sigma: (float, optional): sigma of normal distribution
win (torch.Tensor, optional): 1-D gauss kernel. if None, a new kernel will be created according to win_size and win_sigma
data_range (float or int, optional): value range of input images. (usually 1.0 or 255)
size_average (bool, optional): if size_average=True, ssim of all images will be averaged as a scalar
weights (list, optional): weights for different scales
Returns:
torch.Tensor: ms-ssim results
"""
if len(X.shape) != 4:
raise ValueError('Input images must 4-d tensor.')
if not X.type() == Y.type():
raise ValueError('Input images must have the same dtype.')
if not X.shape == Y.shape:
raise ValueError('Input images must have the same dimensions.')
if not (win_size % 2 == 1):
raise ValueError('Window size must be odd.')
smaller_side = min( X.shape[-2:] )
assert smaller_side > (win_size-1) * (2**4), \
"Image size should be larger than %d due to the 4 downsamplings in ms-ssim"% ((win_size-1) * (2**4))
if weights is None:
weights = torch.FloatTensor(_MS_SSIM_WEIGHTS).to(X.device, dtype=X.dtype)
if win is None:
win = _fspecial_gauss_1d(win_size, win_sigma)
win = win.repeat(X.shape[1], 1, 1, 1)
win = win.to(X.device, dtype=X.dtype)
else:
win_size = win.shape[-1]
scales = weights.shape[0]
mcs_and_ssim = []
for i in range(scales):
if i > 0:
padding = (X.shape[2] % 2, X.shape[3] % 2)
X = F.avg_pool2d(X, kernel_size=2, padding=padding)
Y = F.avg_pool2d(Y, kernel_size=2, padding=padding)
ssim_val = _ssim_per_channel(X, Y,
win=win,
data_range=data_range,
cs_only=(i < scales-1))
mcs_and_ssim.append(ssim_val)
# weights, (scale)
mcs_and_ssim = torch.stack(mcs_and_ssim, dim=-1) # (batch, channel, scale)
msssim_val = torch.prod((F.relu(mcs_and_ssim) ** weights), dim=-1) # (batch, channel)
if size_average:
msssim_val = msssim_val.mean()
else:
msssim_val = msssim_val.mean(-1) # average over channel
return msssim_val | [
"def",
"ms_ssim",
"(",
"X",
",",
"Y",
",",
"win_size",
"=",
"11",
",",
"win_sigma",
"=",
"1.5",
",",
"win",
"=",
"None",
",",
"data_range",
"=",
"255",
",",
"size_average",
"=",
"True",
",",
"weights",
"=",
"None",
")",
":",
"if",
"len",
"(",
"X"... | https://github.com/OpenImageDenoise/oidn/blob/0a9bf27d41a4120a285b033ad743f48c1208a944/training/ssim.py#L138-L202 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/adidas_utils/solvers/symmetric/ate_anneal.py | python | Solver.exploitability | (self, params, payoff_matrices) | return exp.ate_exploitability(params, payoff_matrices, self.p) | Compute and return tsallis entropy regularized exploitability.
Args:
params: tuple of params (dist, y), see ate.gradients
payoff_matrices: (>=2 x A x A) np.array, payoffs for each joint action
Returns:
float, exploitability of current dist | Compute and return tsallis entropy regularized exploitability. | [
"Compute",
"and",
"return",
"tsallis",
"entropy",
"regularized",
"exploitability",
"."
] | def exploitability(self, params, payoff_matrices):
"""Compute and return tsallis entropy regularized exploitability.
Args:
params: tuple of params (dist, y), see ate.gradients
payoff_matrices: (>=2 x A x A) np.array, payoffs for each joint action
Returns:
float, exploitability of current dist
"""
return exp.ate_exploitability(params, payoff_matrices, self.p) | [
"def",
"exploitability",
"(",
"self",
",",
"params",
",",
"payoff_matrices",
")",
":",
"return",
"exp",
".",
"ate_exploitability",
"(",
"params",
",",
"payoff_matrices",
",",
"self",
".",
"p",
")"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/solvers/symmetric/ate_anneal.py#L103-L112 | |
s9xie/hed | 94fb22f10cbfec8d84fbc0642b224022014b6bd6 | scripts/cpp_lint.py | python | ReverseCloseExpression | (clean_lines, linenum, pos) | return (line, 0, -1) | If input points to ) or } or ] or >, finds the position that opens it.
If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
linenum/pos that correspond to the opening of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *at* the opening brace, or
(line, 0, -1) if we never find the matching opening brace. Note
we ignore strings and comments when matching; and the line we
return is the 'cleansed' line at linenum. | If input points to ) or } or ] or >, finds the position that opens it. | [
"If",
"input",
"points",
"to",
")",
"or",
"}",
"or",
"]",
"or",
">",
"finds",
"the",
"position",
"that",
"opens",
"it",
"."
] | def ReverseCloseExpression(clean_lines, linenum, pos):
"""If input points to ) or } or ] or >, finds the position that opens it.
If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
linenum/pos that correspond to the opening of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *at* the opening brace, or
(line, 0, -1) if we never find the matching opening brace. Note
we ignore strings and comments when matching; and the line we
return is the 'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
endchar = line[pos]
if endchar not in ')}]>':
return (line, 0, -1)
if endchar == ')': startchar = '('
if endchar == ']': startchar = '['
if endchar == '}': startchar = '{'
if endchar == '>': startchar = '<'
# Check last line
(start_pos, num_open) = FindStartOfExpressionInLine(
line, pos, 0, startchar, endchar)
if start_pos > -1:
return (line, linenum, start_pos)
# Continue scanning backward
while linenum > 0:
linenum -= 1
line = clean_lines.elided[linenum]
(start_pos, num_open) = FindStartOfExpressionInLine(
line, len(line) - 1, num_open, startchar, endchar)
if start_pos > -1:
return (line, linenum, start_pos)
# Did not find startchar before beginning of file, give up
return (line, 0, -1) | [
"def",
"ReverseCloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"endchar",
"=",
"line",
"[",
"pos",
"]",
"if",
"endchar",
"not",
"in",
"')}]>'",
":",
"return",
"("... | https://github.com/s9xie/hed/blob/94fb22f10cbfec8d84fbc0642b224022014b6bd6/scripts/cpp_lint.py#L1327-L1369 | |
cztomczak/cefpython | 5679f28cec18a57a56e298da2927aac8d8f83ad6 | tools/automate-git.py | python | read_json_url | (url) | return json.loads(response.read()) | Read a JSON URL. | Read a JSON URL. | [
"Read",
"a",
"JSON",
"URL",
"."
] | def read_json_url(url):
""" Read a JSON URL. """
msg('Downloading %s' % url)
response = urllib2.urlopen(url)
return json.loads(response.read()) | [
"def",
"read_json_url",
"(",
"url",
")",
":",
"msg",
"(",
"'Downloading %s'",
"%",
"url",
")",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"read",
"(",
")",
")"
] | https://github.com/cztomczak/cefpython/blob/5679f28cec18a57a56e298da2927aac8d8f83ad6/tools/automate-git.py#L462-L466 | |
BSVino/DoubleAction | c550b168a3e919926c198c30240f506538b92e75 | mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py | python | _VerifyExtensionHandle | (message, extension_handle) | Verify that the given extension handle is valid. | Verify that the given extension handle is valid. | [
"Verify",
"that",
"the",
"given",
"extension",
"handle",
"is",
"valid",
"."
] | def _VerifyExtensionHandle(message, extension_handle):
"""Verify that the given extension handle is valid."""
if not isinstance(extension_handle, _FieldDescriptor):
raise KeyError('HasExtension() expects an extension handle, got: %s' %
extension_handle)
if not extension_handle.is_extension:
raise KeyError('"%s" is not an extension.' % extension_handle.full_name)
if extension_handle.containing_type is not message.DESCRIPTOR:
raise KeyError('Extension "%s" extends message type "%s", but this '
'message is of type "%s".' %
(extension_handle.full_name,
extension_handle.containing_type.full_name,
message.DESCRIPTOR.full_name)) | [
"def",
"_VerifyExtensionHandle",
"(",
"message",
",",
"extension_handle",
")",
":",
"if",
"not",
"isinstance",
"(",
"extension_handle",
",",
"_FieldDescriptor",
")",
":",
"raise",
"KeyError",
"(",
"'HasExtension() expects an extension handle, got: %s'",
"%",
"extension_ha... | https://github.com/BSVino/DoubleAction/blob/c550b168a3e919926c198c30240f506538b92e75/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L214-L229 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/quantization/keras/vitis/utils/model_utils.py | python | _is_valid | (ip, wp, op, bp=0) | return True | Check if the input/weight/output/bias quantize pos is valid. | Check if the input/weight/output/bias quantize pos is valid. | [
"Check",
"if",
"the",
"input",
"/",
"weight",
"/",
"output",
"/",
"bias",
"quantize",
"pos",
"is",
"valid",
"."
] | def _is_valid(ip, wp, op, bp=0):
"""Check if the input/weight/output/bias quantize pos is valid."""
if None in [ip, op]:
return False
if (isinstance(wp, np.ndarray) and None in wp) or wp is None:
return False
if (isinstance(bp, np.ndarray) and None in bp) or bp is None:
return False
return True | [
"def",
"_is_valid",
"(",
"ip",
",",
"wp",
",",
"op",
",",
"bp",
"=",
"0",
")",
":",
"if",
"None",
"in",
"[",
"ip",
",",
"op",
"]",
":",
"return",
"False",
"if",
"(",
"isinstance",
"(",
"wp",
",",
"np",
".",
"ndarray",
")",
"and",
"None",
"in"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/quantization/keras/vitis/utils/model_utils.py#L454-L462 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros/roslib/src/roslib/packages.py | python | _read_rospack_cache | (cache, ros_root, ros_package_path) | Read in rospack_cache data into cache. On-disk cache specifies a
ROS_ROOT and ROS_PACKAGE_PATH, which must match the requested
environment.
@param cache: empty dictionary to store package list in.
If no cache argument provided, will use internal _pkg_dir_cache
and will return cached answers if available.
The format of the cache is {package_name: dir_path, ros_root, ros_package_path}.
@type cache: {str: str, str, str}
@param ros_package_path: ROS_ROOT value
@type ros_root: str
@param ros_package_path: ROS_PACKAGE_PATH value or '' if not specified
@type ros_package_path: str
@return: True if on-disk cache matches and was loaded, false otherwise
@rtype: bool | Read in rospack_cache data into cache. On-disk cache specifies a
ROS_ROOT and ROS_PACKAGE_PATH, which must match the requested
environment. | [
"Read",
"in",
"rospack_cache",
"data",
"into",
"cache",
".",
"On",
"-",
"disk",
"cache",
"specifies",
"a",
"ROS_ROOT",
"and",
"ROS_PACKAGE_PATH",
"which",
"must",
"match",
"the",
"requested",
"environment",
"."
] | def _read_rospack_cache(cache, ros_root, ros_package_path):
"""
Read in rospack_cache data into cache. On-disk cache specifies a
ROS_ROOT and ROS_PACKAGE_PATH, which must match the requested
environment.
@param cache: empty dictionary to store package list in.
If no cache argument provided, will use internal _pkg_dir_cache
and will return cached answers if available.
The format of the cache is {package_name: dir_path, ros_root, ros_package_path}.
@type cache: {str: str, str, str}
@param ros_package_path: ROS_ROOT value
@type ros_root: str
@param ros_package_path: ROS_PACKAGE_PATH value or '' if not specified
@type ros_package_path: str
@return: True if on-disk cache matches and was loaded, false otherwise
@rtype: bool
"""
try:
with open(os.path.join(rospkg.get_ros_home(), 'rospack_cache')) as f:
for l in f.readlines():
l = l[:-1]
if not len(l):
continue
if l[0] == '#':
# check that the cache matches our env
if l.startswith('#ROS_ROOT='):
if not l[len('#ROS_ROOT='):] == ros_root:
return False
elif l.startswith('#ROS_PACKAGE_PATH='):
if not l[len('#ROS_PACKAGE_PATH='):] == ros_package_path:
return False
else:
cache[os.path.basename(l)] = l, ros_root, ros_package_path
return True
except:
pass | [
"def",
"_read_rospack_cache",
"(",
"cache",
",",
"ros_root",
",",
"ros_package_path",
")",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"rospkg",
".",
"get_ros_home",
"(",
")",
",",
"'rospack_cache'",
")",
")",
"as",
"f",
... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/roslib/src/roslib/packages.py#L295-L331 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/stats.py | python | find_repeats | (arr) | return RepeatedResults(*_find_repeats(np.array(arr, dtype=np.float64))) | Find repeats and repeat counts.
Parameters
----------
arr : array_like
Input array. This is cast to float64.
Returns
-------
values : ndarray
The unique values from the (flattened) input that are repeated.
counts : ndarray
Number of times the corresponding 'value' is repeated.
Notes
-----
In numpy >= 1.9 `numpy.unique` provides similar functionality. The main
difference is that `find_repeats` only returns repeated values.
Examples
--------
>>> from scipy import stats
>>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5])
RepeatedResults(values=array([ 2.]), counts=array([4]))
>>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]])
RepeatedResults(values=array([ 4., 5.]), counts=array([2, 2])) | Find repeats and repeat counts. | [
"Find",
"repeats",
"and",
"repeat",
"counts",
"."
] | def find_repeats(arr):
"""
Find repeats and repeat counts.
Parameters
----------
arr : array_like
Input array. This is cast to float64.
Returns
-------
values : ndarray
The unique values from the (flattened) input that are repeated.
counts : ndarray
Number of times the corresponding 'value' is repeated.
Notes
-----
In numpy >= 1.9 `numpy.unique` provides similar functionality. The main
difference is that `find_repeats` only returns repeated values.
Examples
--------
>>> from scipy import stats
>>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5])
RepeatedResults(values=array([ 2.]), counts=array([4]))
>>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]])
RepeatedResults(values=array([ 4., 5.]), counts=array([2, 2]))
"""
# Note: always copies.
return RepeatedResults(*_find_repeats(np.array(arr, dtype=np.float64))) | [
"def",
"find_repeats",
"(",
"arr",
")",
":",
"# Note: always copies.",
"return",
"RepeatedResults",
"(",
"*",
"_find_repeats",
"(",
"np",
".",
"array",
"(",
"arr",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/stats.py#L5181-L5214 | |
google/clif | cab24d6a105609a65c95a36a1712ae3c20c7b5df | clif/pybind11/cindex/extractor.py | python | Type.from_clif | (cls, param_decl: ast_pb2.ParamDecl) | return cls(name, is_pointer, is_reference, is_const, pointee) | Creates a type object from CLIF ast. | Creates a type object from CLIF ast. | [
"Creates",
"a",
"type",
"object",
"from",
"CLIF",
"ast",
"."
] | def from_clif(cls, param_decl: ast_pb2.ParamDecl):
"""Creates a type object from CLIF ast."""
name = param_decl.cpp_exact_type
pointee_name = _get_pointee_name(name)
# TODO: Make this handle reference to pointers,
# rvalue references, pointer to pointers, pointer to constants.
is_pointer = param_decl.cpp_exact_type.strip().endswith('*')
is_reference = param_decl.cpp_exact_type.strip().endswith('&')
is_const = param_decl.cpp_exact_type.strip().startswith('const ')
if is_pointer or is_reference:
pointee = Type(pointee_name, False, False, is_const, None)
else:
pointee = None
return cls(name, is_pointer, is_reference, is_const, pointee) | [
"def",
"from_clif",
"(",
"cls",
",",
"param_decl",
":",
"ast_pb2",
".",
"ParamDecl",
")",
":",
"name",
"=",
"param_decl",
".",
"cpp_exact_type",
"pointee_name",
"=",
"_get_pointee_name",
"(",
"name",
")",
"# TODO: Make this handle reference to pointers,",
"# rvalue re... | https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/pybind11/cindex/extractor.py#L43-L56 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/inspector_protocol/jinja2/sandbox.py | python | SandboxedEnvironment.call | (__self, __context, __obj, *args, **kwargs) | return __context.call(__obj, *args, **kwargs) | Call an object from sandboxed code. | Call an object from sandboxed code. | [
"Call",
"an",
"object",
"from",
"sandboxed",
"code",
"."
] | def call(__self, __context, __obj, *args, **kwargs):
"""Call an object from sandboxed code."""
fmt = inspect_format_method(__obj)
if fmt is not None:
return __self.format_string(fmt, args, kwargs)
# the double prefixes are to avoid double keyword argument
# errors when proxying the call.
if not __self.is_safe_callable(__obj):
raise SecurityError('%r is not safely callable' % (__obj,))
return __context.call(__obj, *args, **kwargs) | [
"def",
"call",
"(",
"__self",
",",
"__context",
",",
"__obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fmt",
"=",
"inspect_format_method",
"(",
"__obj",
")",
"if",
"fmt",
"is",
"not",
"None",
":",
"return",
"__self",
".",
"format_string",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/sandbox.py#L417-L427 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Tool/FortranCommon.py | python | add_fortran_to_env | (env) | Add Builders and construction variables for Fortran to an Environment. | Add Builders and construction variables for Fortran to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"Fortran",
"to",
"an",
"Environment",
"."
] | def add_fortran_to_env(env):
"""Add Builders and construction variables for Fortran to an Environment."""
try:
FortranSuffixes = env['FORTRANFILESUFFIXES']
except KeyError:
FortranSuffixes = ['.f', '.for', '.ftn']
#print("Adding %s to fortran suffixes" % FortranSuffixes)
try:
FortranPPSuffixes = env['FORTRANPPFILESUFFIXES']
except KeyError:
FortranPPSuffixes = ['.fpp', '.FPP']
DialectAddToEnv(env, "FORTRAN", FortranSuffixes,
FortranPPSuffixes, support_module = 1)
env['FORTRANMODPREFIX'] = '' # like $LIBPREFIX
env['FORTRANMODSUFFIX'] = '.mod' # like $LIBSUFFIX
env['FORTRANMODDIR'] = '' # where the compiler should place .mod files
env['FORTRANMODDIRPREFIX'] = '' # some prefix to $FORTRANMODDIR - similar to $INCPREFIX
env['FORTRANMODDIRSUFFIX'] = '' # some suffix to $FORTRANMODDIR - similar to $INCSUFFIX
env['_FORTRANMODFLAG'] = '$( ${_concat(FORTRANMODDIRPREFIX, FORTRANMODDIR, FORTRANMODDIRSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' | [
"def",
"add_fortran_to_env",
"(",
"env",
")",
":",
"try",
":",
"FortranSuffixes",
"=",
"env",
"[",
"'FORTRANFILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"FortranSuffixes",
"=",
"[",
"'.f'",
",",
"'.for'",
",",
"'.ftn'",
"]",
"#print(\"Adding %s to fortran suffi... | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Tool/FortranCommon.py#L163-L185 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/installer.py | python | strip_marker | (req) | return req | Return a new requirement without the environment marker to avoid
calling pip with something like `babel; extra == "i18n"`, which
would always be ignored. | Return a new requirement without the environment marker to avoid
calling pip with something like `babel; extra == "i18n"`, which
would always be ignored. | [
"Return",
"a",
"new",
"requirement",
"without",
"the",
"environment",
"marker",
"to",
"avoid",
"calling",
"pip",
"with",
"something",
"like",
"babel",
";",
"extra",
"==",
"i18n",
"which",
"would",
"always",
"be",
"ignored",
"."
] | def strip_marker(req):
"""
Return a new requirement without the environment marker to avoid
calling pip with something like `babel; extra == "i18n"`, which
would always be ignored.
"""
# create a copy to avoid mutating the input
req = pkg_resources.Requirement.parse(str(req))
req.marker = None
return req | [
"def",
"strip_marker",
"(",
"req",
")",
":",
"# create a copy to avoid mutating the input",
"req",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"str",
"(",
"req",
")",
")",
"req",
".",
"marker",
"=",
"None",
"return",
"req"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/installer.py#L95-L104 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/prepare_bindings.py | python | process_args | (args) | return options | Returns options processed from the provided command line.
@param args the command line to process. | Returns options processed from the provided command line. | [
"Returns",
"options",
"processed",
"from",
"the",
"provided",
"command",
"line",
"."
] | def process_args(args):
"""Returns options processed from the provided command line.
@param args the command line to process.
"""
# Setup the parser arguments that are accepted.
parser = argparse.ArgumentParser(
description="Prepare language bindings for LLDB build.")
# Arguments to control logging verbosity.
parser.add_argument(
"--debug", "-d",
action="store_true",
help="Set program logging level to DEBUG.")
parser.add_argument(
"--verbose", "-v",
action="count",
default=0,
help=(
"Increase logging verbosity level. Default: only error and "
"higher are displayed. Each -v increases level of verbosity."))
# Arguments to control whether we're building an OS X-style
# framework. This is the opposite of the older "-m" (makefile)
# option.
parser.add_argument(
"--config-build-dir",
"--cfgBldDir",
help=(
"Configuration build dir, will use python module path "
"if unspecified."))
parser.add_argument(
"--find-swig",
action="store_true",
help=(
"Indicates the swig executable should be searched for "
"if not eplicitly provided. Either this or the explicit "
"swig executable option must be provided."))
parser.add_argument(
"--framework",
action="store_true",
help="Prepare as OS X-style framework.")
parser.add_argument(
"--generate-dependency-file",
"-M",
action="store_true",
help="Make the dependency (.d) file for the wrappers.")
parser.add_argument(
"--prefix",
help="Override path where the LLDB module is placed.")
parser.add_argument(
"--src-root",
"--srcRoot",
"-s",
# Default to the parent directory of this script's directory.
default=os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.path.pardir)),
help="Specifies the LLDB source root directory.")
parser.add_argument(
"--swig-executable",
"--swigExecutable",
help="Path to the swig executable.")
parser.add_argument(
"--target-dir",
"--targetDir",
required=True,
help=(
"Specifies the build dir where the language binding "
"should be placed"))
parser.add_argument(
"--target-platform",
help=(
"Specifies the platform we are building for."
"Should be the same as what platform.system() returns."))
group = parser.add_argument_group("static binding usage")
group.add_argument(
"--allow-static-binding",
action="store_true",
help=(
"Specify the pre-baked binding can be used if "
"swig cannot be found."))
group.add_argument(
"--static-binding-dir",
default="static-binding",
help="script-relative directory for appropriate static bindings"
)
# Process args.
options = parser.parse_args(args)
# Set logging level based on verbosity count.
if options.debug:
log_level = logging.DEBUG
else:
# See logging documentation for error levels. We'll default
# to showing ERROR or higher error messages. For each -v
# specified, we'll shift to the next lower-priority log level.
log_level = logging.ERROR - 10 * options.verbose
if log_level < logging.NOTSET:
# Displays all logged messages.
log_level = logging.NOTSET
logging.basicConfig(level=log_level)
logging.info("logging is using level: %d", log_level)
return options | [
"def",
"process_args",
"(",
"args",
")",
":",
"# Setup the parser arguments that are accepted.",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Prepare language bindings for LLDB build.\"",
")",
"# Arguments to control logging verbosity.",
"parser",... | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/prepare_bindings.py#L82-L190 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/session_ops.py | python | get_session_handle | (data, name=None) | Return the handle of `data`.
This is EXPERIMENTAL and subject to change.
Keep `data` "in-place" in the runtime and create a handle that can be
used to retrieve `data` in a subsequent run().
Combined with `get_session_tensor`, we can keep a tensor produced in
one run call in place, and use it as the input in a future run call.
Args:
data: A tensor to be stored in the session.
name: Optional name prefix for the return tensor.
Returns:
A scalar string tensor representing a unique handle for `data`.
Raises:
TypeError: if `data` is not a Tensor.
Example:
```python
c = tf.multiply(a, b)
h = tf.compat.v1.get_session_handle(c)
h = sess.run(h)
p, a = tf.compat.v1.get_session_tensor(h.handle, tf.float32)
b = tf.multiply(a, 10)
c = sess.run(b, feed_dict={p: h.handle})
``` | Return the handle of `data`. | [
"Return",
"the",
"handle",
"of",
"data",
"."
] | def get_session_handle(data, name=None):
"""Return the handle of `data`.
This is EXPERIMENTAL and subject to change.
Keep `data` "in-place" in the runtime and create a handle that can be
used to retrieve `data` in a subsequent run().
Combined with `get_session_tensor`, we can keep a tensor produced in
one run call in place, and use it as the input in a future run call.
Args:
data: A tensor to be stored in the session.
name: Optional name prefix for the return tensor.
Returns:
A scalar string tensor representing a unique handle for `data`.
Raises:
TypeError: if `data` is not a Tensor.
Example:
```python
c = tf.multiply(a, b)
h = tf.compat.v1.get_session_handle(c)
h = sess.run(h)
p, a = tf.compat.v1.get_session_tensor(h.handle, tf.float32)
b = tf.multiply(a, 10)
c = sess.run(b, feed_dict={p: h.handle})
```
"""
if not isinstance(data, ops.Tensor):
raise TypeError("`data` must be of type Tensor.")
# Colocate this operation with data.
with ops.colocate_with(data):
return gen_data_flow_ops.get_session_handle(data, name=name) | [
"def",
"get_session_handle",
"(",
"data",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"ops",
".",
"Tensor",
")",
":",
"raise",
"TypeError",
"(",
"\"`data` must be of type Tensor.\"",
")",
"# Colocate this operation with data.",... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/session_ops.py#L135-L174 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/html.py | python | HtmlBookRecord.SetContentsRange | (*args, **kwargs) | return _html.HtmlBookRecord_SetContentsRange(*args, **kwargs) | SetContentsRange(self, int start, int end) | SetContentsRange(self, int start, int end) | [
"SetContentsRange",
"(",
"self",
"int",
"start",
"int",
"end",
")"
] | def SetContentsRange(*args, **kwargs):
"""SetContentsRange(self, int start, int end)"""
return _html.HtmlBookRecord_SetContentsRange(*args, **kwargs) | [
"def",
"SetContentsRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlBookRecord_SetContentsRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L1427-L1429 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/global_notification.py | python | GlobalNotification.wait_for_visibility | (self, wait_for_visibility) | Sets the wait_for_visibility of this GlobalNotification.
:param wait_for_visibility: The wait_for_visibility of this GlobalNotification. # noqa: E501
:type: bool | Sets the wait_for_visibility of this GlobalNotification. | [
"Sets",
"the",
"wait_for_visibility",
"of",
"this",
"GlobalNotification",
"."
] | def wait_for_visibility(self, wait_for_visibility):
"""Sets the wait_for_visibility of this GlobalNotification.
:param wait_for_visibility: The wait_for_visibility of this GlobalNotification. # noqa: E501
:type: bool
"""
self._wait_for_visibility = wait_for_visibility | [
"def",
"wait_for_visibility",
"(",
"self",
",",
"wait_for_visibility",
")",
":",
"self",
".",
"_wait_for_visibility",
"=",
"wait_for_visibility"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/global_notification.py#L284-L292 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/ctc_ops.py | python | _CTCLossGrad | (op, grad_loss, _) | return _CTCLossGradImpl(op, grad_loss, _) | The derivative provided by CTC Loss.
Args:
op: the CTCLoss op.
grad_loss: The backprop for cost.
Returns:
The CTC Loss gradient. | The derivative provided by CTC Loss. | [
"The",
"derivative",
"provided",
"by",
"CTC",
"Loss",
"."
] | def _CTCLossGrad(op, grad_loss, _):
"""The derivative provided by CTC Loss.
Args:
op: the CTCLoss op.
grad_loss: The backprop for cost.
Returns:
The CTC Loss gradient.
"""
return _CTCLossGradImpl(op, grad_loss, _) | [
"def",
"_CTCLossGrad",
"(",
"op",
",",
"grad_loss",
",",
"_",
")",
":",
"return",
"_CTCLossGradImpl",
"(",
"op",
",",
"grad_loss",
",",
"_",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ctc_ops.py#L267-L277 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | EncodingConverter.Init | (*args, **kwargs) | return _gdi_.EncodingConverter_Init(*args, **kwargs) | Init(self, int input_enc, int output_enc, int method=CONVERT_STRICT) -> bool | Init(self, int input_enc, int output_enc, int method=CONVERT_STRICT) -> bool | [
"Init",
"(",
"self",
"int",
"input_enc",
"int",
"output_enc",
"int",
"method",
"=",
"CONVERT_STRICT",
")",
"-",
">",
"bool"
] | def Init(*args, **kwargs):
"""Init(self, int input_enc, int output_enc, int method=CONVERT_STRICT) -> bool"""
return _gdi_.EncodingConverter_Init(*args, **kwargs) | [
"def",
"Init",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"EncodingConverter_Init",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L3195-L3197 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/module/base_module.py | python | BaseModule.data_names | (self) | A list of names for data required by this module. | A list of names for data required by this module. | [
"A",
"list",
"of",
"names",
"for",
"data",
"required",
"by",
"this",
"module",
"."
] | def data_names(self):
"""A list of names for data required by this module."""
raise NotImplementedError() | [
"def",
"data_names",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/module/base_module.py#L540-L542 | ||
stitchEm/stitchEm | 0f399501d41ab77933677f2907f41f80ceb704d7 | lib/doc/doxy2swig/doxy2swig.py | python | Doxy2SWIG.generate | (self) | Parses the file set in the initialization. The resulting
data is stored in `self.pieces`. | Parses the file set in the initialization. The resulting
data is stored in `self.pieces`. | [
"Parses",
"the",
"file",
"set",
"in",
"the",
"initialization",
".",
"The",
"resulting",
"data",
"is",
"stored",
"in",
"self",
".",
"pieces",
"."
] | def generate(self):
"""Parses the file set in the initialization. The resulting
data is stored in `self.pieces`.
"""
self.parse(self.xmldoc) | [
"def",
"generate",
"(",
"self",
")",
":",
"self",
".",
"parse",
"(",
"self",
".",
"xmldoc",
")"
] | https://github.com/stitchEm/stitchEm/blob/0f399501d41ab77933677f2907f41f80ceb704d7/lib/doc/doxy2swig/doxy2swig.py#L158-L163 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | IntProperty.__init__ | (self, *args) | __init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
long value=0) -> IntProperty
__init__(self, String label, String name, wxLongLong value) -> IntProperty | __init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
long value=0) -> IntProperty
__init__(self, String label, String name, wxLongLong value) -> IntProperty | [
"__init__",
"(",
"self",
"String",
"label",
"=",
"(",
"*",
"wxPGProperty",
"::",
"sm_wxPG_LABEL",
")",
"String",
"name",
"=",
"(",
"*",
"wxPGProperty",
"::",
"sm_wxPG_LABEL",
")",
"long",
"value",
"=",
"0",
")",
"-",
">",
"IntProperty",
"__init__",
"(",
... | def __init__(self, *args):
"""
__init__(self, String label=(*wxPGProperty::sm_wxPG_LABEL), String name=(*wxPGProperty::sm_wxPG_LABEL),
long value=0) -> IntProperty
__init__(self, String label, String name, wxLongLong value) -> IntProperty
"""
_propgrid.IntProperty_swiginit(self,_propgrid.new_IntProperty(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_propgrid",
".",
"IntProperty_swiginit",
"(",
"self",
",",
"_propgrid",
".",
"new_IntProperty",
"(",
"*",
"args",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2900-L2906 | ||
apache/mesos | 97d9a4063332aae3825d78de71611657e05cf5e2 | src/python/interface/src/mesos/interface/__init__.py | python | SchedulerDriver.acceptOffers | (self, offerIds, operations, filters=None) | Accepts the given offers and performs a sequence of operations on
those accepted offers. See Offer.Operation in mesos.proto for the
set of available operations. Any remaining resources (i.e., those
that are not used by the launched tasks or their executors) will
be considered declined. Note that this includes resources used by
tasks that the framework attempted to launch but failed (with
TASK_ERROR) due to a malformed task description. The specified
filters are applied on all unused resources (see mesos.proto for
a description of Filters). Available resources are aggregated
when multiple offers are provided. Note that all offers must
belong to the same slave. | Accepts the given offers and performs a sequence of operations on
those accepted offers. See Offer.Operation in mesos.proto for the
set of available operations. Any remaining resources (i.e., those
that are not used by the launched tasks or their executors) will
be considered declined. Note that this includes resources used by
tasks that the framework attempted to launch but failed (with
TASK_ERROR) due to a malformed task description. The specified
filters are applied on all unused resources (see mesos.proto for
a description of Filters). Available resources are aggregated
when multiple offers are provided. Note that all offers must
belong to the same slave. | [
"Accepts",
"the",
"given",
"offers",
"and",
"performs",
"a",
"sequence",
"of",
"operations",
"on",
"those",
"accepted",
"offers",
".",
"See",
"Offer",
".",
"Operation",
"in",
"mesos",
".",
"proto",
"for",
"the",
"set",
"of",
"available",
"operations",
".",
... | def acceptOffers(self, offerIds, operations, filters=None):
"""
Accepts the given offers and performs a sequence of operations on
those accepted offers. See Offer.Operation in mesos.proto for the
set of available operations. Any remaining resources (i.e., those
that are not used by the launched tasks or their executors) will
be considered declined. Note that this includes resources used by
tasks that the framework attempted to launch but failed (with
TASK_ERROR) due to a malformed task description. The specified
filters are applied on all unused resources (see mesos.proto for
a description of Filters). Available resources are aggregated
when multiple offers are provided. Note that all offers must
belong to the same slave.
""" | [
"def",
"acceptOffers",
"(",
"self",
",",
"offerIds",
",",
"operations",
",",
"filters",
"=",
"None",
")",
":"
] | https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/src/python/interface/src/mesos/interface/__init__.py#L217-L230 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/profiler/parser/optime_parser.py | python | OPComputeTimeParser._write_timeline_data_into_file | (self, timeline_data) | Write the timeline information into the file, including
operator name, stream id, start time and duration.
Args:
timeline_data (list): The metadata to be written into the file.
[
['op_name_1', 'stream_id_1', 'start_time_1', 'duration_1'],
['op_name_2', 'stream_id_2', 'start_time_2', 'duration_2'],
[...]
] | Write the timeline information into the file, including
operator name, stream id, start time and duration. | [
"Write",
"the",
"timeline",
"information",
"into",
"the",
"file",
"including",
"operator",
"name",
"stream",
"id",
"start",
"time",
"and",
"duration",
"."
] | def _write_timeline_data_into_file(self, timeline_data):
"""
Write the timeline information into the file, including
operator name, stream id, start time and duration.
Args:
timeline_data (list): The metadata to be written into the file.
[
['op_name_1', 'stream_id_1', 'start_time_1', 'duration_1'],
['op_name_2', 'stream_id_2', 'start_time_2', 'duration_2'],
[...]
]
"""
# sorted by start times
timeline_data.sort(key=lambda x: float(x[2]))
filename = 'output_timeline_data_{}.txt'.format(self._device_id)
file_path = os.path.join(self._output_path, filename)
file_path = validate_and_normalize_path(file_path)
# write to file
try:
with open(file_path, 'w') as f_obj:
f_obj.write(TIMELINE_FILE_COLUMN_TITLE + '\n')
for timeline in timeline_data:
timeline = [str(item) for item in timeline]
f_obj.write(','.join(timeline) + '\n')
os.chmod(file_path, stat.S_IREAD | stat.S_IWRITE)
except (IOError, OSError) as err:
logger.critical('Error occurred when writing intermediate timeline file: %s', err)
raise ProfilerIOException | [
"def",
"_write_timeline_data_into_file",
"(",
"self",
",",
"timeline_data",
")",
":",
"# sorted by start times",
"timeline_data",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"float",
"(",
"x",
"[",
"2",
"]",
")",
")",
"filename",
"=",
"'output_timeline_d... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/optime_parser.py#L144-L173 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/tensor_forest/python/tensor_forest.py | python | RandomTreeGraphs._gini | (self, class_counts) | return 1.0 - sum_squares / (sums * sums) | Calculate the Gini impurity.
If c(i) denotes the i-th class count and c = sum_i c(i) then
score = 1 - sum_i ( c(i) / c )^2
Args:
class_counts: A 2-D tensor of per-class counts, usually a slice or
gather from variables.node_sums.
Returns:
A 1-D tensor of the Gini impurities for each row in the input. | Calculate the Gini impurity. | [
"Calculate",
"the",
"Gini",
"impurity",
"."
] | def _gini(self, class_counts):
"""Calculate the Gini impurity.
If c(i) denotes the i-th class count and c = sum_i c(i) then
score = 1 - sum_i ( c(i) / c )^2
Args:
class_counts: A 2-D tensor of per-class counts, usually a slice or
gather from variables.node_sums.
Returns:
A 1-D tensor of the Gini impurities for each row in the input.
"""
smoothed = 1.0 + array_ops.slice(class_counts, [0, 1], [-1, -1])
sums = math_ops.reduce_sum(smoothed, 1)
sum_squares = math_ops.reduce_sum(math_ops.square(smoothed), 1)
return 1.0 - sum_squares / (sums * sums) | [
"def",
"_gini",
"(",
"self",
",",
"class_counts",
")",
":",
"smoothed",
"=",
"1.0",
"+",
"array_ops",
".",
"slice",
"(",
"class_counts",
",",
"[",
"0",
",",
"1",
"]",
",",
"[",
"-",
"1",
",",
"-",
"1",
"]",
")",
"sums",
"=",
"math_ops",
".",
"r... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/tensor_forest/python/tensor_forest.py#L530-L547 | |
OpenLightingProject/ola | d1433a1bed73276fbe55ce18c03b1c208237decc | python/ola/OlaClient.py | python | OlaClient._UniverseInfoComplete | (self, callback, controller, response) | Called when the Universe info request returns.
Args:
callback: the callback to run
controller: an RpcController
response: a UniverseInfoReply message. | Called when the Universe info request returns. | [
"Called",
"when",
"the",
"Universe",
"info",
"request",
"returns",
"."
] | def _UniverseInfoComplete(self, callback, controller, response):
"""Called when the Universe info request returns.
Args:
callback: the callback to run
controller: an RpcController
response: a UniverseInfoReply message.
"""
if not callback:
return
status = RequestStatus(controller)
universes = None
if status.Succeeded():
universes = [Universe.FromProtobuf(u) for u in response.universe]
callback(status, universes) | [
"def",
"_UniverseInfoComplete",
"(",
"self",
",",
"callback",
",",
"controller",
",",
"response",
")",
":",
"if",
"not",
"callback",
":",
"return",
"status",
"=",
"RequestStatus",
"(",
"controller",
")",
"universes",
"=",
"None",
"if",
"status",
".",
"Succee... | https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/python/ola/OlaClient.py#L1446-L1462 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/sliceviewer/view.py | python | SliceViewerDataView.toggle_grid | (self, state) | Toggle the visibility of the grid on the axes | Toggle the visibility of the grid on the axes | [
"Toggle",
"the",
"visibility",
"of",
"the",
"grid",
"on",
"the",
"axes"
] | def toggle_grid(self, state):
"""
Toggle the visibility of the grid on the axes
"""
self._grid_on = state
self.ax.grid(self._grid_on)
self.canvas.draw_idle() | [
"def",
"toggle_grid",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_grid_on",
"=",
"state",
"self",
".",
"ax",
".",
"grid",
"(",
"self",
".",
"_grid_on",
")",
"self",
".",
"canvas",
".",
"draw_idle",
"(",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/sliceviewer/view.py#L513-L519 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/pytree.py | python | LeafPattern.match | (self, node, results=None) | return BasePattern.match(self, node, results) | Override match() to insist on a leaf node. | Override match() to insist on a leaf node. | [
"Override",
"match",
"()",
"to",
"insist",
"on",
"a",
"leaf",
"node",
"."
] | def match(self, node, results=None):
"""Override match() to insist on a leaf node."""
if not isinstance(node, Leaf):
return False
return BasePattern.match(self, node, results) | [
"def",
"match",
"(",
"self",
",",
"node",
",",
"results",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"Leaf",
")",
":",
"return",
"False",
"return",
"BasePattern",
".",
"match",
"(",
"self",
",",
"node",
",",
"results",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/pytree.py#L556-L560 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.