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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/agents/ppo/algorithm.py | python | PPOAlgorithm._training | (self) | Perform multiple training iterations of both policy and value baseline.
Training on the episodes collected in the memory. Reset the memory
afterwards. Always returns a summary string.
Returns:
Summary tensor. | Perform multiple training iterations of both policy and value baseline. | [
"Perform",
"multiple",
"training",
"iterations",
"of",
"both",
"policy",
"and",
"value",
"baseline",
"."
] | def _training(self):
"""Perform multiple training iterations of both policy and value baseline.
Training on the episodes collected in the memory. Reset the memory
afterwards. Always returns a summary string.
Returns:
Summary tensor.
"""
with tf.name_scope('training'):
assert_full = tf.assert_equal(self._memory_index, self._config.update_every)
with tf.control_dependencies([assert_full]):
data = self._memory.data()
(observ, action, old_mean, old_logstd, reward), length = data
with tf.control_dependencies([tf.assert_greater(length, 0)]):
length = tf.identity(length)
observ = self._observ_filter.transform(observ)
reward = self._reward_filter.transform(reward)
update_summary = self._perform_update_steps(observ, action, old_mean, old_logstd, reward,
length)
with tf.control_dependencies([update_summary]):
penalty_summary = self._adjust_penalty(observ, old_mean, old_logstd, length)
with tf.control_dependencies([penalty_summary]):
clear_memory = tf.group(self._memory.clear(), self._memory_index.assign(0))
with tf.control_dependencies([clear_memory]):
weight_summary = utility.variable_summaries(tf.trainable_variables(),
self._config.weight_summaries)
return tf.summary.merge([update_summary, penalty_summary, weight_summary]) | [
"def",
"_training",
"(",
"self",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'training'",
")",
":",
"assert_full",
"=",
"tf",
".",
"assert_equal",
"(",
"self",
".",
"_memory_index",
",",
"self",
".",
"_config",
".",
"update_every",
")",
"with",
"tf"... | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/ppo/algorithm.py#L245-L272 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/util/fslike/path.py | python | Path.mtime | (self) | return self.fsobj.mtime(self.parts) | Returns the time of last modification of the file or directory. | Returns the time of last modification of the file or directory. | [
"Returns",
"the",
"time",
"of",
"last",
"modification",
"of",
"the",
"file",
"or",
"directory",
"."
] | def mtime(self):
""" Returns the time of last modification of the file or directory. """
return self.fsobj.mtime(self.parts) | [
"def",
"mtime",
"(",
"self",
")",
":",
"return",
"self",
".",
"fsobj",
".",
"mtime",
"(",
"self",
".",
"parts",
")"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/fslike/path.py#L230-L232 | |
rpp0/gr-lora | 90343d45a3c73c84d32d74b8603b6c01de025b08 | docs/doxygen/swig_doc.py | python | make_class_entry | (klass, description=None, ignored_methods=[], params=None) | return "\n\n".join(output) | Create a class docstring for a swig interface file. | Create a class docstring for a swig interface file. | [
"Create",
"a",
"class",
"docstring",
"for",
"a",
"swig",
"interface",
"file",
"."
] | def make_class_entry(klass, description=None, ignored_methods=[], params=None):
"""
Create a class docstring for a swig interface file.
"""
if params is None:
params = klass.params
output = []
output.append(make_entry(klass, description=description, params=params))
for func in klass.in_category(DoxyFunction):
if func.name() not in ignored_methods:
name = klass.name() + '::' + func.name()
output.append(make_func_entry(func, name=name))
return "\n\n".join(output) | [
"def",
"make_class_entry",
"(",
"klass",
",",
"description",
"=",
"None",
",",
"ignored_methods",
"=",
"[",
"]",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"klass",
".",
"params",
"output",
"=",
"[",
"]",
... | https://github.com/rpp0/gr-lora/blob/90343d45a3c73c84d32d74b8603b6c01de025b08/docs/doxygen/swig_doc.py#L166-L178 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/pkg_resources.py | python | get_supported_platform | () | return plat | Return this platform's maximum compatible version.
distutils.util.get_platform() normally reports the minimum version
of Mac OS X that would be required to *use* extensions produced by
distutils. But what we want when checking compatibility is to know the
version of Mac OS X that we are *running*. To allow usage of packages that
explicitly require a newer version of Mac OS X, we must also know the
current version of the OS.
If this condition occurs for any other platform with a version in its
platform strings, this function should be extended accordingly. | Return this platform's maximum compatible version. | [
"Return",
"this",
"platform",
"s",
"maximum",
"compatible",
"version",
"."
] | def get_supported_platform():
"""Return this platform's maximum compatible version.
distutils.util.get_platform() normally reports the minimum version
of Mac OS X that would be required to *use* extensions produced by
distutils. But what we want when checking compatibility is to know the
version of Mac OS X that we are *running*. To allow usage of packages that
explicitly require a newer version of Mac OS X, we must also know the
current version of the OS.
If this condition occurs for any other platform with a version in its
platform strings, this function should be extended accordingly.
"""
plat = get_build_platform(); m = macosVersionString.match(plat)
if m is not None and sys.platform == "darwin":
try:
plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))
except ValueError:
pass # not Mac OS X
return plat | [
"def",
"get_supported_platform",
"(",
")",
":",
"plat",
"=",
"get_build_platform",
"(",
")",
"m",
"=",
"macosVersionString",
".",
"match",
"(",
"plat",
")",
"if",
"m",
"is",
"not",
"None",
"and",
"sys",
".",
"platform",
"==",
"\"darwin\"",
":",
"try",
":... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/pkg_resources.py#L27-L46 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | WhileContext._MaybeAddControlDependency | (self, op) | Add a control input to the op if it only depends on loop invariants. | Add a control input to the op if it only depends on loop invariants. | [
"Add",
"a",
"control",
"input",
"to",
"the",
"op",
"if",
"it",
"only",
"depends",
"on",
"loop",
"invariants",
"."
] | def _MaybeAddControlDependency(self, op):
"""Add a control input to the op if it only depends on loop invariants."""
def _IsOpFree(op):
if op.control_inputs:
return False
for x in op.inputs:
if not _IsLoopConstantEnter(x.op):
return False
return True
if _IsOpFree(op):
# pylint: disable=protected-access
op._add_control_input(self.GetControlPivot().op) | [
"def",
"_MaybeAddControlDependency",
"(",
"self",
",",
"op",
")",
":",
"def",
"_IsOpFree",
"(",
"op",
")",
":",
"if",
"op",
".",
"control_inputs",
":",
"return",
"False",
"for",
"x",
"in",
"op",
".",
"inputs",
":",
"if",
"not",
"_IsLoopConstantEnter",
"(... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L1544-L1555 | ||
peteanderson80/Matterport3DSimulator | 589d091b111333f9e9f9d6cfd021b2eb68435925 | tasks/R2R/env.py | python | R2RBatch.step | (self, actions) | return self._get_obs() | Take action (same interface as makeActions) | Take action (same interface as makeActions) | [
"Take",
"action",
"(",
"same",
"interface",
"as",
"makeActions",
")"
] | def step(self, actions):
''' Take action (same interface as makeActions) '''
self.env.makeActions(actions)
return self._get_obs() | [
"def",
"step",
"(",
"self",
",",
"actions",
")",
":",
"self",
".",
"env",
".",
"makeActions",
"(",
"actions",
")",
"return",
"self",
".",
"_get_obs",
"(",
")"
] | https://github.com/peteanderson80/Matterport3DSimulator/blob/589d091b111333f9e9f9d6cfd021b2eb68435925/tasks/R2R/env.py#L224-L227 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py | python | Context.clear_flags | (self) | Reset all flags to zero | Reset all flags to zero | [
"Reset",
"all",
"flags",
"to",
"zero"
] | def clear_flags(self):
"""Reset all flags to zero"""
for flag in self.flags:
self.flags[flag] = 0 | [
"def",
"clear_flags",
"(",
"self",
")",
":",
"for",
"flag",
"in",
"self",
".",
"flags",
":",
"self",
".",
"flags",
"[",
"flag",
"]",
"=",
"0"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L3832-L3835 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/framework/ops.py | python | add_to_collections | (names, value) | Wrapper for `Graph.add_to_collections()` using the default graph.
See [`Graph.add_to_collections()`](../../api_docs/python/framework.md#Graph.add_to_collections)
for more details.
Args:
names: The key for the collections. The `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collections. | Wrapper for `Graph.add_to_collections()` using the default graph. | [
"Wrapper",
"for",
"Graph",
".",
"add_to_collections",
"()",
"using",
"the",
"default",
"graph",
"."
] | def add_to_collections(names, value):
"""Wrapper for `Graph.add_to_collections()` using the default graph.
See [`Graph.add_to_collections()`](../../api_docs/python/framework.md#Graph.add_to_collections)
for more details.
Args:
names: The key for the collections. The `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collections.
"""
get_default_graph().add_to_collections(names, value) | [
"def",
"add_to_collections",
"(",
"names",
",",
"value",
")",
":",
"get_default_graph",
"(",
")",
".",
"add_to_collections",
"(",
"names",
",",
"value",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/ops.py#L3929-L3940 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | IconBundle.IsOk | (*args, **kwargs) | return _gdi_.IconBundle_IsOk(*args, **kwargs) | IsOk(self) -> bool | IsOk(self) -> bool | [
"IsOk",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsOk(*args, **kwargs):
"""IsOk(self) -> bool"""
return _gdi_.IconBundle_IsOk(*args, **kwargs) | [
"def",
"IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"IconBundle_IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L1433-L1435 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/xcodeproj_file.py | python | PBXProject.RootGroupForPath | (self, path) | return (self.SourceGroup(), True) | Returns a PBXGroup child of this object to which path should be added.
This method is intended to choose between SourceGroup and
IntermediatesGroup on the basis of whether path is present in a source
directory or an intermediates directory. For the purposes of this
determination, any path located within a derived file directory such as
PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates
directory.
The returned value is a two-element tuple. The first element is the
PBXGroup, and the second element specifies whether that group should be
organized hierarchically (True) or as a single flat list (False). | Returns a PBXGroup child of this object to which path should be added. | [
"Returns",
"a",
"PBXGroup",
"child",
"of",
"this",
"object",
"to",
"which",
"path",
"should",
"be",
"added",
"."
] | def RootGroupForPath(self, path):
"""Returns a PBXGroup child of this object to which path should be added.
This method is intended to choose between SourceGroup and
IntermediatesGroup on the basis of whether path is present in a source
directory or an intermediates directory. For the purposes of this
determination, any path located within a derived file directory such as
PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates
directory.
The returned value is a two-element tuple. The first element is the
PBXGroup, and the second element specifies whether that group should be
organized hierarchically (True) or as a single flat list (False).
"""
# TODO(mark): make this a class variable and bind to self on call?
# Also, this list is nowhere near exhaustive.
# INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by
# gyp.generator.xcode. There should probably be some way for that module
# to push the names in, rather than having to hard-code them here.
source_tree_groups = {
"DERIVED_FILE_DIR": (self.IntermediatesGroup, True),
"INTERMEDIATE_DIR": (self.IntermediatesGroup, True),
"PROJECT_DERIVED_FILE_DIR": (self.IntermediatesGroup, True),
"SHARED_INTERMEDIATE_DIR": (self.IntermediatesGroup, True),
}
(source_tree, path) = SourceTreeAndPathFromPath(path)
if source_tree is not None and source_tree in source_tree_groups:
(group_func, hierarchical) = source_tree_groups[source_tree]
group = group_func()
return (group, hierarchical)
# TODO(mark): make additional choices based on file extension.
return (self.SourceGroup(), True) | [
"def",
"RootGroupForPath",
"(",
"self",
",",
"path",
")",
":",
"# TODO(mark): make this a class variable and bind to self on call?",
"# Also, this list is nowhere near exhaustive.",
"# INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by",
"# gyp.generator.xcode. There should probably be ... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/xcodeproj_file.py#L2838-L2873 | |
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/msgmerge.py | python | _POUpdateBuilderWrapper | (env, target=None, source=_null, **kw) | return env._POUpdateBuilder(target, source, **kw) | Wrapper for `POUpdate` builder - make user's life easier | Wrapper for `POUpdate` builder - make user's life easier | [
"Wrapper",
"for",
"POUpdate",
"builder",
"-",
"make",
"user",
"s",
"life",
"easier"
] | def _POUpdateBuilderWrapper(env, target=None, source=_null, **kw):
""" Wrapper for `POUpdate` builder - make user's life easier """
if source is _null:
if 'POTDOMAIN' in kw:
domain = kw['POTDOMAIN']
elif 'POTDOMAIN' in env and env['POTDOMAIN']:
domain = env['POTDOMAIN']
else:
domain = 'messages'
source = [ domain ] # NOTE: Suffix shall be appended automatically
return env._POUpdateBuilder(target, source, **kw) | [
"def",
"_POUpdateBuilderWrapper",
"(",
"env",
",",
"target",
"=",
"None",
",",
"source",
"=",
"_null",
",",
"*",
"*",
"kw",
")",
":",
"if",
"source",
"is",
"_null",
":",
"if",
"'POTDOMAIN'",
"in",
"kw",
":",
"domain",
"=",
"kw",
"[",
"'POTDOMAIN'",
"... | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/msgmerge.py#L56-L66 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/training/supervisor.py | python | SVTimerCheckpointThread.__init__ | (self, sv, sess) | Create a `SVTimerCheckpointThread`.
Args:
sv: A `Supervisor`.
sess: A `Session`. | Create a `SVTimerCheckpointThread`. | [
"Create",
"a",
"SVTimerCheckpointThread",
"."
] | def __init__(self, sv, sess):
"""Create a `SVTimerCheckpointThread`.
Args:
sv: A `Supervisor`.
sess: A `Session`.
"""
super(SVTimerCheckpointThread, self).__init__(sv.coord, sv.save_model_secs)
self._sv = sv
self._sess = sess | [
"def",
"__init__",
"(",
"self",
",",
"sv",
",",
"sess",
")",
":",
"super",
"(",
"SVTimerCheckpointThread",
",",
"self",
")",
".",
"__init__",
"(",
"sv",
".",
"coord",
",",
"sv",
".",
"save_model_secs",
")",
"self",
".",
"_sv",
"=",
"sv",
"self",
".",... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/supervisor.py#L1056-L1065 | ||
robotology/yarp | 3d6e3f258db7755a3c44dd1e62c303cc36c49a8f | extern/thrift/thrift/lib/py/src/server/TNonblockingServer.py | python | TNonblockingServer.stop | (self) | Stop the server.
This method causes the serve() method to return. stop() may be invoked
from within your handler, or from another thread.
After stop() is called, serve() will return but the server will still
be listening on the socket. serve() may then be called again to resume
processing requests. Alternatively, close() may be called after
serve() returns to close the server socket and shutdown all worker
threads. | Stop the server. | [
"Stop",
"the",
"server",
"."
] | def stop(self):
"""Stop the server.
This method causes the serve() method to return. stop() may be invoked
from within your handler, or from another thread.
After stop() is called, serve() will return but the server will still
be listening on the socket. serve() may then be called again to resume
processing requests. Alternatively, close() may be called after
serve() returns to close the server socket and shutdown all worker
threads.
"""
self._stop = True
self.wake_up() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_stop",
"=",
"True",
"self",
".",
"wake_up",
"(",
")"
] | https://github.com/robotology/yarp/blob/3d6e3f258db7755a3c44dd1e62c303cc36c49a8f/extern/thrift/thrift/lib/py/src/server/TNonblockingServer.py#L283-L296 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/ConfigSet.py | python | ConfigSet.append_value | (self, var, val) | Appends a value to the specified config key::
def build(bld):
bld.env.append_value('CFLAGS', ['-O2'])
The value must be a list or a tuple | Appends a value to the specified config key:: | [
"Appends",
"a",
"value",
"to",
"the",
"specified",
"config",
"key",
"::"
] | def append_value(self, var, val):
"""
Appends a value to the specified config key::
def build(bld):
bld.env.append_value('CFLAGS', ['-O2'])
The value must be a list or a tuple
"""
current_value = self._get_list_value_for_modification(var)
if isinstance(val, str): # if there were string everywhere we could optimize this
val = [val]
current_value.extend(val) | [
"def",
"append_value",
"(",
"self",
",",
"var",
",",
"val",
")",
":",
"current_value",
"=",
"self",
".",
"_get_list_value_for_modification",
"(",
"var",
")",
"if",
"isinstance",
"(",
"val",
",",
"str",
")",
":",
"# if there were string everywhere we could optimize... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/ConfigSet.py#L205-L217 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/configure.d/nodedownload.py | python | unpack | (packedfile, parent_path) | Unpacks packedfile into parent_path. Assumes .zip. Returns parent_path | Unpacks packedfile into parent_path. Assumes .zip. Returns parent_path | [
"Unpacks",
"packedfile",
"into",
"parent_path",
".",
"Assumes",
".",
"zip",
".",
"Returns",
"parent_path"
] | def unpack(packedfile, parent_path):
"""Unpacks packedfile into parent_path. Assumes .zip. Returns parent_path"""
if zipfile.is_zipfile(packedfile):
with contextlib.closing(zipfile.ZipFile(packedfile, 'r')) as icuzip:
print ' Extracting zipfile: %s' % packedfile
icuzip.extractall(parent_path)
return parent_path
elif tarfile.is_tarfile(packedfile):
with contextlib.closing(tarfile.TarFile.open(packedfile, 'r')) as icuzip:
print ' Extracting tarfile: %s' % packedfile
icuzip.extractall(parent_path)
return parent_path
else:
packedsuffix = packedfile.lower().split('.')[-1] # .zip, .tgz etc
raise Exception('Error: Don\'t know how to unpack %s with extension %s' % (packedfile, packedsuffix)) | [
"def",
"unpack",
"(",
"packedfile",
",",
"parent_path",
")",
":",
"if",
"zipfile",
".",
"is_zipfile",
"(",
"packedfile",
")",
":",
"with",
"contextlib",
".",
"closing",
"(",
"zipfile",
".",
"ZipFile",
"(",
"packedfile",
",",
"'r'",
")",
")",
"as",
"icuzi... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/configure.d/nodedownload.py#L55-L69 | ||
wujixiu/helmet-detection | 8eff5c59ddfba5a29e0b76aeb48babcb49246178 | hardhat-wearing-detection/SSD-RPA/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/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/tools/extra/extract_seconds.py#L31-L41 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/io/idl.py | python | _read_string_data | (f) | return string_data | Read a data string (length is specified twice) | Read a data string (length is specified twice) | [
"Read",
"a",
"data",
"string",
"(",
"length",
"is",
"specified",
"twice",
")"
] | def _read_string_data(f):
'''Read a data string (length is specified twice)'''
length = _read_long(f)
if length > 0:
length = _read_long(f)
string_data = _read_bytes(f, length)
_align_32(f)
else:
string_data = ''
return string_data | [
"def",
"_read_string_data",
"(",
"f",
")",
":",
"length",
"=",
"_read_long",
"(",
"f",
")",
"if",
"length",
">",
"0",
":",
"length",
"=",
"_read_long",
"(",
"f",
")",
"string_data",
"=",
"_read_bytes",
"(",
"f",
",",
"length",
")",
"_align_32",
"(",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/io/idl.py#L171-L180 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/posixpath.py | python | islink | (path) | return stat.S_ISLNK(st.st_mode) | Test whether a path is a symbolic link | Test whether a path is a symbolic link | [
"Test",
"whether",
"a",
"path",
"is",
"a",
"symbolic",
"link"
] | def islink(path):
"""Test whether a path is a symbolic link"""
try:
st = os.lstat(path)
except (os.error, AttributeError):
return False
return stat.S_ISLNK(st.st_mode) | [
"def",
"islink",
"(",
"path",
")",
":",
"try",
":",
"st",
"=",
"os",
".",
"lstat",
"(",
"path",
")",
"except",
"(",
"os",
".",
"error",
",",
"AttributeError",
")",
":",
"return",
"False",
"return",
"stat",
".",
"S_ISLNK",
"(",
"st",
".",
"st_mode",... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/posixpath.py#L139-L145 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/pydoc.py | python | HTMLDoc.docother | (self, object, name=None, mod=None, *ignored) | return lhs + self.repr(object) | Produce HTML documentation for a data object. | Produce HTML documentation for a data object. | [
"Produce",
"HTML",
"documentation",
"for",
"a",
"data",
"object",
"."
] | def docother(self, object, name=None, mod=None, *ignored):
"""Produce HTML documentation for a data object."""
lhs = name and '<strong>%s</strong> = ' % name or ''
return lhs + self.repr(object) | [
"def",
"docother",
"(",
"self",
",",
"object",
",",
"name",
"=",
"None",
",",
"mod",
"=",
"None",
",",
"*",
"ignored",
")",
":",
"lhs",
"=",
"name",
"and",
"'<strong>%s</strong> = '",
"%",
"name",
"or",
"''",
"return",
"lhs",
"+",
"self",
".",
"repr"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pydoc.py#L1013-L1016 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd.py | python | _flip_vector_to_matrix | (vec, batch_shape, static_batch_shape) | Flip dims to reshape batch vector `x` to a matrix with given batch shape.
```python
vec = tf.random_normal(2, 3, 4, 5)
# Flip the leading dimension to the end.
_flip_vector_to_matrix(vec, [3, 4], [3, 4]) # Shape [3, 4, 5, 2]
# Flip nothing, just extend with a singleton dimension.
_flip_vector_to_matrix(vec, [2, 3, 4], [2, 3, 4]) # Shape [2, 3, 4, 5, 1]
# Flip leading dimension to the end and reshape the batch indices to
# batch_shape.
_flip_vector_to_matrix(vec, [4, 3], [4, 3]) # Shape [4, 3, 5, 2]
```
Suppose `batch_shape` is length `n`. Then...
Given `vec.shape = [M1,...,Mm] + [N1,...,Nn] + [k]`, for some
`m > 0` we reshape to a batch matrix with shape `batch_shape + [k, M]`
where `M = M1*...*Mm`. This is done by "flipping" the leading dimensions to
the end and possibly reshaping `[N1,...,Nn]` to `batch_shape`.
In the case `vec.shape = [N1,...,Nn] + [k]`, we reshape to
`batch_shape + [k, 1]` by extending the tensor with a singleton dimension and
possibly reshaping `[N1,...,Nn]` to `batch_shape`.
See also: _flip_matrix_to_vector.
Args:
vec: `Tensor` with shape `[M1,...,Mm] + [N1,...,Nn] + [k]`
batch_shape: `int32` `Tensor`.
static_batch_shape: `TensorShape` with statically determined batch shape.
Returns:
`Tensor` with same `dtype` as `vec` and new shape. | Flip dims to reshape batch vector `x` to a matrix with given batch shape. | [
"Flip",
"dims",
"to",
"reshape",
"batch",
"vector",
"x",
"to",
"a",
"matrix",
"with",
"given",
"batch",
"shape",
"."
] | def _flip_vector_to_matrix(vec, batch_shape, static_batch_shape):
"""Flip dims to reshape batch vector `x` to a matrix with given batch shape.
```python
vec = tf.random_normal(2, 3, 4, 5)
# Flip the leading dimension to the end.
_flip_vector_to_matrix(vec, [3, 4], [3, 4]) # Shape [3, 4, 5, 2]
# Flip nothing, just extend with a singleton dimension.
_flip_vector_to_matrix(vec, [2, 3, 4], [2, 3, 4]) # Shape [2, 3, 4, 5, 1]
# Flip leading dimension to the end and reshape the batch indices to
# batch_shape.
_flip_vector_to_matrix(vec, [4, 3], [4, 3]) # Shape [4, 3, 5, 2]
```
Suppose `batch_shape` is length `n`. Then...
Given `vec.shape = [M1,...,Mm] + [N1,...,Nn] + [k]`, for some
`m > 0` we reshape to a batch matrix with shape `batch_shape + [k, M]`
where `M = M1*...*Mm`. This is done by "flipping" the leading dimensions to
the end and possibly reshaping `[N1,...,Nn]` to `batch_shape`.
In the case `vec.shape = [N1,...,Nn] + [k]`, we reshape to
`batch_shape + [k, 1]` by extending the tensor with a singleton dimension and
possibly reshaping `[N1,...,Nn]` to `batch_shape`.
See also: _flip_matrix_to_vector.
Args:
vec: `Tensor` with shape `[M1,...,Mm] + [N1,...,Nn] + [k]`
batch_shape: `int32` `Tensor`.
static_batch_shape: `TensorShape` with statically determined batch shape.
Returns:
`Tensor` with same `dtype` as `vec` and new shape.
"""
vec = ops.convert_to_tensor(vec, name='vec')
if (
vec.get_shape().is_fully_defined()
and static_batch_shape.is_fully_defined()):
return _flip_vector_to_matrix_static(vec, static_batch_shape)
else:
return _flip_vector_to_matrix_dynamic(vec, batch_shape) | [
"def",
"_flip_vector_to_matrix",
"(",
"vec",
",",
"batch_shape",
",",
"static_batch_shape",
")",
":",
"vec",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"vec",
",",
"name",
"=",
"'vec'",
")",
"if",
"(",
"vec",
".",
"get_shape",
"(",
")",
".",
"is_fully_defi... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd.py#L689-L733 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/pytree.py | python | Leaf.post_order | (self) | Return a post-order iterator for the tree. | Return a post-order iterator for the tree. | [
"Return",
"a",
"post",
"-",
"order",
"iterator",
"for",
"the",
"tree",
"."
] | def post_order(self):
"""Return a post-order iterator for the tree."""
yield self | [
"def",
"post_order",
"(",
"self",
")",
":",
"yield",
"self"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/pytree.py#L409-L411 | ||
PaddlePaddle/Anakin | 5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730 | tools/external_converter_v2/parser/tensorflow/freeze.py | python | freeze_graph | (model_folder, output_name) | freeze graph from meta input
:param model_folder:
:param output_name:
:return: | freeze graph from meta input
:param model_folder:
:param output_name:
:return: | [
"freeze",
"graph",
"from",
"meta",
"input",
":",
"param",
"model_folder",
":",
":",
"param",
"output_name",
":",
":",
"return",
":"
] | def freeze_graph(model_folder, output_name):
'''
freeze graph from meta input
:param model_folder:
:param output_name:
:return:
'''
# We retrieve our checkpoint fullpath
checkpoint = tf.train.get_checkpoint_state(model_folder)
input_checkpoint = checkpoint.model_checkpoint_path
# We precise the file fullname of our freezed graph
absolute_model_folder = "/".join(input_checkpoint.split('/')[:-1])
output_graph = absolute_model_folder + "/frozen_model.pb"
# Before exporting our graph, we need to precise what is our output node
# this variables is plural, because you can have multiple output nodes
# freeze之前必须明确哪个是输出结点,也就是我们要得到推论结果的结点
# 输出结点可以看我们模型的定义
# 只有定义了输出结点,freeze才会把得到输出结点所必要的结点都保存下来,或者哪些结点可以丢弃
# 所以,output_node_names必须根据不同的网络进行修改
output_node_names = output_name
# We clear the devices, to allow TensorFlow to control on the loading where it wants operations to be calculated
clear_devices = True
# We import the meta graph and retrive a Saver
saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)
# We retrieve the protobuf graph definition
graph = tf.get_default_graph()
input_graph_def = graph.as_graph_def()
# We start a session and restore the graph weights
# 这边已经将训练好的参数加载进来,也即最后保存的模型是有图,并且图里面已经有参数了,所以才叫做是frozen
# 相当于将参数已经固化在了图当中
with tf.Session() as sess:
saver.restore(sess, input_checkpoint)
#fix batch norm nodes
for node in input_graph_def.node:
if node.op == 'RefSwitch':
node.op = 'Switch'
for index in range(len(node.input)):
if 'moving_' in node.input[index] and 'biased' in node.input[index]:
node.input[index] = node.input[index] + '/read'
elif node.op == 'AssignSub':
node.op = 'Sub'
if 'use_locking' in node.attr: del node.attr['use_locking']
elif node.op == 'AssignAdd':
node.op = 'Add'
if 'use_locking' in node.attr: del node.attr['use_locking']
# We use a built-in TF helper to export variables to constant
output_graph_def = graph_util.convert_variables_to_constants(
sess,
input_graph_def,
output_node_names.split(",") # We split on comma for convenience
)
# Finally we serialize and dump the output graph to the filesystem
with tf.gfile.GFile(output_graph, "wb") as f:
f.write(output_graph_def.SerializeToString())
print("%d ops in the final graph." % len(output_graph_def.node)) | [
"def",
"freeze_graph",
"(",
"model_folder",
",",
"output_name",
")",
":",
"# We retrieve our checkpoint fullpath",
"checkpoint",
"=",
"tf",
".",
"train",
".",
"get_checkpoint_state",
"(",
"model_folder",
")",
"input_checkpoint",
"=",
"checkpoint",
".",
"model_checkpoint... | https://github.com/PaddlePaddle/Anakin/blob/5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730/tools/external_converter_v2/parser/tensorflow/freeze.py#L9-L71 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.RGBAImageSetWidth | (*args, **kwargs) | return _stc.StyledTextCtrl_RGBAImageSetWidth(*args, **kwargs) | RGBAImageSetWidth(self, int width) | RGBAImageSetWidth(self, int width) | [
"RGBAImageSetWidth",
"(",
"self",
"int",
"width",
")"
] | def RGBAImageSetWidth(*args, **kwargs):
"""RGBAImageSetWidth(self, int width)"""
return _stc.StyledTextCtrl_RGBAImageSetWidth(*args, **kwargs) | [
"def",
"RGBAImageSetWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_RGBAImageSetWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L6361-L6363 | |
cielavenir/procon | 81aa949a1313999803eefbb2efebca516a779b7f | hackerrank/hash-length-extension.py | python | md5 | (arg=None) | return new(arg) | Same as new().
For backward compatibility reasons, this is an alternative
name for the new() function. | Same as new(). | [
"Same",
"as",
"new",
"()",
"."
] | def md5(arg=None):
"""Same as new().
For backward compatibility reasons, this is an alternative
name for the new() function.
"""
return new(arg) | [
"def",
"md5",
"(",
"arg",
"=",
"None",
")",
":",
"return",
"new",
"(",
"arg",
")"
] | https://github.com/cielavenir/procon/blob/81aa949a1313999803eefbb2efebca516a779b7f/hackerrank/hash-length-extension.py#L438-L445 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/cpp.py | python | PreProcessor.do_endif | (self, t) | Default handling of a #endif line. | Default handling of a #endif line. | [
"Default",
"handling",
"of",
"a",
"#endif",
"line",
"."
] | def do_endif(self, t):
"""
Default handling of a #endif line.
"""
self.restore() | [
"def",
"do_endif",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"restore",
"(",
")"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/cpp.py#L512-L516 | ||
plumonito/dtslam | 5994bb9cf7a11981b830370db206bceb654c085d | 3rdparty/opencv-git/doc/pattern_tools/svgfig.py | python | SVG.standalone_xml | (self, indent=u" ", newl=u"\n", encoding=u"utf-8") | return u"""\
<?xml version="1.0" encoding="%s" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
""" % encoding + (u"".join(top.__standalone_xml(indent, newl))) | Get an XML representation of the SVG that can be saved/rendered.
indent string used for indenting
newl string used for newlines | Get an XML representation of the SVG that can be saved/rendered. | [
"Get",
"an",
"XML",
"representation",
"of",
"the",
"SVG",
"that",
"can",
"be",
"saved",
"/",
"rendered",
"."
] | def standalone_xml(self, indent=u" ", newl=u"\n", encoding=u"utf-8"):
"""Get an XML representation of the SVG that can be saved/rendered.
indent string used for indenting
newl string used for newlines
"""
if self.t == "svg":
top = self
else:
top = canvas(self)
return u"""\
<?xml version="1.0" encoding="%s" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
""" % encoding + (u"".join(top.__standalone_xml(indent, newl))) | [
"def",
"standalone_xml",
"(",
"self",
",",
"indent",
"=",
"u\" \"",
",",
"newl",
"=",
"u\"\\n\"",
",",
"encoding",
"=",
"u\"utf-8\"",
")",
":",
"if",
"self",
".",
"t",
"==",
"\"svg\"",
":",
"top",
"=",
"self",
"else",
":",
"top",
"=",
"canvas",
"(... | https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/doc/pattern_tools/svgfig.py#L388-L403 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Dbase/StorageUtils.py | python | RDIdToInt | (ID, validate=1) | return res | Returns the integer index for a given RDId
Throws a ValueError on error
>>> RDIdToInt('RDCmpd-000-009-9')
9
>>> RDIdToInt('RDCmpd-009-000-009-8')
9000009
>>> RDIdToInt('RDData_000_009_9')
9
>>> try:
... RDIdToInt('RDCmpd-009-000-109-8')
... except ValueError:
... print('ok')
... else:
... print('failed')
ok
>>> try:
... RDIdToInt('bogus')
... except ValueError:
... print('ok')
... else:
... print('failed')
ok | Returns the integer index for a given RDId
Throws a ValueError on error | [
"Returns",
"the",
"integer",
"index",
"for",
"a",
"given",
"RDId",
"Throws",
"a",
"ValueError",
"on",
"error"
] | def RDIdToInt(ID, validate=1):
""" Returns the integer index for a given RDId
Throws a ValueError on error
>>> RDIdToInt('RDCmpd-000-009-9')
9
>>> RDIdToInt('RDCmpd-009-000-009-8')
9000009
>>> RDIdToInt('RDData_000_009_9')
9
>>> try:
... RDIdToInt('RDCmpd-009-000-109-8')
... except ValueError:
... print('ok')
... else:
... print('failed')
ok
>>> try:
... RDIdToInt('bogus')
... except ValueError:
... print('ok')
... else:
... print('failed')
ok
"""
if validate and not ValidateRDId(ID):
raise ValueError("Bad RD Id")
ID = ID.replace('_', '-')
terms = ID.split('-')[1:-1]
res = 0
factor = 1
terms.reverse()
for term in terms:
res += factor * int(term)
factor *= 1000
return res | [
"def",
"RDIdToInt",
"(",
"ID",
",",
"validate",
"=",
"1",
")",
":",
"if",
"validate",
"and",
"not",
"ValidateRDId",
"(",
"ID",
")",
":",
"raise",
"ValueError",
"(",
"\"Bad RD Id\"",
")",
"ID",
"=",
"ID",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
... | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Dbase/StorageUtils.py#L47-L83 | |
apache/incubator-weex | 5c25f0b59f7ac90703c363e7261f60bd06356dbe | weex_core/tools/cpplint.py | python | NestingState.InNamespaceBody | (self) | return self.stack and isinstance(self.stack[-1], _NamespaceInfo) | Check if we are currently one level inside a namespace body.
Returns:
True if top of the stack is a namespace block, False otherwise. | Check if we are currently one level inside a namespace body. | [
"Check",
"if",
"we",
"are",
"currently",
"one",
"level",
"inside",
"a",
"namespace",
"body",
"."
] | def InNamespaceBody(self):
"""Check if we are currently one level inside a namespace body.
Returns:
True if top of the stack is a namespace block, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _NamespaceInfo) | [
"def",
"InNamespaceBody",
"(",
"self",
")",
":",
"return",
"self",
".",
"stack",
"and",
"isinstance",
"(",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_NamespaceInfo",
")"
] | https://github.com/apache/incubator-weex/blob/5c25f0b59f7ac90703c363e7261f60bd06356dbe/weex_core/tools/cpplint.py#L2441-L2447 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros/roslib/src/roslib/msgs.py | python | is_builtin | (msg_type_name) | return msg_type_name in BUILTIN_TYPES | @param msg_type_name: name of message type
@type msg_type_name: str
@return: True if msg_type_name is a builtin/primitive type
@rtype: bool | [] | def is_builtin(msg_type_name):
"""
@param msg_type_name: name of message type
@type msg_type_name: str
@return: True if msg_type_name is a builtin/primitive type
@rtype: bool
"""
return msg_type_name in BUILTIN_TYPES | [
"def",
"is_builtin",
"(",
"msg_type_name",
")",
":",
"return",
"msg_type_name",
"in",
"BUILTIN_TYPES"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/roslib/src/roslib/msgs.py#L708-L715 | ||
jasperla/openbsd-wip | ecf1bf2548d497b9032213f85844e250b75ae359 | devel/arduino/files/fetch_extra_libs.py | python | Lib.clone | (self) | Clones the lib in the current directory and sets the git HEAD to the
required version | Clones the lib in the current directory and sets the git HEAD to the
required version | [
"Clones",
"the",
"lib",
"in",
"the",
"current",
"directory",
"and",
"sets",
"the",
"git",
"HEAD",
"to",
"the",
"required",
"version"
] | def clone(self):
"""Clones the lib in the current directory and sets the git HEAD to the
required version"""
# Clone the repo itself.
direc = "%s-%s" % (self.repo_name, self.version)
shell([GIT, "clone", self.repo_url(), direc])
# Switch to the right version.
os.chdir(direc)
shell([GIT, "checkout", self.version])
os.chdir("..") | [
"def",
"clone",
"(",
"self",
")",
":",
"# Clone the repo itself.",
"direc",
"=",
"\"%s-%s\"",
"%",
"(",
"self",
".",
"repo_name",
",",
"self",
".",
"version",
")",
"shell",
"(",
"[",
"GIT",
",",
"\"clone\"",
",",
"self",
".",
"repo_url",
"(",
")",
",",... | https://github.com/jasperla/openbsd-wip/blob/ecf1bf2548d497b9032213f85844e250b75ae359/devel/arduino/files/fetch_extra_libs.py#L44-L55 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/handler.py | python | ContentHandler.startElementNS | (self, name, qname, attrs) | Signals the start of an element in namespace mode.
The name parameter contains the name of the element type as a
(uri, localname) tuple, the qname parameter the raw XML 1.0
name used in the source document, and the attrs parameter
holds an instance of the Attributes class containing the
attributes of the element.
The uri part of the name tuple is None for elements which have
no namespace. | Signals the start of an element in namespace mode. | [
"Signals",
"the",
"start",
"of",
"an",
"element",
"in",
"namespace",
"mode",
"."
] | def startElementNS(self, name, qname, attrs):
"""Signals the start of an element in namespace mode.
The name parameter contains the name of the element type as a
(uri, localname) tuple, the qname parameter the raw XML 1.0
name used in the source document, and the attrs parameter
holds an instance of the Attributes class containing the
attributes of the element.
The uri part of the name tuple is None for elements which have
no namespace.""" | [
"def",
"startElementNS",
"(",
"self",
",",
"name",
",",
"qname",
",",
"attrs",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/sax/handler.py#L140-L150 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rosmaster/src/rosmaster/registrations.py | python | Registrations.get_service_api | (self, service) | return None | Lookup service API URI. NOTE: this should only be valid if type==SERVICE as
service Registrations instances are the only ones that track service API URIs.
@param service: service name
@type service: str
@return str: service_api for registered key or None if
registration is no longer valid.
@type: str | Lookup service API URI. NOTE: this should only be valid if type==SERVICE as
service Registrations instances are the only ones that track service API URIs. | [
"Lookup",
"service",
"API",
"URI",
".",
"NOTE",
":",
"this",
"should",
"only",
"be",
"valid",
"if",
"type",
"==",
"SERVICE",
"as",
"service",
"Registrations",
"instances",
"are",
"the",
"only",
"ones",
"that",
"track",
"service",
"API",
"URIs",
"."
] | def get_service_api(self, service):
"""
Lookup service API URI. NOTE: this should only be valid if type==SERVICE as
service Registrations instances are the only ones that track service API URIs.
@param service: service name
@type service: str
@return str: service_api for registered key or None if
registration is no longer valid.
@type: str
"""
if self.service_api_map and service in self.service_api_map:
caller_id, service_api = self.service_api_map[service]
return service_api
return None | [
"def",
"get_service_api",
"(",
"self",
",",
"service",
")",
":",
"if",
"self",
".",
"service_api_map",
"and",
"service",
"in",
"self",
".",
"service_api_map",
":",
"caller_id",
",",
"service_api",
"=",
"self",
".",
"service_api_map",
"[",
"service",
"]",
"re... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosmaster/src/rosmaster/registrations.py#L185-L198 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBValue.IsRuntimeSupportValue | (self) | return _lldb.SBValue_IsRuntimeSupportValue(self) | IsRuntimeSupportValue(SBValue self) -> bool | IsRuntimeSupportValue(SBValue self) -> bool | [
"IsRuntimeSupportValue",
"(",
"SBValue",
"self",
")",
"-",
">",
"bool"
] | def IsRuntimeSupportValue(self):
"""IsRuntimeSupportValue(SBValue self) -> bool"""
return _lldb.SBValue_IsRuntimeSupportValue(self) | [
"def",
"IsRuntimeSupportValue",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBValue_IsRuntimeSupportValue",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L14526-L14528 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/common.py | python | CopyTool | (flavor, out_path, generator_flags={}) | Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it
to |out_path|. | Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it
to |out_path|. | [
"Finds",
"(",
"flock|mac|win",
")",
"_tool",
".",
"gyp",
"in",
"the",
"gyp",
"directory",
"and",
"copies",
"it",
"to",
"|out_path|",
"."
] | def CopyTool(flavor, out_path, generator_flags={}):
"""Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it
to |out_path|."""
# aix and solaris just need flock emulation. mac and win use more complicated
# support scripts.
prefix = {
'aix': 'flock',
'solaris': 'flock',
'mac': 'mac',
'win': 'win'
}.get(flavor, None)
if not prefix:
return
# Slurp input file.
source_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), '%s_tool.py' % prefix)
with open(source_path) as source_file:
source = source_file.readlines()
# Set custom header flags.
header = '# Generated by gyp. Do not edit.\n'
mac_toolchain_dir = generator_flags.get('mac_toolchain_dir', None)
if flavor == 'mac' and mac_toolchain_dir:
header += "import os;\nos.environ['DEVELOPER_DIR']='%s'\n" \
% mac_toolchain_dir
# Add header and write it out.
tool_path = os.path.join(out_path, 'gyp-%s-tool' % prefix)
with open(tool_path, 'w') as tool_file:
tool_file.write(
''.join([source[0], header] + source[1:]))
# Make file executable.
os.chmod(tool_path, 0o755) | [
"def",
"CopyTool",
"(",
"flavor",
",",
"out_path",
",",
"generator_flags",
"=",
"{",
"}",
")",
":",
"# aix and solaris just need flock emulation. mac and win use more complicated",
"# support scripts.",
"prefix",
"=",
"{",
"'aix'",
":",
"'flock'",
",",
"'solaris'",
":",... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/common.py#L451-L485 | ||
syoyo/tinygltf | e7f1ff5c59d3ca2489923beb239bdf93d863498f | deps/cpplint.py | python | FindCheckMacro | (line) | return (None, -1) | Find a replaceable CHECK-like macro.
Args:
line: line to search on.
Returns:
(macro name, start position), or (None, -1) if no replaceable
macro is found. | Find a replaceable CHECK-like macro. | [
"Find",
"a",
"replaceable",
"CHECK",
"-",
"like",
"macro",
"."
] | def FindCheckMacro(line):
"""Find a replaceable CHECK-like macro.
Args:
line: line to search on.
Returns:
(macro name, start position), or (None, -1) if no replaceable
macro is found.
"""
for macro in _CHECK_MACROS:
i = line.find(macro)
if i >= 0:
# Find opening parenthesis. Do a regular expression match here
# to make sure that we are matching the expected CHECK macro, as
# opposed to some other macro that happens to contain the CHECK
# substring.
matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
if not matched:
continue
return (macro, len(matched.group(1)))
return (None, -1) | [
"def",
"FindCheckMacro",
"(",
"line",
")",
":",
"for",
"macro",
"in",
"_CHECK_MACROS",
":",
"i",
"=",
"line",
".",
"find",
"(",
"macro",
")",
"if",
"i",
">=",
"0",
":",
"# Find opening parenthesis. Do a regular expression match here",
"# to make sure that we are ma... | https://github.com/syoyo/tinygltf/blob/e7f1ff5c59d3ca2489923beb239bdf93d863498f/deps/cpplint.py#L4178-L4198 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | samples/ide/activegrid/util/datetimeparser.py | python | parse | (datestr, formatstr=None, asdate=False, astime=False) | return rtn | Instantiates and returns a datetime instance from the datestr datetime
representation.
Optionally, a format string may be used. The format is only loosely
interpreted, its only purpose beeing to determine if the year is first
or last in datestr, and whether the day is in front or follows the
month. If no formatstr is passed in, dateutil tries its best to parse
the datestr. The default date format is YYYY-mm-dd HH:SS.
If asdate is True, returns a date instance instead of a datetime
instance, if astime is True, returns a time instance instead of a
datetime instance. | Instantiates and returns a datetime instance from the datestr datetime
representation.
Optionally, a format string may be used. The format is only loosely
interpreted, its only purpose beeing to determine if the year is first
or last in datestr, and whether the day is in front or follows the
month. If no formatstr is passed in, dateutil tries its best to parse
the datestr. The default date format is YYYY-mm-dd HH:SS.
If asdate is True, returns a date instance instead of a datetime
instance, if astime is True, returns a time instance instead of a
datetime instance. | [
"Instantiates",
"and",
"returns",
"a",
"datetime",
"instance",
"from",
"the",
"datestr",
"datetime",
"representation",
".",
"Optionally",
"a",
"format",
"string",
"may",
"be",
"used",
".",
"The",
"format",
"is",
"only",
"loosely",
"interpreted",
"its",
"only",
... | def parse(datestr, formatstr=None, asdate=False, astime=False):
"""Instantiates and returns a datetime instance from the datestr datetime
representation.
Optionally, a format string may be used. The format is only loosely
interpreted, its only purpose beeing to determine if the year is first
or last in datestr, and whether the day is in front or follows the
month. If no formatstr is passed in, dateutil tries its best to parse
the datestr. The default date format is YYYY-mm-dd HH:SS.
If asdate is True, returns a date instance instead of a datetime
instance, if astime is True, returns a time instance instead of a
datetime instance."""
dayfirst, yearfirst = _getDayFirstAndYearFirst(formatstr)
rtn = None
try:
if DATEUTIL_INSTALLED:
rtn = dateutil.parser.parse(str(datestr), fuzzy=True,
dayfirst=dayfirst, yearfirst=yearfirst,
default=DEFAULT_DATETIME)
else:
rtn = DEFAULT_DATETIME
except:
rtn = DEFAULT_DATETIME
if (asdate and isinstance(rtn, datetime.datetime)):
rtn = datetime.date(rtn.year, rtn.month, rtn.day)
elif (astime and isinstance(rtn, datetime.datetime)):
rtn = datetime.time(rtn.hour, rtn.minute, rtn.second, rtn.microsecond)
return rtn | [
"def",
"parse",
"(",
"datestr",
",",
"formatstr",
"=",
"None",
",",
"asdate",
"=",
"False",
",",
"astime",
"=",
"False",
")",
":",
"dayfirst",
",",
"yearfirst",
"=",
"_getDayFirstAndYearFirst",
"(",
"formatstr",
")",
"rtn",
"=",
"None",
"try",
":",
"if",... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/ide/activegrid/util/datetimeparser.py#L41-L75 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/multi_process_runner.py | python | MultiProcessPoolRunner.run | (self, fn, args=None, kwargs=None) | return return_values | Runs `fn` with `args` and `kwargs` on all jobs.
Args:
fn: The function to be run.
args: Optional positional arguments to be supplied in `fn`.
kwargs: Optional keyword arguments to be supplied in `fn`.
Returns:
A list of return values. | Runs `fn` with `args` and `kwargs` on all jobs. | [
"Runs",
"fn",
"with",
"args",
"and",
"kwargs",
"on",
"all",
"jobs",
"."
] | def run(self, fn, args=None, kwargs=None):
"""Runs `fn` with `args` and `kwargs` on all jobs.
Args:
fn: The function to be run.
args: Optional positional arguments to be supplied in `fn`.
kwargs: Optional keyword arguments to be supplied in `fn`.
Returns:
A list of return values.
"""
_check_initialization()
# TODO(b/150264776): skip in OSS until it's implemented.
multi_process_lib.Process()
if self._runner is None:
self._start()
fn = dill.dumps(fn, dill.HIGHEST_PROTOCOL)
for conn in self._conn.values():
conn.send((fn, args or [], kwargs or {}))
process_statuses = []
for (task_type, task_id), conn in self._conn.items():
logging.info('Waiting for the result from %s-%d', task_type, task_id)
try:
process_statuses.append(conn.recv())
except EOFError:
# This shouldn't happen due to exceptions in fn. This usually
# means bugs in the runner.
self.shutdown()
raise RuntimeError('Unexpected EOF. Worker process may have died. '
'Please report a bug')
return_values = []
for process_status in process_statuses:
assert isinstance(process_status, _ProcessStatusInfo)
if not process_status.is_successful:
six.reraise(*process_status.exc_info)
if process_status.return_value is not None:
return_values.append(process_status.return_value)
return return_values | [
"def",
"run",
"(",
"self",
",",
"fn",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"_check_initialization",
"(",
")",
"# TODO(b/150264776): skip in OSS until it's implemented.",
"multi_process_lib",
".",
"Process",
"(",
")",
"if",
"self",
".",... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/multi_process_runner.py#L967-L1008 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/fields.py | python | guess_content_type | (filename, default="application/octet-stream") | return default | Guess the "Content-Type" of a file.
:param filename:
The filename to guess the "Content-Type" of using :mod:`mimetypes`.
:param default:
If no "Content-Type" can be guessed, default to `default`. | Guess the "Content-Type" of a file. | [
"Guess",
"the",
"Content",
"-",
"Type",
"of",
"a",
"file",
"."
] | def guess_content_type(filename, default="application/octet-stream"):
"""
Guess the "Content-Type" of a file.
:param filename:
The filename to guess the "Content-Type" of using :mod:`mimetypes`.
:param default:
If no "Content-Type" can be guessed, default to `default`.
"""
if filename:
return mimetypes.guess_type(filename)[0] or default
return default | [
"def",
"guess_content_type",
"(",
"filename",
",",
"default",
"=",
"\"application/octet-stream\"",
")",
":",
"if",
"filename",
":",
"return",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"[",
"0",
"]",
"or",
"default",
"return",
"default"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/fields.py#L10-L21 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/locale.py | python | _build_localename | (localetuple) | Builds a locale code from the given tuple (language code,
encoding).
No aliasing or normalizing takes place. | Builds a locale code from the given tuple (language code,
encoding). | [
"Builds",
"a",
"locale",
"code",
"from",
"the",
"given",
"tuple",
"(",
"language",
"code",
"encoding",
")",
"."
] | def _build_localename(localetuple):
""" Builds a locale code from the given tuple (language code,
encoding).
No aliasing or normalizing takes place.
"""
language, encoding = localetuple
if language is None:
language = 'C'
if encoding is None:
return language
else:
return language + '.' + encoding | [
"def",
"_build_localename",
"(",
"localetuple",
")",
":",
"language",
",",
"encoding",
"=",
"localetuple",
"if",
"language",
"is",
"None",
":",
"language",
"=",
"'C'",
"if",
"encoding",
"is",
"None",
":",
"return",
"language",
"else",
":",
"return",
"languag... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/locale.py#L445-L459 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/fourwaysplitter.py | python | FourWaySplitterEvent.GetSashIdx | (self) | return self.sashIdx | Returns the index of the sash currently involved in the event. | Returns the index of the sash currently involved in the event. | [
"Returns",
"the",
"index",
"of",
"the",
"sash",
"currently",
"involved",
"in",
"the",
"event",
"."
] | def GetSashIdx(self):
""" Returns the index of the sash currently involved in the event. """
return self.sashIdx | [
"def",
"GetSashIdx",
"(",
"self",
")",
":",
"return",
"self",
".",
"sashIdx"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/fourwaysplitter.py#L230-L233 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/syntax/synextreg.py | python | ExtensionRegister.Remove | (self, ftype) | return False | Remove a filetype from the register
@param ftype: File type description string
@return: bool removed or not | Remove a filetype from the register
@param ftype: File type description string
@return: bool removed or not | [
"Remove",
"a",
"filetype",
"from",
"the",
"register",
"@param",
"ftype",
":",
"File",
"type",
"description",
"string",
"@return",
":",
"bool",
"removed",
"or",
"not"
] | def Remove(self, ftype):
"""Remove a filetype from the register
@param ftype: File type description string
@return: bool removed or not
"""
if ftype in self:
del self[ftype]
return True
return False | [
"def",
"Remove",
"(",
"self",
",",
"ftype",
")",
":",
"if",
"ftype",
"in",
"self",
":",
"del",
"self",
"[",
"ftype",
"]",
"return",
"True",
"return",
"False"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/synextreg.py#L554-L563 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Compiler/ExprNodes.py | python | ExprNode.make_owned_memoryviewslice | (self, code) | Make sure we own the reference to this memoryview slice. | Make sure we own the reference to this memoryview slice. | [
"Make",
"sure",
"we",
"own",
"the",
"reference",
"to",
"this",
"memoryview",
"slice",
"."
] | def make_owned_memoryviewslice(self, code):
"""
Make sure we own the reference to this memoryview slice.
"""
if not self.result_in_temp():
code.put_incref_memoryviewslice(self.result(),
have_gil=self.in_nogil_context) | [
"def",
"make_owned_memoryviewslice",
"(",
"self",
",",
"code",
")",
":",
"if",
"not",
"self",
".",
"result_in_temp",
"(",
")",
":",
"code",
".",
"put_incref_memoryviewslice",
"(",
"self",
".",
"result",
"(",
")",
",",
"have_gil",
"=",
"self",
".",
"in_nogi... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/ExprNodes.py#L755-L761 | ||
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/third_party/Python/module/pexpect-4.6/pexpect/utils.py | python | is_executable_file | (path) | return os.access(fpath, os.X_OK) | Checks that path is an executable regular file, or a symlink towards one.
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. | Checks that path is an executable regular file, or a symlink towards one. | [
"Checks",
"that",
"path",
"is",
"an",
"executable",
"regular",
"file",
"or",
"a",
"symlink",
"towards",
"one",
"."
] | def is_executable_file(path):
"""Checks that path is an executable regular file, or a symlink towards one.
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``.
"""
# follow symlinks,
fpath = os.path.realpath(path)
if not os.path.isfile(fpath):
# non-files (directories, fifo, etc.)
return False
mode = os.stat(fpath).st_mode
if (sys.platform.startswith('sunos')
and os.getuid() == 0):
# When root on Solaris, os.X_OK is True for *all* files, irregardless
# of their executability -- instead, any permission bit of any user,
# group, or other is fine enough.
#
# (This may be true for other "Unix98" OS's such as HP-UX and AIX)
return bool(mode & (stat.S_IXUSR |
stat.S_IXGRP |
stat.S_IXOTH))
return os.access(fpath, os.X_OK) | [
"def",
"is_executable_file",
"(",
"path",
")",
":",
"# follow symlinks,",
"fpath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"fpath",
")",
":",
"# non-files (directories, fifo, etc.)",
"ret... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/pexpect-4.6/pexpect/utils.py#L20-L45 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FlatMenuBar.DoGiveHelp | (self, hit) | Gives tooltips and help in :class:`StatusBar`.
:param `hit`: the toolbar tool currently hovered by the mouse. | Gives tooltips and help in :class:`StatusBar`. | [
"Gives",
"tooltips",
"and",
"help",
"in",
":",
"class",
":",
"StatusBar",
"."
] | def DoGiveHelp(self, hit):
"""
Gives tooltips and help in :class:`StatusBar`.
:param `hit`: the toolbar tool currently hovered by the mouse.
"""
shortHelp = hit.GetShortHelp()
if shortHelp:
self.SetToolTipString(shortHelp)
self._haveTip = True
longHelp = hit.GetLongHelp()
if not longHelp:
return
topLevel = wx.GetTopLevelParent(self)
if isinstance(topLevel, wx.Frame) and topLevel.GetStatusBar():
statusBar = topLevel.GetStatusBar()
if self._statusTimer and self._statusTimer.IsRunning():
self._statusTimer.Stop()
statusBar.PopStatusText(0)
statusBar.PushStatusText(longHelp, 0)
self._statusTimer = StatusBarTimer(self)
self._statusTimer.Start(_DELAY, wx.TIMER_ONE_SHOT) | [
"def",
"DoGiveHelp",
"(",
"self",
",",
"hit",
")",
":",
"shortHelp",
"=",
"hit",
".",
"GetShortHelp",
"(",
")",
"if",
"shortHelp",
":",
"self",
".",
"SetToolTipString",
"(",
"shortHelp",
")",
"self",
".",
"_haveTip",
"=",
"True",
"longHelp",
"=",
"hit",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L3803-L3830 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | IconLocation.IsOk | (*args, **kwargs) | return _gdi_.IconLocation_IsOk(*args, **kwargs) | IsOk(self) -> bool | IsOk(self) -> bool | [
"IsOk",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsOk(*args, **kwargs):
"""IsOk(self) -> bool"""
return _gdi_.IconLocation_IsOk(*args, **kwargs) | [
"def",
"IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"IconLocation_IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L1396-L1398 | |
JoseExposito/touchegg | 1f3fda214358d071c05da4bf17c070c33d67b5eb | cmake/cpplint.py | python | Search | (pattern, s) | return _regexp_compile_cache[pattern].search(s) | Searches the string for the pattern, caching the compiled regexp. | Searches the string for the pattern, caching the compiled regexp. | [
"Searches",
"the",
"string",
"for",
"the",
"pattern",
"caching",
"the",
"compiled",
"regexp",
"."
] | def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s) | [
"def",
"Search",
"(",
"pattern",
",",
"s",
")",
":",
"if",
"pattern",
"not",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_cache",
"[",
"pat... | https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L685-L689 | |
microsoft/ELL | a1d6bacc37a14879cc025d9be2ba40b1a0632315 | tools/importers/darknet/darknet_to_ell.py | python | create_layer_parameters | (inputShape, inputPadding, inputPaddingScheme, outputShape, outputPadding,
outputPaddingScheme) | return ell.neural.LayerParameters(inputShape, inputPaddingParameters, outputShape, outputPaddingParameters,
ell.nodes.PortType.smallReal) | Helper function to return ell.neural.LayerParameters given input and output shapes/padding/paddingScheme | Helper function to return ell.neural.LayerParameters given input and output shapes/padding/paddingScheme | [
"Helper",
"function",
"to",
"return",
"ell",
".",
"neural",
".",
"LayerParameters",
"given",
"input",
"and",
"output",
"shapes",
"/",
"padding",
"/",
"paddingScheme"
] | def create_layer_parameters(inputShape, inputPadding, inputPaddingScheme, outputShape, outputPadding,
outputPaddingScheme):
"""Helper function to return ell.neural.LayerParameters given input and output shapes/padding/paddingScheme"""
inputPaddingParameters = ell.neural.PaddingParameters(inputPaddingScheme, inputPadding)
outputPaddingParameters = ell.neural.PaddingParameters(outputPaddingScheme, outputPadding)
return ell.neural.LayerParameters(inputShape, inputPaddingParameters, outputShape, outputPaddingParameters,
ell.nodes.PortType.smallReal) | [
"def",
"create_layer_parameters",
"(",
"inputShape",
",",
"inputPadding",
",",
"inputPaddingScheme",
",",
"outputShape",
",",
"outputPadding",
",",
"outputPaddingScheme",
")",
":",
"inputPaddingParameters",
"=",
"ell",
".",
"neural",
".",
"PaddingParameters",
"(",
"in... | https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/darknet/darknet_to_ell.py#L214-L221 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/distutils/dep_util.py | python | newer | (source, target) | return mtime1 > mtime2 | Return true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't. Return false if
both exist and 'target' is the same age or younger than 'source'.
Raise DistutilsFileError if 'source' does not exist. | Return true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't. Return false if
both exist and 'target' is the same age or younger than 'source'.
Raise DistutilsFileError if 'source' does not exist. | [
"Return",
"true",
"if",
"source",
"exists",
"and",
"is",
"more",
"recently",
"modified",
"than",
"target",
"or",
"if",
"source",
"exists",
"and",
"target",
"doesn",
"t",
".",
"Return",
"false",
"if",
"both",
"exist",
"and",
"target",
"is",
"the",
"same",
... | def newer (source, target):
"""Return true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't. Return false if
both exist and 'target' is the same age or younger than 'source'.
Raise DistutilsFileError if 'source' does not exist.
"""
if not os.path.exists(source):
raise DistutilsFileError("file '%s' does not exist" %
os.path.abspath(source))
if not os.path.exists(target):
return 1
from stat import ST_MTIME
mtime1 = os.stat(source)[ST_MTIME]
mtime2 = os.stat(target)[ST_MTIME]
return mtime1 > mtime2 | [
"def",
"newer",
"(",
"source",
",",
"target",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"source",
")",
":",
"raise",
"DistutilsFileError",
"(",
"\"file '%s' does not exist\"",
"%",
"os",
".",
"path",
".",
"abspath",
"(",
"source",
")"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/dep_util.py#L11-L27 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py | python | Babyl.__setitem__ | (self, key, message) | Replace the keyed message; raise KeyError if it doesn't exist. | Replace the keyed message; raise KeyError if it doesn't exist. | [
"Replace",
"the",
"keyed",
"message",
";",
"raise",
"KeyError",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | def __setitem__(self, key, message):
"""Replace the keyed message; raise KeyError if it doesn't exist."""
_singlefileMailbox.__setitem__(self, key, message)
if isinstance(message, BabylMessage):
self._labels[key] = message.get_labels() | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"message",
")",
":",
"_singlefileMailbox",
".",
"__setitem__",
"(",
"self",
",",
"key",
",",
"message",
")",
"if",
"isinstance",
"(",
"message",
",",
"BabylMessage",
")",
":",
"self",
".",
"_labels",
"[... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py#L1261-L1265 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlNode.addContentLen | (self, content, len) | Append the extra substring to the node content. NOTE: In
contrast to xmlNodeSetContentLen(), @content is supposed to
be raw text, so unescaped XML special chars are allowed,
entity references are not supported. | Append the extra substring to the node content. NOTE: In
contrast to xmlNodeSetContentLen(), | [
"Append",
"the",
"extra",
"substring",
"to",
"the",
"node",
"content",
".",
"NOTE",
":",
"In",
"contrast",
"to",
"xmlNodeSetContentLen",
"()"
] | def addContentLen(self, content, len):
"""Append the extra substring to the node content. NOTE: In
contrast to xmlNodeSetContentLen(), @content is supposed to
be raw text, so unescaped XML special chars are allowed,
entity references are not supported. """
libxml2mod.xmlNodeAddContentLen(self._o, content, len) | [
"def",
"addContentLen",
"(",
"self",
",",
"content",
",",
"len",
")",
":",
"libxml2mod",
".",
"xmlNodeAddContentLen",
"(",
"self",
".",
"_o",
",",
"content",
",",
"len",
")"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L3058-L3063 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/training/python/training/sampling_ops.py | python | _make_per_class_queues | (tensor_list, labels, num_classes, queue_capacity,
threads_per_queue) | return queues | Creates per-class-queues based on data and labels. | Creates per-class-queues based on data and labels. | [
"Creates",
"per",
"-",
"class",
"-",
"queues",
"based",
"on",
"data",
"and",
"labels",
"."
] | def _make_per_class_queues(tensor_list, labels, num_classes, queue_capacity,
threads_per_queue):
"""Creates per-class-queues based on data and labels."""
# Create one queue per class.
queues = []
data_shapes = []
data_dtypes = []
for data_tensor in tensor_list:
per_data_shape = data_tensor.get_shape().with_rank_at_least(1)[1:]
per_data_shape.assert_is_fully_defined()
data_shapes.append(per_data_shape)
data_dtypes.append(data_tensor.dtype)
for i in range(num_classes):
q = data_flow_ops.FIFOQueue(capacity=queue_capacity,
shapes=data_shapes, dtypes=data_dtypes,
name='stratified_sample_class%d_queue' % i)
logging_ops.scalar_summary(
'queue/%s/stratified_sample_class%d' % (q.name, i), q.size())
queues.append(q)
# Partition tensors according to labels. `partitions` is a list of lists, of
# size num_classes X len(tensor_list). The number of tensors in partition `i`
# should be the same for all tensors.
all_partitions = [data_flow_ops.dynamic_partition(data, labels, num_classes)
for data in tensor_list]
partitions = [[cur_partition[i] for cur_partition in all_partitions] for i in
range(num_classes)]
# Enqueue each tensor on the per-class-queue.
for i in range(num_classes):
enqueue_op = queues[i].enqueue_many(partitions[i]),
queue_runner.add_queue_runner(queue_runner.QueueRunner(
queues[i], [enqueue_op] * threads_per_queue))
return queues | [
"def",
"_make_per_class_queues",
"(",
"tensor_list",
",",
"labels",
",",
"num_classes",
",",
"queue_capacity",
",",
"threads_per_queue",
")",
":",
"# Create one queue per class.",
"queues",
"=",
"[",
"]",
"data_shapes",
"=",
"[",
"]",
"data_dtypes",
"=",
"[",
"]",... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/training/python/training/sampling_ops.py#L429-L464 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/client/session.py | python | SessionInterface.run | (self, fetches, feed_dict=None, options=None, run_metadata=None) | Runs operations in the session. See `BaseSession.run()` for details. | Runs operations in the session. See `BaseSession.run()` for details. | [
"Runs",
"operations",
"in",
"the",
"session",
".",
"See",
"BaseSession",
".",
"run",
"()",
"for",
"details",
"."
] | def run(self, fetches, feed_dict=None, options=None, run_metadata=None):
"""Runs operations in the session. See `BaseSession.run()` for details."""
raise NotImplementedError('run') | [
"def",
"run",
"(",
"self",
",",
"fetches",
",",
"feed_dict",
"=",
"None",
",",
"options",
"=",
"None",
",",
"run_metadata",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'run'",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/client/session.py#L63-L65 | ||
larroy/clearskies_core | 3574ddf0edc8555454c7044126e786a6c29444dc | tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetCflagsObjC | (self, configname) | return cflags_objc | Returns flags that need to be added to .m compilations. | Returns flags that need to be added to .m compilations. | [
"Returns",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
".",
"m",
"compilations",
"."
] | def GetCflagsObjC(self, configname):
"""Returns flags that need to be added to .m compilations."""
self.configname = configname
cflags_objc = []
self._AddObjectiveCGarbageCollectionFlags(cflags_objc)
self._AddObjectiveCARCFlags(cflags_objc)
self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objc)
self.configname = None
return cflags_objc | [
"def",
"GetCflagsObjC",
"(",
"self",
",",
"configname",
")",
":",
"self",
".",
"configname",
"=",
"configname",
"cflags_objc",
"=",
"[",
"]",
"self",
".",
"_AddObjectiveCGarbageCollectionFlags",
"(",
"cflags_objc",
")",
"self",
".",
"_AddObjectiveCARCFlags",
"(",
... | https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/xcode_emulation.py#L493-L501 | |
may0324/DeepCompression-caffe | 0aff6c1287bda4cfc7f378ed8a16524e1afabd8c | scripts/cpp_lint.py | python | GetPreviousNonBlankLine | (clean_lines, linenum) | return ('', -1) | Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line. | Return the most recent non-blank line and its line number. | [
"Return",
"the",
"most",
"recent",
"non",
"-",
"blank",
"line",
"and",
"its",
"line",
"number",
"."
] | def GetPreviousNonBlankLine(clean_lines, linenum):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line.
"""
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline): # if not a blank line...
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1) | [
"def",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"prevlinenum",
"=",
"linenum",
"-",
"1",
"while",
"prevlinenum",
">=",
"0",
":",
"prevline",
"=",
"clean_lines",
".",
"elided",
"[",
"prevlinenum",
"]",
"if",
"not",
"IsBlankLine",... | https://github.com/may0324/DeepCompression-caffe/blob/0aff6c1287bda4cfc7f378ed8a16524e1afabd8c/scripts/cpp_lint.py#L3046-L3066 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus2.in.py | python | exodus.get_side_set_property_names | (self) | return list(names) | ssprop_names = exo.get_side_set_property_names()
-> get the list of side set property names for all side sets in
the model
return value(s):
<list<string>> ssprop_names | ssprop_names = exo.get_side_set_property_names() | [
"ssprop_names",
"=",
"exo",
".",
"get_side_set_property_names",
"()"
] | def get_side_set_property_names(self):
"""
ssprop_names = exo.get_side_set_property_names()
-> get the list of side set property names for all side sets in
the model
return value(s):
<list<string>> ssprop_names
"""
names = []
ssType = ex_entity_type("EX_SIDE_SET")
inqType = "EX_INQ_SS_PROP"
names = self.__ex_get_prop_names(ssType, inqType)
return list(names) | [
"def",
"get_side_set_property_names",
"(",
"self",
")",
":",
"names",
"=",
"[",
"]",
"ssType",
"=",
"ex_entity_type",
"(",
"\"EX_SIDE_SET\"",
")",
"inqType",
"=",
"\"EX_INQ_SS_PROP\"",
"names",
"=",
"self",
".",
"__ex_get_prop_names",
"(",
"ssType",
",",
"inqTyp... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus2.in.py#L3026-L3040 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | Contrib/AtomAtomSimilarity/AtomAtomPathSimilarity.py | python | getpathintegers | (m1, uptolength=7) | return pathintegers | returns a list of integers describing the paths for molecule m1. This uses numpy 16 bit unsigned integers to reproduce the data in the Gobbi paper. The returned list is sorted | returns a list of integers describing the paths for molecule m1. This uses numpy 16 bit unsigned integers to reproduce the data in the Gobbi paper. The returned list is sorted | [
"returns",
"a",
"list",
"of",
"integers",
"describing",
"the",
"paths",
"for",
"molecule",
"m1",
".",
"This",
"uses",
"numpy",
"16",
"bit",
"unsigned",
"integers",
"to",
"reproduce",
"the",
"data",
"in",
"the",
"Gobbi",
"paper",
".",
"The",
"returned",
"li... | def getpathintegers(m1, uptolength=7):
'''returns a list of integers describing the paths for molecule m1. This uses numpy 16 bit unsigned integers to reproduce the data in the Gobbi paper. The returned list is sorted'''
bondtypelookup = {}
for b in m1.GetBonds():
bondtypelookup[b.GetIdx()] = _BK_[b.GetBondType()], b.GetBeginAtom(), b.GetEndAtom()
pathintegers = {}
for a in m1.GetAtoms():
idx = a.GetIdx()
pathintegers[idx] = []
# for pathlength in range(1, uptolength+1):
# for path in rdmolops.FindAllPathsOfLengthN(m1, pathlength, rootedAtAtom=idx):
for ipath, path in enumerate(
FindAllPathsOfLengthMToN_Gobbi(m1, 1, uptolength, rootedAtAtom=idx, uniquepaths=False)):
strpath = []
currentidx = idx
res = []
for ip, p in enumerate(path):
bk, a1, a2 = bondtypelookup[p]
strpath.append(_BONDSYMBOL_[bk])
if a1.GetIdx() == currentidx:
a = a2
else:
a = a1
ak = a.GetAtomicNum()
if a.GetIsAromatic():
ak += 108
#trying to get the same behaviour as the Gobbi test code - it looks like a circular path includes the bond, but not the closure atom - this fix works
if a.GetIdx() == idx:
ak = None
if ak is not None:
astr = a.GetSymbol()
if a.GetIsAromatic():
strpath.append(astr.lower())
else:
strpath.append(astr)
res.append((bk, ak))
currentidx = a.GetIdx()
pathuniqueint = numpy.ushort(0) # work with 16 bit unsigned integers and ignore overflow...
for ires, (bi, ai) in enumerate(res):
#use 16 bit unsigned integer arithmetic to reproduce the Gobbi ints
# pathuniqueint = ((pathuniqueint+bi)*_nAT_+ai)*_nBT_
val1 = pathuniqueint + numpy.ushort(bi)
val2 = val1 * numpy.ushort(_nAT_)
#trying to get the same behaviour as the Gobbi test code - it looks like a circular path includes the bond, but not the closure atom - this fix works
if ai is not None:
val3 = val2 + numpy.ushort(ai)
val4 = val3 * numpy.ushort(_nBT_)
else:
val4 = val2
pathuniqueint = val4
pathintegers[idx].append(pathuniqueint)
#sorted lists allow for a quicker comparison algorithm
for p in pathintegers.values():
p.sort()
return pathintegers | [
"def",
"getpathintegers",
"(",
"m1",
",",
"uptolength",
"=",
"7",
")",
":",
"bondtypelookup",
"=",
"{",
"}",
"for",
"b",
"in",
"m1",
".",
"GetBonds",
"(",
")",
":",
"bondtypelookup",
"[",
"b",
".",
"GetIdx",
"(",
")",
"]",
"=",
"_BK_",
"[",
"b",
... | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/Contrib/AtomAtomSimilarity/AtomAtomPathSimilarity.py#L80-L134 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/importOCA.py | python | export | (exportList, filename) | Export the OCA file with a given list of objects.
The objects must be edges or faces, in order to be processed
and exported.
Parameters
----------
exportList : list
List of document objects to export.
filename : str
Path to the new file.
Returns
-------
None
If `exportList` doesn't have shapes to export. | Export the OCA file with a given list of objects. | [
"Export",
"the",
"OCA",
"file",
"with",
"a",
"given",
"list",
"of",
"objects",
"."
] | def export(exportList, filename):
"""Export the OCA file with a given list of objects.
The objects must be edges or faces, in order to be processed
and exported.
Parameters
----------
exportList : list
List of document objects to export.
filename : str
Path to the new file.
Returns
-------
None
If `exportList` doesn't have shapes to export.
"""
faces = []
edges = []
# getting faces and edges
for ob in exportList:
if ob.Shape.Faces:
for f in ob.Shape.Faces:
faces.append(f)
else:
for e in ob.Shape.Edges:
edges.append(e)
if not (edges or faces):
FCC.PrintMessage(translate("importOCA",
"OCA: found no data to export")
+ "\n")
return
# writing file
oca = pythonopen(filename, 'w')
oca.write("#oca file generated from FreeCAD\r\n")
oca.write("# edges\r\n")
count = 1
for e in edges:
if DraftGeomUtils.geomType(e) == "Line":
oca.write("L"+str(count)+"=")
oca.write(writepoint(e.Vertexes[0].Point))
oca.write(" ")
oca.write(writepoint(e.Vertexes[-1].Point))
oca.write("\r\n")
elif DraftGeomUtils.geomType(e) == "Circle":
if len(e.Vertexes) > 1:
oca.write("C"+str(count)+"=ARC ")
oca.write(writepoint(e.Vertexes[0].Point))
oca.write(" ")
oca.write(writepoint(DraftGeomUtils.findMidpoint(e)))
oca.write(" ")
oca.write(writepoint(e.Vertexes[-1].Point))
else:
oca.write("C"+str(count)+"= ")
oca.write(writepoint(e.Curve.Center))
oca.write(" ")
oca.write(str(e.Curve.Radius))
oca.write("\r\n")
count += 1
oca.write("# faces\r\n")
for f in faces:
oca.write("A"+str(count)+"=S(POL")
for v in f.Vertexes:
oca.write(" ")
oca.write(writepoint(v.Point))
oca.write(" ")
oca.write(writepoint(f.Vertexes[0].Point))
oca.write(")\r\n")
count += 1
# closing
oca.close()
FCC.PrintMessage(translate("importOCA",
"successfully exported")
+ " " + filename + "\n") | [
"def",
"export",
"(",
"exportList",
",",
"filename",
")",
":",
"faces",
"=",
"[",
"]",
"edges",
"=",
"[",
"]",
"# getting faces and edges",
"for",
"ob",
"in",
"exportList",
":",
"if",
"ob",
".",
"Shape",
".",
"Faces",
":",
"for",
"f",
"in",
"ob",
"."... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/importOCA.py#L415-L492 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | external/tools/build/v2/build/toolset.py | python | inherit_flags | (toolset, base, prohibited_properties = []) | Brings all flag definitions from the 'base' toolset into the 'toolset'
toolset. Flag definitions whose conditions make use of properties in
'prohibited-properties' are ignored. Don't confuse property and feature, for
example <debug-symbols>on and <debug-symbols>off, so blocking one of them does
not block the other one.
The flag conditions are not altered at all, so if a condition includes a name,
or version of a base toolset, it won't ever match the inheriting toolset. When
such flag settings must be inherited, define a rule in base toolset module and
call it as needed. | Brings all flag definitions from the 'base' toolset into the 'toolset'
toolset. Flag definitions whose conditions make use of properties in
'prohibited-properties' are ignored. Don't confuse property and feature, for
example <debug-symbols>on and <debug-symbols>off, so blocking one of them does
not block the other one.
The flag conditions are not altered at all, so if a condition includes a name,
or version of a base toolset, it won't ever match the inheriting toolset. When
such flag settings must be inherited, define a rule in base toolset module and
call it as needed. | [
"Brings",
"all",
"flag",
"definitions",
"from",
"the",
"base",
"toolset",
"into",
"the",
"toolset",
"toolset",
".",
"Flag",
"definitions",
"whose",
"conditions",
"make",
"use",
"of",
"properties",
"in",
"prohibited",
"-",
"properties",
"are",
"ignored",
".",
"... | def inherit_flags(toolset, base, prohibited_properties = []):
"""Brings all flag definitions from the 'base' toolset into the 'toolset'
toolset. Flag definitions whose conditions make use of properties in
'prohibited-properties' are ignored. Don't confuse property and feature, for
example <debug-symbols>on and <debug-symbols>off, so blocking one of them does
not block the other one.
The flag conditions are not altered at all, so if a condition includes a name,
or version of a base toolset, it won't ever match the inheriting toolset. When
such flag settings must be inherited, define a rule in base toolset module and
call it as needed."""
for f in __module_flags.get(base, []):
if not f.condition or b2.util.set.difference(f.condition, prohibited_properties):
match = __re_first_group.match(f.rule)
rule_ = None
if match:
rule_ = match.group(1)
new_rule_or_module = ''
if rule_:
new_rule_or_module = toolset + '.' + rule_
else:
new_rule_or_module = toolset
__add_flag (new_rule_or_module, f.variable_name, f.condition, f.values) | [
"def",
"inherit_flags",
"(",
"toolset",
",",
"base",
",",
"prohibited_properties",
"=",
"[",
"]",
")",
":",
"for",
"f",
"in",
"__module_flags",
".",
"get",
"(",
"base",
",",
"[",
"]",
")",
":",
"if",
"not",
"f",
".",
"condition",
"or",
"b2",
".",
"... | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/external/tools/build/v2/build/toolset.py#L227-L253 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/nyan/import_tree.py | python | ImportTree.get_import_dict | (self) | return aliases | Get the fqons of the nodes that are used for alias, i.e. fqons of all
nodes in self.alias_nodes. The dict can be used for creating imports
of a nyan file.
Call this function after all object references in a file have been
searched for aliases with get_alias_fqon(). | Get the fqons of the nodes that are used for alias, i.e. fqons of all
nodes in self.alias_nodes. The dict can be used for creating imports
of a nyan file. | [
"Get",
"the",
"fqons",
"of",
"the",
"nodes",
"that",
"are",
"used",
"for",
"alias",
"i",
".",
"e",
".",
"fqons",
"of",
"all",
"nodes",
"in",
"self",
".",
"alias_nodes",
".",
"The",
"dict",
"can",
"be",
"used",
"for",
"creating",
"imports",
"of",
"a",... | def get_import_dict(self):
"""
Get the fqons of the nodes that are used for alias, i.e. fqons of all
nodes in self.alias_nodes. The dict can be used for creating imports
of a nyan file.
Call this function after all object references in a file have been
searched for aliases with get_alias_fqon().
"""
aliases = {}
for current_node in self.alias_nodes:
if current_node.alias in aliases.keys():
raise Exception(f"duplicate alias: {current_node.alias}")
aliases.update({current_node.alias: current_node.get_fqon()})
# Sort by imported name because it looks NICE!
aliases = dict(sorted(aliases.items(), key=lambda item: item[1]))
return aliases | [
"def",
"get_import_dict",
"(",
"self",
")",
":",
"aliases",
"=",
"{",
"}",
"for",
"current_node",
"in",
"self",
".",
"alias_nodes",
":",
"if",
"current_node",
".",
"alias",
"in",
"aliases",
".",
"keys",
"(",
")",
":",
"raise",
"Exception",
"(",
"f\"dupli... | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/nyan/import_tree.py#L152-L171 | |
msftguy/ssh-rd | a5f3a79daeac5844edebf01916c9613563f1c390 | _3rd/boost_1_48_0/tools/build/v2/build/feature.py | python | validate_value_string | (f, value_string) | Checks that value-string is a valid value-string for the given feature. | Checks that value-string is a valid value-string for the given feature. | [
"Checks",
"that",
"value",
"-",
"string",
"is",
"a",
"valid",
"value",
"-",
"string",
"for",
"the",
"given",
"feature",
"."
] | def validate_value_string (f, value_string):
""" Checks that value-string is a valid value-string for the given feature.
"""
if f.free() or value_string in f.values():
return
values = [value_string]
if f.subfeatures():
if not value_string in f.values() and \
not value_string in f.subfeatures():
values = value_string.split('-')
# An empty value is allowed for optional features
if not values[0] in f.values() and \
(values[0] or not f.optional()):
raise InvalidValue ("'%s' is not a known value of feature '%s'\nlegal values: '%s'" % (values [0], feature, f.values()))
for v in values [1:]:
# this will validate any subfeature values in value-string
implied_subfeature(f, v, values[0]) | [
"def",
"validate_value_string",
"(",
"f",
",",
"value_string",
")",
":",
"if",
"f",
".",
"free",
"(",
")",
"or",
"value_string",
"in",
"f",
".",
"values",
"(",
")",
":",
"return",
"values",
"=",
"[",
"value_string",
"]",
"if",
"f",
".",
"subfeatures",
... | https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/feature.py#L429-L449 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/hexfileutils.py | python | _write_hex_to_file | (intelhex, filename) | Write intelhex object to file.
Directories will be created if path does not exist
:param intelhex: IntelHex instance
:param filename: Name/path to write intelhex object to | Write intelhex object to file. | [
"Write",
"intelhex",
"object",
"to",
"file",
"."
] | def _write_hex_to_file(intelhex, filename):
"""
Write intelhex object to file.
Directories will be created if path does not exist
:param intelhex: IntelHex instance
:param filename: Name/path to write intelhex object to
"""
directory = os.path.dirname(filename)
if directory != '' and not os.path.exists(directory):
Path(directory).mkdir(exist_ok=True, parents=True)
intelhex.write_hex_file(filename) | [
"def",
"_write_hex_to_file",
"(",
"intelhex",
",",
"filename",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"if",
"directory",
"!=",
"''",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":... | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/hexfileutils.py#L169-L181 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | Grid.MoveCursorRightBlock | (*args, **kwargs) | return _grid.Grid_MoveCursorRightBlock(*args, **kwargs) | MoveCursorRightBlock(self, bool expandSelection) -> bool | MoveCursorRightBlock(self, bool expandSelection) -> bool | [
"MoveCursorRightBlock",
"(",
"self",
"bool",
"expandSelection",
")",
"-",
">",
"bool"
] | def MoveCursorRightBlock(*args, **kwargs):
"""MoveCursorRightBlock(self, bool expandSelection) -> bool"""
return _grid.Grid_MoveCursorRightBlock(*args, **kwargs) | [
"def",
"MoveCursorRightBlock",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_MoveCursorRightBlock",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L1466-L1468 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/linalg/matfuncs.py | python | inv | (A) | return Ainv | Compute the inverse of a sparse matrix
Parameters
----------
A : (M,M) ndarray or sparse matrix
square matrix to be inverted
Returns
-------
Ainv : (M,M) ndarray or sparse matrix
inverse of `A`
Notes
-----
This computes the sparse inverse of `A`. If the inverse of `A` is expected
to be non-sparse, it will likely be faster to convert `A` to dense and use
scipy.linalg.inv.
Examples
--------
>>> from scipy.sparse import csc_matrix
>>> from scipy.sparse.linalg import inv
>>> A = csc_matrix([[1., 0.], [1., 2.]])
>>> Ainv = inv(A)
>>> Ainv
<2x2 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in Compressed Sparse Column format>
>>> A.dot(Ainv)
<2x2 sparse matrix of type '<class 'numpy.float64'>'
with 2 stored elements in Compressed Sparse Column format>
>>> A.dot(Ainv).todense()
matrix([[ 1., 0.],
[ 0., 1.]])
.. versionadded:: 0.12.0 | Compute the inverse of a sparse matrix | [
"Compute",
"the",
"inverse",
"of",
"a",
"sparse",
"matrix"
] | def inv(A):
"""
Compute the inverse of a sparse matrix
Parameters
----------
A : (M,M) ndarray or sparse matrix
square matrix to be inverted
Returns
-------
Ainv : (M,M) ndarray or sparse matrix
inverse of `A`
Notes
-----
This computes the sparse inverse of `A`. If the inverse of `A` is expected
to be non-sparse, it will likely be faster to convert `A` to dense and use
scipy.linalg.inv.
Examples
--------
>>> from scipy.sparse import csc_matrix
>>> from scipy.sparse.linalg import inv
>>> A = csc_matrix([[1., 0.], [1., 2.]])
>>> Ainv = inv(A)
>>> Ainv
<2x2 sparse matrix of type '<class 'numpy.float64'>'
with 3 stored elements in Compressed Sparse Column format>
>>> A.dot(Ainv)
<2x2 sparse matrix of type '<class 'numpy.float64'>'
with 2 stored elements in Compressed Sparse Column format>
>>> A.dot(Ainv).todense()
matrix([[ 1., 0.],
[ 0., 1.]])
.. versionadded:: 0.12.0
"""
#check input
if not scipy.sparse.isspmatrix(A):
raise TypeError('Input must be a sparse matrix')
I = speye(A.shape[0], A.shape[1], dtype=A.dtype, format=A.format)
Ainv = spsolve(A, I)
return Ainv | [
"def",
"inv",
"(",
"A",
")",
":",
"#check input",
"if",
"not",
"scipy",
".",
"sparse",
".",
"isspmatrix",
"(",
"A",
")",
":",
"raise",
"TypeError",
"(",
"'Input must be a sparse matrix'",
")",
"I",
"=",
"speye",
"(",
"A",
".",
"shape",
"[",
"0",
"]",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/linalg/matfuncs.py#L34-L79 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/Paste/paste/auth/open_id.py | python | AuthOpenIDHandler.page_footer | (self, request, form_contents) | Render the page footer | Render the page footer | [
"Render",
"the",
"page",
"footer"
] | def page_footer(self, request, form_contents):
"""Render the page footer"""
if not form_contents:
form_contents = ''
request['body'].append('''\
<div id="verify-form">
<form method="get" action=%s>
Identity URL:
<input type="text" name="openid_url" value=%s />
<input type="submit" value="Verify" />
</form>
</div>
</body>
</html>
''' % (quoteattr(self.build_url(request, 'verify')), quoteattr(form_contents))) | [
"def",
"page_footer",
"(",
"self",
",",
"request",
",",
"form_contents",
")",
":",
"if",
"not",
"form_contents",
":",
"form_contents",
"=",
"''",
"request",
"[",
"'body'",
"]",
".",
"append",
"(",
"'''\\\n <div id=\"verify-form\">\n <form method=\"get\" action... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/auth/open_id.py#L368-L383 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tensor_tracer.py | python | TensorTracer._process_op_fetches | (self, op_fetches) | return fetches | Check that op_fetches have valid ops. | Check that op_fetches have valid ops. | [
"Check",
"that",
"op_fetches",
"have",
"valid",
"ops",
"."
] | def _process_op_fetches(self, op_fetches):
"""Check that op_fetches have valid ops."""
if op_fetches is None:
return []
if not isinstance(op_fetches, (list, tuple)):
op_fetches = [op_fetches]
fetches = []
for fetch in op_fetches:
if isinstance(fetch, ops.Operation):
fetches.append(fetch)
elif isinstance(fetch, ops.Tensor):
fetches.append(fetch.op)
else:
logging.warning('Ignoring the given op_fetch:%s, which is not an op.' %
fetch)
return fetches | [
"def",
"_process_op_fetches",
"(",
"self",
",",
"op_fetches",
")",
":",
"if",
"op_fetches",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"op_fetches",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"op_fetches",
"=",
"[",
"op_... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tensor_tracer.py#L1136-L1153 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/inspector_protocol/jinja2/utils.py | python | LRUCache.get | (self, key, default=None) | Return an item from the cache dict or `default` | Return an item from the cache dict or `default` | [
"Return",
"an",
"item",
"from",
"the",
"cache",
"dict",
"or",
"default"
] | def get(self, key, default=None):
"""Return an item from the cache dict or `default`"""
try:
return self[key]
except KeyError:
return default | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"return",
"default"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/utils.py#L348-L353 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchRoof.py | python | _Roof.calcAngle | (self, id) | return ang | Get the angle from height and run of the given roof profile | Get the angle from height and run of the given roof profile | [
"Get",
"the",
"angle",
"from",
"height",
"and",
"run",
"of",
"the",
"given",
"roof",
"profile"
] | def calcAngle(self, id):
'''Get the angle from height and run of the given roof profile'''
ang = math.degrees(math.atan(self.profilsDico[id]["height"] / self.profilsDico[id]["run"]))
return ang | [
"def",
"calcAngle",
"(",
"self",
",",
"id",
")",
":",
"ang",
"=",
"math",
".",
"degrees",
"(",
"math",
".",
"atan",
"(",
"self",
".",
"profilsDico",
"[",
"id",
"]",
"[",
"\"height\"",
"]",
"/",
"self",
".",
"profilsDico",
"[",
"id",
"]",
"[",
"\"... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchRoof.py#L335-L338 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py | python | NeuralNetworkBuilder.add_clip | (self, name, input_name, output_name, min_value=0.0, max_value=1.0) | return spec_layer | Add a clip layer to the model that performs element-wise clip operation.
Clip the values in the input tensor to the range [min_value, max_value].
Refer to the **ClipLayerParams** message in specification (NeuralNetwork.proto) for more details.
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of this layer.
min_value: float, optional
Lower bound / minimum value for clip, default: 0.0.
max_value: float, optional
Upper bound / maximum value for clip, default: 1.0.
See Also
--------
add_floor, add_ceil | Add a clip layer to the model that performs element-wise clip operation.
Clip the values in the input tensor to the range [min_value, max_value].
Refer to the **ClipLayerParams** message in specification (NeuralNetwork.proto) for more details. | [
"Add",
"a",
"clip",
"layer",
"to",
"the",
"model",
"that",
"performs",
"element",
"-",
"wise",
"clip",
"operation",
".",
"Clip",
"the",
"values",
"in",
"the",
"input",
"tensor",
"to",
"the",
"range",
"[",
"min_value",
"max_value",
"]",
".",
"Refer",
"to"... | def add_clip(self, name, input_name, output_name, min_value=0.0, max_value=1.0):
"""
Add a clip layer to the model that performs element-wise clip operation.
Clip the values in the input tensor to the range [min_value, max_value].
Refer to the **ClipLayerParams** message in specification (NeuralNetwork.proto) for more details.
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of this layer.
min_value: float, optional
Lower bound / minimum value for clip, default: 0.0.
max_value: float, optional
Upper bound / maximum value for clip, default: 1.0.
See Also
--------
add_floor, add_ceil
"""
spec_layer = self._add_generic_layer(name, [input_name], [output_name])
spec_layer.clip.MergeFromString(b"")
spec_params = spec_layer.clip
spec_params.minVal = float(min_value)
spec_params.maxVal = float(max_value)
return spec_layer | [
"def",
"add_clip",
"(",
"self",
",",
"name",
",",
"input_name",
",",
"output_name",
",",
"min_value",
"=",
"0.0",
",",
"max_value",
"=",
"1.0",
")",
":",
"spec_layer",
"=",
"self",
".",
"_add_generic_layer",
"(",
"name",
",",
"[",
"input_name",
"]",
",",... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py#L5299-L5330 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_abcoll.py | python | MutableMapping.pop | (self, key, default=__marker) | D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised. | D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised. | [
"D",
".",
"pop",
"(",
"k",
"[",
"d",
"]",
")",
"-",
">",
"v",
"remove",
"specified",
"key",
"and",
"return",
"the",
"corresponding",
"value",
".",
"If",
"key",
"is",
"not",
"found",
"d",
"is",
"returned",
"if",
"given",
"otherwise",
"KeyError",
"is",... | def pop(self, key, default=__marker):
'''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.
'''
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value | [
"def",
"pop",
"(",
"self",
",",
"key",
",",
"default",
"=",
"__marker",
")",
":",
"try",
":",
"value",
"=",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"if",
"default",
"is",
"self",
".",
"__marker",
":",
"raise",
"return",
"default",
"else",... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_abcoll.py#L492-L504 | ||
OpenChemistry/tomviz | 0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a | tomviz/python/SegmentPores.py | python | SegmentPores.transform | (self, dataset, minimum_radius=0.5, maximum_radius=6.) | return returnValues | Segment pores. The pore size must be greater than the minimum radius
and less than the maximum radius. Pores will be separated according to
the minimum radius. | Segment pores. The pore size must be greater than the minimum radius
and less than the maximum radius. Pores will be separated according to
the minimum radius. | [
"Segment",
"pores",
".",
"The",
"pore",
"size",
"must",
"be",
"greater",
"than",
"the",
"minimum",
"radius",
"and",
"less",
"than",
"the",
"maximum",
"radius",
".",
"Pores",
"will",
"be",
"separated",
"according",
"to",
"the",
"minimum",
"radius",
"."
] | def transform(self, dataset, minimum_radius=0.5, maximum_radius=6.):
"""Segment pores. The pore size must be greater than the minimum radius
and less than the maximum radius. Pores will be separated according to
the minimum radius."""
# Initial progress
self.progress.value = 0
self.progress.maximum = 100
# Approximate percentage of work completed after each step in the
# transform
step_pct = iter([5, 5, 5, 5, 5, 5, 5, 5, 5, 30, 10, 5, 5, 5])
try:
import itk
from tomviz import itkutils
import numpy as np
except Exception as exc:
print("Could not import necessary module(s)")
raise exc
# Return values
returnValues = None
# Add a try/except around the ITK portion. ITK exceptions are
# passed up to the Python layer, so we can at least report what
# went wrong with the script, e.g,, unsupported image type.
try:
self.progress.message = "Converting data to ITK image"
# Get the ITK image
itk_input_image = itkutils.dataset_to_itk_image(dataset)
self.progress.value = next(step_pct)
# Reduce noise
smoothed = median_filter(self, step_pct, itk_input_image)
# Enhance pore contrast
enhanced = unsharp_mask(self, step_pct, smoothed)
thresholded = threshold(self, step_pct, enhanced)
dimension = itk_input_image.GetImageDimension()
spacing = itk_input_image.GetSpacing()
closing_radius = itk.Size[dimension]()
closing_radius.Fill(1)
for dim in range(dimension):
radius = int(np.round(maximum_radius / spacing[dim]))
if radius > closing_radius[dim]:
closing_radius[dim] = radius
StructuringElementType = itk.FlatStructuringElement[dimension]
structuring_element = \
StructuringElementType.Ball(closing_radius)
particle_mask = morphological_closing(self, step_pct, thresholded,
structuring_element)
encapsulated = encapsulate(self, step_pct, thresholded,
particle_mask, structuring_element)
distance = get_distance(self, step_pct, encapsulated)
segmented = watershed(self, step_pct, distance, minimum_radius)
inverted = invert(self, step_pct, thresholded)
segmented.DisconnectPipeline()
inverted.DisconnectPipeline()
separated = apply_mask(self, step_pct, segmented, inverted)
separated.DisconnectPipeline()
particle_mask.DisconnectPipeline()
in_particles = apply_mask(self, step_pct, separated, particle_mask)
opening_radius = itk.Size[dimension]()
opening_radius.Fill(1)
for dim in range(dimension):
radius = int(np.round(minimum_radius / spacing[dim]))
if radius > opening_radius[dim]:
opening_radius[dim] = radius
structuring_element = \
StructuringElementType.Ball(opening_radius)
opened = opening_by_reconstruction(self, step_pct, in_particles,
structuring_element)
self.progress.message = "Saving results"
label_map_dataset = dataset.create_child_dataset()
itkutils.set_itk_image_on_dataset(opened, label_map_dataset)
# Set up dictionary to return operator results
returnValues = {}
returnValues["label_map"] = label_map_dataset
except Exception as exc:
print("Problem encountered while running %s" %
self.__class__.__name__)
raise exc
return returnValues | [
"def",
"transform",
"(",
"self",
",",
"dataset",
",",
"minimum_radius",
"=",
"0.5",
",",
"maximum_radius",
"=",
"6.",
")",
":",
"# Initial progress",
"self",
".",
"progress",
".",
"value",
"=",
"0",
"self",
".",
"progress",
".",
"maximum",
"=",
"100",
"#... | https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/SegmentPores.py#L271-L369 | |
mysql/mysql-router | cc0179f982bb9739a834eb6fd205a56224616133 | ext/gmock/scripts/upload.py | python | VersionControlSystem.GetBaseFiles | (self, diff) | return files | Helper that calls GetBase file for each file in the patch.
Returns:
A dictionary that maps from filename to GetBaseFile's tuple. Filenames
are retrieved based on lines that start with "Index:" or
"Property changes on:". | Helper that calls GetBase file for each file in the patch. | [
"Helper",
"that",
"calls",
"GetBase",
"file",
"for",
"each",
"file",
"in",
"the",
"patch",
"."
] | def GetBaseFiles(self, diff):
"""Helper that calls GetBase file for each file in the patch.
Returns:
A dictionary that maps from filename to GetBaseFile's tuple. Filenames
are retrieved based on lines that start with "Index:" or
"Property changes on:".
"""
files = {}
for line in diff.splitlines(True):
if line.startswith('Index:') or line.startswith('Property changes on:'):
unused, filename = line.split(':', 1)
# On Windows if a file has property changes its filename uses '\'
# instead of '/'.
filename = filename.strip().replace('\\', '/')
files[filename] = self.GetBaseFile(filename)
return files | [
"def",
"GetBaseFiles",
"(",
"self",
",",
"diff",
")",
":",
"files",
"=",
"{",
"}",
"for",
"line",
"in",
"diff",
".",
"splitlines",
"(",
"True",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'Index:'",
")",
"or",
"line",
".",
"startswith",
"(",
"... | https://github.com/mysql/mysql-router/blob/cc0179f982bb9739a834eb6fd205a56224616133/ext/gmock/scripts/upload.py#L642-L658 | |
cathywu/Sentiment-Analysis | eb501fd1375c0c3f3ab430f963255f1bb858e659 | PyML-0.7.9/PyML/feature_selection/featsel.py | python | golub | (data, targetClass, otherClass, **args) | return g | The Golub feature score:
s = (mu1 - mu2) / sqrt(sigma1^2 + sigma2^2) | The Golub feature score:
s = (mu1 - mu2) / sqrt(sigma1^2 + sigma2^2) | [
"The",
"Golub",
"feature",
"score",
":",
"s",
"=",
"(",
"mu1",
"-",
"mu2",
")",
"/",
"sqrt",
"(",
"sigma1^2",
"+",
"sigma2^2",
")"
] | def golub(data, targetClass, otherClass, **args) :
'''The Golub feature score:
s = (mu1 - mu2) / sqrt(sigma1^2 + sigma2^2)
'''
if 'Y' in args :
Y = args['Y']
targetClassSize = numpy.sum(numpy.equal(Y, targetClass))
otherClassSize = numpy.sum(numpy.equal(Y, otherClass))
else :
Y = None
targetClassSize = data.labels.classSize[targetClass]
otherClassSize = data.labels.classSize[otherClass]
m1 = numpy.array(featureMean(data, targetClass, Y))
m2 = numpy.array(featureMean(data, otherClass, Y))
s1 = numpy.array(featureStd(data, targetClass, Y))
s2 = numpy.array(featureStd(data, otherClass, Y))
s = numpy.sqrt(s1**2 + s2**2)
m = (m1 + m2) / 2.0
# perfect features will have s[i] = 0, so need to take care of that:
numpy.putmask(s, numpy.equal(s, 0), m)
# features that are zero will still have s[i] = 0 so :
numpy.putmask(s, numpy.equal(s, 0) ,1)
g = (m1 - m2) / s
return g | [
"def",
"golub",
"(",
"data",
",",
"targetClass",
",",
"otherClass",
",",
"*",
"*",
"args",
")",
":",
"if",
"'Y'",
"in",
"args",
":",
"Y",
"=",
"args",
"[",
"'Y'",
"]",
"targetClassSize",
"=",
"numpy",
".",
"sum",
"(",
"numpy",
".",
"equal",
"(",
... | https://github.com/cathywu/Sentiment-Analysis/blob/eb501fd1375c0c3f3ab430f963255f1bb858e659/PyML-0.7.9/PyML/feature_selection/featsel.py#L863-L892 | |
tensorflow/io | 92b44e180674a8af0e12e405530f7343e3e693e4 | tensorflow_io/python/experimental/color_ops.py | python | rgb_to_yiq | (input, name=None) | return tf.image.rgb_to_yiq(input) | Convert a RGB image to YIQ.
Args:
input: A 3-D (`[H, W, 3]`) or 4-D (`[N, H, W, 3]`) Tensor.
name: A name for the operation (optional).
Returns:
A 3-D (`[H, W, 3]`) or 4-D (`[N, H, W, 3]`) Tensor. | Convert a RGB image to YIQ. | [
"Convert",
"a",
"RGB",
"image",
"to",
"YIQ",
"."
] | def rgb_to_yiq(input, name=None):
"""
Convert a RGB image to YIQ.
Args:
input: A 3-D (`[H, W, 3]`) or 4-D (`[N, H, W, 3]`) Tensor.
name: A name for the operation (optional).
Returns:
A 3-D (`[H, W, 3]`) or 4-D (`[N, H, W, 3]`) Tensor.
"""
# Note: Alias to tf.image.rgb_to_yiq for completeness
input = tf.convert_to_tensor(input)
return tf.image.rgb_to_yiq(input) | [
"def",
"rgb_to_yiq",
"(",
"input",
",",
"name",
"=",
"None",
")",
":",
"# Note: Alias to tf.image.rgb_to_yiq for completeness",
"input",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"input",
")",
"return",
"tf",
".",
"image",
".",
"rgb_to_yiq",
"(",
"input",
")"
] | https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/experimental/color_ops.py#L269-L282 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/protobuf/python/mox.py | python | MockObject.__class__ | (self) | return self._class_to_mock | Return the class that is being mocked. | Return the class that is being mocked. | [
"Return",
"the",
"class",
"that",
"is",
"being",
"mocked",
"."
] | def __class__(self):
"""Return the class that is being mocked."""
return self._class_to_mock | [
"def",
"__class__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_class_to_mock"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/mox.py#L504-L507 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/enum_types.py | python | EnumTypeInfoBase.get_cpp_type_name | (self) | Get the C++ type name for an enum. | Get the C++ type name for an enum. | [
"Get",
"the",
"C",
"++",
"type",
"name",
"for",
"an",
"enum",
"."
] | def get_cpp_type_name(self):
# type: () -> str
"""Get the C++ type name for an enum."""
pass | [
"def",
"get_cpp_type_name",
"(",
"self",
")",
":",
"# type: () -> str",
"pass"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/enum_types.py#L60-L63 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/integrate/quadrature.py | python | vectorize1 | (func, args=(), vec_func=False) | return vfunc | Vectorize the call to a function.
This is an internal utility function used by `romberg` and
`quadrature` to create a vectorized version of a function.
If `vec_func` is True, the function `func` is assumed to take vector
arguments.
Parameters
----------
func : callable
User defined function.
args : tuple, optional
Extra arguments for the function.
vec_func : bool, optional
True if the function func takes vector arguments.
Returns
-------
vfunc : callable
A function that will take a vector argument and return the
result. | Vectorize the call to a function. | [
"Vectorize",
"the",
"call",
"to",
"a",
"function",
"."
] | def vectorize1(func, args=(), vec_func=False):
"""Vectorize the call to a function.
This is an internal utility function used by `romberg` and
`quadrature` to create a vectorized version of a function.
If `vec_func` is True, the function `func` is assumed to take vector
arguments.
Parameters
----------
func : callable
User defined function.
args : tuple, optional
Extra arguments for the function.
vec_func : bool, optional
True if the function func takes vector arguments.
Returns
-------
vfunc : callable
A function that will take a vector argument and return the
result.
"""
if vec_func:
def vfunc(x):
return func(x, *args)
else:
def vfunc(x):
if np.isscalar(x):
return func(x, *args)
x = np.asarray(x)
# call with first point to get output type
y0 = func(x[0], *args)
n = len(x)
dtype = getattr(y0, 'dtype', type(y0))
output = np.empty((n,), dtype=dtype)
output[0] = y0
for i in xrange(1, n):
output[i] = func(x[i], *args)
return output
return vfunc | [
"def",
"vectorize1",
"(",
"func",
",",
"args",
"=",
"(",
")",
",",
"vec_func",
"=",
"False",
")",
":",
"if",
"vec_func",
":",
"def",
"vfunc",
"(",
"x",
")",
":",
"return",
"func",
"(",
"x",
",",
"*",
"args",
")",
"else",
":",
"def",
"vfunc",
"(... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/integrate/quadrature.py#L108-L150 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/index/package_finder.py | python | CandidateEvaluator.sort_best_candidate | (
self,
candidates, # type: List[InstallationCandidate]
) | return best_candidate | Return the best candidate per the instance's sort order, or None if
no candidate is acceptable. | Return the best candidate per the instance's sort order, or None if
no candidate is acceptable. | [
"Return",
"the",
"best",
"candidate",
"per",
"the",
"instance",
"s",
"sort",
"order",
"or",
"None",
"if",
"no",
"candidate",
"is",
"acceptable",
"."
] | def sort_best_candidate(
self,
candidates, # type: List[InstallationCandidate]
):
# type: (...) -> Optional[InstallationCandidate]
"""
Return the best candidate per the instance's sort order, or None if
no candidate is acceptable.
"""
if not candidates:
return None
best_candidate = max(candidates, key=self._sort_key)
return best_candidate | [
"def",
"sort_best_candidate",
"(",
"self",
",",
"candidates",
",",
"# type: List[InstallationCandidate]",
")",
":",
"# type: (...) -> Optional[InstallationCandidate]",
"if",
"not",
"candidates",
":",
"return",
"None",
"best_candidate",
"=",
"max",
"(",
"candidates",
",",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/index/package_finder.py#L542-L554 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/html.py | python | HtmlParser.AddTagHandler | (*args, **kwargs) | return _html.HtmlParser_AddTagHandler(*args, **kwargs) | AddTagHandler(self, HtmlTagHandler handler) | AddTagHandler(self, HtmlTagHandler handler) | [
"AddTagHandler",
"(",
"self",
"HtmlTagHandler",
"handler",
")"
] | def AddTagHandler(*args, **kwargs):
"""AddTagHandler(self, HtmlTagHandler handler)"""
return _html.HtmlParser_AddTagHandler(*args, **kwargs) | [
"def",
"AddTagHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlParser_AddTagHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L213-L215 | |
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/framework/interfaces/face/utilities.py | python | unary_stream_event | (behavior) | return _MethodImplementation(cardinality.Cardinality.UNARY_STREAM,
style.Service.EVENT, None, None, None, None,
None, behavior, None, None) | Creates an face.MethodImplementation for the given behavior.
Args:
behavior: The implementation of a unary-stream RPC method as a callable
value that takes a request value, a stream.Consumer to which to pass the
the response values of the RPC, and an face.ServicerContext.
Returns:
An face.MethodImplementation derived from the given behavior. | Creates an face.MethodImplementation for the given behavior. | [
"Creates",
"an",
"face",
".",
"MethodImplementation",
"for",
"the",
"given",
"behavior",
"."
] | def unary_stream_event(behavior):
"""Creates an face.MethodImplementation for the given behavior.
Args:
behavior: The implementation of a unary-stream RPC method as a callable
value that takes a request value, a stream.Consumer to which to pass the
the response values of the RPC, and an face.ServicerContext.
Returns:
An face.MethodImplementation derived from the given behavior.
"""
return _MethodImplementation(cardinality.Cardinality.UNARY_STREAM,
style.Service.EVENT, None, None, None, None,
None, behavior, None, None) | [
"def",
"unary_stream_event",
"(",
"behavior",
")",
":",
"return",
"_MethodImplementation",
"(",
"cardinality",
".",
"Cardinality",
".",
"UNARY_STREAM",
",",
"style",
".",
"Service",
".",
"EVENT",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"None... | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/framework/interfaces/face/utilities.py#L121-L134 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | PhotoImage.copy | (self) | return destImage | Return a new PhotoImage with the same image as this widget. | Return a new PhotoImage with the same image as this widget. | [
"Return",
"a",
"new",
"PhotoImage",
"with",
"the",
"same",
"image",
"as",
"this",
"widget",
"."
] | def copy(self):
"""Return a new PhotoImage with the same image as this widget."""
destImage = PhotoImage()
self.tk.call(destImage, 'copy', self.name)
return destImage | [
"def",
"copy",
"(",
"self",
")",
":",
"destImage",
"=",
"PhotoImage",
"(",
")",
"self",
".",
"tk",
".",
"call",
"(",
"destImage",
",",
"'copy'",
",",
"self",
".",
"name",
")",
"return",
"destImage"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3317-L3321 | |
ethz-asl/kalibr | 1c9d7e0e57cf7b0d2e0351a71b312adfd8996f05 | Schweizer-Messer/sm_python/python/sm/PlotCollection.py | python | PlotCollection.add_figure | (self, tabname, fig) | Add a matplotlib figure to the collection | Add a matplotlib figure to the collection | [
"Add",
"a",
"matplotlib",
"figure",
"to",
"the",
"collection"
] | def add_figure(self, tabname, fig):
"""
Add a matplotlib figure to the collection
"""
self.figureList[tabname] = fig | [
"def",
"add_figure",
"(",
"self",
",",
"tabname",
",",
"fig",
")",
":",
"self",
".",
"figureList",
"[",
"tabname",
"]",
"=",
"fig"
] | https://github.com/ethz-asl/kalibr/blob/1c9d7e0e57cf7b0d2e0351a71b312adfd8996f05/Schweizer-Messer/sm_python/python/sm/PlotCollection.py#L39-L43 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/plugins/codebrowser/codebrowser/cbrowser.py | python | CodeBrowserTree.AppendClass | (self, cobj) | Append a class node to the tree
@param cobj: Class item object | Append a class node to the tree
@param cobj: Class item object | [
"Append",
"a",
"class",
"node",
"to",
"the",
"tree",
"@param",
"cobj",
":",
"Class",
"item",
"object"
] | def AppendClass(self, cobj):
"""Append a class node to the tree
@param cobj: Class item object
"""
if self.nodes.get('classes', None) is None:
desc = self._cdoc.GetElementDescription('class')
if desc == 'class':
desc = "Class Definitions"
croot = self.AppendItem(self.GetRootItem(), _(desc))
self.SetItemHasChildren(croot)
self.SetPyData(croot, None)
self.SetItemImage(croot, self.icons['class'])
self.nodes['classes'] = croot
croot = self.AppendCodeObj(self.nodes['classes'], cobj, self.icons['class']) | [
"def",
"AppendClass",
"(",
"self",
",",
"cobj",
")",
":",
"if",
"self",
".",
"nodes",
".",
"get",
"(",
"'classes'",
",",
"None",
")",
"is",
"None",
":",
"desc",
"=",
"self",
".",
"_cdoc",
".",
"GetElementDescription",
"(",
"'class'",
")",
"if",
"desc... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/codebrowser/codebrowser/cbrowser.py#L269-L284 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/ttk.py | python | Treeview.heading | (self, column, option=None, **kw) | return _val_or_dict(self.tk, kw, self._w, 'heading', column) | Query or modify the heading options for the specified column.
If kw is not given, returns a dict of the heading option values. If
option is specified then the value for that option is returned.
Otherwise, sets the options to the corresponding values.
Valid options/values are:
text: text
The text to display in the column heading
image: image_name
Specifies an image to display to the right of the column
heading
anchor: anchor
Specifies how the heading text should be aligned. One of
the standard Tk anchor values
command: callback
A callback to be invoked when the heading label is
pressed.
To configure the tree column heading, call this with column = "#0" | Query or modify the heading options for the specified column. | [
"Query",
"or",
"modify",
"the",
"heading",
"options",
"for",
"the",
"specified",
"column",
"."
] | def heading(self, column, option=None, **kw):
"""Query or modify the heading options for the specified column.
If kw is not given, returns a dict of the heading option values. If
option is specified then the value for that option is returned.
Otherwise, sets the options to the corresponding values.
Valid options/values are:
text: text
The text to display in the column heading
image: image_name
Specifies an image to display to the right of the column
heading
anchor: anchor
Specifies how the heading text should be aligned. One of
the standard Tk anchor values
command: callback
A callback to be invoked when the heading label is
pressed.
To configure the tree column heading, call this with column = "#0" """
cmd = kw.get('command')
if cmd and not isinstance(cmd, basestring):
# callback not registered yet, do it now
kw['command'] = self.master.register(cmd, self._substitute)
if option is not None:
kw[option] = None
return _val_or_dict(self.tk, kw, self._w, 'heading', column) | [
"def",
"heading",
"(",
"self",
",",
"column",
",",
"option",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"cmd",
"=",
"kw",
".",
"get",
"(",
"'command'",
")",
"if",
"cmd",
"and",
"not",
"isinstance",
"(",
"cmd",
",",
"basestring",
")",
":",
"# cal... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/ttk.py#L1245-L1274 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pyparsing/py3/pyparsing/core.py | python | ParserElement.parse_file | (
self,
file_or_filename: Union[str, Path, TextIO],
encoding: str = "utf-8",
parse_all: bool = False,
*,
parseAll: bool = False,
) | Execute the parse expression on the given file or filename.
If a filename is specified (instead of a file object),
the entire file is opened, read, and closed before parsing. | Execute the parse expression on the given file or filename.
If a filename is specified (instead of a file object),
the entire file is opened, read, and closed before parsing. | [
"Execute",
"the",
"parse",
"expression",
"on",
"the",
"given",
"file",
"or",
"filename",
".",
"If",
"a",
"filename",
"is",
"specified",
"(",
"instead",
"of",
"a",
"file",
"object",
")",
"the",
"entire",
"file",
"is",
"opened",
"read",
"and",
"closed",
"b... | def parse_file(
self,
file_or_filename: Union[str, Path, TextIO],
encoding: str = "utf-8",
parse_all: bool = False,
*,
parseAll: bool = False,
) -> ParseResults:
"""
Execute the parse expression on the given file or filename.
If a filename is specified (instead of a file object),
the entire file is opened, read, and closed before parsing.
"""
parseAll = parseAll or parse_all
try:
file_contents = file_or_filename.read()
except AttributeError:
with open(file_or_filename, "r", encoding=encoding) as f:
file_contents = f.read()
try:
return self.parse_string(file_contents, parseAll)
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc.with_traceback(None) | [
"def",
"parse_file",
"(",
"self",
",",
"file_or_filename",
":",
"Union",
"[",
"str",
",",
"Path",
",",
"TextIO",
"]",
",",
"encoding",
":",
"str",
"=",
"\"utf-8\"",
",",
"parse_all",
":",
"bool",
"=",
"False",
",",
"*",
",",
"parseAll",
":",
"bool",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pyparsing/py3/pyparsing/core.py#L1880-L1906 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/html.py | python | HtmlLinkInfo.SetHtmlCell | (*args, **kwargs) | return _html.HtmlLinkInfo_SetHtmlCell(*args, **kwargs) | SetHtmlCell(self, HtmlCell e) | SetHtmlCell(self, HtmlCell e) | [
"SetHtmlCell",
"(",
"self",
"HtmlCell",
"e",
")"
] | def SetHtmlCell(*args, **kwargs):
"""SetHtmlCell(self, HtmlCell e)"""
return _html.HtmlLinkInfo_SetHtmlCell(*args, **kwargs) | [
"def",
"SetHtmlCell",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlLinkInfo_SetHtmlCell",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L122-L124 | |
kevinlin311tw/caffe-cvprw15 | 45c2a1bf0368569c54e0be4edf8d34285cf79e70 | scripts/cpp_lint.py | python | FindPreviousMatchingAngleBracket | (clean_lines, linenum, init_prefix) | return False | Find the corresponding < that started a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_prefix: Part of the current line before the initial >.
Returns:
True if a matching bracket exists. | Find the corresponding < that started a template. | [
"Find",
"the",
"corresponding",
"<",
"that",
"started",
"a",
"template",
"."
] | def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix):
"""Find the corresponding < that started a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_prefix: Part of the current line before the initial >.
Returns:
True if a matching bracket exists.
"""
line = init_prefix
nesting_stack = ['>']
while True:
# Find the previous operator
match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line)
if match:
# Found an operator, update nesting stack
operator = match.group(2)
line = match.group(1)
if nesting_stack[-1] == '>':
# Expecting opening angle bracket
if operator in ('>', ')', ']'):
nesting_stack.append(operator)
elif operator == '<':
nesting_stack.pop()
if not nesting_stack:
# Found matching angle bracket
return True
elif operator == ',':
# Got a comma before a bracket, this is most likely a
# template argument. The opening angle bracket is probably
# there if we look for it, so just return early here.
return True
else:
# Got some other operator.
return False
else:
# Expecting opening parenthesis or opening bracket
if operator in ('>', ')', ']'):
nesting_stack.append(operator)
elif operator in ('(', '['):
nesting_stack.pop()
else:
# Scan the previous line
linenum -= 1
if linenum < 0:
break
line = clean_lines.elided[linenum]
# Exhausted all earlier lines and still no matching angle bracket.
return False | [
"def",
"FindPreviousMatchingAngleBracket",
"(",
"clean_lines",
",",
"linenum",
",",
"init_prefix",
")",
":",
"line",
"=",
"init_prefix",
"nesting_stack",
"=",
"[",
"'>'",
"]",
"while",
"True",
":",
"# Find the previous operator",
"match",
"=",
"Search",
"(",
"r'^(... | https://github.com/kevinlin311tw/caffe-cvprw15/blob/45c2a1bf0368569c54e0be4edf8d34285cf79e70/scripts/cpp_lint.py#L2586-L2640 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py | python | Tree.close | (self, entrypath) | Close the entry given by entryPath if its mode is close. | Close the entry given by entryPath if its mode is close. | [
"Close",
"the",
"entry",
"given",
"by",
"entryPath",
"if",
"its",
"mode",
"is",
"close",
"."
] | def close(self, entrypath):
'''Close the entry given by entryPath if its mode is close.'''
self.tk.call(self._w, 'close', entrypath) | [
"def",
"close",
"(",
"self",
",",
"entrypath",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'close'",
",",
"entrypath",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py#L1542-L1544 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/rfc822.py | python | dump_address_pair | (pair) | Dump a (name, address) pair in a canonicalized form. | Dump a (name, address) pair in a canonicalized form. | [
"Dump",
"a",
"(",
"name",
"address",
")",
"pair",
"in",
"a",
"canonicalized",
"form",
"."
] | def dump_address_pair(pair):
"""Dump a (name, address) pair in a canonicalized form."""
if pair[0]:
return '"' + pair[0] + '" <' + pair[1] + '>'
else:
return pair[1] | [
"def",
"dump_address_pair",
"(",
"pair",
")",
":",
"if",
"pair",
"[",
"0",
"]",
":",
"return",
"'\"'",
"+",
"pair",
"[",
"0",
"]",
"+",
"'\" <'",
"+",
"pair",
"[",
"1",
"]",
"+",
"'>'",
"else",
":",
"return",
"pair",
"[",
"1",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/rfc822.py#L825-L830 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/findertools.py | python | _setlocation | (object_alias, (x, y)) | return (x,y) | _setlocation: Set the location of the icon for the object. | _setlocation: Set the location of the icon for the object. | [
"_setlocation",
":",
"Set",
"the",
"location",
"of",
"the",
"icon",
"for",
"the",
"object",
"."
] | def _setlocation(object_alias, (x, y)):
"""_setlocation: Set the location of the icon for the object."""
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None)
aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('posn'), fr=aeobj_00)
args['----'] = aeobj_01
args["data"] = [x, y]
_reply, args, attrs = finder.send("core", "setd", args, attrs)
if 'errn' in args:
raise Error, aetools.decodeerror(args)
return (x,y) | [
"def",
"_setlocation",
"(",
"object_alias",
",",
"(",
"x",
",",
"y",
")",
")",
":",
"finder",
"=",
"_getfinder",
"(",
")",
"args",
"=",
"{",
"}",
"attrs",
"=",
"{",
"}",
"aeobj_00",
"=",
"aetypes",
".",
"ObjectSpecifier",
"(",
"want",
"=",
"aetypes",... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/findertools.py#L303-L315 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/utils/gc.py | python | largest_export_versions | (n) | return keep | Creates a filter that keeps the largest n export versions.
Args:
n: number of versions to keep.
Returns:
A filter function that keeps the n largest paths. | Creates a filter that keeps the largest n export versions. | [
"Creates",
"a",
"filter",
"that",
"keeps",
"the",
"largest",
"n",
"export",
"versions",
"."
] | def largest_export_versions(n):
"""Creates a filter that keeps the largest n export versions.
Args:
n: number of versions to keep.
Returns:
A filter function that keeps the n largest paths.
"""
def keep(paths):
heap = []
for idx, path in enumerate(paths):
if path.export_version is not None:
heapq.heappush(heap, (path.export_version, idx))
keepers = [paths[i] for _, i in heapq.nlargest(n, heap)]
return sorted(keepers)
return keep | [
"def",
"largest_export_versions",
"(",
"n",
")",
":",
"def",
"keep",
"(",
"paths",
")",
":",
"heap",
"=",
"[",
"]",
"for",
"idx",
",",
"path",
"in",
"enumerate",
"(",
"paths",
")",
":",
"if",
"path",
".",
"export_version",
"is",
"not",
"None",
":",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/utils/gc.py#L80-L97 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/scripts/parse_html5_entities.py | python | compare_dicts | (old, new) | Compare the old and new dicts and print the differences. | Compare the old and new dicts and print the differences. | [
"Compare",
"the",
"old",
"and",
"new",
"dicts",
"and",
"print",
"the",
"differences",
"."
] | def compare_dicts(old, new):
"""Compare the old and new dicts and print the differences."""
added = new.keys() - old.keys()
if added:
print('{} entitie(s) have been added:'.format(len(added)))
for name in sorted(added):
print(' {!r}: {!r}'.format(name, new[name]))
removed = old.keys() - new.keys()
if removed:
print('{} entitie(s) have been removed:'.format(len(removed)))
for name in sorted(removed):
print(' {!r}: {!r}'.format(name, old[name]))
changed = set()
for name in (old.keys() & new.keys()):
if old[name] != new[name]:
changed.add((name, old[name], new[name]))
if changed:
print('{} entitie(s) have been modified:'.format(len(changed)))
for item in sorted(changed):
print(' {!r}: {!r} -> {!r}'.format(*item)) | [
"def",
"compare_dicts",
"(",
"old",
",",
"new",
")",
":",
"added",
"=",
"new",
".",
"keys",
"(",
")",
"-",
"old",
".",
"keys",
"(",
")",
"if",
"added",
":",
"print",
"(",
"'{} entitie(s) have been added:'",
".",
"format",
"(",
"len",
"(",
"added",
")... | 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/scripts/parse_html5_entities.py#L32-L51 | ||
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings._Setting | (self, path, config,
default=None, prefix='', append=None, map=None) | return self._GetAndMunge(
self.msvs_settings[config], path, default, prefix, append, map) | _GetAndMunge for msvs_settings. | _GetAndMunge for msvs_settings. | [
"_GetAndMunge",
"for",
"msvs_settings",
"."
] | def _Setting(self, path, config,
default=None, prefix='', append=None, map=None):
"""_GetAndMunge for msvs_settings."""
return self._GetAndMunge(
self.msvs_settings[config], path, default, prefix, append, map) | [
"def",
"_Setting",
"(",
"self",
",",
"path",
",",
"config",
",",
"default",
"=",
"None",
",",
"prefix",
"=",
"''",
",",
"append",
"=",
"None",
",",
"map",
"=",
"None",
")",
":",
"return",
"self",
".",
"_GetAndMunge",
"(",
"self",
".",
"msvs_settings"... | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/msvs_emulation.py#L319-L323 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Canvas.create_arc | (self, *args, **kw) | return self._create('arc', args, kw) | Create arc shaped region with coordinates x1,y1,x2,y2. | Create arc shaped region with coordinates x1,y1,x2,y2. | [
"Create",
"arc",
"shaped",
"region",
"with",
"coordinates",
"x1",
"y1",
"x2",
"y2",
"."
] | def create_arc(self, *args, **kw):
"""Create arc shaped region with coordinates x1,y1,x2,y2."""
return self._create('arc', args, kw) | [
"def",
"create_arc",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"_create",
"(",
"'arc'",
",",
"args",
",",
"kw",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L2317-L2319 | |
ablab/quast | 5f6709528129a6ad266a6b24ef3f40b88f0fe04b | quast_libs/N50.py | python | N50 | (numlist, percentage=50.0) | return NG50(numlist, sum(numlist), percentage) | Abstract: Returns the N50 value of the passed list of numbers.
Comments: Works for any percentage (e.g. N60, N70) with optional argument
Usage: N50(numlist) | Abstract: Returns the N50 value of the passed list of numbers.
Comments: Works for any percentage (e.g. N60, N70) with optional argument
Usage: N50(numlist) | [
"Abstract",
":",
"Returns",
"the",
"N50",
"value",
"of",
"the",
"passed",
"list",
"of",
"numbers",
".",
"Comments",
":",
"Works",
"for",
"any",
"percentage",
"(",
"e",
".",
"g",
".",
"N60",
"N70",
")",
"with",
"optional",
"argument",
"Usage",
":",
"N50... | def N50(numlist, percentage=50.0):
"""
Abstract: Returns the N50 value of the passed list of numbers.
Comments: Works for any percentage (e.g. N60, N70) with optional argument
Usage: N50(numlist)
"""
return NG50(numlist, sum(numlist), percentage) | [
"def",
"N50",
"(",
"numlist",
",",
"percentage",
"=",
"50.0",
")",
":",
"return",
"NG50",
"(",
"numlist",
",",
"sum",
"(",
"numlist",
")",
",",
"percentage",
")"
] | https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/N50.py#L37-L43 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/core.py | python | Value.is_sparse | (self) | return super(Value, self).is_sparse() | Whether the data is sparse or dense | Whether the data is sparse or dense | [
"Whether",
"the",
"data",
"is",
"sparse",
"or",
"dense"
] | def is_sparse(self):
'''
Whether the data is sparse or dense
'''
return super(Value, self).is_sparse() | [
"def",
"is_sparse",
"(",
"self",
")",
":",
"return",
"super",
"(",
"Value",
",",
"self",
")",
".",
"is_sparse",
"(",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/core.py#L624-L628 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | DateTime.Now | (*args, **kwargs) | return _misc_.DateTime_Now(*args, **kwargs) | Now() -> DateTime | Now() -> DateTime | [
"Now",
"()",
"-",
">",
"DateTime"
] | def Now(*args, **kwargs):
"""Now() -> DateTime"""
return _misc_.DateTime_Now(*args, **kwargs) | [
"def",
"Now",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_Now",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L3766-L3768 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/logging/graph.py | python | get_node_outputs | (node, depth=0) | return node_outputs | Walks through every node of the graph starting at ``node``
and returns a list of all node outputs.
Args:
node (graph node): the node to start the journey from
Returns:
A list of all node outputs | Walks through every node of the graph starting at ``node``
and returns a list of all node outputs. | [
"Walks",
"through",
"every",
"node",
"of",
"the",
"graph",
"starting",
"at",
"node",
"and",
"returns",
"a",
"list",
"of",
"all",
"node",
"outputs",
"."
] | def get_node_outputs(node, depth=0):
'''
Walks through every node of the graph starting at ``node``
and returns a list of all node outputs.
Args:
node (graph node): the node to start the journey from
Returns:
A list of all node outputs
'''
node_list = depth_first_search(node, lambda x: True, depth)
node_outputs = []
for node in node_list:
try:
for out in node.outputs:
node_outputs.append(out)
except AttributeError:
pass
return node_outputs | [
"def",
"get_node_outputs",
"(",
"node",
",",
"depth",
"=",
"0",
")",
":",
"node_list",
"=",
"depth_first_search",
"(",
"node",
",",
"lambda",
"x",
":",
"True",
",",
"depth",
")",
"node_outputs",
"=",
"[",
"]",
"for",
"node",
"in",
"node_list",
":",
"tr... | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/logging/graph.py#L390-L410 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/mirroring/module.py | python | Module.snapshot_mirror_peer_remove | (self,
fs_name: str,
peer_uuid: str) | return self.fs_snapshot_mirror.peer_remove(fs_name, peer_uuid) | Remove a filesystem peer | Remove a filesystem peer | [
"Remove",
"a",
"filesystem",
"peer"
] | def snapshot_mirror_peer_remove(self,
fs_name: str,
peer_uuid: str):
"""Remove a filesystem peer"""
return self.fs_snapshot_mirror.peer_remove(fs_name, peer_uuid) | [
"def",
"snapshot_mirror_peer_remove",
"(",
"self",
",",
"fs_name",
":",
"str",
",",
"peer_uuid",
":",
"str",
")",
":",
"return",
"self",
".",
"fs_snapshot_mirror",
".",
"peer_remove",
"(",
"fs_name",
",",
"peer_uuid",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/mirroring/module.py#L52-L56 | |
mapsme/omim | 1892903b63f2c85b16ed4966d21fe76aba06b9ba | tools/python/mwm/mwm_python.py | python | read_bounds | (f, coord_size) | return mi.Rect(left_bottom=pmin, right_top=pmax) | Reads mercator bounds, returns (min_lon, min_lat, max_lon, max_lat). | Reads mercator bounds, returns (min_lon, min_lat, max_lon, max_lat). | [
"Reads",
"mercator",
"bounds",
"returns",
"(",
"min_lon",
"min_lat",
"max_lon",
"max_lat",
")",
"."
] | def read_bounds(f, coord_size) -> mi.Rect:
"""Reads mercator bounds, returns (min_lon, min_lat, max_lon, max_lat)."""
rmin = mwm_bitwise_split(read_varint(f))
rmax = mwm_bitwise_split(read_varint(f))
pmin = to_4326(coord_size, rmin)
pmax = to_4326(coord_size, rmax)
return mi.Rect(left_bottom=pmin, right_top=pmax) | [
"def",
"read_bounds",
"(",
"f",
",",
"coord_size",
")",
"->",
"mi",
".",
"Rect",
":",
"rmin",
"=",
"mwm_bitwise_split",
"(",
"read_varint",
"(",
"f",
")",
")",
"rmax",
"=",
"mwm_bitwise_split",
"(",
"read_varint",
"(",
"f",
")",
")",
"pmin",
"=",
"to_4... | https://github.com/mapsme/omim/blob/1892903b63f2c85b16ed4966d21fe76aba06b9ba/tools/python/mwm/mwm_python.py#L336-L342 | |
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/tools/build/src/build/feature.py | python | __validate_feature | (feature) | Generates an error if the feature is unknown. | Generates an error if the feature is unknown. | [
"Generates",
"an",
"error",
"if",
"the",
"feature",
"is",
"unknown",
"."
] | def __validate_feature (feature):
""" Generates an error if the feature is unknown.
"""
assert isinstance(feature, basestring)
if feature not in __all_features:
raise BaseException ('unknown feature "%s"' % feature) | [
"def",
"__validate_feature",
"(",
"feature",
")",
":",
"assert",
"isinstance",
"(",
"feature",
",",
"basestring",
")",
"if",
"feature",
"not",
"in",
"__all_features",
":",
"raise",
"BaseException",
"(",
"'unknown feature \"%s\"'",
"%",
"feature",
")"
] | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/feature.py#L894-L899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.