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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/structured/structured_tensor.py | python | StructuredTensor._from_pyval | (cls, pyval, typespec, path_so_far) | Helper function for from_pyval.
Args:
pyval: The nested Python structure that should be used to create the new
`StructuredTensor`.
typespec: A `StructuredTensorSpec` specifying the expected type for each
field. If not specified, then all nested dictionaries are turned into
StructuredTensors, and all nested lists are turned into Tensors (if
rank<2) or RaggedTensors (if rank>=2).
path_so_far: the path of fields that led here (for error messages).
Returns:
A `StructuredTensor`. | Helper function for from_pyval. | [
"Helper",
"function",
"for",
"from_pyval",
"."
] | def _from_pyval(cls, pyval, typespec, path_so_far):
"""Helper function for from_pyval.
Args:
pyval: The nested Python structure that should be used to create the new
`StructuredTensor`.
typespec: A `StructuredTensorSpec` specifying the expected type for each
field. If not specified, then all nested dictionaries are turned into
StructuredTensors, and all nested lists are turned into Tensors (if
rank<2) or RaggedTensors (if rank>=2).
path_so_far: the path of fields that led here (for error messages).
Returns:
A `StructuredTensor`.
"""
if isinstance(pyval, dict):
return cls._from_pydict(pyval, typespec, path_so_far)
elif isinstance(pyval, (list, tuple)):
keys = set()
rank = _pyval_find_struct_keys_and_depth(pyval, keys)
if rank is not None:
return cls._from_pylist_of_dict(pyval, keys, rank, typespec,
path_so_far)
else:
return cls._from_pylist_of_value(pyval, typespec, path_so_far)
else:
return cls._from_pyscalar(pyval, typespec, path_so_far) | [
"def",
"_from_pyval",
"(",
"cls",
",",
"pyval",
",",
"typespec",
",",
"path_so_far",
")",
":",
"if",
"isinstance",
"(",
"pyval",
",",
"dict",
")",
":",
"return",
"cls",
".",
"_from_pydict",
"(",
"pyval",
",",
"typespec",
",",
"path_so_far",
")",
"elif",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/structured/structured_tensor.py#L888-L915 | ||
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/frameworks/methodManager.py | python | ParameterInversionManager.__init__ | (self, funct=None, fop=None, **kwargs) | Constructor. | Constructor. | [
"Constructor",
"."
] | def __init__(self, funct=None, fop=None, **kwargs):
"""Constructor."""
if fop is not None:
if not isinstance(fop, pg.frameworks.ParameterModelling):
pg.critical("We need a fop if type ",
pg.frameworks.ParameterModelling)
elif funct is not None:
fop = pg.frameworks.ParameterModelling(funct)
else:
pg.critical("you should either give a valid fop or a function so "
"I can create the fop for you")
super(ParameterInversionManager, self).__init__(fop, **kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"funct",
"=",
"None",
",",
"fop",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"fop",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"fop",
",",
"pg",
".",
"frameworks",
".",
"ParameterModell... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/frameworks/methodManager.py#L572-L584 | ||
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | scripts/cluster.py | python | server_locator | (transport, host, port=server_port) | return locator | Generate a service locator for a master/backup process.
@param transport: A transport name (e.g. infrc, basic+infud, tcp, ...)
@type transport: C{str}
@param host: A 3-tuple of (hostname, ip, id).
@type host: C{(str, str, int)}
@param port: Port which should be part of the locator (if any).
Allows multiple services to be started on the same host.
@type port: C{int}
@return: A service locator.
@rtype: C{str} | Generate a service locator for a master/backup process. | [
"Generate",
"a",
"service",
"locator",
"for",
"a",
"master",
"/",
"backup",
"process",
"."
] | def server_locator(transport, host, port=server_port):
"""Generate a service locator for a master/backup process.
@param transport: A transport name (e.g. infrc, basic+infud, tcp, ...)
@type transport: C{str}
@param host: A 3-tuple of (hostname, ip, id).
@type host: C{(str, str, int)}
@param port: Port which should be part of the locator (if any).
Allows multiple services to be started on the same host.
@type port: C{int}
@return: A service locator.
@rtype: C{str}
"""
locator = (server_locator_templates[transport] %
{'host': host[1],
'host1g': host[0],
'port': port,
'id': host[2]})
return locator | [
"def",
"server_locator",
"(",
"transport",
",",
"host",
",",
"port",
"=",
"server_port",
")",
":",
"locator",
"=",
"(",
"server_locator_templates",
"[",
"transport",
"]",
"%",
"{",
"'host'",
":",
"host",
"[",
"1",
"]",
",",
"'host1g'",
":",
"host",
"[",
... | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/scripts/cluster.py#L85-L106 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/algorithms/sfm/OpenSfM/opensfm/reconstruction.py | python | bundle | (graph, reconstruction, gcp, config) | return report | Bundle adjust a reconstruction. | Bundle adjust a reconstruction. | [
"Bundle",
"adjust",
"a",
"reconstruction",
"."
] | def bundle(graph, reconstruction, gcp, config):
"""Bundle adjust a reconstruction."""
fix_cameras = not config['optimize_camera_parameters']
chrono = Chronometer()
ba = csfm.BundleAdjuster()
for camera in reconstruction.cameras.values():
_add_camera_to_bundle(ba, camera, fix_cameras)
for shot in reconstruction.shots.values():
r = shot.pose.rotation
t = shot.pose.translation
ba.add_shot(
shot.id, shot.camera.id,
r[0], r[1], r[2],
t[0], t[1], t[2],
False
)
for point in reconstruction.points.values():
x = point.coordinates
ba.add_point(point.id, x[0], x[1], x[2], False)
for shot_id in reconstruction.shots:
if shot_id in graph:
for track in graph[shot_id]:
if track in reconstruction.points:
ba.add_observation(shot_id, track,
*graph[shot_id][track]['feature'])
if config['bundle_use_gps']:
for shot in reconstruction.shots.values():
g = shot.metadata.gps_position
ba.add_position_prior(shot.id, g[0], g[1], g[2],
shot.metadata.gps_dop)
if config['bundle_use_gcp'] and gcp:
for observation in gcp:
if observation.shot_id in reconstruction.shots:
ba.add_ground_control_point_observation(
observation.shot_id,
observation.coordinates[0],
observation.coordinates[1],
observation.coordinates[2],
observation.shot_coordinates[0],
observation.shot_coordinates[1])
ba.set_loss_function(config['loss_function'],
config['loss_function_threshold'])
ba.set_reprojection_error_sd(config['reprojection_error_sd'])
ba.set_internal_parameters_prior_sd(
config['exif_focal_sd'],
config['principal_point_sd'],
config['radial_distorsion_k1_sd'],
config['radial_distorsion_k2_sd'],
config['radial_distorsion_p1_sd'],
config['radial_distorsion_p2_sd'],
config['radial_distorsion_k3_sd'])
ba.set_num_threads(config['processes'])
ba.set_max_num_iterations(50)
ba.set_linear_solver_type("SPARSE_SCHUR")
chrono.lap('setup')
ba.run()
chrono.lap('run')
for camera in reconstruction.cameras.values():
_get_camera_from_bundle(ba, camera)
for shot in reconstruction.shots.values():
s = ba.get_shot(shot.id)
shot.pose.rotation = [s.rx, s.ry, s.rz]
shot.pose.translation = [s.tx, s.ty, s.tz]
for point in reconstruction.points.values():
p = ba.get_point(point.id)
point.coordinates = [p.x, p.y, p.z]
point.reprojection_error = p.reprojection_error
chrono.lap('teardown')
logger.debug(ba.brief_report())
report = {
'wall_times': dict(chrono.lap_times()),
'brief_report': ba.brief_report(),
}
return report | [
"def",
"bundle",
"(",
"graph",
",",
"reconstruction",
",",
"gcp",
",",
"config",
")",
":",
"fix_cameras",
"=",
"not",
"config",
"[",
"'optimize_camera_parameters'",
"]",
"chrono",
"=",
"Chronometer",
"(",
")",
"ba",
"=",
"csfm",
".",
"BundleAdjuster",
"(",
... | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/reconstruction.py#L92-L179 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | lldb/third_party/Python/module/pexpect-4.6/pexpect/fdpexpect.py | python | fdspawn.read_nonblocking | (self, size=1, timeout=-1) | return super(fdspawn, self).read_nonblocking(size) | Read from the file descriptor and return the result as a string.
The read_nonblocking method of :class:`SpawnBase` assumes that a call
to os.read will not block (timeout parameter is ignored). This is not
the case for POSIX file-like objects such as sockets and serial ports.
Use :func:`select.select`, timeout is implemented conditionally for
POSIX systems.
:param int size: Read at most *size* bytes.
:param int timeout: Wait timeout seconds for file descriptor to be
ready to read. When -1 (default), use self.timeout. When 0, poll.
:return: String containing the bytes read | Read from the file descriptor and return the result as a string. | [
"Read",
"from",
"the",
"file",
"descriptor",
"and",
"return",
"the",
"result",
"as",
"a",
"string",
"."
] | def read_nonblocking(self, size=1, timeout=-1):
"""
Read from the file descriptor and return the result as a string.
The read_nonblocking method of :class:`SpawnBase` assumes that a call
to os.read will not block (timeout parameter is ignored). This is not
the case for POSIX file-like objects such as sockets and serial ports.
Use :func:`select.select`, timeout is implemented conditionally for
POSIX systems.
:param int size: Read at most *size* bytes.
:param int timeout: Wait timeout seconds for file descriptor to be
ready to read. When -1 (default), use self.timeout. When 0, poll.
:return: String containing the bytes read
"""
if os.name == 'posix':
if timeout == -1:
timeout = self.timeout
rlist = [self.child_fd]
wlist = []
xlist = []
if self.use_poll:
rlist = poll_ignore_interrupts(rlist, timeout)
else:
rlist, wlist, xlist = select_ignore_interrupts(
rlist, wlist, xlist, timeout
)
if self.child_fd not in rlist:
raise TIMEOUT('Timeout exceeded.')
return super(fdspawn, self).read_nonblocking(size) | [
"def",
"read_nonblocking",
"(",
"self",
",",
"size",
"=",
"1",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"if",
"timeout",
"==",
"-",
"1",
":",
"timeout",
"=",
"self",
".",
"timeout",
"rlist",
"=",
"["... | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/third_party/Python/module/pexpect-4.6/pexpect/fdpexpect.py#L118-L148 | |
zlgopen/awtk | 2c49e854a78749d9092907c027a7fba9062be549 | 3rd/mbedtls/scripts/mbedtls_dev/c_build_helper.py | python | create_c_file | (file_label) | return c_file, c_name, exe_name | Create a temporary C file.
* ``file_label``: a string that will be included in the file name.
Return ```(c_file, c_name, exe_name)``` where ``c_file`` is a Python
stream open for writing to the file, ``c_name`` is the name of the file
and ``exe_name`` is the name of the executable that will be produced
by compiling the file. | Create a temporary C file. | [
"Create",
"a",
"temporary",
"C",
"file",
"."
] | def create_c_file(file_label):
"""Create a temporary C file.
* ``file_label``: a string that will be included in the file name.
Return ```(c_file, c_name, exe_name)``` where ``c_file`` is a Python
stream open for writing to the file, ``c_name`` is the name of the file
and ``exe_name`` is the name of the executable that will be produced
by compiling the file.
"""
c_fd, c_name = tempfile.mkstemp(prefix='tmp-{}-'.format(file_label),
suffix='.c')
exe_suffix = '.exe' if platform.system() == 'Windows' else ''
exe_name = c_name[:-2] + exe_suffix
remove_file_if_exists(exe_name)
c_file = os.fdopen(c_fd, 'w', encoding='ascii')
return c_file, c_name, exe_name | [
"def",
"create_c_file",
"(",
"file_label",
")",
":",
"c_fd",
",",
"c_name",
"=",
"tempfile",
".",
"mkstemp",
"(",
"prefix",
"=",
"'tmp-{}-'",
".",
"format",
"(",
"file_label",
")",
",",
"suffix",
"=",
"'.c'",
")",
"exe_suffix",
"=",
"'.exe'",
"if",
"plat... | https://github.com/zlgopen/awtk/blob/2c49e854a78749d9092907c027a7fba9062be549/3rd/mbedtls/scripts/mbedtls_dev/c_build_helper.py#L34-L50 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/mixture/_base.py | python | BaseMixture._print_verbose_msg_init_beg | (self, n_init) | Print verbose message on initialization. | Print verbose message on initialization. | [
"Print",
"verbose",
"message",
"on",
"initialization",
"."
] | def _print_verbose_msg_init_beg(self, n_init):
"""Print verbose message on initialization."""
if self.verbose == 1:
print("Initialization %d" % n_init)
elif self.verbose >= 2:
print("Initialization %d" % n_init)
self._init_prev_time = time()
self._iter_prev_time = self._init_prev_time | [
"def",
"_print_verbose_msg_init_beg",
"(",
"self",
",",
"n_init",
")",
":",
"if",
"self",
".",
"verbose",
"==",
"1",
":",
"print",
"(",
"\"Initialization %d\"",
"%",
"n_init",
")",
"elif",
"self",
".",
"verbose",
">=",
"2",
":",
"print",
"(",
"\"Initializa... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/mixture/_base.py#L508-L515 | ||
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/bindings/python/MythTV/dataheap.py | python | Artist.fromSong | (cls, song, db=None) | return cls(artist, db) | Returns the artist for the given song. | Returns the artist for the given song. | [
"Returns",
"the",
"artist",
"for",
"the",
"given",
"song",
"."
] | def fromSong(cls, song, db=None):
"""Returns the artist for the given song."""
try:
artist = song.artist_id
db = song._db
except AttributeError:
db = DBCache(db)
artist = Song(song, db).artist_id
return cls(artist, db) | [
"def",
"fromSong",
"(",
"cls",
",",
"song",
",",
"db",
"=",
"None",
")",
":",
"try",
":",
"artist",
"=",
"song",
".",
"artist_id",
"db",
"=",
"song",
".",
"_db",
"except",
"AttributeError",
":",
"db",
"=",
"DBCache",
"(",
"db",
")",
"artist",
"=",
... | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/dataheap.py#L1343-L1351 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/bdb.py | python | Bdb.run | (self, cmd, globals=None, locals=None) | Debug a statement executed via the exec() function.
globals defaults to __main__.dict; locals defaults to globals. | Debug a statement executed via the exec() function. | [
"Debug",
"a",
"statement",
"executed",
"via",
"the",
"exec",
"()",
"function",
"."
] | def run(self, cmd, globals=None, locals=None):
"""Debug a statement executed via the exec() function.
globals defaults to __main__.dict; locals defaults to globals.
"""
if globals is None:
import __main__
globals = __main__.__dict__
if locals is None:
locals = globals
self.reset()
if isinstance(cmd, str):
cmd = compile(cmd, "<string>", "exec")
sys.settrace(self.trace_dispatch)
try:
exec(cmd, globals, locals)
except BdbQuit:
pass
finally:
self.quitting = True
sys.settrace(None) | [
"def",
"run",
"(",
"self",
",",
"cmd",
",",
"globals",
"=",
"None",
",",
"locals",
"=",
"None",
")",
":",
"if",
"globals",
"is",
"None",
":",
"import",
"__main__",
"globals",
"=",
"__main__",
".",
"__dict__",
"if",
"locals",
"is",
"None",
":",
"local... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/bdb.py#L563-L583 | ||
SonarOpenCommunity/sonar-cxx | 6e1d456fdcd45d35bcdc61c980e34d85fe88971e | cxx-squid/dox/tools/grammar_parser/grammar_parser.py | python | GrammarParser.__sort_attachments | (sequences) | return sequences | Move all [[xxx]] to the end. | Move all [[xxx]] to the end. | [
"Move",
"all",
"[[",
"xxx",
"]]",
"to",
"the",
"end",
"."
] | def __sort_attachments(sequences):
"""
Move all [[xxx]] to the end.
"""
for i, sequence in enumerate(sequences):
expressions = []
attachments = []
for expression in sequence:
if expression.startswith('[['):
attachments.append(expression)
else:
expressions.append(expression)
attachments.reverse()
expressions.extend(attachments)
sequences[i] = expressions
return sequences | [
"def",
"__sort_attachments",
"(",
"sequences",
")",
":",
"for",
"i",
",",
"sequence",
"in",
"enumerate",
"(",
"sequences",
")",
":",
"expressions",
"=",
"[",
"]",
"attachments",
"=",
"[",
"]",
"for",
"expression",
"in",
"sequence",
":",
"if",
"expression",... | https://github.com/SonarOpenCommunity/sonar-cxx/blob/6e1d456fdcd45d35bcdc61c980e34d85fe88971e/cxx-squid/dox/tools/grammar_parser/grammar_parser.py#L195-L210 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/io/loader.py | python | writeMatrix3 | (x) | return writeSo3(so3.from_matrix(text)) | Writes a 3x3 matrix to a string | Writes a 3x3 matrix to a string | [
"Writes",
"a",
"3x3",
"matrix",
"to",
"a",
"string"
] | def writeMatrix3(x):
"""Writes a 3x3 matrix to a string"""
return writeSo3(so3.from_matrix(text)) | [
"def",
"writeMatrix3",
"(",
"x",
")",
":",
"return",
"writeSo3",
"(",
"so3",
".",
"from_matrix",
"(",
"text",
")",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/io/loader.py#L192-L194 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | SimBody.getSurface | (self) | return _robotsim.SimBody_getSurface(self) | r"""
Gets (a copy of) the surface properties. | r"""
Gets (a copy of) the surface properties. | [
"r",
"Gets",
"(",
"a",
"copy",
"of",
")",
"the",
"surface",
"properties",
"."
] | def getSurface(self) -> "ContactParameters":
r"""
Gets (a copy of) the surface properties.
"""
return _robotsim.SimBody_getSurface(self) | [
"def",
"getSurface",
"(",
"self",
")",
"->",
"\"ContactParameters\"",
":",
"return",
"_robotsim",
".",
"SimBody_getSurface",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L7579-L7584 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/virtualenv.py | python | VirtualenvManager.__init__ | (self, topsrcdir, topobjdir, virtualenv_path, log_handle,
manifest_path) | Create a new manager.
Each manager is associated with a source directory, a path where you
want the virtualenv to be created, and a handle to write output to. | Create a new manager. | [
"Create",
"a",
"new",
"manager",
"."
] | def __init__(self, topsrcdir, topobjdir, virtualenv_path, log_handle,
manifest_path):
"""Create a new manager.
Each manager is associated with a source directory, a path where you
want the virtualenv to be created, and a handle to write output to.
"""
assert os.path.isabs(manifest_path), "manifest_path must be an absolute path: %s" % (manifest_path)
self.topsrcdir = topsrcdir
self.topobjdir = topobjdir
self.virtualenv_root = virtualenv_path
self.log_handle = log_handle
self.manifest_path = manifest_path | [
"def",
"__init__",
"(",
"self",
",",
"topsrcdir",
",",
"topobjdir",
",",
"virtualenv_path",
",",
"log_handle",
",",
"manifest_path",
")",
":",
"assert",
"os",
".",
"path",
".",
"isabs",
"(",
"manifest_path",
")",
",",
"\"manifest_path must be an absolute path: %s\... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/virtualenv.py#L42-L54 | ||
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/tools/clang/tools/scan-build-py/libscanbuild/analyze.py | python | dispatch_ctu | (opts, continuation=run_analyzer) | return continuation(opts) | Execute only one phase of 2 phases of CTU if needed. | Execute only one phase of 2 phases of CTU if needed. | [
"Execute",
"only",
"one",
"phase",
"of",
"2",
"phases",
"of",
"CTU",
"if",
"needed",
"."
] | def dispatch_ctu(opts, continuation=run_analyzer):
""" Execute only one phase of 2 phases of CTU if needed. """
ctu_config = opts['ctu']
if ctu_config.collect or ctu_config.analyze:
assert ctu_config.collect != ctu_config.analyze
if ctu_config.collect:
return ctu_collect_phase(opts)
if ctu_config.analyze:
cwd = opts['directory']
cmd = [opts['clang'], '--analyze'] + opts['direct_args'] \
+ opts['flags'] + [opts['file']]
triarch = get_triple_arch(cmd, cwd)
ctu_options = ['ctu-dir=' + os.path.join(ctu_config.dir, triarch),
'experimental-enable-naive-ctu-analysis=true']
analyzer_options = prefix_with('-analyzer-config', ctu_options)
direct_options = prefix_with('-Xanalyzer', analyzer_options)
opts['direct_args'].extend(direct_options)
return continuation(opts) | [
"def",
"dispatch_ctu",
"(",
"opts",
",",
"continuation",
"=",
"run_analyzer",
")",
":",
"ctu_config",
"=",
"opts",
"[",
"'ctu'",
"]",
"if",
"ctu_config",
".",
"collect",
"or",
"ctu_config",
".",
"analyze",
":",
"assert",
"ctu_config",
".",
"collect",
"!=",
... | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/tools/scan-build-py/libscanbuild/analyze.py#L627-L647 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/turtle.py | python | RawTurtle._getshapepoly | (self, polygon, compound=False) | return tuple((t11*x + t12*y, t21*x + t22*y) for (x, y) in polygon) | Calculate transformed shape polygon according to resizemode
and shapetransform. | Calculate transformed shape polygon according to resizemode
and shapetransform. | [
"Calculate",
"transformed",
"shape",
"polygon",
"according",
"to",
"resizemode",
"and",
"shapetransform",
"."
] | def _getshapepoly(self, polygon, compound=False):
"""Calculate transformed shape polygon according to resizemode
and shapetransform.
"""
if self._resizemode == "user" or compound:
t11, t12, t21, t22 = self._shapetrafo
elif self._resizemode == "auto":
l = max(1, self._pensize/5.0)
t11, t12, t21, t22 = l, 0, 0, l
elif self._resizemode == "noresize":
return polygon
return tuple((t11*x + t12*y, t21*x + t22*y) for (x, y) in polygon) | [
"def",
"_getshapepoly",
"(",
"self",
",",
"polygon",
",",
"compound",
"=",
"False",
")",
":",
"if",
"self",
".",
"_resizemode",
"==",
"\"user\"",
"or",
"compound",
":",
"t11",
",",
"t12",
",",
"t21",
",",
"t22",
"=",
"self",
".",
"_shapetrafo",
"elif",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L2983-L2994 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/fuchsia/binary_sizes.py | python | GetSdkModules | () | return lib_names | Finds shared objects (.so) under the Fuchsia SDK arch directory in dist or
lib subdirectories.
Returns a set of shared objects' filenames. | Finds shared objects (.so) under the Fuchsia SDK arch directory in dist or
lib subdirectories. | [
"Finds",
"shared",
"objects",
"(",
".",
"so",
")",
"under",
"the",
"Fuchsia",
"SDK",
"arch",
"directory",
"in",
"dist",
"or",
"lib",
"subdirectories",
"."
] | def GetSdkModules():
"""Finds shared objects (.so) under the Fuchsia SDK arch directory in dist or
lib subdirectories.
Returns a set of shared objects' filenames.
"""
# Fuchsia SDK arch directory path (contains all shared object files).
sdk_arch_dir = os.path.join(SDK_ROOT, 'arch')
# Leaf subdirectories containing shared object files.
sdk_so_leaf_dirs = ['dist', 'lib']
# Match a shared object file name.
sdk_so_filename_re = r'\.so(\.\d+)?$'
lib_names = set()
for dirpath, _, file_names in os.walk(sdk_arch_dir):
if os.path.basename(dirpath) in sdk_so_leaf_dirs:
for name in file_names:
if SO_FILENAME_REGEXP.search(name):
lib_names.add(name)
return lib_names | [
"def",
"GetSdkModules",
"(",
")",
":",
"# Fuchsia SDK arch directory path (contains all shared object files).",
"sdk_arch_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SDK_ROOT",
",",
"'arch'",
")",
"# Leaf subdirectories containing shared object files.",
"sdk_so_leaf_dirs",... | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/fuchsia/binary_sizes.py#L313-L333 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | ManualHandler.WriteBucketServiceImplementation | (self, func, file) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteBucketServiceImplementation(self, func, file):
"""Overrriden from TypeHandler."""
pass | [
"def",
"WriteBucketServiceImplementation",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"pass"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L3609-L3611 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/dtypes/missing.py | python | _infer_fill_value | (val) | return np.nan | infer the fill value for the nan/NaT from the provided
scalar/ndarray/list-like if we are a NaT, return the correct dtyped
element to provide proper block construction | infer the fill value for the nan/NaT from the provided
scalar/ndarray/list-like if we are a NaT, return the correct dtyped
element to provide proper block construction | [
"infer",
"the",
"fill",
"value",
"for",
"the",
"nan",
"/",
"NaT",
"from",
"the",
"provided",
"scalar",
"/",
"ndarray",
"/",
"list",
"-",
"like",
"if",
"we",
"are",
"a",
"NaT",
"return",
"the",
"correct",
"dtyped",
"element",
"to",
"provide",
"proper",
... | def _infer_fill_value(val):
"""
infer the fill value for the nan/NaT from the provided
scalar/ndarray/list-like if we are a NaT, return the correct dtyped
element to provide proper block construction
"""
if not is_list_like(val):
val = [val]
val = np.array(val, copy=False)
if is_datetimelike(val):
return np.array('NaT', dtype=val.dtype)
elif is_object_dtype(val.dtype):
dtype = lib.infer_dtype(ensure_object(val), skipna=False)
if dtype in ['datetime', 'datetime64']:
return np.array('NaT', dtype=_NS_DTYPE)
elif dtype in ['timedelta', 'timedelta64']:
return np.array('NaT', dtype=_TD_DTYPE)
return np.nan | [
"def",
"_infer_fill_value",
"(",
"val",
")",
":",
"if",
"not",
"is_list_like",
"(",
"val",
")",
":",
"val",
"=",
"[",
"val",
"]",
"val",
"=",
"np",
".",
"array",
"(",
"val",
",",
"copy",
"=",
"False",
")",
"if",
"is_datetimelike",
"(",
"val",
")",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/dtypes/missing.py#L448-L466 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py | python | getpager | () | Decide what method to use for paging through text. | Decide what method to use for paging through text. | [
"Decide",
"what",
"method",
"to",
"use",
"for",
"paging",
"through",
"text",
"."
] | def getpager():
"""Decide what method to use for paging through text."""
if type(sys.stdout) is not types.FileType:
return plainpager
if not sys.stdin.isatty() or not sys.stdout.isatty():
return plainpager
if 'PAGER' in os.environ:
if sys.platform == 'win32': # pipes completely broken in Windows
return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
elif sys.platform == 'uefi':
return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
elif os.environ.get('TERM') in ('dumb', 'emacs'):
return lambda text: pipepager(plain(text), os.environ['PAGER'])
else:
return lambda text: pipepager(text, os.environ['PAGER'])
if os.environ.get('TERM') in ('dumb', 'emacs'):
return plainpager
if sys.platform == 'uefi':
return plainpager
if sys.platform == 'win32' or sys.platform.startswith('os2'):
return lambda text: tempfilepager(plain(text), 'more <')
if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
return lambda text: pipepager(text, 'less')
import tempfile
(fd, filename) = tempfile.mkstemp()
os.close(fd)
try:
if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
return lambda text: pipepager(text, 'more')
else:
return ttypager
finally:
os.unlink(filename) | [
"def",
"getpager",
"(",
")",
":",
"if",
"type",
"(",
"sys",
".",
"stdout",
")",
"is",
"not",
"types",
".",
"FileType",
":",
"return",
"plainpager",
"if",
"not",
"sys",
".",
"stdin",
".",
"isatty",
"(",
")",
"or",
"not",
"sys",
".",
"stdout",
".",
... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py#L1320-L1353 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/training/queue_runner_impl.py | python | add_queue_runner | (qr, collection=ops.GraphKeys.QUEUE_RUNNERS) | Adds a `QueueRunner` to a collection in the graph.
When building a complex model that uses many queues it is often difficult to
gather all the queue runners that need to be run. This convenience function
allows you to add a queue runner to a well known collection in the graph.
The companion method `start_queue_runners()` can be used to start threads for
all the collected queue runners.
@compatibility(TF2)
QueueRunners are not compatible with eager execution. Instead, please
use [tf.data](https://www.tensorflow.org/guide/data) to get data into your
model.
@end_compatibility
Args:
qr: A `QueueRunner`.
collection: A `GraphKey` specifying the graph collection to add
the queue runner to. Defaults to `GraphKeys.QUEUE_RUNNERS`. | Adds a `QueueRunner` to a collection in the graph. | [
"Adds",
"a",
"QueueRunner",
"to",
"a",
"collection",
"in",
"the",
"graph",
"."
] | def add_queue_runner(qr, collection=ops.GraphKeys.QUEUE_RUNNERS):
"""Adds a `QueueRunner` to a collection in the graph.
When building a complex model that uses many queues it is often difficult to
gather all the queue runners that need to be run. This convenience function
allows you to add a queue runner to a well known collection in the graph.
The companion method `start_queue_runners()` can be used to start threads for
all the collected queue runners.
@compatibility(TF2)
QueueRunners are not compatible with eager execution. Instead, please
use [tf.data](https://www.tensorflow.org/guide/data) to get data into your
model.
@end_compatibility
Args:
qr: A `QueueRunner`.
collection: A `GraphKey` specifying the graph collection to add
the queue runner to. Defaults to `GraphKeys.QUEUE_RUNNERS`.
"""
ops.add_to_collection(collection, qr) | [
"def",
"add_queue_runner",
"(",
"qr",
",",
"collection",
"=",
"ops",
".",
"GraphKeys",
".",
"QUEUE_RUNNERS",
")",
":",
"ops",
".",
"add_to_collection",
"(",
"collection",
",",
"qr",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/queue_runner_impl.py#L393-L414 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/lite/python/convert_phase.py | python | ConverterError._parse_error_message | (self, message) | If the message matches a pattern, assigns the associated error code.
It is difficult to assign an error code to some errrors in MLIR side, Ex:
errors thrown by other components than TFLite or not using mlir::emitError.
This function try to detect them by the error message and assign the
corresponding error code.
Args:
message: The error message of this exception. | If the message matches a pattern, assigns the associated error code. | [
"If",
"the",
"message",
"matches",
"a",
"pattern",
"assigns",
"the",
"associated",
"error",
"code",
"."
] | def _parse_error_message(self, message):
"""If the message matches a pattern, assigns the associated error code.
It is difficult to assign an error code to some errrors in MLIR side, Ex:
errors thrown by other components than TFLite or not using mlir::emitError.
This function try to detect them by the error message and assign the
corresponding error code.
Args:
message: The error message of this exception.
"""
error_code_mapping = {
"Failed to functionalize Control Flow V1 ops. Consider using Control "
"Flow V2 ops instead. See https://www.tensorflow.org/api_docs/python/"
"tf/compat/v1/enable_control_flow_v2.":
converter_error_data_pb2.ConverterErrorData
.ERROR_UNSUPPORTED_CONTROL_FLOW_V1,
}
for pattern, error_code in error_code_mapping.items():
if pattern in message:
error_data = converter_error_data_pb2.ConverterErrorData()
error_data.error_message = message
error_data.error_code = error_code
self.append_error(error_data)
return | [
"def",
"_parse_error_message",
"(",
"self",
",",
"message",
")",
":",
"error_code_mapping",
"=",
"{",
"\"Failed to functionalize Control Flow V1 ops. Consider using Control \"",
"\"Flow V2 ops instead. See https://www.tensorflow.org/api_docs/python/\"",
"\"tf/compat/v1/enable_control_flow_... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/convert_phase.py#L139-L163 | ||
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/utils/benchmark/mingw.py | python | download | (url, location, log = EmptyLogger()) | return possible | Downloads and unpacks a mingw-builds archive | Downloads and unpacks a mingw-builds archive | [
"Downloads",
"and",
"unpacks",
"a",
"mingw",
"-",
"builds",
"archive"
] | def download(url, location, log = EmptyLogger()):
'''
Downloads and unpacks a mingw-builds archive
'''
log.info('downloading MinGW')
log.debug(' - url: %s', url)
log.debug(' - location: %s', location)
re_content = re.compile(r'attachment;[ \t]*filename=(")?([^"]*)(")?[\r\n]*')
stream = request.urlopen(url)
try:
content = stream.getheader('Content-Disposition') or ''
except AttributeError:
content = stream.headers.getheader('Content-Disposition') or ''
matches = re_content.match(content)
if matches:
filename = matches.group(2)
else:
parsed = parse.urlparse(stream.geturl())
filename = os.path.basename(parsed.path)
try:
os.makedirs(location)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(location):
pass
else:
raise
archive = os.path.join(location, filename)
with open(archive, 'wb') as out:
while True:
buf = stream.read(1024)
if not buf:
break
out.write(buf)
unpack(archive, location, log = log)
os.remove(archive)
possible = os.path.join(location, 'mingw64')
if not os.path.exists(possible):
possible = os.path.join(location, 'mingw32')
if not os.path.exists(possible):
raise ValueError('Failed to find unpacked MinGW: ' + possible)
return possible | [
"def",
"download",
"(",
"url",
",",
"location",
",",
"log",
"=",
"EmptyLogger",
"(",
")",
")",
":",
"log",
".",
"info",
"(",
"'downloading MinGW'",
")",
"log",
".",
"debug",
"(",
"' - url: %s'",
",",
"url",
")",
"log",
".",
"debug",
"(",
"' - location:... | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/utils/benchmark/mingw.py#L125-L170 | |
Z3Prover/z3 | d745d03afdfdf638d66093e2bfbacaf87187f35b | src/api/python/z3/z3.py | python | CharSort | (ctx=None) | return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx) | Create a character sort
>>> ch = CharSort()
>>> print(ch)
Char | Create a character sort
>>> ch = CharSort()
>>> print(ch)
Char | [
"Create",
"a",
"character",
"sort",
">>>",
"ch",
"=",
"CharSort",
"()",
">>>",
"print",
"(",
"ch",
")",
"Char"
] | def CharSort(ctx=None):
"""Create a character sort
>>> ch = CharSort()
>>> print(ch)
Char
"""
ctx = _get_ctx(ctx)
return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx) | [
"def",
"CharSort",
"(",
"ctx",
"=",
"None",
")",
":",
"ctx",
"=",
"_get_ctx",
"(",
"ctx",
")",
"return",
"CharSortRef",
"(",
"Z3_mk_char_sort",
"(",
"ctx",
".",
"ref",
"(",
")",
")",
",",
"ctx",
")"
] | https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L10625-L10632 | |
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | python/mxnet/io.py | python | DataIter.iter_next | (self) | Iterate to next batch.
Returns
-------
has_next : boolean
Whether the move is successful. | Iterate to next batch.
Returns
-------
has_next : boolean
Whether the move is successful. | [
"Iterate",
"to",
"next",
"batch",
".",
"Returns",
"-------",
"has_next",
":",
"boolean",
"Whether",
"the",
"move",
"is",
"successful",
"."
] | def iter_next(self):
"""Iterate to next batch.
Returns
-------
has_next : boolean
Whether the move is successful.
"""
pass | [
"def",
"iter_next",
"(",
"self",
")",
":",
"pass"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/mxnet/io.py#L66-L73 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/telemetry/core/backends/adb_commands.py | python | AdbCommands.KillAll | (self, process) | return self._adb.KillAll(process) | Android version of killall, connected via adb.
Args:
process: name of the process to kill off
Returns:
the number of processess killed | Android version of killall, connected via adb. | [
"Android",
"version",
"of",
"killall",
"connected",
"via",
"adb",
"."
] | def KillAll(self, process):
"""Android version of killall, connected via adb.
Args:
process: name of the process to kill off
Returns:
the number of processess killed
"""
return self._adb.KillAll(process) | [
"def",
"KillAll",
"(",
"self",
",",
"process",
")",
":",
"return",
"self",
".",
"_adb",
".",
"KillAll",
"(",
"process",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/core/backends/adb_commands.py#L105-L114 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | Region.UnionRegion | (*args, **kwargs) | return _gdi_.Region_UnionRegion(*args, **kwargs) | UnionRegion(self, Region region) -> bool | UnionRegion(self, Region region) -> bool | [
"UnionRegion",
"(",
"self",
"Region",
"region",
")",
"-",
">",
"bool"
] | def UnionRegion(*args, **kwargs):
"""UnionRegion(self, Region region) -> bool"""
return _gdi_.Region_UnionRegion(*args, **kwargs) | [
"def",
"UnionRegion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Region_UnionRegion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L1692-L1694 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py | python | PrecompiledHeader.GetFlagsModifications | (self, input, output, implicit, command,
cflags_c, cflags_cc, expand_special) | return [], output, implicit | Get the modified cflags and implicit dependencies that should be used
for the pch compilation step. | Get the modified cflags and implicit dependencies that should be used
for the pch compilation step. | [
"Get",
"the",
"modified",
"cflags",
"and",
"implicit",
"dependencies",
"that",
"should",
"be",
"used",
"for",
"the",
"pch",
"compilation",
"step",
"."
] | def GetFlagsModifications(self, input, output, implicit, command,
cflags_c, cflags_cc, expand_special):
"""Get the modified cflags and implicit dependencies that should be used
for the pch compilation step."""
if input == self.pch_source:
pch_output = ['/Yc' + self._PchHeader()]
if command == 'cxx':
return ([('cflags_cc', map(expand_special, cflags_cc + pch_output))],
self.output_obj, [])
elif command == 'cc':
return ([('cflags_c', map(expand_special, cflags_c + pch_output))],
self.output_obj, [])
return [], output, implicit | [
"def",
"GetFlagsModifications",
"(",
"self",
",",
"input",
",",
"output",
",",
"implicit",
",",
"command",
",",
"cflags_c",
",",
"cflags_cc",
",",
"expand_special",
")",
":",
"if",
"input",
"==",
"self",
".",
"pch_source",
":",
"pch_output",
"=",
"[",
"'/Y... | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py#L924-L936 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | PyTipProvider.__init__ | (self, *args, **kwargs) | __init__(self, size_t currentTip) -> PyTipProvider | __init__(self, size_t currentTip) -> PyTipProvider | [
"__init__",
"(",
"self",
"size_t",
"currentTip",
")",
"-",
">",
"PyTipProvider"
] | def __init__(self, *args, **kwargs):
"""__init__(self, size_t currentTip) -> PyTipProvider"""
_misc_.PyTipProvider_swiginit(self,_misc_.new_PyTipProvider(*args, **kwargs))
PyTipProvider._setCallbackInfo(self, self, PyTipProvider) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_misc_",
".",
"PyTipProvider_swiginit",
"(",
"self",
",",
"_misc_",
".",
"new_PyTipProvider",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"PyTipProvider",
".... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L1275-L1278 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/gluon/block.py | python | HybridBlock.export | (self, path, epoch=0, remove_amp_cast=True) | return sym, arg_dict | Export HybridBlock to json format that can be loaded by
`gluon.SymbolBlock.imports` or the C++ interface.
.. note:: When there are only one input, it will have name `data`. When there
Are more than one inputs, they will be named as `data0`, `data1`, etc.
Parameters
----------
path : str or None
Path to save model. Two files `path-symbol.json` and `path-xxxx.params`
will be created, where xxxx is the 4 digits epoch number.
If None, do not export to file but return Python Symbol object and
corresponding dictionary of parameters.
epoch : int
Epoch number of saved model.
remove_amp_cast : bool, optional
Whether to remove the amp_cast and amp_multicast operators, before saving the model.
Returns
-------
symbol_filename : str
Filename to which model symbols were saved, including `path` prefix.
params_filename : str
Filename to which model parameters were saved, including `path` prefix. | Export HybridBlock to json format that can be loaded by
`gluon.SymbolBlock.imports` or the C++ interface. | [
"Export",
"HybridBlock",
"to",
"json",
"format",
"that",
"can",
"be",
"loaded",
"by",
"gluon",
".",
"SymbolBlock",
".",
"imports",
"or",
"the",
"C",
"++",
"interface",
"."
] | def export(self, path, epoch=0, remove_amp_cast=True):
"""Export HybridBlock to json format that can be loaded by
`gluon.SymbolBlock.imports` or the C++ interface.
.. note:: When there are only one input, it will have name `data`. When there
Are more than one inputs, they will be named as `data0`, `data1`, etc.
Parameters
----------
path : str or None
Path to save model. Two files `path-symbol.json` and `path-xxxx.params`
will be created, where xxxx is the 4 digits epoch number.
If None, do not export to file but return Python Symbol object and
corresponding dictionary of parameters.
epoch : int
Epoch number of saved model.
remove_amp_cast : bool, optional
Whether to remove the amp_cast and amp_multicast operators, before saving the model.
Returns
-------
symbol_filename : str
Filename to which model symbols were saved, including `path` prefix.
params_filename : str
Filename to which model parameters were saved, including `path` prefix.
"""
if not self._cached_graph:
raise RuntimeError(
"Please first call block.hybridize() and then run forward with "
"this block at least once before calling export.")
sym = copy.copy(self._cached_graph[1])
# Deduplicate params (shared parameters use the same input symbol)
reverse_params = {v: k for k, v in self.collect_params().items()}
params = {v: k for k, v in reverse_params.items()}
# In export we have global information on the structure of the graph
# can rename the symbol inputs to human-readable, deterministic names.
# That's not true in general, which is why internally random unique identifiers are used.
rename_map = {param.var().name: name for name, param in params.items()}
for var in sym.get_inputs():
if var.name in rename_map:
var._set_attr(name=rename_map[var.name])
sym_filename = '%s-symbol.json' % (path if path is not None else "")
if path is not None:
sym.save(sym_filename, remove_amp_cast=remove_amp_cast)
arg_names = set(sym.list_arguments())
aux_names = set(sym.list_auxiliary_states())
arg_dict = {}
for is_arg, name, param in self._cached_op_args:
if not is_arg:
if name in arg_names:
arg_dict['arg:{}'.format(name)] = param._reduce()
else:
if name not in aux_names:
warnings.warn('Parameter "{name}" is not found in the graph. '
.format(name=name), stacklevel=3)
else:
arg_dict['aux:%s'%name] = param._reduce()
params_filename = '%s-%04d.params'%((path if path is not None else ""), epoch)
if path is not None:
if is_np_array():
_mx_npx.savez(params_filename, **arg_dict)
else:
ndarray.save(params_filename, arg_dict)
return (sym_filename, params_filename if arg_dict else None)
if remove_amp_cast:
handle = SymbolHandle()
import ctypes
check_call(_LIB.MXSymbolRemoveAmpCast(sym.handle, ctypes.byref(handle)))
sym = type(sym)(handle)
return sym, arg_dict | [
"def",
"export",
"(",
"self",
",",
"path",
",",
"epoch",
"=",
"0",
",",
"remove_amp_cast",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"_cached_graph",
":",
"raise",
"RuntimeError",
"(",
"\"Please first call block.hybridize() and then run forward with \"",
"\... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/block.py#L1480-L1555 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/json_schema_compiler/cc_generator.py | python | _Generator.Generate | (self) | return c | Generates a Code object with the .cc for a single namespace. | Generates a Code object with the .cc for a single namespace. | [
"Generates",
"a",
"Code",
"object",
"with",
"the",
".",
"cc",
"for",
"a",
"single",
"namespace",
"."
] | def Generate(self):
"""Generates a Code object with the .cc for a single namespace.
"""
c = Code()
(c.Append(cpp_util.CHROMIUM_LICENSE)
.Append()
.Append(cpp_util.GENERATED_FILE_MESSAGE % self._namespace.source_file)
.Append()
.Append(self._util_cc_helper.GetIncludePath())
.Append('#include "base/logging.h"')
.Append('#include "base/strings/string_number_conversions.h"')
.Append('#include "base/strings/utf_string_conversions.h"')
.Append('#include "%s/%s.h"' %
(self._namespace.source_file_dir, self._namespace.short_filename))
.Cblock(self._type_helper.GenerateIncludes(include_soft=True))
.Append()
.Concat(cpp_util.OpenNamespace(self._cpp_namespace))
.Cblock(self._type_helper.GetNamespaceStart())
)
if self._namespace.properties:
(c.Append('//')
.Append('// Properties')
.Append('//')
.Append()
)
for property in self._namespace.properties.values():
property_code = self._type_helper.GeneratePropertyValues(
property,
'const %(type)s %(name)s = %(value)s;',
nodoc=True)
if property_code:
c.Cblock(property_code)
if self._namespace.types:
(c.Append('//')
.Append('// Types')
.Append('//')
.Append()
.Cblock(self._GenerateTypes(None, self._namespace.types.values()))
)
if self._namespace.functions:
(c.Append('//')
.Append('// Functions')
.Append('//')
.Append()
)
for function in self._namespace.functions.values():
c.Cblock(self._GenerateFunction(function))
if self._namespace.events:
(c.Append('//')
.Append('// Events')
.Append('//')
.Append()
)
for event in self._namespace.events.values():
c.Cblock(self._GenerateEvent(event))
(c.Concat(self._type_helper.GetNamespaceEnd())
.Cblock(cpp_util.CloseNamespace(self._cpp_namespace))
)
c.Append()
return c | [
"def",
"Generate",
"(",
"self",
")",
":",
"c",
"=",
"Code",
"(",
")",
"(",
"c",
".",
"Append",
"(",
"cpp_util",
".",
"CHROMIUM_LICENSE",
")",
".",
"Append",
"(",
")",
".",
"Append",
"(",
"cpp_util",
".",
"GENERATED_FILE_MESSAGE",
"%",
"self",
".",
"_... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/json_schema_compiler/cc_generator.py#L36-L95 | |
mcneel/rhino-developer-samples | 995d8bb985da7080cb8df3b94326165d9eaf58cc | rhinocommon/snippets/py/custom-undo.py | python | OnUndoFavoriteNumber | (sender, e) | !!!!!!!!!!
NEVER change any setting in the Rhino document or application. Rhino
handles ALL changes to the application and document and you will break
the Undo/Redo commands if you make any changes to the application or
document. This is meant only for your own private plugin data
!!!!!!!!!!
This function can be called either by undo or redo
In order to get redo to work, add another custom undo event with the
current value. If you don't want redo to work, just skip adding
a custom undo event here | !!!!!!!!!!
NEVER change any setting in the Rhino document or application. Rhino
handles ALL changes to the application and document and you will break
the Undo/Redo commands if you make any changes to the application or
document. This is meant only for your own private plugin data
!!!!!!!!!! | [
"!!!!!!!!!!",
"NEVER",
"change",
"any",
"setting",
"in",
"the",
"Rhino",
"document",
"or",
"application",
".",
"Rhino",
"handles",
"ALL",
"changes",
"to",
"the",
"application",
"and",
"document",
"and",
"you",
"will",
"break",
"the",
"Undo",
"/",
"Redo",
"co... | def OnUndoFavoriteNumber(sender, e):
"""!!!!!!!!!!
NEVER change any setting in the Rhino document or application. Rhino
handles ALL changes to the application and document and you will break
the Undo/Redo commands if you make any changes to the application or
document. This is meant only for your own private plugin data
!!!!!!!!!!
This function can be called either by undo or redo
In order to get redo to work, add another custom undo event with the
current value. If you don't want redo to work, just skip adding
a custom undo event here
"""
current_value = scriptcontext.sticky["FavoriteNumber"]
e.Document.AddCustomUndoEvent("Favorite Number", OnUndoFavoriteNumber, current_value)
old_value = e.Tag
print "Going back to your favorite =", old_value
scriptcontext.sticky["FavoriteNumber"]= old_value; | [
"def",
"OnUndoFavoriteNumber",
"(",
"sender",
",",
"e",
")",
":",
"current_value",
"=",
"scriptcontext",
".",
"sticky",
"[",
"\"FavoriteNumber\"",
"]",
"e",
".",
"Document",
".",
"AddCustomUndoEvent",
"(",
"\"Favorite Number\"",
",",
"OnUndoFavoriteNumber",
",",
"... | https://github.com/mcneel/rhino-developer-samples/blob/995d8bb985da7080cb8df3b94326165d9eaf58cc/rhinocommon/snippets/py/custom-undo.py#L5-L23 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py | python | Future.running | (self) | Return True if the future is currently executing. | Return True if the future is currently executing. | [
"Return",
"True",
"if",
"the",
"future",
"is",
"currently",
"executing",
"."
] | def running(self):
"""Return True if the future is currently executing."""
with self._condition:
return self._state == RUNNING | [
"def",
"running",
"(",
"self",
")",
":",
"with",
"self",
".",
"_condition",
":",
"return",
"self",
".",
"_state",
"==",
"RUNNING"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py#L372-L375 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | Mass.getInertia | (self) | return _robotsim.Mass_getInertia(self) | r"""
getInertia(Mass self)
Returns the inertia matrix as a list of 3 floats or 9 floats. | r"""
getInertia(Mass self) | [
"r",
"getInertia",
"(",
"Mass",
"self",
")"
] | def getInertia(self) -> "void":
r"""
getInertia(Mass self)
Returns the inertia matrix as a list of 3 floats or 9 floats.
"""
return _robotsim.Mass_getInertia(self) | [
"def",
"getInertia",
"(",
"self",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"Mass_getInertia",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L3934-L3942 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/docs/bcdoc/style.py | python | ReSTStyle.codeblock | (self, code) | Literal code blocks are introduced by ending a paragraph with
the special marker ::. The literal block must be indented
(and, like all paragraphs, separated from the surrounding
ones by blank lines). | Literal code blocks are introduced by ending a paragraph with
the special marker ::. The literal block must be indented
(and, like all paragraphs, separated from the surrounding
ones by blank lines). | [
"Literal",
"code",
"blocks",
"are",
"introduced",
"by",
"ending",
"a",
"paragraph",
"with",
"the",
"special",
"marker",
"::",
".",
"The",
"literal",
"block",
"must",
"be",
"indented",
"(",
"and",
"like",
"all",
"paragraphs",
"separated",
"from",
"the",
"surr... | def codeblock(self, code):
"""
Literal code blocks are introduced by ending a paragraph with
the special marker ::. The literal block must be indented
(and, like all paragraphs, separated from the surrounding
ones by blank lines).
"""
self.start_codeblock()
self.doc.writeln(code)
self.end_codeblock() | [
"def",
"codeblock",
"(",
"self",
",",
"code",
")",
":",
"self",
".",
"start_codeblock",
"(",
")",
"self",
".",
"doc",
".",
"writeln",
"(",
"code",
")",
"self",
".",
"end_codeblock",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/docs/bcdoc/style.py#L325-L334 | ||
KhronosGroup/Vulkan-Headers | b32da5329b50e3cb96229aaecba9ded032fe29cc | registry/reg.py | python | apiNameMatch | (str, supported) | return False | Return whether a required api name matches a pattern specified for an
XML <feature> 'api' attribute or <extension> 'supported' attribute.
- str - API name such as 'vulkan' or 'openxr'. May be None, in which
case it never matches (this should not happen).
- supported - comma-separated list of XML API names. May be None, in
which case str always matches (this is the usual case). | Return whether a required api name matches a pattern specified for an
XML <feature> 'api' attribute or <extension> 'supported' attribute. | [
"Return",
"whether",
"a",
"required",
"api",
"name",
"matches",
"a",
"pattern",
"specified",
"for",
"an",
"XML",
"<feature",
">",
"api",
"attribute",
"or",
"<extension",
">",
"supported",
"attribute",
"."
] | def apiNameMatch(str, supported):
"""Return whether a required api name matches a pattern specified for an
XML <feature> 'api' attribute or <extension> 'supported' attribute.
- str - API name such as 'vulkan' or 'openxr'. May be None, in which
case it never matches (this should not happen).
- supported - comma-separated list of XML API names. May be None, in
which case str always matches (this is the usual case)."""
if str is not None:
return supported is None or str in supported.split(',')
# Fallthrough case - either str is None or the test failed
return False | [
"def",
"apiNameMatch",
"(",
"str",
",",
"supported",
")",
":",
"if",
"str",
"is",
"not",
"None",
":",
"return",
"supported",
"is",
"None",
"or",
"str",
"in",
"supported",
".",
"split",
"(",
"','",
")",
"# Fallthrough case - either str is None or the test failed"... | https://github.com/KhronosGroup/Vulkan-Headers/blob/b32da5329b50e3cb96229aaecba9ded032fe29cc/registry/reg.py#L17-L30 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/abins/sdata.py | python | SData.add_dict | (self, data: dict) | Add data in dict form to existing values.
These atoms/orders must already be present; use self.update() to add new data. | Add data in dict form to existing values. | [
"Add",
"data",
"in",
"dict",
"form",
"to",
"existing",
"values",
"."
] | def add_dict(self, data: dict) -> None:
"""Add data in dict form to existing values.
These atoms/orders must already be present; use self.update() to add new data.
"""
for atom_key, atom_data in data.items():
for order, order_data in atom_data['s'].items():
self._data[atom_key]['s'][order] += order_data | [
"def",
"add_dict",
"(",
"self",
",",
"data",
":",
"dict",
")",
"->",
"None",
":",
"for",
"atom_key",
",",
"atom_data",
"in",
"data",
".",
"items",
"(",
")",
":",
"for",
"order",
",",
"order_data",
"in",
"atom_data",
"[",
"'s'",
"]",
".",
"items",
"... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/sdata.py#L83-L91 | ||
hakuna-m/wubiuefi | caec1af0a09c78fd5a345180ada1fe45e0c63493 | src/openpgp/sap/crypto.py | python | verify_ElGamal | (msg, sig_tuple, key_tuple) | return elg.verify(msg, sig_tuple) | Verify an ElGamal signature.
:Parameters:
- `msg`: string of data signature applies to
- `sig_tuple`: tuple of ElGamal signature integers (a, b)
(see `ElGamal signature tuple`_)
- `key_tuple`: tuple of ElGamal key integers (p, g, y)
(see `ElGamal key tuple`_)
:Returns: tuple (integer, None) where integer == 1 or 0, verification
true or false
.. _ElGamal signature tuple:
ElGamal signature tuple:
- `a`: integer ElGamal "a"
- `b`: integer ElGamal "b"
.. _ElGamal key tuple:
ElGamal key tuple:
- `p`: integer ElGamal prime
- `g`: integer ElGamal group
- `y`: integer ElGamal public key | Verify an ElGamal signature. | [
"Verify",
"an",
"ElGamal",
"signature",
"."
] | def verify_ElGamal(msg, sig_tuple, key_tuple):
"""Verify an ElGamal signature.
:Parameters:
- `msg`: string of data signature applies to
- `sig_tuple`: tuple of ElGamal signature integers (a, b)
(see `ElGamal signature tuple`_)
- `key_tuple`: tuple of ElGamal key integers (p, g, y)
(see `ElGamal key tuple`_)
:Returns: tuple (integer, None) where integer == 1 or 0, verification
true or false
.. _ElGamal signature tuple:
ElGamal signature tuple:
- `a`: integer ElGamal "a"
- `b`: integer ElGamal "b"
.. _ElGamal key tuple:
ElGamal key tuple:
- `p`: integer ElGamal prime
- `g`: integer ElGamal group
- `y`: integer ElGamal public key
"""
import Crypto.PublicKey.ElGamal as ELG
elg = ELG.construct(key_tuple) # note change in ordering
return elg.verify(msg, sig_tuple) | [
"def",
"verify_ElGamal",
"(",
"msg",
",",
"sig_tuple",
",",
"key_tuple",
")",
":",
"import",
"Crypto",
".",
"PublicKey",
".",
"ElGamal",
"as",
"ELG",
"elg",
"=",
"ELG",
".",
"construct",
"(",
"key_tuple",
")",
"# note change in ordering",
"return",
"elg",
".... | https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/openpgp/sap/crypto.py#L533-L563 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/ensemble/gradient_boosting.py | python | BinomialDeviance._update_terminal_region | (self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight) | Make a single Newton-Raphson step.
our node estimate is given by:
sum(w * (y - prob)) / sum(w * prob * (1 - prob))
we take advantage that: y - prob = residual | Make a single Newton-Raphson step. | [
"Make",
"a",
"single",
"Newton",
"-",
"Raphson",
"step",
"."
] | def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
"""Make a single Newton-Raphson step.
our node estimate is given by:
sum(w * (y - prob)) / sum(w * prob * (1 - prob))
we take advantage that: y - prob = residual
"""
terminal_region = np.where(terminal_regions == leaf)[0]
residual = residual.take(terminal_region, axis=0)
y = y.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)
numerator = np.sum(sample_weight * residual)
denominator = np.sum(sample_weight * (y - residual) * (1 - y + residual))
if denominator == 0.0:
tree.value[leaf, 0, 0] = 0.0
else:
tree.value[leaf, 0, 0] = numerator / denominator | [
"def",
"_update_terminal_region",
"(",
"self",
",",
"tree",
",",
"terminal_regions",
",",
"leaf",
",",
"X",
",",
"y",
",",
"residual",
",",
"pred",
",",
"sample_weight",
")",
":",
"terminal_region",
"=",
"np",
".",
"where",
"(",
"terminal_regions",
"==",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/ensemble/gradient_boosting.py#L496-L517 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/stats/mstats_basic.py | python | skew | (a, axis=0, bias=True) | return vals | Computes the skewness of a data set.
Parameters
----------
a : ndarray
data
axis : int or None, optional
Axis along which skewness is calculated. Default is 0.
If None, compute over the whole array `a`.
bias : bool, optional
If False, then the calculations are corrected for statistical bias.
Returns
-------
skewness : ndarray
The skewness of values along an axis, returning 0 where all values are
equal.
Notes
-----
For more details about `skew`, see `stats.skew`. | Computes the skewness of a data set. | [
"Computes",
"the",
"skewness",
"of",
"a",
"data",
"set",
"."
] | def skew(a, axis=0, bias=True):
"""
Computes the skewness of a data set.
Parameters
----------
a : ndarray
data
axis : int or None, optional
Axis along which skewness is calculated. Default is 0.
If None, compute over the whole array `a`.
bias : bool, optional
If False, then the calculations are corrected for statistical bias.
Returns
-------
skewness : ndarray
The skewness of values along an axis, returning 0 where all values are
equal.
Notes
-----
For more details about `skew`, see `stats.skew`.
"""
a, axis = _chk_asarray(a,axis)
n = a.count(axis)
m2 = moment(a, 2, axis)
m3 = moment(a, 3, axis)
olderr = np.seterr(all='ignore')
try:
vals = ma.where(m2 == 0, 0, m3 / m2**1.5)
finally:
np.seterr(**olderr)
if not bias:
can_correct = (n > 2) & (m2 > 0)
if can_correct.any():
m2 = np.extract(can_correct, m2)
m3 = np.extract(can_correct, m3)
nval = ma.sqrt((n-1.0)*n)/(n-2.0)*m3/m2**1.5
np.place(vals, can_correct, nval)
return vals | [
"def",
"skew",
"(",
"a",
",",
"axis",
"=",
"0",
",",
"bias",
"=",
"True",
")",
":",
"a",
",",
"axis",
"=",
"_chk_asarray",
"(",
"a",
",",
"axis",
")",
"n",
"=",
"a",
".",
"count",
"(",
"axis",
")",
"m2",
"=",
"moment",
"(",
"a",
",",
"2",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/mstats_basic.py#L2135-L2177 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Window.CanScroll | (*args, **kwargs) | return _core_.Window_CanScroll(*args, **kwargs) | CanScroll(self, int orient) -> bool
Can the window have the scrollbar in this orientation? | CanScroll(self, int orient) -> bool | [
"CanScroll",
"(",
"self",
"int",
"orient",
")",
"-",
">",
"bool"
] | def CanScroll(*args, **kwargs):
"""
CanScroll(self, int orient) -> bool
Can the window have the scrollbar in this orientation?
"""
return _core_.Window_CanScroll(*args, **kwargs) | [
"def",
"CanScroll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_CanScroll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L11203-L11209 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/data/ops/dataset_ops.py | python | SkipDataset.__init__ | (self, input_dataset, count, name=None) | See `Dataset.skip()` for details. | See `Dataset.skip()` for details. | [
"See",
"Dataset",
".",
"skip",
"()",
"for",
"details",
"."
] | def __init__(self, input_dataset, count, name=None):
"""See `Dataset.skip()` for details."""
self._input_dataset = input_dataset
self._count = ops.convert_to_tensor(count, dtype=dtypes.int64, name="count")
self._name = name
variant_tensor = gen_dataset_ops.skip_dataset(
input_dataset._variant_tensor, # pylint: disable=protected-access
count=self._count,
**self._common_args)
super(SkipDataset, self).__init__(input_dataset, variant_tensor) | [
"def",
"__init__",
"(",
"self",
",",
"input_dataset",
",",
"count",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"_input_dataset",
"=",
"input_dataset",
"self",
".",
"_count",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"count",
",",
"dtype",
"=",
"dt... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/data/ops/dataset_ops.py#L4850-L4859 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/adidas_utils/solvers/nonsymmetric/ate_regmatch.py | python | Solver.__init__ | (self, p=1., lrs=(1e-2,), optimism=True, discount=False,
rnd_init=False, seed=None, **kwargs) | Ctor. | Ctor. | [
"Ctor",
"."
] | def __init__(self, p=1., lrs=(1e-2,), optimism=True, discount=False,
rnd_init=False, seed=None, **kwargs):
"""Ctor."""
del kwargs
if (p < 0.) or (p > 1.):
raise ValueError('p must be in [0, 1]')
self.num_players = None
self.p = p
self.rnd_init = rnd_init
self.lrs = lrs
self.optimism = optimism
self.discount = discount
self.has_aux = True
self.aux_errors = []
self.seed = seed
self.random = np.random.RandomState(seed) | [
"def",
"__init__",
"(",
"self",
",",
"p",
"=",
"1.",
",",
"lrs",
"=",
"(",
"1e-2",
",",
")",
",",
"optimism",
"=",
"True",
",",
"discount",
"=",
"False",
",",
"rnd_init",
"=",
"False",
",",
"seed",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":"... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/solvers/nonsymmetric/ate_regmatch.py#L29-L45 | ||
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/ansic/clex.py | python | t_preprocessor | (t) | r'\#(.)*?\n | r'\#(.)*?\n | [
"r",
"\\",
"#",
"(",
".",
")",
"*",
"?",
"\\",
"n"
] | def t_preprocessor(t):
r'\#(.)*?\n'
t.lexer.lineno += 1 | [
"def",
"t_preprocessor",
"(",
"t",
")",
":",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"1"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/clex.py#L149-L151 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMS_ECC_POINT.GetUnionSelector | (self) | return TPM_ALG_ID.ECC | TpmUnion method | TpmUnion method | [
"TpmUnion",
"method"
] | def GetUnionSelector(self): # TPM_ALG_ID
""" TpmUnion method """
return TPM_ALG_ID.ECC | [
"def",
"GetUnionSelector",
"(",
"self",
")",
":",
"# TPM_ALG_ID",
"return",
"TPM_ALG_ID",
".",
"ECC"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L7256-L7258 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/MSVSSettings.py | python | _ValidateSettings | (validators, settings, stderr) | Validates that the settings are valid for MSBuild or MSVS.
We currently only validate the names of the settings, not their values.
Args:
validators: A dictionary of tools and their validators.
settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages. | Validates that the settings are valid for MSBuild or MSVS. | [
"Validates",
"that",
"the",
"settings",
"are",
"valid",
"for",
"MSBuild",
"or",
"MSVS",
"."
] | def _ValidateSettings(validators, settings, stderr):
"""Validates that the settings are valid for MSBuild or MSVS.
We currently only validate the names of the settings, not their values.
Args:
validators: A dictionary of tools and their validators.
settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages.
"""
for tool_name in settings:
if tool_name in validators:
tool_validators = validators[tool_name]
for setting, value in settings[tool_name].items():
if setting in tool_validators:
try:
tool_validators[setting](value)
except ValueError as e:
print('Warning: for %s/%s, %s' %
(tool_name, setting, e), file=stderr)
else:
_ValidateExclusionSetting(setting,
tool_validators,
('Warning: unrecognized setting %s/%s' %
(tool_name, setting)),
stderr)
else:
print('Warning: unrecognized tool %s' % (tool_name), file=stderr) | [
"def",
"_ValidateSettings",
"(",
"validators",
",",
"settings",
",",
"stderr",
")",
":",
"for",
"tool_name",
"in",
"settings",
":",
"if",
"tool_name",
"in",
"validators",
":",
"tool_validators",
"=",
"validators",
"[",
"tool_name",
"]",
"for",
"setting",
",",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/MSVSSettings.py#L506-L535 | ||
synfig/synfig | a5ec91db5b751dc12e4400ccfb5c063fd6d2d928 | synfig-studio/plugins/lottie-exporter/common/Param.py | python | Param.getparent | (self) | return self.parent | Returns the parent of this parameter | Returns the parent of this parameter | [
"Returns",
"the",
"parent",
"of",
"this",
"parameter"
] | def getparent(self):
"""
Returns the parent of this parameter
"""
return self.parent | [
"def",
"getparent",
"(",
"self",
")",
":",
"return",
"self",
".",
"parent"
] | https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/Param.py#L135-L139 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/magnetic-force-between-two-balls.py | python | Solution.maxDistance | (self, position, m) | return right | :type position: List[int]
:type m: int
:rtype: int | :type position: List[int]
:type m: int
:rtype: int | [
":",
"type",
"position",
":",
"List",
"[",
"int",
"]",
":",
"type",
"m",
":",
"int",
":",
"rtype",
":",
"int"
] | def maxDistance(self, position, m):
"""
:type position: List[int]
:type m: int
:rtype: int
"""
def check(position, m, x):
count, prev = 1, position[0]
for i in xrange(1, len(position)):
if position[i]-prev >= x:
count += 1
prev = position[i]
return count >= m
position.sort()
left, right = 1, position[-1]-position[0]
while left <= right:
mid = left + (right-left)//2
if not check(position, m, mid):
right = mid-1
else:
left = mid+1
return right | [
"def",
"maxDistance",
"(",
"self",
",",
"position",
",",
"m",
")",
":",
"def",
"check",
"(",
"position",
",",
"m",
",",
"x",
")",
":",
"count",
",",
"prev",
"=",
"1",
",",
"position",
"[",
"0",
"]",
"for",
"i",
"in",
"xrange",
"(",
"1",
",",
... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/magnetic-force-between-two-balls.py#L5-L27 | |
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | cpplint.py | python | Error | (filename, linenum, category, confidence, message) | Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message. | Logs the fact we've found a lint error. | [
"Logs",
"the",
"fact",
"we",
"ve",
"found",
"a",
"lint",
"error",
"."
] | def Error(filename, linenum, category, confidence, message):
"""Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message.
"""
# There are two ways we might decide not to print an error message:
# the verbosity level isn't high enough, or the filters filter it out.
if _ShouldPrintError(category, confidence):
_cpplint_state.IncrementErrorCount(category)
if _cpplint_state.output_format == 'vs7':
sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
else:
sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence)) | [
"def",
"Error",
"(",
"filename",
",",
"linenum",
",",
"category",
",",
"confidence",
",",
"message",
")",
":",
"# There are two ways we might decide not to print an error message:",
"# the verbosity level isn't high enough, or the filters filter it out.",
"if",
"_ShouldPrintError",... | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/cpplint.py#L734-L761 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/gdal-utils/osgeo_utils/gdal2tiles.py | python | GlobalGeodetic.TileLatLonBounds | (self, tx, ty, zoom) | return (b[1], b[0], b[3], b[2]) | Returns bounds of the given tile in the SWNE form | Returns bounds of the given tile in the SWNE form | [
"Returns",
"bounds",
"of",
"the",
"given",
"tile",
"in",
"the",
"SWNE",
"form"
] | def TileLatLonBounds(self, tx, ty, zoom):
"Returns bounds of the given tile in the SWNE form"
b = self.TileBounds(tx, ty, zoom)
return (b[1], b[0], b[3], b[2]) | [
"def",
"TileLatLonBounds",
"(",
"self",
",",
"tx",
",",
"ty",
",",
"zoom",
")",
":",
"b",
"=",
"self",
".",
"TileBounds",
"(",
"tx",
",",
"ty",
",",
"zoom",
")",
"return",
"(",
"b",
"[",
"1",
"]",
",",
"b",
"[",
"0",
"]",
",",
"b",
"[",
"3"... | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/gdal-utils/osgeo_utils/gdal2tiles.py#L551-L554 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/stats/mstats_extras.py | python | trimmed_mean_ci | (data, limits=(0.2,0.2), inclusive=(True,True),
alpha=0.05, axis=None) | return np.array((tmean - tppf*tstde, tmean+tppf*tstde)) | Selected confidence interval of the trimmed mean along the given axis.
Parameters
----------
data : array_like
Input data.
limits : {None, tuple}, optional
None or a two item tuple.
Tuple of the percentages to cut on each side of the array, with respect
to the number of unmasked data, as floats between 0. and 1. If ``n``
is the number of unmasked data before trimming, then
(``n * limits[0]``)th smallest data and (``n * limits[1]``)th
largest data are masked. The total number of unmasked data after
trimming is ``n * (1. - sum(limits))``.
The value of one limit can be set to None to indicate an open interval.
Defaults to (0.2, 0.2).
inclusive : (2,) tuple of boolean, optional
If relative==False, tuple indicating whether values exactly equal to
the absolute limits are allowed.
If relative==True, tuple indicating whether the number of data being
masked on each side should be rounded (True) or truncated (False).
Defaults to (True, True).
alpha : float, optional
Confidence level of the intervals.
Defaults to 0.05.
axis : int, optional
Axis along which to cut. If None, uses a flattened version of `data`.
Defaults to None.
Returns
-------
trimmed_mean_ci : (2,) ndarray
The lower and upper confidence intervals of the trimmed data. | Selected confidence interval of the trimmed mean along the given axis. | [
"Selected",
"confidence",
"interval",
"of",
"the",
"trimmed",
"mean",
"along",
"the",
"given",
"axis",
"."
] | def trimmed_mean_ci(data, limits=(0.2,0.2), inclusive=(True,True),
alpha=0.05, axis=None):
"""
Selected confidence interval of the trimmed mean along the given axis.
Parameters
----------
data : array_like
Input data.
limits : {None, tuple}, optional
None or a two item tuple.
Tuple of the percentages to cut on each side of the array, with respect
to the number of unmasked data, as floats between 0. and 1. If ``n``
is the number of unmasked data before trimming, then
(``n * limits[0]``)th smallest data and (``n * limits[1]``)th
largest data are masked. The total number of unmasked data after
trimming is ``n * (1. - sum(limits))``.
The value of one limit can be set to None to indicate an open interval.
Defaults to (0.2, 0.2).
inclusive : (2,) tuple of boolean, optional
If relative==False, tuple indicating whether values exactly equal to
the absolute limits are allowed.
If relative==True, tuple indicating whether the number of data being
masked on each side should be rounded (True) or truncated (False).
Defaults to (True, True).
alpha : float, optional
Confidence level of the intervals.
Defaults to 0.05.
axis : int, optional
Axis along which to cut. If None, uses a flattened version of `data`.
Defaults to None.
Returns
-------
trimmed_mean_ci : (2,) ndarray
The lower and upper confidence intervals of the trimmed data.
"""
data = ma.array(data, copy=False)
trimmed = mstats.trimr(data, limits=limits, inclusive=inclusive, axis=axis)
tmean = trimmed.mean(axis)
tstde = mstats.trimmed_stde(data,limits=limits,inclusive=inclusive,axis=axis)
df = trimmed.count(axis) - 1
tppf = t.ppf(1-alpha/2.,df)
return np.array((tmean - tppf*tstde, tmean+tppf*tstde)) | [
"def",
"trimmed_mean_ci",
"(",
"data",
",",
"limits",
"=",
"(",
"0.2",
",",
"0.2",
")",
",",
"inclusive",
"=",
"(",
"True",
",",
"True",
")",
",",
"alpha",
"=",
"0.05",
",",
"axis",
"=",
"None",
")",
":",
"data",
"=",
"ma",
".",
"array",
"(",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/mstats_extras.py#L193-L241 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/aui.py | python | AuiDockArt.DrawSash | (*args, **kwargs) | return _aui.AuiDockArt_DrawSash(*args, **kwargs) | DrawSash(self, DC dc, Window window, int orientation, Rect rect) | DrawSash(self, DC dc, Window window, int orientation, Rect rect) | [
"DrawSash",
"(",
"self",
"DC",
"dc",
"Window",
"window",
"int",
"orientation",
"Rect",
"rect",
")"
] | def DrawSash(*args, **kwargs):
"""DrawSash(self, DC dc, Window window, int orientation, Rect rect)"""
return _aui.AuiDockArt_DrawSash(*args, **kwargs) | [
"def",
"DrawSash",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiDockArt_DrawSash",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L998-L1000 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/iobench/iobench.py | python | write_small_chunks | (f, source) | write 20 units at a time | write 20 units at a time | [
"write",
"20",
"units",
"at",
"a",
"time"
] | def write_small_chunks(f, source):
""" write 20 units at a time """
for i in xrange(0, len(source), 20):
f.write(source[i:i+20]) | [
"def",
"write_small_chunks",
"(",
"f",
",",
"source",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"source",
")",
",",
"20",
")",
":",
"f",
".",
"write",
"(",
"source",
"[",
"i",
":",
"i",
"+",
"20",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/iobench/iobench.py#L145-L148 | ||
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | demo/BERT/builder_utils.py | python | onnx_to_trt_name | (onnx_name) | return parsed | Converting variables in the onnx checkpoint to names corresponding to the naming convention used in the TF version, expected by the builder | Converting variables in the onnx checkpoint to names corresponding to the naming convention used in the TF version, expected by the builder | [
"Converting",
"variables",
"in",
"the",
"onnx",
"checkpoint",
"to",
"names",
"corresponding",
"to",
"the",
"naming",
"convention",
"used",
"in",
"the",
"TF",
"version",
"expected",
"by",
"the",
"builder"
] | def onnx_to_trt_name(onnx_name):
"""
Converting variables in the onnx checkpoint to names corresponding to the naming convention used in the TF version, expected by the builder
"""
qkv_strings = {'key', 'value', 'query', 'query_key_value'}
onnx_name = onnx_name.lower()
toks = [t.strip('_') for t in onnx_name.split('.')]
if toks[0] == 'bert': #embeddings or encoder
if toks[1] == 'encoder': #transformer
# Token conversions for sparse checkpoints
if toks[-2] == 'dense_act':
toks[-2] = 'dense'
elif toks[-3] == 'dense_act':
if toks[-2] == 'input_quantizer':
toks[-2] = 'input'
elif toks[-2] == 'weight_quantizer':
toks[-2] = 'kernel'
toks[-3] = 'dense'
elif toks[-2].startswith('matmul'):
toks[-2] = {
'matmul_q_quantizer': 'qv_a_input_quantizer',
'matmul_k_quantizer': 'qv_b_input_quantizer',
'matmul_v_quantizer': 'av_b_input_quantizer',
'matmul_a_quantizer': 'av_a_input_quantizer',
}[toks[-2].replace('input_', '')]
# Token conversions for all checkpoints
if toks[-2] == 'layernorm': #bias->beta, weight->gamma
toks[-1] = 'beta' if toks[-1] == 'bias' else 'gamma'
elif (toks[-2] == 'dense' or toks[-2] in qkv_strings) and toks[-1] == 'weight':
toks[-1] = 'kernel'
elif (toks[-3] == 'dense' or toks[-3] in qkv_strings) and toks[-1] == 'amax':
if toks[-2] == 'weight_quantizer':
toks[-2] = 'kernel'
elif toks[-2] == 'input_quantizer':
toks[-2] = 'input'
if 'final_input_quantizer' not in toks[2]:
ind = toks.index('layers')+1 if 'layers' in toks else 3
toks = toks[ind:]
toks[0] = 'l{}'.format(int(toks[0]))
else:
if toks[-2] == 'layernorm': #bias->beta, weight->gamma
toks[-1] = 'beta' if toks[-1] == 'bias' else 'gamma'
else: #embeddings: drop "_weight" suffix
if toks[-1] == 'amax':
toks[-2] = 'amax'
toks = toks[:-1]
elif 'qa' in onnx_name:
name = 'cls_squad_output_bias' if toks[-1] == 'bias' else 'cls_squad_output_weights'
return name
else:
print("Encountered unknown case:", onnx_name)
assert(False)
parsed = '_'.join(toks)
return parsed | [
"def",
"onnx_to_trt_name",
"(",
"onnx_name",
")",
":",
"qkv_strings",
"=",
"{",
"'key'",
",",
"'value'",
",",
"'query'",
",",
"'query_key_value'",
"}",
"onnx_name",
"=",
"onnx_name",
".",
"lower",
"(",
")",
"toks",
"=",
"[",
"t",
".",
"strip",
"(",
"'_'"... | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/demo/BERT/builder_utils.py#L136-L191 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | EnumProperty.GetItemCount | (*args, **kwargs) | return _propgrid.EnumProperty_GetItemCount(*args, **kwargs) | GetItemCount(self) -> size_t | GetItemCount(self) -> size_t | [
"GetItemCount",
"(",
"self",
")",
"-",
">",
"size_t"
] | def GetItemCount(*args, **kwargs):
"""GetItemCount(self) -> size_t"""
return _propgrid.EnumProperty_GetItemCount(*args, **kwargs) | [
"def",
"GetItemCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"EnumProperty_GetItemCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L3001-L3003 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/mfg/algorithms/nash_conv.py | python | NashConv.nash_conv | (self) | return sum([
self._br_value.eval_state(state) - self._pi_value.eval_state(state)
for state in self._root_states
]) | Returns the nash conv.
Returns:
A float representing the nash conv for the policy. | Returns the nash conv. | [
"Returns",
"the",
"nash",
"conv",
"."
] | def nash_conv(self):
"""Returns the nash conv.
Returns:
A float representing the nash conv for the policy.
"""
return sum([
self._br_value.eval_state(state) - self._pi_value.eval_state(state)
for state in self._root_states
]) | [
"def",
"nash_conv",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"[",
"self",
".",
"_br_value",
".",
"eval_state",
"(",
"state",
")",
"-",
"self",
".",
"_pi_value",
".",
"eval_state",
"(",
"state",
")",
"for",
"state",
"in",
"self",
".",
"_root_states"... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/mfg/algorithms/nash_conv.py#L61-L70 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FlatMenuButton.SetSize | (self, input1, input2=None) | Sets the size for :class:`FlatMenuButton`.
:param `input1`: if it is an instance of :class:`Size`, it represents the :class:`FlatMenuButton`
size and the `input2` parameter is not used. Otherwise it is an integer representing
the button width;
:param `input2`: if not ``None``, it is an integer representing the button height. | Sets the size for :class:`FlatMenuButton`. | [
"Sets",
"the",
"size",
"for",
":",
"class",
":",
"FlatMenuButton",
"."
] | def SetSize(self, input1, input2=None):
"""
Sets the size for :class:`FlatMenuButton`.
:param `input1`: if it is an instance of :class:`Size`, it represents the :class:`FlatMenuButton`
size and the `input2` parameter is not used. Otherwise it is an integer representing
the button width;
:param `input2`: if not ``None``, it is an integer representing the button height.
"""
if type(input) == type(1):
self._size = wx.Size(input1, input2)
else:
self._size = input1 | [
"def",
"SetSize",
"(",
"self",
",",
"input1",
",",
"input2",
"=",
"None",
")",
":",
"if",
"type",
"(",
"input",
")",
"==",
"type",
"(",
"1",
")",
":",
"self",
".",
"_size",
"=",
"wx",
".",
"Size",
"(",
"input1",
",",
"input2",
")",
"else",
":",... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L4098-L4111 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/metrics_impl.py | python | recall_at_top_k | (labels,
predictions_idx,
k=None,
class_id=None,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None) | Computes recall@k of top-k predictions with respect to sparse labels.
Differs from `recall_at_k` in that predictions must be in the form of top `k`
class indices, whereas `recall_at_k` expects logits. Refer to `recall_at_k`
for more details.
Args:
labels: `int64` `Tensor` or `SparseTensor` with shape
[D1, ... DN, num_labels] or [D1, ... DN], where the latter implies
num_labels=1. N >= 1 and num_labels is the number of target classes for
the associated prediction. Commonly, N=1 and `labels` has shape
[batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values
should be in range [0, num_classes), where num_classes is the last
dimension of `predictions`. Values outside this range always count
towards `false_negative_at_<k>`.
predictions_idx: Integer `Tensor` with shape [D1, ... DN, k] where N >= 1.
Commonly, N=1 and predictions has shape [batch size, k]. The final
dimension contains the top `k` predicted class indices. [D1, ... DN] must
match `labels`.
k: Integer, k for @k metric. Only used for the default op name.
class_id: Integer class ID for which we want binary metrics. This should be
in range [0, num_classes), where num_classes is the last dimension of
`predictions`. If class_id is outside this range, the method returns NAN.
weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of
`labels`. If the latter, it must be broadcastable to `labels` (i.e., all
dimensions must be either `1`, or the same as the corresponding `labels`
dimension).
metrics_collections: An optional list of collections that values should
be added to.
updates_collections: An optional list of collections that updates should
be added to.
name: Name of new update operation, and namespace for other dependent ops.
Returns:
recall: Scalar `float64` `Tensor` with the value of `true_positives` divided
by the sum of `true_positives` and `false_negatives`.
update_op: `Operation` that increments `true_positives` and
`false_negatives` variables appropriately, and whose value matches
`recall`.
Raises:
ValueError: If `weights` is not `None` and its shape doesn't match
`predictions`, or if either `metrics_collections` or `updates_collections`
are not a list or tuple. | Computes recall@k of top-k predictions with respect to sparse labels. | [
"Computes",
"recall@k",
"of",
"top",
"-",
"k",
"predictions",
"with",
"respect",
"to",
"sparse",
"labels",
"."
] | def recall_at_top_k(labels,
predictions_idx,
k=None,
class_id=None,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None):
"""Computes recall@k of top-k predictions with respect to sparse labels.
Differs from `recall_at_k` in that predictions must be in the form of top `k`
class indices, whereas `recall_at_k` expects logits. Refer to `recall_at_k`
for more details.
Args:
labels: `int64` `Tensor` or `SparseTensor` with shape
[D1, ... DN, num_labels] or [D1, ... DN], where the latter implies
num_labels=1. N >= 1 and num_labels is the number of target classes for
the associated prediction. Commonly, N=1 and `labels` has shape
[batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values
should be in range [0, num_classes), where num_classes is the last
dimension of `predictions`. Values outside this range always count
towards `false_negative_at_<k>`.
predictions_idx: Integer `Tensor` with shape [D1, ... DN, k] where N >= 1.
Commonly, N=1 and predictions has shape [batch size, k]. The final
dimension contains the top `k` predicted class indices. [D1, ... DN] must
match `labels`.
k: Integer, k for @k metric. Only used for the default op name.
class_id: Integer class ID for which we want binary metrics. This should be
in range [0, num_classes), where num_classes is the last dimension of
`predictions`. If class_id is outside this range, the method returns NAN.
weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of
`labels`. If the latter, it must be broadcastable to `labels` (i.e., all
dimensions must be either `1`, or the same as the corresponding `labels`
dimension).
metrics_collections: An optional list of collections that values should
be added to.
updates_collections: An optional list of collections that updates should
be added to.
name: Name of new update operation, and namespace for other dependent ops.
Returns:
recall: Scalar `float64` `Tensor` with the value of `true_positives` divided
by the sum of `true_positives` and `false_negatives`.
update_op: `Operation` that increments `true_positives` and
`false_negatives` variables appropriately, and whose value matches
`recall`.
Raises:
ValueError: If `weights` is not `None` and its shape doesn't match
`predictions`, or if either `metrics_collections` or `updates_collections`
are not a list or tuple.
"""
with ops.name_scope(name, _at_k_name('recall', k, class_id=class_id),
(predictions_idx, labels, weights)) as scope:
labels = _maybe_expand_labels(labels, predictions_idx)
top_k_idx = math_ops.cast(predictions_idx, dtypes.int64)
tp, tp_update = _streaming_sparse_true_positive_at_k(
predictions_idx=top_k_idx,
labels=labels,
k=k,
class_id=class_id,
weights=weights)
fn, fn_update = _streaming_sparse_false_negative_at_k(
predictions_idx=top_k_idx,
labels=labels,
k=k,
class_id=class_id,
weights=weights)
def compute_recall(_, tp, fn):
return math_ops.div(tp, math_ops.add(tp, fn), name=scope)
metric = _aggregate_across_replicas(
metrics_collections, compute_recall, tp, fn)
update = math_ops.div(
tp_update, math_ops.add(tp_update, fn_update), name='update')
if updates_collections:
ops.add_to_collections(updates_collections, update)
return metric, update | [
"def",
"recall_at_top_k",
"(",
"labels",
",",
"predictions_idx",
",",
"k",
"=",
"None",
",",
"class_id",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"metrics_collections",
"=",
"None",
",",
"updates_collections",
"=",
"None",
",",
"name",
"=",
"None",
"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/metrics_impl.py#L2568-L2648 | ||
CGRU/cgru | 1881a4128530e3d31ac6c25314c18314fc50c2c7 | lib/python/filelock.py | python | FileLock.__enter__ | (self) | return self | Activated when used in the with statement.
Should automatically acquire a lock to be used in the with block. | Activated when used in the with statement.
Should automatically acquire a lock to be used in the with block. | [
"Activated",
"when",
"used",
"in",
"the",
"with",
"statement",
".",
"Should",
"automatically",
"acquire",
"a",
"lock",
"to",
"be",
"used",
"in",
"the",
"with",
"block",
"."
] | def __enter__(self):
"""Activated when used in the with statement.
Should automatically acquire a lock to be used in the with block.
"""
if not self.is_locked:
self.acquire()
return self | [
"def",
"__enter__",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_locked",
":",
"self",
".",
"acquire",
"(",
")",
"return",
"self"
] | https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/lib/python/filelock.py#L90-L96 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/polynomial/legendre.py | python | leggauss | (deg) | return x, w | Gauss-Legendre quadrature.
Computes the sample points and weights for Gauss-Legendre quadrature.
These sample points and weights will correctly integrate polynomials of
degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with
the weight function :math:`f(x) = 1`.
Parameters
----------
deg : int
Number of sample points and weights. It must be >= 1.
Returns
-------
x : ndarray
1-D ndarray containing the sample points.
y : ndarray
1-D ndarray containing the weights.
Notes
-----
.. versionadded:: 1.7.0
The results have only been tested up to degree 100, higher degrees may
be problematic. The weights are determined by using the fact that
.. math:: w_k = c / (L'_n(x_k) * L_{n-1}(x_k))
where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
is the k'th root of :math:`L_n`, and then scaling the results to get
the right value when integrating 1. | Gauss-Legendre quadrature. | [
"Gauss",
"-",
"Legendre",
"quadrature",
"."
] | def leggauss(deg):
"""
Gauss-Legendre quadrature.
Computes the sample points and weights for Gauss-Legendre quadrature.
These sample points and weights will correctly integrate polynomials of
degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with
the weight function :math:`f(x) = 1`.
Parameters
----------
deg : int
Number of sample points and weights. It must be >= 1.
Returns
-------
x : ndarray
1-D ndarray containing the sample points.
y : ndarray
1-D ndarray containing the weights.
Notes
-----
.. versionadded:: 1.7.0
The results have only been tested up to degree 100, higher degrees may
be problematic. The weights are determined by using the fact that
.. math:: w_k = c / (L'_n(x_k) * L_{n-1}(x_k))
where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
is the k'th root of :math:`L_n`, and then scaling the results to get
the right value when integrating 1.
"""
ideg = int(deg)
if ideg != deg or ideg < 1:
raise ValueError("deg must be a non-negative integer")
# first approximation of roots. We use the fact that the companion
# matrix is symmetric in this case in order to obtain better zeros.
c = np.array([0]*deg + [1])
m = legcompanion(c)
x = la.eigvalsh(m)
# improve roots by one application of Newton
dy = legval(x, c)
df = legval(x, legder(c))
x -= dy/df
# compute the weights. We scale the factor to avoid possible numerical
# overflow.
fm = legval(x, c[1:])
fm /= np.abs(fm).max()
df /= np.abs(df).max()
w = 1/(fm * df)
# for Legendre we can also symmetrize
w = (w + w[::-1])/2
x = (x - x[::-1])/2
# scale w to get the right value
w *= 2. / w.sum()
return x, w | [
"def",
"leggauss",
"(",
"deg",
")",
":",
"ideg",
"=",
"int",
"(",
"deg",
")",
"if",
"ideg",
"!=",
"deg",
"or",
"ideg",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"deg must be a non-negative integer\"",
")",
"# first approximation of roots. We use the fact that t... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/legendre.py#L1705-L1770 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/notebook/callback.py | python | PandasLogger.elapsed | (self) | return datetime.datetime.now() - self.start_time | Calcaulate the elapsed time from training starting. | Calcaulate the elapsed time from training starting. | [
"Calcaulate",
"the",
"elapsed",
"time",
"from",
"training",
"starting",
"."
] | def elapsed(self):
"""Calcaulate the elapsed time from training starting.
"""
return datetime.datetime.now() - self.start_time | [
"def",
"elapsed",
"(",
"self",
")",
":",
"return",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"start_time"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/notebook/callback.py#L125-L128 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | TimeSpan.__lt__ | (*args, **kwargs) | return _misc_.TimeSpan___lt__(*args, **kwargs) | __lt__(self, TimeSpan other) -> bool | __lt__(self, TimeSpan other) -> bool | [
"__lt__",
"(",
"self",
"TimeSpan",
"other",
")",
"-",
">",
"bool"
] | def __lt__(*args, **kwargs):
"""__lt__(self, TimeSpan other) -> bool"""
return _misc_.TimeSpan___lt__(*args, **kwargs) | [
"def",
"__lt__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"TimeSpan___lt__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L4466-L4468 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | OutputStream.close | (*args, **kwargs) | return _core_.OutputStream_close(*args, **kwargs) | close(self) | close(self) | [
"close",
"(",
"self",
")"
] | def close(*args, **kwargs):
"""close(self)"""
return _core_.OutputStream_close(*args, **kwargs) | [
"def",
"close",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"OutputStream_close",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L2235-L2237 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/layers/advanced_activations.py | python | _large_compatible_negative | (tensor_type) | return -1e9 | Large negative number as Tensor.
This function is necessary because the standard value for epsilon
in this module (-1e9) cannot be represented using tf.float16
Args:
tensor_type: a dtype to determine the type.
Returns:
a large negative number. | Large negative number as Tensor. | [
"Large",
"negative",
"number",
"as",
"Tensor",
"."
] | def _large_compatible_negative(tensor_type):
"""Large negative number as Tensor.
This function is necessary because the standard value for epsilon
in this module (-1e9) cannot be represented using tf.float16
Args:
tensor_type: a dtype to determine the type.
Returns:
a large negative number.
"""
if tensor_type == dtypes.float16:
return dtypes.float16.min
return -1e9 | [
"def",
"_large_compatible_negative",
"(",
"tensor_type",
")",
":",
"if",
"tensor_type",
"==",
"dtypes",
".",
"float16",
":",
"return",
"dtypes",
".",
"float16",
".",
"min",
"return",
"-",
"1e9"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/layers/advanced_activations.py#L277-L291 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextBuffer.BeginSymbolBullet | (*args, **kwargs) | return _richtext.RichTextBuffer_BeginSymbolBullet(*args, **kwargs) | BeginSymbolBullet(self, String symbol, int leftIndent, int leftSubIndent, int bulletStyle=TEXT_ATTR_BULLET_STYLE_SYMBOL) -> bool | BeginSymbolBullet(self, String symbol, int leftIndent, int leftSubIndent, int bulletStyle=TEXT_ATTR_BULLET_STYLE_SYMBOL) -> bool | [
"BeginSymbolBullet",
"(",
"self",
"String",
"symbol",
"int",
"leftIndent",
"int",
"leftSubIndent",
"int",
"bulletStyle",
"=",
"TEXT_ATTR_BULLET_STYLE_SYMBOL",
")",
"-",
">",
"bool"
] | def BeginSymbolBullet(*args, **kwargs):
"""BeginSymbolBullet(self, String symbol, int leftIndent, int leftSubIndent, int bulletStyle=TEXT_ATTR_BULLET_STYLE_SYMBOL) -> bool"""
return _richtext.RichTextBuffer_BeginSymbolBullet(*args, **kwargs) | [
"def",
"BeginSymbolBullet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_BeginSymbolBullet",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2432-L2434 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/resource_variable_ops.py | python | BaseResourceVariable.assign_sub | (self, delta, use_locking=None, name=None, read_value=True) | return assign_sub_op | Subtracts a value from this variable.
Args:
delta: A `Tensor`. The value to subtract from this variable.
use_locking: If `True`, use locking during the operation.
name: The name to use for the operation.
read_value: A `bool`. Whether to read and return the new value of the
variable or not.
Returns:
If `read_value` is `True`, this method will return the new value of the
variable after the assignment has completed. Otherwise, when in graph mode
it will return the `Operation` that does the assignment, and when in eager
mode it will return `None`. | Subtracts a value from this variable. | [
"Subtracts",
"a",
"value",
"from",
"this",
"variable",
"."
] | def assign_sub(self, delta, use_locking=None, name=None, read_value=True):
"""Subtracts a value from this variable.
Args:
delta: A `Tensor`. The value to subtract from this variable.
use_locking: If `True`, use locking during the operation.
name: The name to use for the operation.
read_value: A `bool`. Whether to read and return the new value of the
variable or not.
Returns:
If `read_value` is `True`, this method will return the new value of the
variable after the assignment has completed. Otherwise, when in graph mode
it will return the `Operation` that does the assignment, and when in eager
mode it will return `None`.
"""
# TODO(apassos): this here and below is not atomic. Consider making it
# atomic if there's a way to do so without a performance cost for those who
# don't need it.
with _handle_graph(self.handle), self._assign_dependencies():
assign_sub_op = gen_resource_variable_ops.assign_sub_variable_op(
self.handle,
ops.convert_to_tensor(delta, dtype=self.dtype),
name=name)
if read_value:
return self._lazy_read(assign_sub_op)
return assign_sub_op | [
"def",
"assign_sub",
"(",
"self",
",",
"delta",
",",
"use_locking",
"=",
"None",
",",
"name",
"=",
"None",
",",
"read_value",
"=",
"True",
")",
":",
"# TODO(apassos): this here and below is not atomic. Consider making it",
"# atomic if there's a way to do so without a perfo... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/resource_variable_ops.py#L842-L868 | |
greenheartgames/greenworks | 3ea4ab490b56676de3f0a237c74bcfdb17323e60 | deps/cpplint/cpplint.py | python | ProcessGlobalSuppresions | (lines) | Updates the list of global error suppressions.
Parses any lint directives in the file that have global effect.
Args:
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline. | Updates the list of global error suppressions. | [
"Updates",
"the",
"list",
"of",
"global",
"error",
"suppressions",
"."
] | def ProcessGlobalSuppresions(lines):
"""Updates the list of global error suppressions.
Parses any lint directives in the file that have global effect.
Args:
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
"""
for line in lines:
if _SEARCH_C_FILE.search(line):
for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
_global_error_suppressions[category] = True
if _SEARCH_KERNEL_FILE.search(line):
for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
_global_error_suppressions[category] = True | [
"def",
"ProcessGlobalSuppresions",
"(",
"lines",
")",
":",
"for",
"line",
"in",
"lines",
":",
"if",
"_SEARCH_C_FILE",
".",
"search",
"(",
"line",
")",
":",
"for",
"category",
"in",
"_DEFAULT_C_SUPPRESSED_CATEGORIES",
":",
"_global_error_suppressions",
"[",
"catego... | https://github.com/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L603-L618 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/backend.py | python | Backend._is_connected_to_serialport | (self) | return self.connected_to_tool and isinstance(self.transport, str) | Check if a connection to a Serial port is active | Check if a connection to a Serial port is active | [
"Check",
"if",
"a",
"connection",
"to",
"a",
"Serial",
"port",
"is",
"active"
] | def _is_connected_to_serialport(self):
"""
Check if a connection to a Serial port is active
"""
# For Serial port communication transport is only set to a string with the name of the serial port
# to use (e.g. 'COM1').
return self.connected_to_tool and isinstance(self.transport, str) | [
"def",
"_is_connected_to_serialport",
"(",
"self",
")",
":",
"# For Serial port communication transport is only set to a string with the name of the serial port",
"# to use (e.g. 'COM1').",
"return",
"self",
".",
"connected_to_tool",
"and",
"isinstance",
"(",
"self",
".",
"transpor... | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/backend.py#L643-L649 | |
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/win_tool.py | python | WinTool.ExecLinkWrapper | (self, arch, *args) | Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe. | Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe. | [
"Filter",
"diagnostic",
"output",
"from",
"link",
"that",
"looks",
"like",
":",
"Creating",
"library",
"ui",
".",
"dll",
".",
"lib",
"and",
"object",
"ui",
".",
"dll",
".",
"exp",
"This",
"happens",
"when",
"there",
"are",
"exports",
"from",
"the",
"dll"... | def ExecLinkWrapper(self, arch, *args):
"""Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe.
"""
with LinkLock():
env = self._GetEnv(arch)
popen = subprocess.Popen(args, shell=True, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = popen.communicate()
for line in out.splitlines():
if not line.startswith(' Creating library '):
print line
return popen.returncode | [
"def",
"ExecLinkWrapper",
"(",
"self",
",",
"arch",
",",
"*",
"args",
")",
":",
"with",
"LinkLock",
"(",
")",
":",
"env",
"=",
"self",
".",
"_GetEnv",
"(",
"arch",
")",
"popen",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"shell",
"=",
"True... | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/win_tool.py#L85-L98 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/control/robotinterface.py | python | RobotInterfaceBase.robotToPartConfig | (self,
robotConfig: Vector,
part: str,
joint_idx: Optional[int] = None
) | return [robotConfig[i] for i in pindices] | Retrieves a part's configuration from a robot configuration | Retrieves a part's configuration from a robot configuration | [
"Retrieves",
"a",
"part",
"s",
"configuration",
"from",
"a",
"robot",
"configuration"
] | def robotToPartConfig(self,
robotConfig: Vector,
part: str,
joint_idx: Optional[int] = None
) -> Vector:
"""Retrieves a part's configuration from a robot configuration"""
pindices = self.indices(part,joint_idx)
return [robotConfig[i] for i in pindices] | [
"def",
"robotToPartConfig",
"(",
"self",
",",
"robotConfig",
":",
"Vector",
",",
"part",
":",
"str",
",",
"joint_idx",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"Vector",
":",
"pindices",
"=",
"self",
".",
"indices",
"(",
"part",
",",
... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterface.py#L844-L851 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/utils/jit_utils.py | python | get_attr_chains | (root_getattr_node) | return get_use_chains(root_getattr_node, terminate) | Returns chains of attribute access starting from root_getattr_node
For example, given attribute "block", as in "self.block" when "self" points
to the top level torch.nn.Module, it returns lists of attribute "chains",
e.g. ['block', '2'], ['block', '1'], ['block', '0', '_packed_params']
These sets of attributes form full attribute accessors. For example,
"self.block.1", "self.block.2" will return the second and third submodule,
and "self.block.0._packed_params" will return the parameters of the first
submodule. | Returns chains of attribute access starting from root_getattr_node | [
"Returns",
"chains",
"of",
"attribute",
"access",
"starting",
"from",
"root_getattr_node"
] | def get_attr_chains(root_getattr_node):
"""Returns chains of attribute access starting from root_getattr_node
For example, given attribute "block", as in "self.block" when "self" points
to the top level torch.nn.Module, it returns lists of attribute "chains",
e.g. ['block', '2'], ['block', '1'], ['block', '0', '_packed_params']
These sets of attributes form full attribute accessors. For example,
"self.block.1", "self.block.2" will return the second and third submodule,
and "self.block.0._packed_params" will return the parameters of the first
submodule.
"""
def terminate(users):
next_attrs = [user for user in users if user.kind() == "prim::GetAttr"]
return len(next_attrs) == 0
return get_use_chains(root_getattr_node, terminate) | [
"def",
"get_attr_chains",
"(",
"root_getattr_node",
")",
":",
"def",
"terminate",
"(",
"users",
")",
":",
"next_attrs",
"=",
"[",
"user",
"for",
"user",
"in",
"users",
"if",
"user",
".",
"kind",
"(",
")",
"==",
"\"prim::GetAttr\"",
"]",
"return",
"len",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/utils/jit_utils.py#L425-L442 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/v7.9.317/third_party/jinja2/utils.py | python | LRUCache.__setitem__ | (self, key, value) | Sets the value for an item. Moves the item up so that it
has the highest priority then. | Sets the value for an item. Moves the item up so that it
has the highest priority then. | [
"Sets",
"the",
"value",
"for",
"an",
"item",
".",
"Moves",
"the",
"item",
"up",
"so",
"that",
"it",
"has",
"the",
"highest",
"priority",
"then",
"."
] | def __setitem__(self, key, value):
"""Sets the value for an item. Moves the item up so that it
has the highest priority then.
"""
self._wlock.acquire()
try:
if key in self._mapping:
self._remove(key)
elif len(self._mapping) == self.capacity:
del self._mapping[self._popleft()]
self._append(key)
self._mapping[key] = value
finally:
self._wlock.release() | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_wlock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"key",
"in",
"self",
".",
"_mapping",
":",
"self",
".",
"_remove",
"(",
"key",
")",
"elif",
"len",
"(",
"sel... | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/utils.py#L414-L427 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | Grid.GetSelectionBlockBottomRight | (*args, **kwargs) | return _grid.Grid_GetSelectionBlockBottomRight(*args, **kwargs) | GetSelectionBlockBottomRight(self) -> wxGridCellCoordsArray | GetSelectionBlockBottomRight(self) -> wxGridCellCoordsArray | [
"GetSelectionBlockBottomRight",
"(",
"self",
")",
"-",
">",
"wxGridCellCoordsArray"
] | def GetSelectionBlockBottomRight(*args, **kwargs):
"""GetSelectionBlockBottomRight(self) -> wxGridCellCoordsArray"""
return _grid.Grid_GetSelectionBlockBottomRight(*args, **kwargs) | [
"def",
"GetSelectionBlockBottomRight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_GetSelectionBlockBottomRight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L2065-L2067 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Memoize.py | python | CountMethodCall | (fn) | Decorator for counting memoizer hits/misses while retrieving
a simple value in a class method. It wraps the given method
fn and uses a CountValue object to keep track of the
caching statistics.
Wrapping gets enabled by calling EnableMemoization(). | Decorator for counting memoizer hits/misses while retrieving
a simple value in a class method. It wraps the given method
fn and uses a CountValue object to keep track of the
caching statistics.
Wrapping gets enabled by calling EnableMemoization(). | [
"Decorator",
"for",
"counting",
"memoizer",
"hits",
"/",
"misses",
"while",
"retrieving",
"a",
"simple",
"value",
"in",
"a",
"class",
"method",
".",
"It",
"wraps",
"the",
"given",
"method",
"fn",
"and",
"uses",
"a",
"CountValue",
"object",
"to",
"keep",
"t... | def CountMethodCall(fn):
""" Decorator for counting memoizer hits/misses while retrieving
a simple value in a class method. It wraps the given method
fn and uses a CountValue object to keep track of the
caching statistics.
Wrapping gets enabled by calling EnableMemoization().
"""
if use_memoizer:
def wrapper(self, *args, **kwargs):
global CounterList
key = self.__class__.__name__+'.'+fn.__name__
if key not in CounterList:
CounterList[key] = CountValue(self.__class__.__name__, fn.__name__)
CounterList[key].count(self, *args, **kwargs)
return fn(self, *args, **kwargs)
wrapper.__name__= fn.__name__
return wrapper
else:
return fn | [
"def",
"CountMethodCall",
"(",
"fn",
")",
":",
"if",
"use_memoizer",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"CounterList",
"key",
"=",
"self",
".",
"__class__",
".",
"__name__",
"+",
"'.'",
... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Memoize.py#L196-L214 | ||
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | clang/utils/check_cfc/obj_diff.py | python | first_diff | (a, b, fromfile, tofile) | return difference | Returns the first few lines of a difference, if there is one. Python
diff can be very slow with large objects and the most interesting changes
are the first ones. Truncate data before sending to difflib. Returns None
is there is no difference. | Returns the first few lines of a difference, if there is one. Python
diff can be very slow with large objects and the most interesting changes
are the first ones. Truncate data before sending to difflib. Returns None
is there is no difference. | [
"Returns",
"the",
"first",
"few",
"lines",
"of",
"a",
"difference",
"if",
"there",
"is",
"one",
".",
"Python",
"diff",
"can",
"be",
"very",
"slow",
"with",
"large",
"objects",
"and",
"the",
"most",
"interesting",
"changes",
"are",
"the",
"first",
"ones",
... | def first_diff(a, b, fromfile, tofile):
"""Returns the first few lines of a difference, if there is one. Python
diff can be very slow with large objects and the most interesting changes
are the first ones. Truncate data before sending to difflib. Returns None
is there is no difference."""
# Find first diff
first_diff_idx = None
for idx, val in enumerate(a):
if val != b[idx]:
first_diff_idx = idx
break
if first_diff_idx == None:
# No difference
return None
# Diff to first line of diff plus some lines
context = 3
diff = difflib.unified_diff(a[:first_diff_idx+context],
b[:first_diff_idx+context],
fromfile,
tofile)
difference = "\n".join(diff)
if first_diff_idx + context < len(a):
difference += "\n*** Diff truncated ***"
return difference | [
"def",
"first_diff",
"(",
"a",
",",
"b",
",",
"fromfile",
",",
"tofile",
")",
":",
"# Find first diff",
"first_diff_idx",
"=",
"None",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"a",
")",
":",
"if",
"val",
"!=",
"b",
"[",
"idx",
"]",
":",
"f... | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/utils/check_cfc/obj_diff.py#L39-L65 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextPlainText.GetText | (*args, **kwargs) | return _richtext.RichTextPlainText_GetText(*args, **kwargs) | GetText(self) -> String | GetText(self) -> String | [
"GetText",
"(",
"self",
")",
"-",
">",
"String"
] | def GetText(*args, **kwargs):
"""GetText(self) -> String"""
return _richtext.RichTextPlainText_GetText(*args, **kwargs) | [
"def",
"GetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextPlainText_GetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2096-L2098 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/index-pairs-of-a-string.py | python | Solution.indexPairs | (self, text, words) | return result | :type text: str
:type words: List[str]
:rtype: List[List[int]] | :type text: str
:type words: List[str]
:rtype: List[List[int]] | [
":",
"type",
"text",
":",
"str",
":",
"type",
"words",
":",
"List",
"[",
"str",
"]",
":",
"rtype",
":",
"List",
"[",
"List",
"[",
"int",
"]]"
] | def indexPairs(self, text, words):
"""
:type text: str
:type words: List[str]
:rtype: List[List[int]]
"""
result = []
reversed_words = [w[::-1] for w in words]
trie = AhoTrie(reversed_words)
for i in reversed(xrange(len(text))):
for j in trie.step(text[i]):
result.append([i, i+len(reversed_words[j])-1])
result.reverse()
return result | [
"def",
"indexPairs",
"(",
"self",
",",
"text",
",",
"words",
")",
":",
"result",
"=",
"[",
"]",
"reversed_words",
"=",
"[",
"w",
"[",
":",
":",
"-",
"1",
"]",
"for",
"w",
"in",
"words",
"]",
"trie",
"=",
"AhoTrie",
"(",
"reversed_words",
")",
"fo... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/index-pairs-of-a-string.py#L69-L82 | |
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/YouCompleteMe/third_party/requests/requests/utils.py | python | except_on_missing_scheme | (url) | Given a URL, raise a MissingSchema exception if the scheme is missing. | Given a URL, raise a MissingSchema exception if the scheme is missing. | [
"Given",
"a",
"URL",
"raise",
"a",
"MissingSchema",
"exception",
"if",
"the",
"scheme",
"is",
"missing",
"."
] | def except_on_missing_scheme(url):
"""Given a URL, raise a MissingSchema exception if the scheme is missing.
"""
scheme, netloc, path, params, query, fragment = urlparse(url)
if not scheme:
raise MissingSchema('Proxy URLs must have explicit schemes.') | [
"def",
"except_on_missing_scheme",
"(",
"url",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
"=",
"urlparse",
"(",
"url",
")",
"if",
"not",
"scheme",
":",
"raise",
"MissingSchema",
"(",
"'Proxy URLs must have e... | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/requests/requests/utils.py#L536-L542 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | StatusBar.GetBorders | (*args, **kwargs) | return _windows_.StatusBar_GetBorders(*args, **kwargs) | GetBorders(self) -> Size | GetBorders(self) -> Size | [
"GetBorders",
"(",
"self",
")",
"-",
">",
"Size"
] | def GetBorders(*args, **kwargs):
"""GetBorders(self) -> Size"""
return _windows_.StatusBar_GetBorders(*args, **kwargs) | [
"def",
"GetBorders",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"StatusBar_GetBorders",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L1295-L1297 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | DropFilesEvent.GetFiles | (*args, **kwargs) | return _core_.DropFilesEvent_GetFiles(*args, **kwargs) | GetFiles(self) -> PyObject
Returns a list of the filenames that were dropped. | GetFiles(self) -> PyObject | [
"GetFiles",
"(",
"self",
")",
"-",
">",
"PyObject"
] | def GetFiles(*args, **kwargs):
"""
GetFiles(self) -> PyObject
Returns a list of the filenames that were dropped.
"""
return _core_.DropFilesEvent_GetFiles(*args, **kwargs) | [
"def",
"GetFiles",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"DropFilesEvent_GetFiles",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L6670-L6676 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/grid.py | python | Grid.AutoSizeColLabelSize | (*args, **kwargs) | return _grid.Grid_AutoSizeColLabelSize(*args, **kwargs) | AutoSizeColLabelSize(self, int col) | AutoSizeColLabelSize(self, int col) | [
"AutoSizeColLabelSize",
"(",
"self",
"int",
"col",
")"
] | def AutoSizeColLabelSize(*args, **kwargs):
"""AutoSizeColLabelSize(self, int col)"""
return _grid.Grid_AutoSizeColLabelSize(*args, **kwargs) | [
"def",
"AutoSizeColLabelSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_AutoSizeColLabelSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L1906-L1908 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/sparse/series.py | python | SparseSeries.sparse_reindex | (self, new_index) | return self._constructor(values, index=self.index).__finalize__(self) | Conform sparse values to new SparseIndex
Parameters
----------
new_index : {BlockIndex, IntIndex}
Returns
-------
reindexed : SparseSeries | Conform sparse values to new SparseIndex | [
"Conform",
"sparse",
"values",
"to",
"new",
"SparseIndex"
] | def sparse_reindex(self, new_index):
"""
Conform sparse values to new SparseIndex
Parameters
----------
new_index : {BlockIndex, IntIndex}
Returns
-------
reindexed : SparseSeries
"""
if not isinstance(new_index, splib.SparseIndex):
raise TypeError("new index must be a SparseIndex")
values = self.values
values = values.sp_index.to_int_index().reindex(
values.sp_values.astype('float64'), values.fill_value, new_index)
values = SparseArray(values,
sparse_index=new_index,
fill_value=self.values.fill_value)
return self._constructor(values, index=self.index).__finalize__(self) | [
"def",
"sparse_reindex",
"(",
"self",
",",
"new_index",
")",
":",
"if",
"not",
"isinstance",
"(",
"new_index",
",",
"splib",
".",
"SparseIndex",
")",
":",
"raise",
"TypeError",
"(",
"\"new index must be a SparseIndex\"",
")",
"values",
"=",
"self",
".",
"value... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/sparse/series.py#L474-L494 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/patch_builds/change_data.py | python | generate_revision_map | (repos: List[Repo], revisions_data: Dict[str, str]) | return {k: v for k, v in revision_map.items() if v} | Generate a revision map for the given repositories using the revisions in the given file.
:param repos: Repositories to generate map for.
:param revisions_data: Dictionary of revisions to use for repositories.
:return: Map of repositories to revisions | Generate a revision map for the given repositories using the revisions in the given file. | [
"Generate",
"a",
"revision",
"map",
"for",
"the",
"given",
"repositories",
"using",
"the",
"revisions",
"in",
"the",
"given",
"file",
"."
] | def generate_revision_map(repos: List[Repo], revisions_data: Dict[str, str]) -> RevisionMap:
"""
Generate a revision map for the given repositories using the revisions in the given file.
:param repos: Repositories to generate map for.
:param revisions_data: Dictionary of revisions to use for repositories.
:return: Map of repositories to revisions
"""
revision_map = {repo.git_dir: revisions_data.get(_get_id_from_repo(repo)) for repo in repos}
return {k: v for k, v in revision_map.items() if v} | [
"def",
"generate_revision_map",
"(",
"repos",
":",
"List",
"[",
"Repo",
"]",
",",
"revisions_data",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"RevisionMap",
":",
"revision_map",
"=",
"{",
"repo",
".",
"git_dir",
":",
"revisions_data",
".",
"ge... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/patch_builds/change_data.py#L26-L35 | |
daijifeng001/caffe-rfcn | 543f8f6a4b7c88256ea1445ae951a12d1ad9cffd | tools/extra/extract_seconds.py | python | get_start_time | (line_iterable, year) | return start_datetime | Find start time from group of lines | Find start time from group of lines | [
"Find",
"start",
"time",
"from",
"group",
"of",
"lines"
] | def get_start_time(line_iterable, year):
"""Find start time from group of lines
"""
start_datetime = None
for line in line_iterable:
line = line.strip()
if line.find('Solving') != -1:
start_datetime = extract_datetime_from_line(line, year)
break
return start_datetime | [
"def",
"get_start_time",
"(",
"line_iterable",
",",
"year",
")",
":",
"start_datetime",
"=",
"None",
"for",
"line",
"in",
"line_iterable",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"find",
"(",
"'Solving'",
")",
"!=",
"-",
"1... | https://github.com/daijifeng001/caffe-rfcn/blob/543f8f6a4b7c88256ea1445ae951a12d1ad9cffd/tools/extra/extract_seconds.py#L31-L41 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/framework/graph_util.py | python | tensor_shape_from_node_def_name | (graph, input_name) | return shape | Convenience function to get a shape from a NodeDef's input string. | Convenience function to get a shape from a NodeDef's input string. | [
"Convenience",
"function",
"to",
"get",
"a",
"shape",
"from",
"a",
"NodeDef",
"s",
"input",
"string",
"."
] | def tensor_shape_from_node_def_name(graph, input_name):
"""Convenience function to get a shape from a NodeDef's input string."""
# To get a tensor, the name must be in the form <input>:<port>, for example
# 'Mul:0'. The GraphDef input strings don't always have the port specified
# though, so if there isn't a colon we need to add a default ':0' to the end.
if ":" not in input_name:
canonical_name = input_name + ":0"
else:
canonical_name = input_name
tensor = graph.get_tensor_by_name(canonical_name)
shape = tensor.get_shape()
return shape | [
"def",
"tensor_shape_from_node_def_name",
"(",
"graph",
",",
"input_name",
")",
":",
"# To get a tensor, the name must be in the form <input>:<port>, for example",
"# 'Mul:0'. The GraphDef input strings don't always have the port specified",
"# though, so if there isn't a colon we need to add a ... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/graph_util.py#L179-L190 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/util.py | python | check_environ | () | Ensure that 'os.environ' has all the environment variables we
guarantee that users can use in config files, command-line options,
etc. Currently this includes:
HOME - user's home directory (Unix only)
PLAT - description of the current platform, including hardware
and OS (see 'get_platform()') | Ensure that 'os.environ' has all the environment variables we
guarantee that users can use in config files, command-line options,
etc. Currently this includes:
HOME - user's home directory (Unix only)
PLAT - description of the current platform, including hardware
and OS (see 'get_platform()') | [
"Ensure",
"that",
"os",
".",
"environ",
"has",
"all",
"the",
"environment",
"variables",
"we",
"guarantee",
"that",
"users",
"can",
"use",
"in",
"config",
"files",
"command",
"-",
"line",
"options",
"etc",
".",
"Currently",
"this",
"includes",
":",
"HOME",
... | def check_environ ():
"""Ensure that 'os.environ' has all the environment variables we
guarantee that users can use in config files, command-line options,
etc. Currently this includes:
HOME - user's home directory (Unix only)
PLAT - description of the current platform, including hardware
and OS (see 'get_platform()')
"""
global _environ_checked
if _environ_checked:
return
if os.name == 'posix' and 'HOME' not in os.environ:
import pwd
os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
if 'PLAT' not in os.environ:
os.environ['PLAT'] = get_platform()
_environ_checked = 1 | [
"def",
"check_environ",
"(",
")",
":",
"global",
"_environ_checked",
"if",
"_environ_checked",
":",
"return",
"if",
"os",
".",
"name",
"==",
"'posix'",
"and",
"'HOME'",
"not",
"in",
"os",
".",
"environ",
":",
"import",
"pwd",
"os",
".",
"environ",
"[",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/util.py#L175-L194 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | HScrolledWindow.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=PanelNameStr) -> HScrolledWindow | __init__(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=PanelNameStr) -> HScrolledWindow | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"ID_ANY",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"0",
"String",
"name",
"=",
"PanelNameStr",
")",
"-",
">",
"HScrolledWindow"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=PanelNameStr) -> HScrolledWindow
"""
_windows_.HScrolledWindow_swiginit(self,_windows_.new_HScrolledWindow(*args, **kwargs))
self._setOORInfo(self);HScrolledWindow._setCallbackInfo(self, self, HScrolledWindow) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_windows_",
".",
"HScrolledWindow_swiginit",
"(",
"self",
",",
"_windows_",
".",
"new_HScrolledWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
"... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L2501-L2507 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/TiffImagePlugin.py | python | TiffImageFile._setup | (self) | Setup this image object based on current tags | Setup this image object based on current tags | [
"Setup",
"this",
"image",
"object",
"based",
"on",
"current",
"tags"
] | def _setup(self):
"""Setup this image object based on current tags"""
if 0xBC01 in self.tag_v2:
raise OSError("Windows Media Photo files not yet supported")
# extract relevant tags
self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)
# photometric is a required tag, but not everyone is reading
# the specification
photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)
# old style jpeg compression images most certainly are YCbCr
if self._compression == "tiff_jpeg":
photo = 6
fillorder = self.tag_v2.get(FILLORDER, 1)
if DEBUG:
print("*** Summary ***")
print("- compression:", self._compression)
print("- photometric_interpretation:", photo)
print("- planar_configuration:", self._planar_configuration)
print("- fill_order:", fillorder)
print("- YCbCr subsampling:", self.tag.get(530))
# size
xsize = int(self.tag_v2.get(IMAGEWIDTH))
ysize = int(self.tag_v2.get(IMAGELENGTH))
self._size = xsize, ysize
if DEBUG:
print("- size:", self.size)
sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))
if len(sampleFormat) > 1 and max(sampleFormat) == min(sampleFormat) == 1:
# SAMPLEFORMAT is properly per band, so an RGB image will
# be (1,1,1). But, we don't support per band pixel types,
# and anything more than one band is a uint8. So, just
# take the first element. Revisit this if adding support
# for more exotic images.
sampleFormat = (1,)
bps_tuple = self.tag_v2.get(BITSPERSAMPLE, (1,))
extra_tuple = self.tag_v2.get(EXTRASAMPLES, ())
if photo in (2, 6, 8): # RGB, YCbCr, LAB
bps_count = 3
elif photo == 5: # CMYK
bps_count = 4
else:
bps_count = 1
bps_count += len(extra_tuple)
# Some files have only one value in bps_tuple,
# while should have more. Fix it
if bps_count > len(bps_tuple) and len(bps_tuple) == 1:
bps_tuple = bps_tuple * bps_count
# mode: check photometric interpretation and bits per pixel
key = (
self.tag_v2.prefix,
photo,
sampleFormat,
fillorder,
bps_tuple,
extra_tuple,
)
if DEBUG:
print("format key:", key)
try:
self.mode, rawmode = OPEN_INFO[key]
except KeyError:
if DEBUG:
print("- unsupported format")
raise SyntaxError("unknown pixel mode")
if DEBUG:
print("- raw mode:", rawmode)
print("- pil mode:", self.mode)
self.info["compression"] = self._compression
xres = self.tag_v2.get(X_RESOLUTION, 1)
yres = self.tag_v2.get(Y_RESOLUTION, 1)
if xres and yres:
resunit = self.tag_v2.get(RESOLUTION_UNIT)
if resunit == 2: # dots per inch
self.info["dpi"] = int(xres + 0.5), int(yres + 0.5)
elif resunit == 3: # dots per centimeter. convert to dpi
self.info["dpi"] = int(xres * 2.54 + 0.5), int(yres * 2.54 + 0.5)
elif resunit is None: # used to default to 1, but now 2)
self.info["dpi"] = int(xres + 0.5), int(yres + 0.5)
# For backward compatibility,
# we also preserve the old behavior
self.info["resolution"] = xres, yres
else: # No absolute unit of measurement
self.info["resolution"] = xres, yres
# build tile descriptors
x = y = layer = 0
self.tile = []
self.use_load_libtiff = READ_LIBTIFF or self._compression != "raw"
if self.use_load_libtiff:
# Decoder expects entire file as one tile.
# There's a buffer size limit in load (64k)
# so large g4 images will fail if we use that
# function.
#
# Setup the one tile for the whole image, then
# use the _load_libtiff function.
# libtiff handles the fillmode for us, so 1;IR should
# actually be 1;I. Including the R double reverses the
# bits, so stripes of the image are reversed. See
# https://github.com/python-pillow/Pillow/issues/279
if fillorder == 2:
# Replace fillorder with fillorder=1
key = key[:3] + (1,) + key[4:]
if DEBUG:
print("format key:", key)
# this should always work, since all the
# fillorder==2 modes have a corresponding
# fillorder=1 mode
self.mode, rawmode = OPEN_INFO[key]
# libtiff always returns the bytes in native order.
# we're expecting image byte order. So, if the rawmode
# contains I;16, we need to convert from native to image
# byte order.
if rawmode == "I;16":
rawmode = "I;16N"
if ";16B" in rawmode:
rawmode = rawmode.replace(";16B", ";16N")
if ";16L" in rawmode:
rawmode = rawmode.replace(";16L", ";16N")
# Offset in the tile tuple is 0, we go from 0,0 to
# w,h, and we only do this once -- eds
a = (rawmode, self._compression, False, self.tag_v2.offset)
self.tile.append(("libtiff", (0, 0, xsize, ysize), 0, a))
elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2:
# striped image
if STRIPOFFSETS in self.tag_v2:
offsets = self.tag_v2[STRIPOFFSETS]
h = self.tag_v2.get(ROWSPERSTRIP, ysize)
w = self.size[0]
else:
# tiled image
offsets = self.tag_v2[TILEOFFSETS]
w = self.tag_v2.get(322)
h = self.tag_v2.get(323)
for offset in offsets:
if x + w > xsize:
stride = w * sum(bps_tuple) / 8 # bytes per line
else:
stride = 0
tile_rawmode = rawmode
if self._planar_configuration == 2:
# each band on it's own layer
tile_rawmode = rawmode[layer]
# adjust stride width accordingly
stride /= bps_count
a = (tile_rawmode, int(stride), 1)
self.tile.append(
(
self._compression,
(x, y, min(x + w, xsize), min(y + h, ysize)),
offset,
a,
)
)
x = x + w
if x >= self.size[0]:
x, y = 0, y + h
if y >= self.size[1]:
x = y = 0
layer += 1
else:
if DEBUG:
print("- unsupported data organization")
raise SyntaxError("unknown data organization")
# Fix up info.
if ICCPROFILE in self.tag_v2:
self.info["icc_profile"] = self.tag_v2[ICCPROFILE]
# fixup palette descriptor
if self.mode in ["P", "PA"]:
palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]
self.palette = ImagePalette.raw("RGB;L", b"".join(palette))
self._tile_orientation = self.tag_v2.get(0x0112) | [
"def",
"_setup",
"(",
"self",
")",
":",
"if",
"0xBC01",
"in",
"self",
".",
"tag_v2",
":",
"raise",
"OSError",
"(",
"\"Windows Media Photo files not yet supported\"",
")",
"# extract relevant tags",
"self",
".",
"_compression",
"=",
"COMPRESSION_INFO",
"[",
"self",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/TiffImagePlugin.py#L1186-L1383 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/knobctrl.py | python | KnobCtrl.DrawTags | (self, dc, size) | Draws the tags.
:param `dc`: an instance of :class:`DC`;
:param `size`: the control size. | Draws the tags. | [
"Draws",
"the",
"tags",
"."
] | def DrawTags(self, dc, size):
"""
Draws the tags.
:param `dc`: an instance of :class:`DC`;
:param `size`: the control size.
"""
deltarange = abs(self._tags[-1] - self._tags[0])
deltaangle = self._angleend - self._anglestart
width = size.x
height = size.y
xshift = 0
yshift = 0
if width > height:
xshift = width - height
elif width < height:
yshift = height - width
coeff = float(deltaangle)/float(deltarange)
dcPen = wx.Pen(self._tagscolour, 1)
for tags in self._tags:
if tags == self._tags[0] or tags == self._tags[-1]:
# draw first and last tags bigger
dcPen.SetWidth(2)
tagLen = 8
else:
dcPen.SetWidth(1)
tagLen = 6
dc.SetPen(dcPen)
tg = tags - self._tags[0]
angle = tg*coeff + self._anglestart
angle = angle*math.pi/180.0
sxi = math.cos(angle)*(width - xshift + tagLen - 6)/2.0
syi = math.sin(angle)*(height - yshift + tagLen - 6)/2.0
dxi = math.cos(angle)*((width - xshift + tagLen - 6)/2.0 - tagLen)
dyi = math.sin(angle)*((height - yshift + tagLen - 6)/2.0 - tagLen)
dc.DrawLine(width/2 - sxi, height/2 - syi,
width/2 - dxi, height/2 - dyi) | [
"def",
"DrawTags",
"(",
"self",
",",
"dc",
",",
"size",
")",
":",
"deltarange",
"=",
"abs",
"(",
"self",
".",
"_tags",
"[",
"-",
"1",
"]",
"-",
"self",
".",
"_tags",
"[",
"0",
"]",
")",
"deltaangle",
"=",
"self",
".",
"_angleend",
"-",
"self",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/knobctrl.py#L599-L648 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/builder.py | python | IRBuilder.ret_void | (self) | return self._set_terminator(
instructions.Ret(self.block, "ret void")) | Return from function without a value. | Return from function without a value. | [
"Return",
"from",
"function",
"without",
"a",
"value",
"."
] | def ret_void(self):
"""
Return from function without a value.
"""
return self._set_terminator(
instructions.Ret(self.block, "ret void")) | [
"def",
"ret_void",
"(",
"self",
")",
":",
"return",
"self",
".",
"_set_terminator",
"(",
"instructions",
".",
"Ret",
"(",
"self",
".",
"block",
",",
"\"ret void\"",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/builder.py#L811-L816 | |
mickem/nscp | 79f89fdbb6da63f91bc9dedb7aea202fe938f237 | scripts/python/lib/google/protobuf/internal/python_message.py | python | _ExtensionDict.__setitem__ | (self, extension_handle, value) | If extension_handle specifies a non-repeated, scalar extension
field, sets the value of that field. | If extension_handle specifies a non-repeated, scalar extension
field, sets the value of that field. | [
"If",
"extension_handle",
"specifies",
"a",
"non",
"-",
"repeated",
"scalar",
"extension",
"field",
"sets",
"the",
"value",
"of",
"that",
"field",
"."
] | def __setitem__(self, extension_handle, value):
"""If extension_handle specifies a non-repeated, scalar extension
field, sets the value of that field.
"""
_VerifyExtensionHandle(self._extended_message, extension_handle)
if (extension_handle.label == _FieldDescriptor.LABEL_REPEATED or
extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE):
raise TypeError(
'Cannot assign to extension "%s" because it is a repeated or '
'composite type.' % extension_handle.full_name)
# It's slightly wasteful to lookup the type checker each time,
# but we expect this to be a vanishingly uncommon case anyway.
type_checker = type_checkers.GetTypeChecker(
extension_handle.cpp_type, extension_handle.type)
type_checker.CheckValue(value)
self._extended_message._fields[extension_handle] = value
self._extended_message._Modified() | [
"def",
"__setitem__",
"(",
"self",
",",
"extension_handle",
",",
"value",
")",
":",
"_VerifyExtensionHandle",
"(",
"self",
".",
"_extended_message",
",",
"extension_handle",
")",
"if",
"(",
"extension_handle",
".",
"label",
"==",
"_FieldDescriptor",
".",
"LABEL_RE... | https://github.com/mickem/nscp/blob/79f89fdbb6da63f91bc9dedb7aea202fe938f237/scripts/python/lib/google/protobuf/internal/python_message.py#L1068-L1087 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/powercycle/lib/services.py | python | PosixService.delete | (self) | return 0, None | Simulate delete service. Returns (code, output) tuple. | Simulate delete service. Returns (code, output) tuple. | [
"Simulate",
"delete",
"service",
".",
"Returns",
"(",
"code",
"output",
")",
"tuple",
"."
] | def delete(self): # pylint: disable=no-self-use
"""Simulate delete service. Returns (code, output) tuple."""
return 0, None | [
"def",
"delete",
"(",
"self",
")",
":",
"# pylint: disable=no-self-use",
"return",
"0",
",",
"None"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/powercycle/lib/services.py#L202-L204 | |
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_reactor.py | python | SenderOption.apply | (self, sender: 'Sender') | Set the option on the sender.
:param sender: The sender on which this option is to be applied. | Set the option on the sender. | [
"Set",
"the",
"option",
"on",
"the",
"sender",
"."
] | def apply(self, sender: 'Sender') -> None:
"""
Set the option on the sender.
:param sender: The sender on which this option is to be applied.
"""
pass | [
"def",
"apply",
"(",
"self",
",",
"sender",
":",
"'Sender'",
")",
"->",
"None",
":",
"pass"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_reactor.py#L711-L717 | ||
bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | bridge/npbackend/bohrium/reorganization.py | python | gather | (ary, indexes) | return ret | gather(ary, indexes)
Gather elements from 'ary' selected by 'indexes'.
The values of 'indexes' are absolute indexed into a flatten 'ary'
The shape of the returned array equals indexes.shape.
Parameters
----------
ary : array_like
The array to gather elements from.
indexes : array_like, interpreted as integers
Array or list of indexes that will be gather from 'array'
Returns
-------
r : ndarray
The gathered array freshly-allocated. | gather(ary, indexes) | [
"gather",
"(",
"ary",
"indexes",
")"
] | def gather(ary, indexes):
"""
gather(ary, indexes)
Gather elements from 'ary' selected by 'indexes'.
The values of 'indexes' are absolute indexed into a flatten 'ary'
The shape of the returned array equals indexes.shape.
Parameters
----------
ary : array_like
The array to gather elements from.
indexes : array_like, interpreted as integers
Array or list of indexes that will be gather from 'array'
Returns
-------
r : ndarray
The gathered array freshly-allocated.
"""
from . import _bh
ary = array_manipulation.flatten(array_create.array(ary))
# Convert a scalar index to a 1-element array
if is_scalar(indexes):
indexes = [indexes]
indexes = array_create.array(indexes, dtype=numpy.uint64, bohrium=True)
ret = array_create.empty(indexes.shape, dtype=ary.dtype, bohrium=True)
if ary.size == 0 or indexes.size == 0:
return array_create.array([])
_bh.ufunc(_info.op['gather']['id'], (ret, ary, indexes))
return ret | [
"def",
"gather",
"(",
"ary",
",",
"indexes",
")",
":",
"from",
".",
"import",
"_bh",
"ary",
"=",
"array_manipulation",
".",
"flatten",
"(",
"array_create",
".",
"array",
"(",
"ary",
")",
")",
"# Convert a scalar index to a 1-element array",
"if",
"is_scalar",
... | https://github.com/bh107/bohrium/blob/5b83e7117285fefc7779ed0e9acb0f8e74c7e068/bridge/npbackend/bohrium/reorganization.py#L18-L52 | |
francinexue/xuefu | b6ff79747a42e020588c0c0a921048e08fe4680c | cnx/bar.py | python | Bars.__contains__ | (self, instrument) | return instrument in self.__barDict | Returns True if a :class:`pyalgotrade.bar.Bar` for the given instrument is available. | Returns True if a :class:`pyalgotrade.bar.Bar` for the given instrument is available. | [
"Returns",
"True",
"if",
"a",
":",
"class",
":",
"pyalgotrade",
".",
"bar",
".",
"Bar",
"for",
"the",
"given",
"instrument",
"is",
"available",
"."
] | def __contains__(self, instrument):
"""Returns True if a :class:`pyalgotrade.bar.Bar` for the given instrument is available."""
return instrument in self.__barDict | [
"def",
"__contains__",
"(",
"self",
",",
"instrument",
")",
":",
"return",
"instrument",
"in",
"self",
".",
"__barDict"
] | https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/cnx/bar.py#L280-L282 | |
sandialabs/Albany | e7e05599c47f65dee6f1916b26f49a5b80d39416 | PyAlbany/python/Utils.py | python | createAlbanyProblem | (filename, parallelEnv) | return wpa.PyProblem(filename, parallelEnv) | @brief Creates an Albany problem given a yaml file and a parallel environment. | [] | def createAlbanyProblem(filename, parallelEnv):
"""@brief Creates an Albany problem given a yaml file and a parallel environment."""
return wpa.PyProblem(filename, parallelEnv) | [
"def",
"createAlbanyProblem",
"(",
"filename",
",",
"parallelEnv",
")",
":",
"return",
"wpa",
".",
"PyProblem",
"(",
"filename",
",",
"parallelEnv",
")"
] | https://github.com/sandialabs/Albany/blob/e7e05599c47f65dee6f1916b26f49a5b80d39416/PyAlbany/python/Utils.py#L36-L38 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/dist.py | python | check_entry_points | (dist, attr, value) | Verify that entry_points map is parseable | Verify that entry_points map is parseable | [
"Verify",
"that",
"entry_points",
"map",
"is",
"parseable"
] | def check_entry_points(dist, attr, value):
"""Verify that entry_points map is parseable"""
try:
pkg_resources.EntryPoint.parse_map(value)
except ValueError as e:
raise DistutilsSetupError(e) | [
"def",
"check_entry_points",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"pkg_resources",
".",
"EntryPoint",
".",
"parse_map",
"(",
"value",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"DistutilsSetupError",
"(",
"e",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/dist.py#L298-L303 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/py/py/_path/svnwc.py | python | SvnWCCommandPath.status | (self, updates=0, rec=0, externals=0) | return rootstatus | return (collective) Status object for this file. | return (collective) Status object for this file. | [
"return",
"(",
"collective",
")",
"Status",
"object",
"for",
"this",
"file",
"."
] | def status(self, updates=0, rec=0, externals=0):
""" return (collective) Status object for this file. """
# http://svnbook.red-bean.com/book.html#svn-ch-3-sect-4.3.1
# 2201 2192 jum test
# XXX
if externals:
raise ValueError("XXX cannot perform status() "
"on external items yet")
else:
#1.2 supports: externals = '--ignore-externals'
externals = ''
if rec:
rec= ''
else:
rec = '--non-recursive'
# XXX does not work on all subversion versions
#if not externals:
# externals = '--ignore-externals'
if updates:
updates = '-u'
else:
updates = ''
try:
cmd = 'status -v --xml --no-ignore %s %s %s' % (
updates, rec, externals)
out = self._authsvn(cmd)
except py.process.cmdexec.Error:
cmd = 'status -v --no-ignore %s %s %s' % (
updates, rec, externals)
out = self._authsvn(cmd)
rootstatus = WCStatus(self).fromstring(out, self)
else:
rootstatus = XMLWCStatus(self).fromstring(out, self)
return rootstatus | [
"def",
"status",
"(",
"self",
",",
"updates",
"=",
"0",
",",
"rec",
"=",
"0",
",",
"externals",
"=",
"0",
")",
":",
"# http://svnbook.red-bean.com/book.html#svn-ch-3-sect-4.3.1",
"# 2201 2192 jum test",
"# XXX",
"if",
"externals",
":",
"raise"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/py/py/_path/svnwc.py#L616-L652 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/npyio.py | python | zipfile_factory | (file, *args, **kwargs) | return zipfile.ZipFile(file, *args, **kwargs) | Create a ZipFile.
Allows for Zip64, and the `file` argument can accept file, str, or
pathlib.Path objects. `args` and `kwargs` are passed to the zipfile.ZipFile
constructor. | Create a ZipFile. | [
"Create",
"a",
"ZipFile",
"."
] | def zipfile_factory(file, *args, **kwargs):
"""
Create a ZipFile.
Allows for Zip64, and the `file` argument can accept file, str, or
pathlib.Path objects. `args` and `kwargs` are passed to the zipfile.ZipFile
constructor.
"""
if not hasattr(file, 'read'):
file = os_fspath(file)
import zipfile
kwargs['allowZip64'] = True
return zipfile.ZipFile(file, *args, **kwargs) | [
"def",
"zipfile_factory",
"(",
"file",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"file",
",",
"'read'",
")",
":",
"file",
"=",
"os_fspath",
"(",
"file",
")",
"import",
"zipfile",
"kwargs",
"[",
"'allowZip64'",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/npyio.py#L107-L119 | |
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/app/desmonddmsfile.py | python | DesmondDMSFile._addNonbondedForceToSystem | (self, sys, OPLS) | return nb, cnb | Create the nonbonded force | Create the nonbonded force | [
"Create",
"the",
"nonbonded",
"force"
] | def _addNonbondedForceToSystem(self, sys, OPLS):
"""Create the nonbonded force
"""
cnb = None
nb = mm.NonbondedForce()
sys.addForce(nb)
if OPLS:
cnb = mm.CustomNonbondedForce("4.0*epsilon12*((sigma12/r)^12 - (sigma12/r)^6); sigma12=sqrt(sigma1*sigma2); epsilon12=sqrt(epsilon1*epsilon2)")
cnb.addPerParticleParameter("sigma")
cnb.addPerParticleParameter("epsilon")
sys.addForce(cnb)
if OPLS:
q = """SELECT sigma, epsilon
FROM particle INNER JOIN nonbonded_param
ON particle.nbtype=nonbonded_param.id ORDER BY particle.id"""
for (fcounter,conn,tables,offset) in self._localVars():
for sigma, epsilon in conn.execute(q):
cnb.addParticle([sigma*angstrom, epsilon*kilocalorie_per_mole])
q = """SELECT charge, sigma, epsilon
FROM particle INNER JOIN nonbonded_param
ON particle.nbtype=nonbonded_param.id ORDER BY particle.id"""
for (fcounter,conn,tables,offset) in self._localVars():
for charge, sigma, epsilon in conn.execute(q):
if OPLS:
epsilon = 0
nb.addParticle(charge, sigma*angstrom, epsilon*kilocalorie_per_mole)
for (fcounter,conn,tables,offset) in self._localVars():
for p0, p1 in conn.execute('SELECT p0, p1 FROM exclusion'):
p0 += offset
p1 += offset
nb.addException(p0, p1, 0.0, 1.0, 0.0)
if OPLS:
cnb.addExclusion(p0, p1)
q = """SELECT p0, p1, aij, bij, qij
FROM pair_12_6_es_term INNER JOIN pair_12_6_es_param
ON pair_12_6_es_term.param=pair_12_6_es_param.id"""
for (fcounter,conn,tables,offset) in self._localVars():
for p0, p1, a_ij, b_ij, q_ij in conn.execute(q):
p0 += offset
p1 += offset
a_ij = (a_ij*kilocalorie_per_mole*(angstrom**12)).in_units_of(kilojoule_per_mole*(nanometer**12))
b_ij = (b_ij*kilocalorie_per_mole*(angstrom**6)).in_units_of(kilojoule_per_mole*(nanometer**6))
q_ij = q_ij*elementary_charge**2
if (b_ij._value == 0.0) or (a_ij._value == 0.0):
new_epsilon = 0
new_sigma = 1
else:
new_epsilon = b_ij**2/(4*a_ij)
new_sigma = (a_ij / b_ij)**(1.0/6.0)
nb.addException(p0, p1, q_ij, new_sigma, new_epsilon, True)
n_total = conn.execute("""SELECT COUNT(*) FROM pair_12_6_es_term""").fetchone()
n_in_exclusions = conn.execute("""SELECT COUNT(*)
FROM exclusion INNER JOIN pair_12_6_es_term
ON ( ( exclusion.p0==pair_12_6_es_term.p0 AND exclusion.p1==pair_12_6_es_term.p1)
OR ( exclusion.p0==pair_12_6_es_term.p1 AND exclusion.p1==pair_12_6_es_term.p0)
)""").fetchone()
if not n_total == n_in_exclusions:
raise NotImplementedError('All pair_12_6_es_terms must have a corresponding exclusion')
return nb, cnb | [
"def",
"_addNonbondedForceToSystem",
"(",
"self",
",",
"sys",
",",
"OPLS",
")",
":",
"cnb",
"=",
"None",
"nb",
"=",
"mm",
".",
"NonbondedForce",
"(",
")",
"sys",
".",
"addForce",
"(",
"nb",
")",
"if",
"OPLS",
":",
"cnb",
"=",
"mm",
".",
"CustomNonbon... | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/desmonddmsfile.py#L690-L755 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | catboost/python-package/catboost/eval/evaluation_result.py | python | CaseEvaluationResult.get_best_metric_for_fold | (self, fold) | return self._fold_metric[fold], self._fold_metric_iteration[fold] | :param fold: id of fold to get result
:return: best metric value, best metric iteration | [] | def get_best_metric_for_fold(self, fold):
"""
:param fold: id of fold to get result
:return: best metric value, best metric iteration
"""
return self._fold_metric[fold], self._fold_metric_iteration[fold] | [
"def",
"get_best_metric_for_fold",
"(",
"self",
",",
"fold",
")",
":",
"return",
"self",
".",
"_fold_metric",
"[",
"fold",
"]",
",",
"self",
".",
"_fold_metric_iteration",
"[",
"fold",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/python-package/catboost/eval/evaluation_result.py#L131-L137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.