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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/actor/Actor.py | python | Actor.pose | (self, animName, frame, partName=None, lodName=None) | pose(self, string, int, string=None)
Pose the actor in position found at given frame in the specified
animation for the specified part. If no part is specified attempt
to apply pose to all parts. | pose(self, string, int, string=None)
Pose the actor in position found at given frame in the specified
animation for the specified part. If no part is specified attempt
to apply pose to all parts. | [
"pose",
"(",
"self",
"string",
"int",
"string",
"=",
"None",
")",
"Pose",
"the",
"actor",
"in",
"position",
"found",
"at",
"given",
"frame",
"in",
"the",
"specified",
"animation",
"for",
"the",
"specified",
"part",
".",
"If",
"no",
"part",
"is",
"specifi... | def pose(self, animName, frame, partName=None, lodName=None):
"""pose(self, string, int, string=None)
Pose the actor in position found at given frame in the specified
animation for the specified part. If no part is specified attempt
to apply pose to all parts."""
for control in self.getAnimControls(animName, partName, lodName):
control.pose(frame) | [
"def",
"pose",
"(",
"self",
",",
"animName",
",",
"frame",
",",
"partName",
"=",
"None",
",",
"lodName",
"=",
"None",
")",
":",
"for",
"control",
"in",
"self",
".",
"getAnimControls",
"(",
"animName",
",",
"partName",
",",
"lodName",
")",
":",
"control... | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/actor/Actor.py#L1586-L1592 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/internal/containers.py | python | ScalarMap.__init__ | (self, message_listener, key_checker, value_checker,
entry_descriptor) | Args:
message_listener: A MessageListener implementation.
The ScalarMap will call this object's Modified() method when it
is modified.
key_checker: A type_checkers.ValueChecker instance to run on keys
inserted into this container.
value_checker: A type_checkers.ValueChecker instance to run on values
inserted into this container.
entry_descriptor: The MessageDescriptor of a map entry: key and value. | Args:
message_listener: A MessageListener implementation.
The ScalarMap will call this object's Modified() method when it
is modified.
key_checker: A type_checkers.ValueChecker instance to run on keys
inserted into this container.
value_checker: A type_checkers.ValueChecker instance to run on values
inserted into this container.
entry_descriptor: The MessageDescriptor of a map entry: key and value. | [
"Args",
":",
"message_listener",
":",
"A",
"MessageListener",
"implementation",
".",
"The",
"ScalarMap",
"will",
"call",
"this",
"object",
"s",
"Modified",
"()",
"method",
"when",
"it",
"is",
"modified",
".",
"key_checker",
":",
"A",
"type_checkers",
".",
"Val... | def __init__(self, message_listener, key_checker, value_checker,
entry_descriptor):
"""
Args:
message_listener: A MessageListener implementation.
The ScalarMap will call this object's Modified() method when it
is modified.
key_checker: A type_checkers.ValueChecker instance to run on keys
inserted into this container.
value_checker: A type_checkers.ValueChecker instance to run on values
inserted into this container.
entry_descriptor: The MessageDescriptor of a map entry: key and value.
"""
self._message_listener = message_listener
self._key_checker = key_checker
self._value_checker = value_checker
self._entry_descriptor = entry_descriptor
self._values = {} | [
"def",
"__init__",
"(",
"self",
",",
"message_listener",
",",
"key_checker",
",",
"value_checker",
",",
"entry_descriptor",
")",
":",
"self",
".",
"_message_listener",
"=",
"message_listener",
"self",
".",
"_key_checker",
"=",
"key_checker",
"self",
".",
"_value_c... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/containers.py#L469-L486 | ||
moflow/moflow | 2dfb27c799c90c6caf1477508eca3eec616ef7d2 | bap/libtracewrap/libtrace/protobuf/python/mox.py | python | Regex.equals | (self, rhs) | return self.regex.search(rhs) is not None | Check to see if rhs matches regular expression pattern.
Returns:
bool | Check to see if rhs matches regular expression pattern. | [
"Check",
"to",
"see",
"if",
"rhs",
"matches",
"regular",
"expression",
"pattern",
"."
] | def equals(self, rhs):
"""Check to see if rhs matches regular expression pattern.
Returns:
bool
"""
return self.regex.search(rhs) is not None | [
"def",
"equals",
"(",
"self",
",",
"rhs",
")",
":",
"return",
"self",
".",
"regex",
".",
"search",
"(",
"rhs",
")",
"is",
"not",
"None"
] | https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/mox.py#L922-L929 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/operator.py | python | delitem | (a, b) | Same as del a[b]. | Same as del a[b]. | [
"Same",
"as",
"del",
"a",
"[",
"b",
"]",
"."
] | def delitem(a, b):
"Same as del a[b]."
del a[b] | [
"def",
"delitem",
"(",
"a",
",",
"b",
")",
":",
"del",
"a",
"[",
"b",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/operator.py#L165-L167 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/traitlets/py3/traitlets/traitlets.py | python | Set.__init__ | (
self,
trait=None,
default_value=Undefined,
minlen=0,
maxlen=sys.maxsize,
**kwargs,
) | Create a Set trait type from a list, set, or tuple.
The default value is created by doing ``set(default_value)``,
which creates a copy of the ``default_value``.
``trait`` can be specified, which restricts the type of elements
in the container to that TraitType.
If only one arg is given and it is not a Trait, it is taken as
``default_value``:
``c = Set({1, 2, 3})``
Parameters
----------
trait : TraitType [ optional ]
the type for restricting the contents of the Container.
If unspecified, types are not checked.
default_value : SequenceType [ optional ]
The default value for the Trait. Must be list/tuple/set, and
will be cast to the container type.
minlen : Int [ default 0 ]
The minimum length of the input list
maxlen : Int [ default sys.maxsize ]
The maximum length of the input list | Create a Set trait type from a list, set, or tuple. | [
"Create",
"a",
"Set",
"trait",
"type",
"from",
"a",
"list",
"set",
"or",
"tuple",
"."
] | def __init__(
self,
trait=None,
default_value=Undefined,
minlen=0,
maxlen=sys.maxsize,
**kwargs,
):
"""Create a Set trait type from a list, set, or tuple.
The default value is created by doing ``set(default_value)``,
which creates a copy of the ``default_value``.
``trait`` can be specified, which restricts the type of elements
in the container to that TraitType.
If only one arg is given and it is not a Trait, it is taken as
``default_value``:
``c = Set({1, 2, 3})``
Parameters
----------
trait : TraitType [ optional ]
the type for restricting the contents of the Container.
If unspecified, types are not checked.
default_value : SequenceType [ optional ]
The default value for the Trait. Must be list/tuple/set, and
will be cast to the container type.
minlen : Int [ default 0 ]
The minimum length of the input list
maxlen : Int [ default sys.maxsize ]
The maximum length of the input list
"""
super(Set, self).__init__(trait, default_value, minlen, maxlen, **kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"trait",
"=",
"None",
",",
"default_value",
"=",
"Undefined",
",",
"minlen",
"=",
"0",
",",
"maxlen",
"=",
"sys",
".",
"maxsize",
",",
"*",
"*",
"kwargs",
",",
")",
":",
"super",
"(",
"Set",
",",
"self",
")",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py3/traitlets/traitlets.py#L2662-L2696 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ribbon/art_msw.py | python | RibbonMSWArtProvider.GetPageBackgroundRedrawArea | (self, dc, wnd, page_old_size, page_new_size) | return new_rect | Calculate the portion of a page background which needs to be redrawn when a page
is resized.
To optimise the drawing of page backgrounds, as small an area as possible should
be returned. Of couse, if the way in which a background is drawn means that the
entire background needs to be repainted on resize, then the entire new size
should be returned.
:param `dc`: A device context to use when one is required for size calculations;
:param `wnd`: The page which is being resized;
:param `page_old_size`: The size of the page prior to the resize (which has
already been painted);
:param `page_new_size`: The size of the page after the resize. | Calculate the portion of a page background which needs to be redrawn when a page
is resized. | [
"Calculate",
"the",
"portion",
"of",
"a",
"page",
"background",
"which",
"needs",
"to",
"be",
"redrawn",
"when",
"a",
"page",
"is",
"resized",
"."
] | def GetPageBackgroundRedrawArea(self, dc, wnd, page_old_size, page_new_size):
"""
Calculate the portion of a page background which needs to be redrawn when a page
is resized.
To optimise the drawing of page backgrounds, as small an area as possible should
be returned. Of couse, if the way in which a background is drawn means that the
entire background needs to be repainted on resize, then the entire new size
should be returned.
:param `dc`: A device context to use when one is required for size calculations;
:param `wnd`: The page which is being resized;
:param `page_old_size`: The size of the page prior to the resize (which has
already been painted);
:param `page_new_size`: The size of the page after the resize.
"""
if page_new_size.GetWidth() != page_old_size.GetWidth():
if page_new_size.GetHeight() != page_old_size.GetHeight():
# Width and height both changed - redraw everything
return wx.Rect(0, 0, *page_new_size)
else:
# Only width changed - redraw right hand side
right_edge_width = 4
new_rect = wx.Rect(page_new_size.GetWidth() - right_edge_width, 0, right_edge_width, page_new_size.GetHeight())
old_rect = wx.Rect(page_old_size.GetWidth() - right_edge_width, 0, right_edge_width, page_old_size.GetHeight())
else:
if page_new_size.GetHeight() == page_old_size.GetHeight():
# Nothing changed (should never happen) - redraw nothing
return wx.Rect(0, 0, 0, 0)
else:
# Height changed - need to redraw everything (as the background
# gradient is done vertically).
return wx.Rect(0, 0, *page_new_size)
new_rect.Union(old_rect)
new_rect.Intersect(wx.Rect(0, 0, *page_new_size))
return new_rect | [
"def",
"GetPageBackgroundRedrawArea",
"(",
"self",
",",
"dc",
",",
"wnd",
",",
"page_old_size",
",",
"page_new_size",
")",
":",
"if",
"page_new_size",
".",
"GetWidth",
"(",
")",
"!=",
"page_old_size",
".",
"GetWidth",
"(",
")",
":",
"if",
"page_new_size",
".... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ribbon/art_msw.py#L2500-L2539 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/BatchNormalization.py | python | BatchNormalization.channel_based | (self, channel_based) | Sets the channel-based mode. | Sets the channel-based mode. | [
"Sets",
"the",
"channel",
"-",
"based",
"mode",
"."
] | def channel_based(self, channel_based):
"""Sets the channel-based mode.
"""
self._internal.set_channel_based(bool(channel_based)) | [
"def",
"channel_based",
"(",
"self",
",",
"channel_based",
")",
":",
"self",
".",
"_internal",
".",
"set_channel_based",
"(",
"bool",
"(",
"channel_based",
")",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/BatchNormalization.py#L79-L82 | ||
nsnam/ns-3-dev-git | efdb2e21f45c0a87a60b47c547b68fa140a7b686 | utils/grid.py | python | Timelines.get_all | (self) | return self.timelines | ! Get All Timeline
@param self this object
@return all timelines | ! Get All Timeline | [
"!",
"Get",
"All",
"Timeline"
] | def get_all(self):
"""! Get All Timeline
@param self this object
@return all timelines
"""
return self.timelines | [
"def",
"get_all",
"(",
"self",
")",
":",
"return",
"self",
".",
"timelines"
] | https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/utils/grid.py#L390-L395 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/learn/python/learn/graph_actions.py | python | run_n | (output_dict, feed_dict=None, restore_checkpoint_path=None, n=1) | return run_feeds(
output_dict=output_dict,
feed_dicts=itertools.repeat(feed_dict, n),
restore_checkpoint_path=restore_checkpoint_path) | Run `output_dict` tensors `n` times, with the same `feed_dict` each run.
Args:
output_dict: A `dict` mapping string names to tensors to run. Must all be
from the same graph.
feed_dict: `dict` of input values to feed each run.
restore_checkpoint_path: A string containing the path to a checkpoint to
restore.
n: Number of times to repeat.
Returns:
A list of `n` `dict` objects, each containing values read from `output_dict`
tensors. | Run `output_dict` tensors `n` times, with the same `feed_dict` each run. | [
"Run",
"output_dict",
"tensors",
"n",
"times",
"with",
"the",
"same",
"feed_dict",
"each",
"run",
"."
] | def run_n(output_dict, feed_dict=None, restore_checkpoint_path=None, n=1):
"""Run `output_dict` tensors `n` times, with the same `feed_dict` each run.
Args:
output_dict: A `dict` mapping string names to tensors to run. Must all be
from the same graph.
feed_dict: `dict` of input values to feed each run.
restore_checkpoint_path: A string containing the path to a checkpoint to
restore.
n: Number of times to repeat.
Returns:
A list of `n` `dict` objects, each containing values read from `output_dict`
tensors.
"""
return run_feeds(
output_dict=output_dict,
feed_dicts=itertools.repeat(feed_dict, n),
restore_checkpoint_path=restore_checkpoint_path) | [
"def",
"run_n",
"(",
"output_dict",
",",
"feed_dict",
"=",
"None",
",",
"restore_checkpoint_path",
"=",
"None",
",",
"n",
"=",
"1",
")",
":",
"return",
"run_feeds",
"(",
"output_dict",
"=",
"output_dict",
",",
"feed_dicts",
"=",
"itertools",
".",
"repeat",
... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/graph_actions.py#L779-L797 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/rfc822.py | python | Message.__setitem__ | (self, name, value) | Set the value of a header.
Note: This is not a perfect inversion of __getitem__, because any
changed headers get stuck at the end of the raw-headers list rather
than where the altered header was. | Set the value of a header. | [
"Set",
"the",
"value",
"of",
"a",
"header",
"."
] | def __setitem__(self, name, value):
"""Set the value of a header.
Note: This is not a perfect inversion of __getitem__, because any
changed headers get stuck at the end of the raw-headers list rather
than where the altered header was.
"""
del self[name] # Won't fail if it doesn't exist
self.dict[name.lower()] = value
text = name + ": " + value
for line in text.split("\n"):
self.headers.append(line + "\n") | [
"def",
"__setitem__",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"del",
"self",
"[",
"name",
"]",
"# Won't fail if it doesn't exist",
"self",
".",
"dict",
"[",
"name",
".",
"lower",
"(",
")",
"]",
"=",
"value",
"text",
"=",
"name",
"+",
"\": \""... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/rfc822.py#L395-L406 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/ogr.py | python | Feature.SetFieldBinaryFromHexString | (self, *args) | return _ogr.Feature_SetFieldBinaryFromHexString(self, *args) | r"""
SetFieldBinaryFromHexString(Feature self, int id, char const * pszValue)
SetFieldBinaryFromHexString(Feature self, char const * field_name, char const * pszValue) | r"""
SetFieldBinaryFromHexString(Feature self, int id, char const * pszValue)
SetFieldBinaryFromHexString(Feature self, char const * field_name, char const * pszValue) | [
"r",
"SetFieldBinaryFromHexString",
"(",
"Feature",
"self",
"int",
"id",
"char",
"const",
"*",
"pszValue",
")",
"SetFieldBinaryFromHexString",
"(",
"Feature",
"self",
"char",
"const",
"*",
"field_name",
"char",
"const",
"*",
"pszValue",
")"
] | def SetFieldBinaryFromHexString(self, *args):
r"""
SetFieldBinaryFromHexString(Feature self, int id, char const * pszValue)
SetFieldBinaryFromHexString(Feature self, char const * field_name, char const * pszValue)
"""
return _ogr.Feature_SetFieldBinaryFromHexString(self, *args) | [
"def",
"SetFieldBinaryFromHexString",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_ogr",
".",
"Feature_SetFieldBinaryFromHexString",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L3847-L3852 | |
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | bert-gpu/modeling.py | python | BertConfig.from_json_file | (cls, json_file) | return cls.from_dict(json.loads(text)) | Constructs a `BertConfig` from a json file of parameters. | Constructs a `BertConfig` from a json file of parameters. | [
"Constructs",
"a",
"BertConfig",
"from",
"a",
"json",
"file",
"of",
"parameters",
"."
] | def from_json_file(cls, json_file):
"""Constructs a `BertConfig` from a json file of parameters."""
with tf.gfile.GFile(json_file, "r") as reader:
text = reader.read()
return cls.from_dict(json.loads(text)) | [
"def",
"from_json_file",
"(",
"cls",
",",
"json_file",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"GFile",
"(",
"json_file",
",",
"\"r\"",
")",
"as",
"reader",
":",
"text",
"=",
"reader",
".",
"read",
"(",
")",
"return",
"cls",
".",
"from_dict",
"(",... | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/modeling.py#L92-L96 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py | python | Decimal.__hash__ | (self) | return -2 if ans == -1 else ans | x.__hash__() <==> hash(x) | x.__hash__() <==> hash(x) | [
"x",
".",
"__hash__",
"()",
"<",
"==",
">",
"hash",
"(",
"x",
")"
] | def __hash__(self):
"""x.__hash__() <==> hash(x)"""
# In order to make sure that the hash of a Decimal instance
# agrees with the hash of a numerically equal integer, float
# or Fraction, we follow the rules for numeric hashes outlined
# in the documentation. (See library docs, 'Built-in Types').
if self._is_special:
if self.is_snan():
raise TypeError('Cannot hash a signaling NaN value.')
elif self.is_nan():
return _PyHASH_NAN
else:
if self._sign:
return -_PyHASH_INF
else:
return _PyHASH_INF
if self._exp >= 0:
exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
else:
exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
ans = hash_ if self >= 0 else -hash_
return -2 if ans == -1 else ans | [
"def",
"__hash__",
"(",
"self",
")",
":",
"# In order to make sure that the hash of a Decimal instance",
"# agrees with the hash of a numerically equal integer, float",
"# or Fraction, we follow the rules for numeric hashes outlined",
"# in the documentation. (See library docs, 'Built-in Types').... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py#L943-L967 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/distutils/fcompiler/gnu.py | python | Gnu95FCompiler._link_wrapper_lib | (self, objects, output_dir, extra_dll_dir,
chained_dlls, is_archive) | return lib_path, dll_path | Create a wrapper shared library for the given objects
Return an MSVC-compatible lib | Create a wrapper shared library for the given objects | [
"Create",
"a",
"wrapper",
"shared",
"library",
"for",
"the",
"given",
"objects"
] | def _link_wrapper_lib(self, objects, output_dir, extra_dll_dir,
chained_dlls, is_archive):
"""Create a wrapper shared library for the given objects
Return an MSVC-compatible lib
"""
c_compiler = self.c_compiler
if c_compiler.compiler_type != "msvc":
raise ValueError("This method only supports MSVC")
object_hash = self._hash_files(list(objects) + list(chained_dlls))
if is_win64():
tag = 'win_amd64'
else:
tag = 'win32'
basename = 'lib' + os.path.splitext(
os.path.basename(objects[0]))[0][:8]
root_name = basename + '.' + object_hash + '.gfortran-' + tag
dll_name = root_name + '.dll'
def_name = root_name + '.def'
lib_name = root_name + '.lib'
dll_path = os.path.join(extra_dll_dir, dll_name)
def_path = os.path.join(output_dir, def_name)
lib_path = os.path.join(output_dir, lib_name)
if os.path.isfile(lib_path):
# Nothing to do
return lib_path, dll_path
if is_archive:
objects = (["-Wl,--whole-archive"] + list(objects) +
["-Wl,--no-whole-archive"])
self.link_shared_object(
objects,
dll_name,
output_dir=extra_dll_dir,
extra_postargs=list(chained_dlls) + [
'-Wl,--allow-multiple-definition',
'-Wl,--output-def,' + def_path,
'-Wl,--export-all-symbols',
'-Wl,--enable-auto-import',
'-static',
'-mlong-double-64',
])
# No PowerPC!
if is_win64():
specifier = '/MACHINE:X64'
else:
specifier = '/MACHINE:X86'
# MSVC specific code
lib_args = ['/def:' + def_path, '/OUT:' + lib_path, specifier]
if not c_compiler.initialized:
c_compiler.initialize()
c_compiler.spawn([c_compiler.lib] + lib_args)
return lib_path, dll_path | [
"def",
"_link_wrapper_lib",
"(",
"self",
",",
"objects",
",",
"output_dir",
",",
"extra_dll_dir",
",",
"chained_dlls",
",",
"is_archive",
")",
":",
"c_compiler",
"=",
"self",
".",
"c_compiler",
"if",
"c_compiler",
".",
"compiler_type",
"!=",
"\"msvc\"",
":",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/distutils/fcompiler/gnu.py#L422-L482 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/py/shell.py | python | ShellFacade.__init__ | (self, other) | Create a ShellFacade instance. | Create a ShellFacade instance. | [
"Create",
"a",
"ShellFacade",
"instance",
"."
] | def __init__(self, other):
"""Create a ShellFacade instance."""
d = self.__dict__
d['other'] = other
d['helpText'] = HELP_TEXT
d['this'] = other.this | [
"def",
"__init__",
"(",
"self",
",",
"other",
")",
":",
"d",
"=",
"self",
".",
"__dict__",
"d",
"[",
"'other'",
"]",
"=",
"other",
"d",
"[",
"'helpText'",
"]",
"=",
"HELP_TEXT",
"d",
"[",
"'this'",
"]",
"=",
"other",
".",
"this"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/shell.py#L171-L176 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/op_selector.py | python | make_list_of_op | (tops, check_graph=True, allow_graph=True, ignore_ts=False) | Convert ops to a list of `tf.Operation`.
Args:
tops: can be an iterable of `tf.Operation`, a `tf.Graph` or a single
operation.
check_graph: if `True` check if all the operations belong to the same graph.
allow_graph: if `False` a `tf.Graph` cannot be converted.
ignore_ts: if True, silently ignore `tf.Tensor`.
Returns:
A newly created list of `tf.Operation`.
Raises:
TypeError: if tops cannot be converted to a list of `tf.Operation` or,
if `check_graph` is `True`, if all the ops do not belong to the
same graph. | Convert ops to a list of `tf.Operation`. | [
"Convert",
"ops",
"to",
"a",
"list",
"of",
"tf",
".",
"Operation",
"."
] | def make_list_of_op(tops, check_graph=True, allow_graph=True, ignore_ts=False):
"""Convert ops to a list of `tf.Operation`.
Args:
tops: can be an iterable of `tf.Operation`, a `tf.Graph` or a single
operation.
check_graph: if `True` check if all the operations belong to the same graph.
allow_graph: if `False` a `tf.Graph` cannot be converted.
ignore_ts: if True, silently ignore `tf.Tensor`.
Returns:
A newly created list of `tf.Operation`.
Raises:
TypeError: if tops cannot be converted to a list of `tf.Operation` or,
if `check_graph` is `True`, if all the ops do not belong to the
same graph.
"""
if isinstance(tops, ops.Graph):
if allow_graph:
return tops.get_operations()
else:
raise TypeError("allow_graph is False: cannot convert a tf.Graph.")
else:
if not is_iterable(tops):
tops = [tops]
if not tops:
return []
if check_graph:
check_types = None if ignore_ts else ops.Operation
get_unique_graph(tops, check_types=check_types)
return [op for op in tops if isinstance(op, ops.Operation)] | [
"def",
"make_list_of_op",
"(",
"tops",
",",
"check_graph",
"=",
"True",
",",
"allow_graph",
"=",
"True",
",",
"ignore_ts",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"tops",
",",
"ops",
".",
"Graph",
")",
":",
"if",
"allow_graph",
":",
"return",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/op_selector.py#L194-L223 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Misc.winfo_id | (self) | return int(self.tk.call('winfo', 'id', self._w), 0) | Return identifier ID for this widget. | Return identifier ID for this widget. | [
"Return",
"identifier",
"ID",
"for",
"this",
"widget",
"."
] | def winfo_id(self):
"""Return identifier ID for this widget."""
return int(self.tk.call('winfo', 'id', self._w), 0) | [
"def",
"winfo_id",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'id'",
",",
"self",
".",
"_w",
")",
",",
"0",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L851-L853 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/utils/vim-lldb/python-vim-lldb/lldb_controller.py | python | LLDBController.doHide | (self, name) | handle :Lhide <name> | handle :Lhide <name> | [
"handle",
":",
"Lhide",
"<name",
">"
] | def doHide(self, name):
""" handle :Lhide <name> """
if self.ui.hideWindow(name):
self.ui.update(self.target, "", self) | [
"def",
"doHide",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"ui",
".",
"hideWindow",
"(",
"name",
")",
":",
"self",
".",
"ui",
".",
"update",
"(",
"self",
".",
"target",
",",
"\"\"",
",",
"self",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/utils/vim-lldb/python-vim-lldb/lldb_controller.py#L297-L300 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/macosx.py | python | tkVersionWarning | (root) | Returns a string warning message if the Tk version in use appears to
be one known to cause problems with IDLE.
1. Apple Cocoa-based Tk 8.5.7 shipped with Mac OS X 10.6 is unusable.
2. Apple Cocoa-based Tk 8.5.9 in OS X 10.7 and 10.8 is better but
can still crash unexpectedly. | Returns a string warning message if the Tk version in use appears to
be one known to cause problems with IDLE.
1. Apple Cocoa-based Tk 8.5.7 shipped with Mac OS X 10.6 is unusable.
2. Apple Cocoa-based Tk 8.5.9 in OS X 10.7 and 10.8 is better but
can still crash unexpectedly. | [
"Returns",
"a",
"string",
"warning",
"message",
"if",
"the",
"Tk",
"version",
"in",
"use",
"appears",
"to",
"be",
"one",
"known",
"to",
"cause",
"problems",
"with",
"IDLE",
".",
"1",
".",
"Apple",
"Cocoa",
"-",
"based",
"Tk",
"8",
".",
"5",
".",
"7",... | def tkVersionWarning(root):
"""
Returns a string warning message if the Tk version in use appears to
be one known to cause problems with IDLE.
1. Apple Cocoa-based Tk 8.5.7 shipped with Mac OS X 10.6 is unusable.
2. Apple Cocoa-based Tk 8.5.9 in OS X 10.7 and 10.8 is better but
can still crash unexpectedly.
"""
if isCocoaTk():
patchlevel = root.tk.call('info', 'patchlevel')
if patchlevel not in ('8.5.7', '8.5.9'):
return False
return ("WARNING: The version of Tcl/Tk ({0}) in use may"
" be unstable.\n"
"Visit http://www.python.org/download/mac/tcltk/"
" for current information.".format(patchlevel))
else:
return False | [
"def",
"tkVersionWarning",
"(",
"root",
")",
":",
"if",
"isCocoaTk",
"(",
")",
":",
"patchlevel",
"=",
"root",
".",
"tk",
".",
"call",
"(",
"'info'",
",",
"'patchlevel'",
")",
"if",
"patchlevel",
"not",
"in",
"(",
"'8.5.7'",
",",
"'8.5.9'",
")",
":",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/macosx.py#L71-L89 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TNEANet.AddNode | (self, *args) | return _snap.TNEANet_AddNode(self, *args) | AddNode(TNEANet self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TNEANet self) -> int
AddNode(TNEANet self, TNEANet::TNodeI const & NodeId) -> int
Parameters:
NodeId: TNEANet::TNodeI const & | AddNode(TNEANet self, int NId=-1) -> int | [
"AddNode",
"(",
"TNEANet",
"self",
"int",
"NId",
"=",
"-",
"1",
")",
"-",
">",
"int"
] | def AddNode(self, *args):
"""
AddNode(TNEANet self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TNEANet self) -> int
AddNode(TNEANet self, TNEANet::TNodeI const & NodeId) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
"""
return _snap.TNEANet_AddNode(self, *args) | [
"def",
"AddNode",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TNEANet_AddNode",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L21353-L21367 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/io/io.py | python | NDArrayIter.next | (self) | return DataBatch(data=data, label=label, \
pad=self.getpad(), index=None) | Returns the next batch of data. | Returns the next batch of data. | [
"Returns",
"the",
"next",
"batch",
"of",
"data",
"."
] | def next(self):
"""Returns the next batch of data."""
if not self.iter_next():
raise StopIteration
data = self.getdata()
label = self.getlabel()
# iter should stop when last batch is not complete
if data[0].shape[0] != self.batch_size:
# in this case, cache it for next epoch
self._cache_data = data
self._cache_label = label
raise StopIteration
return DataBatch(data=data, label=label, \
pad=self.getpad(), index=None) | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"iter_next",
"(",
")",
":",
"raise",
"StopIteration",
"data",
"=",
"self",
".",
"getdata",
"(",
")",
"label",
"=",
"self",
".",
"getlabel",
"(",
")",
"# iter should stop when last batch is not... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/io/io.py#L677-L690 | |
neopenx/Dragon | 0e639a7319035ddc81918bd3df059230436ee0a1 | Dragon/python/dragon/vm/tensorflow/framework/ops.py | python | convert_to_tensor | (value, dtype=None, name=None, **kwargs) | return tensor | Converts the given value to a Tensor.
Parameters
----------
value : basic type, list or numpy.ndarray
The value to convert.
dtype : Dtype or None
The data type. If ``None``, inferred from the type of `value`.
name : str or None
The Optional name.
Returns
-------
Tensor
The output tensor. | Converts the given value to a Tensor. | [
"Converts",
"the",
"given",
"value",
"to",
"a",
"Tensor",
"."
] | def convert_to_tensor(value, dtype=None, name=None, **kwargs):
"""Converts the given value to a Tensor.
Parameters
----------
value : basic type, list or numpy.ndarray
The value to convert.
dtype : Dtype or None
The data type. If ``None``, inferred from the type of `value`.
name : str or None
The Optional name.
Returns
-------
Tensor
The output tensor.
"""
if dtype is not None:
if not isinstance(dtype, str):
if isinstance(dtype, dtypes.DType):
dtype = dtype.name
else:
raise ValueError('The dtype should be a str of a tf.Dtype.')
tensor = Tensor(name=name, dtype=dtype)
tensor.set_value(value)
return tensor | [
"def",
"convert_to_tensor",
"(",
"value",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dtype",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"dtype",
",",
"str",
")",
":",
"if",
"isinsta... | https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/tensorflow/framework/ops.py#L17-L43 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/io/resource.py | python | visualEditTypes | () | return ['Config','Configs','Trajectory','Vector3','Point','RigidTransform','Rotation','WorldModel'] | Returns types that can be visually edited | Returns types that can be visually edited | [
"Returns",
"types",
"that",
"can",
"be",
"visually",
"edited"
] | def visualEditTypes():
"""Returns types that can be visually edited"""
return ['Config','Configs','Trajectory','Vector3','Point','RigidTransform','Rotation','WorldModel'] | [
"def",
"visualEditTypes",
"(",
")",
":",
"return",
"[",
"'Config'",
",",
"'Configs'",
",",
"'Trajectory'",
",",
"'Vector3'",
",",
"'Point'",
",",
"'RigidTransform'",
",",
"'Rotation'",
",",
"'WorldModel'",
"]"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/io/resource.py#L108-L110 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Environment.py | python | Base._canonicalize | (self, path) | return path | Allow Dirs and strings beginning with # for top-relative.
Note this uses the current env's fs (in self). | Allow Dirs and strings beginning with # for top-relative. | [
"Allow",
"Dirs",
"and",
"strings",
"beginning",
"with",
"#",
"for",
"top",
"-",
"relative",
"."
] | def _canonicalize(self, path):
"""Allow Dirs and strings beginning with # for top-relative.
Note this uses the current env's fs (in self).
"""
if not is_String(path): # typically a Dir
path = str(path)
if path and path[0] == '#':
path = str(self.fs.Dir(path))
return path | [
"def",
"_canonicalize",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"is_String",
"(",
"path",
")",
":",
"# typically a Dir",
"path",
"=",
"str",
"(",
"path",
")",
"if",
"path",
"and",
"path",
"[",
"0",
"]",
"==",
"'#'",
":",
"path",
"=",
"str"... | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Environment.py#L1255-L1264 | |
gnina/gnina | b9ae032f52fc7a8153987bde09c0efa3620d8bb6 | caffe/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/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/tools/extra/extract_seconds.py#L31-L41 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mapreduce/mapreduce/shuffler.py | python | _HashingGCSOutputWriter.from_json | (cls, json) | return cls(pickle.loads(json["filehandles"])) | Creates an instance of the OutputWriter for the given json state.
Args:
json: The OutputWriter state as a dict-like object.
Returns:
An instance of the OutputWriter configured using the values of json. | Creates an instance of the OutputWriter for the given json state. | [
"Creates",
"an",
"instance",
"of",
"the",
"OutputWriter",
"for",
"the",
"given",
"json",
"state",
"."
] | def from_json(cls, json):
"""Creates an instance of the OutputWriter for the given json state.
Args:
json: The OutputWriter state as a dict-like object.
Returns:
An instance of the OutputWriter configured using the values of json.
"""
return cls(pickle.loads(json["filehandles"])) | [
"def",
"from_json",
"(",
"cls",
",",
"json",
")",
":",
"return",
"cls",
"(",
"pickle",
".",
"loads",
"(",
"json",
"[",
"\"filehandles\"",
"]",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/shuffler.py#L447-L456 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/ops.py | python | squeeze | (labeled_tensor, axis_names=None, name=None) | Remove size-1 dimensions.
See tf.squeeze.
Args:
labeled_tensor: The input tensor.
axis_names: The names of the dimensions to remove, or None to remove
all size-1 dimensions.
name: Optional op name.
Returns:
A tensor with the specified dimensions removed.
Raises:
ValueError: If the named axes are not in the tensor, or if they are
not size-1. | Remove size-1 dimensions. | [
"Remove",
"size",
"-",
"1",
"dimensions",
"."
] | def squeeze(labeled_tensor, axis_names=None, name=None):
"""Remove size-1 dimensions.
See tf.squeeze.
Args:
labeled_tensor: The input tensor.
axis_names: The names of the dimensions to remove, or None to remove
all size-1 dimensions.
name: Optional op name.
Returns:
A tensor with the specified dimensions removed.
Raises:
ValueError: If the named axes are not in the tensor, or if they are
not size-1.
"""
with ops.name_scope(name, 'lt_squeeze', [labeled_tensor]) as scope:
labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor)
if axis_names is None:
axis_names = [a.name for a in labeled_tensor.axes.values() if len(a) == 1]
for axis_name in axis_names:
if axis_name not in labeled_tensor.axes:
raise ValueError('axis %s is not in tensor axes %s' %
(axis_name, labeled_tensor.axes))
elif len(labeled_tensor.axes[axis_name]) != 1:
raise ValueError(
'cannot squeeze axis with size greater than 1: (%s, %s)' %
(axis_name, labeled_tensor.axes[axis_name]))
squeeze_dimensions = []
axes = []
for i, axis in enumerate(labeled_tensor.axes.values()):
if axis.name in axis_names:
squeeze_dimensions.append(i)
else:
axes.append(axis)
if squeeze_dimensions:
squeeze_op = array_ops.squeeze(
labeled_tensor.tensor, squeeze_dimensions, name=scope)
else:
squeeze_op = array_ops.identity(labeled_tensor.tensor, name=scope)
return core.LabeledTensor(squeeze_op, axes) | [
"def",
"squeeze",
"(",
"labeled_tensor",
",",
"axis_names",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"'lt_squeeze'",
",",
"[",
"labeled_tensor",
"]",
")",
"as",
"scope",
":",
"labeled_tensor",
"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/labeled_tensor/python/ops/ops.py#L705-L752 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/coremodules/demand/turnflows_wxgui.py | python | AddTurnflowTool.get_optionspanel | (self, parent, size=wx.DefaultSize) | return self._optionspanel | Return tool option widgets on given parent | Return tool option widgets on given parent | [
"Return",
"tool",
"option",
"widgets",
"on",
"given",
"parent"
] | def get_optionspanel(self, parent, size=wx.DefaultSize):
"""
Return tool option widgets on given parent
"""
size = (200, -1)
buttons = [('Add flow', self.on_add_flow, 'Add flow generation on from-edge to demand.'),
('Add turns', self.on_add_turn, 'Add turn flow from from-edge to to-edge to demand.'),
('Clear', self.on_clear_edges, 'Clear edge selection.'),
#('Save flows', self.on_add, 'Save OD flows to current demand.'),
#('Cancel', self.on_close, 'Close wizzard without adding flows.'),
]
defaultbuttontext = 'Add flow'
self._optionspanel = ObjPanel(parent, obj=self,
attrconfigs=None,
groupnames=['options'],
func_change_obj=None,
show_groupnames=False, show_title=True, is_modal=False,
mainframe=self.parent.get_mainframe(),
pos=wx.DefaultPosition, size=size, style=wx.MAXIMIZE_BOX | wx.RESIZE_BORDER,
immediate_apply=True, panelstyle='default', # 'instrumental'
buttons=buttons, defaultbutton=defaultbuttontext,
standartbuttons=[], # standartbuttons=['restore']
)
return self._optionspanel | [
"def",
"get_optionspanel",
"(",
"self",
",",
"parent",
",",
"size",
"=",
"wx",
".",
"DefaultSize",
")",
":",
"size",
"=",
"(",
"200",
",",
"-",
"1",
")",
"buttons",
"=",
"[",
"(",
"'Add flow'",
",",
"self",
".",
"on_add_flow",
",",
"'Add flow generatio... | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/turnflows_wxgui.py#L465-L489 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/auibar.py | python | AuiToolBar.SetMargins | (self, left=-1, right=-1, top=-1, bottom=-1) | Set the values to be used as margins for the toolbar.
:param integer `left`: the left toolbar margin;
:param integer `right`: the right toolbar margin;
:param integer `top`: the top toolbar margin;
:param integer `bottom`: the bottom toolbar margin. | Set the values to be used as margins for the toolbar. | [
"Set",
"the",
"values",
"to",
"be",
"used",
"as",
"margins",
"for",
"the",
"toolbar",
"."
] | def SetMargins(self, left=-1, right=-1, top=-1, bottom=-1):
"""
Set the values to be used as margins for the toolbar.
:param integer `left`: the left toolbar margin;
:param integer `right`: the right toolbar margin;
:param integer `top`: the top toolbar margin;
:param integer `bottom`: the bottom toolbar margin.
"""
if left != -1:
self._left_padding = left
if right != -1:
self._right_padding = right
if top != -1:
self._top_padding = top
if bottom != -1:
self._bottom_padding = bottom | [
"def",
"SetMargins",
"(",
"self",
",",
"left",
"=",
"-",
"1",
",",
"right",
"=",
"-",
"1",
",",
"top",
"=",
"-",
"1",
",",
"bottom",
"=",
"-",
"1",
")",
":",
"if",
"left",
"!=",
"-",
"1",
":",
"self",
".",
"_left_padding",
"=",
"left",
"if",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L2433-L2450 | ||
v8mips/v8mips | f0c9cc0bbfd461c7f516799d9a58e9a7395f737e | tools/grokdump.py | python | InspectionShell.do_lm | (self, arg) | List details for all loaded modules in the minidump. An argument can
be passed to limit the output to only those modules that contain the
argument as a substring (case insensitive match). | List details for all loaded modules in the minidump. An argument can
be passed to limit the output to only those modules that contain the
argument as a substring (case insensitive match). | [
"List",
"details",
"for",
"all",
"loaded",
"modules",
"in",
"the",
"minidump",
".",
"An",
"argument",
"can",
"be",
"passed",
"to",
"limit",
"the",
"output",
"to",
"only",
"those",
"modules",
"that",
"contain",
"the",
"argument",
"as",
"a",
"substring",
"("... | def do_lm(self, arg):
"""
List details for all loaded modules in the minidump. An argument can
be passed to limit the output to only those modules that contain the
argument as a substring (case insensitive match).
"""
for module in self.reader.module_list.modules:
if arg:
name = GetModuleName(self.reader, module).lower()
if name.find(arg.lower()) >= 0:
PrintModuleDetails(self.reader, module)
else:
PrintModuleDetails(self.reader, module)
print | [
"def",
"do_lm",
"(",
"self",
",",
"arg",
")",
":",
"for",
"module",
"in",
"self",
".",
"reader",
".",
"module_list",
".",
"modules",
":",
"if",
"arg",
":",
"name",
"=",
"GetModuleName",
"(",
"self",
".",
"reader",
",",
"module",
")",
".",
"lower",
... | https://github.com/v8mips/v8mips/blob/f0c9cc0bbfd461c7f516799d9a58e9a7395f737e/tools/grokdump.py#L2931-L2944 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/graph_editor/select.py | python | get_walks_intersection_ops | (forward_seed_ops,
backward_seed_ops,
forward_inclusive=True,
backward_inclusive=True,
within_ops=None,
control_inputs=False,
control_outputs=None,
control_ios=None) | return [op for op in forward_ops if op in backward_ops] | Return the intersection of a foward and a backward walk.
Args:
forward_seed_ops: an iterable of operations from which the forward graph
walk starts. If a list of tensors is given instead, the seed_ops are set
to be the consumers of those tensors.
backward_seed_ops: an iterable of operations from which the backward graph
walk starts. If a list of tensors is given instead, the seed_ops are set
to be the generators of those tensors.
forward_inclusive: if True the given forward_seed_ops are also part of the
resulting set.
backward_inclusive: if True the given backward_seed_ops are also part of the
resulting set.
within_ops: an iterable of tf.Operation whithin which the search is
restricted. If within_ops is None, the search is performed within
the whole graph.
control_inputs: A boolean indicating whether control inputs are enabled.
control_outputs: An instance of util.ControlOutputs or None. If not None,
control outputs are enabled.
control_ios: An instance of util.ControlOutputs or None. If not None, both
control inputs and control outputs are enabled. This is equivalent to set
control_inputs to True and control_outputs to the util.ControlOutputs
instance.
Returns:
A Python set of all the tf.Operation in the intersection of a foward and a
backward walk.
Raises:
TypeError: if forward_seed_ops or backward_seed_ops or within_ops cannot be
converted to a list of tf.Operation. | Return the intersection of a foward and a backward walk. | [
"Return",
"the",
"intersection",
"of",
"a",
"foward",
"and",
"a",
"backward",
"walk",
"."
] | def get_walks_intersection_ops(forward_seed_ops,
backward_seed_ops,
forward_inclusive=True,
backward_inclusive=True,
within_ops=None,
control_inputs=False,
control_outputs=None,
control_ios=None):
"""Return the intersection of a foward and a backward walk.
Args:
forward_seed_ops: an iterable of operations from which the forward graph
walk starts. If a list of tensors is given instead, the seed_ops are set
to be the consumers of those tensors.
backward_seed_ops: an iterable of operations from which the backward graph
walk starts. If a list of tensors is given instead, the seed_ops are set
to be the generators of those tensors.
forward_inclusive: if True the given forward_seed_ops are also part of the
resulting set.
backward_inclusive: if True the given backward_seed_ops are also part of the
resulting set.
within_ops: an iterable of tf.Operation whithin which the search is
restricted. If within_ops is None, the search is performed within
the whole graph.
control_inputs: A boolean indicating whether control inputs are enabled.
control_outputs: An instance of util.ControlOutputs or None. If not None,
control outputs are enabled.
control_ios: An instance of util.ControlOutputs or None. If not None, both
control inputs and control outputs are enabled. This is equivalent to set
control_inputs to True and control_outputs to the util.ControlOutputs
instance.
Returns:
A Python set of all the tf.Operation in the intersection of a foward and a
backward walk.
Raises:
TypeError: if forward_seed_ops or backward_seed_ops or within_ops cannot be
converted to a list of tf.Operation.
"""
control_inputs, control_outputs = check_cios(control_inputs, control_outputs,
control_ios)
forward_ops = get_forward_walk_ops(forward_seed_ops,
inclusive=forward_inclusive,
within_ops=within_ops,
control_outputs=control_outputs)
backward_ops = get_backward_walk_ops(backward_seed_ops,
inclusive=backward_inclusive,
within_ops=within_ops,
control_inputs=control_inputs)
return [op for op in forward_ops if op in backward_ops] | [
"def",
"get_walks_intersection_ops",
"(",
"forward_seed_ops",
",",
"backward_seed_ops",
",",
"forward_inclusive",
"=",
"True",
",",
"backward_inclusive",
"=",
"True",
",",
"within_ops",
"=",
"None",
",",
"control_inputs",
"=",
"False",
",",
"control_outputs",
"=",
"... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/graph_editor/select.py#L471-L519 | |
DaFuCoding/MTCNN_Caffe | 09c30c3ff391bd9cb6b249c1910afaf147767ab3 | scripts/cpp_lint.py | python | ReplaceAll | (pattern, rep, s) | return _regexp_compile_cache[pattern].sub(rep, s) | Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements) | Replaces instances of pattern in a string with a replacement. | [
"Replaces",
"instances",
"of",
"pattern",
"in",
"a",
"string",
"with",
"a",
"replacement",
"."
] | def ReplaceAll(pattern, rep, s):
"""Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements)
"""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].sub(rep, s) | [
"def",
"ReplaceAll",
"(",
"pattern",
",",
"rep",
",",
"s",
")",
":",
"if",
"pattern",
"not",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_c... | https://github.com/DaFuCoding/MTCNN_Caffe/blob/09c30c3ff391bd9cb6b249c1910afaf147767ab3/scripts/cpp_lint.py#L525-L540 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rosgraph/src/rosgraph/impl/graph.py | python | Graph._node_refresh | (self, node, bad_node=False) | return updated | Contact node for stats/connectivity information
@param node: name of node to contact
@type node: str
@param bad_node: if True, node has connectivity issues
@type bad_node: bool
@return: True if node was successfully contacted
@rtype bool | Contact node for stats/connectivity information | [
"Contact",
"node",
"for",
"stats",
"/",
"connectivity",
"information"
] | def _node_refresh(self, node, bad_node=False):
"""
Contact node for stats/connectivity information
@param node: name of node to contact
@type node: str
@param bad_node: if True, node has connectivity issues
@type bad_node: bool
@return: True if node was successfully contacted
@rtype bool
"""
# TODO: I'd like for master to provide this information in
# getSystemState() instead to prevent the extra connection per node
updated = False
uri = self._node_uri_refresh(node)
try:
if uri:
api = ServerProxy(uri)
updated = self._node_refresh_businfo(node, api, bad_node)
except KeyError as e:
logger.warn('cannot contact node [%s] as it is not in the lookup table'%node)
return updated | [
"def",
"_node_refresh",
"(",
"self",
",",
"node",
",",
"bad_node",
"=",
"False",
")",
":",
"# TODO: I'd like for master to provide this information in",
"# getSystemState() instead to prevent the extra connection per node",
"updated",
"=",
"False",
"uri",
"=",
"self",
".",
... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosgraph/src/rosgraph/impl/graph.py#L439-L459 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/lookup/lookup_ops.py | python | TableInitializerBase.initialize | (self, table) | Returns the table initialization op. | Returns the table initialization op. | [
"Returns",
"the",
"table",
"initialization",
"op",
"."
] | def initialize(self, table):
"""Returns the table initialization op."""
raise NotImplementedError | [
"def",
"initialize",
"(",
"self",
",",
"table",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/lookup/lookup_ops.py#L257-L259 | ||
Z3Prover/z3 | d745d03afdfdf638d66093e2bfbacaf87187f35b | src/api/python/z3/z3.py | python | BitVec | (name, bv, ctx=None) | return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx) | Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
If `ctx=None`, then the global context is used.
>>> x = BitVec('x', 16)
>>> is_bv(x)
True
>>> x.size()
16
>>> x.sort()
BitVec(16)
>>> word = BitVecSort(16)
>>> x2 = BitVec('x', word)
>>> eq(x, x2)
True | Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
If `ctx=None`, then the global context is used. | [
"Return",
"a",
"bit",
"-",
"vector",
"constant",
"named",
"name",
".",
"bv",
"may",
"be",
"the",
"number",
"of",
"bits",
"of",
"a",
"bit",
"-",
"vector",
"sort",
".",
"If",
"ctx",
"=",
"None",
"then",
"the",
"global",
"context",
"is",
"used",
"."
] | def BitVec(name, bv, ctx=None):
"""Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
If `ctx=None`, then the global context is used.
>>> x = BitVec('x', 16)
>>> is_bv(x)
True
>>> x.size()
16
>>> x.sort()
BitVec(16)
>>> word = BitVecSort(16)
>>> x2 = BitVec('x', word)
>>> eq(x, x2)
True
"""
if isinstance(bv, BitVecSortRef):
ctx = bv.ctx
else:
ctx = _get_ctx(ctx)
bv = BitVecSort(bv, ctx)
return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx) | [
"def",
"BitVec",
"(",
"name",
",",
"bv",
",",
"ctx",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"bv",
",",
"BitVecSortRef",
")",
":",
"ctx",
"=",
"bv",
".",
"ctx",
"else",
":",
"ctx",
"=",
"_get_ctx",
"(",
"ctx",
")",
"bv",
"=",
"BitVecSort"... | https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L4002-L4023 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/exploitability.py | python | _state_values | (state, num_players, policy) | Value of a state for every player given a policy. | Value of a state for every player given a policy. | [
"Value",
"of",
"a",
"state",
"for",
"every",
"player",
"given",
"a",
"policy",
"."
] | def _state_values(state, num_players, policy):
"""Value of a state for every player given a policy."""
if state.is_terminal():
return np.array(state.returns())
else:
p_action = (
state.chance_outcomes() if state.is_chance_node() else
policy.action_probabilities(state).items())
return sum(prob * _state_values(state.child(action), num_players, policy)
for action, prob in p_action) | [
"def",
"_state_values",
"(",
"state",
",",
"num_players",
",",
"policy",
")",
":",
"if",
"state",
".",
"is_terminal",
"(",
")",
":",
"return",
"np",
".",
"array",
"(",
"state",
".",
"returns",
"(",
")",
")",
"else",
":",
"p_action",
"=",
"(",
"state"... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/exploitability.py#L49-L58 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/nanops.py | python | nankurt | (
values: np.ndarray,
*,
axis: int | None = None,
skipna: bool = True,
mask: np.ndarray | None = None,
) | return result | Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G2, computed directly from the second and fourth
central moment.
Parameters
----------
values : ndarray
axis : int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 1, 3, 2])
>>> nanops.nankurt(s)
-1.2892561983471076 | Compute the sample excess kurtosis | [
"Compute",
"the",
"sample",
"excess",
"kurtosis"
] | def nankurt(
values: np.ndarray,
*,
axis: int | None = None,
skipna: bool = True,
mask: np.ndarray | None = None,
) -> float:
"""
Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G2, computed directly from the second and fourth
central moment.
Parameters
----------
values : ndarray
axis : int, optional
skipna : bool, default True
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float64
Unless input is a float array, in which case use the same
precision as the input array.
Examples
--------
>>> import pandas.core.nanops as nanops
>>> s = pd.Series([1, np.nan, 1, 3, 2])
>>> nanops.nankurt(s)
-1.2892561983471076
"""
# error: Incompatible types in assignment (expression has type "Union[Any,
# Union[ExtensionArray, ndarray]]", variable has type "ndarray")
values = extract_array(values, extract_numpy=True) # type: ignore[assignment]
mask = _maybe_get_mask(values, skipna, mask)
if not is_float_dtype(values.dtype):
values = values.astype("f8")
count = _get_counts(values.shape, mask, axis)
else:
count = _get_counts(values.shape, mask, axis, dtype=values.dtype)
if skipna and mask is not None:
values = values.copy()
np.putmask(values, mask, 0)
mean = values.sum(axis, dtype=np.float64) / count
if axis is not None:
mean = np.expand_dims(mean, axis)
adjusted = values - mean
if skipna and mask is not None:
np.putmask(adjusted, mask, 0)
adjusted2 = adjusted ** 2
adjusted4 = adjusted2 ** 2
m2 = adjusted2.sum(axis, dtype=np.float64)
m4 = adjusted4.sum(axis, dtype=np.float64)
with np.errstate(invalid="ignore", divide="ignore"):
adj = 3 * (count - 1) ** 2 / ((count - 2) * (count - 3))
numerator = count * (count + 1) * (count - 1) * m4
denominator = (count - 2) * (count - 3) * m2 ** 2
# floating point error
#
# #18044 in _libs/windows.pyx calc_kurt follow this behavior
# to fix the fperr to treat denom <1e-14 as zero
numerator = _zero_out_fperr(numerator)
denominator = _zero_out_fperr(denominator)
if not isinstance(denominator, np.ndarray):
# if ``denom`` is a scalar, check these corner cases first before
# doing division
if count < 4:
return np.nan
if denominator == 0:
return 0
with np.errstate(invalid="ignore", divide="ignore"):
result = numerator / denominator - adj
dtype = values.dtype
if is_float_dtype(dtype):
result = result.astype(dtype)
if isinstance(result, np.ndarray):
result = np.where(denominator == 0, 0, result)
result[count < 4] = np.nan
return result | [
"def",
"nankurt",
"(",
"values",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"axis",
":",
"int",
"|",
"None",
"=",
"None",
",",
"skipna",
":",
"bool",
"=",
"True",
",",
"mask",
":",
"np",
".",
"ndarray",
"|",
"None",
"=",
"None",
",",
")",
"->",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/nanops.py#L1210-L1302 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py | python | _BaseV4._is_valid_netmask | (self, netmask) | return 0 <= netmask <= self._max_prefixlen | Verify that the netmask is valid.
Args:
netmask: A string, either a prefix or dotted decimal
netmask.
Returns:
A boolean, True if the prefix represents a valid IPv4
netmask. | Verify that the netmask is valid. | [
"Verify",
"that",
"the",
"netmask",
"is",
"valid",
"."
] | def _is_valid_netmask(self, netmask):
"""Verify that the netmask is valid.
Args:
netmask: A string, either a prefix or dotted decimal
netmask.
Returns:
A boolean, True if the prefix represents a valid IPv4
netmask.
"""
mask = netmask.split('.')
if len(mask) == 4:
try:
for x in mask:
if int(x) not in self._valid_mask_octets:
return False
except ValueError:
# Found something that isn't an integer or isn't valid
return False
for idx, y in enumerate(mask):
if idx > 0 and y > mask[idx - 1]:
return False
return True
try:
netmask = int(netmask)
except ValueError:
return False
return 0 <= netmask <= self._max_prefixlen | [
"def",
"_is_valid_netmask",
"(",
"self",
",",
"netmask",
")",
":",
"mask",
"=",
"netmask",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"mask",
")",
"==",
"4",
":",
"try",
":",
"for",
"x",
"in",
"mask",
":",
"if",
"int",
"(",
"x",
")",
"not... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py#L1218-L1247 | |
GoSSIP-SJTU/Armariris | ad5d868482956b2194a77b39c8d543c7c2318200 | tools/clang/tools/scan-build-py/libscanbuild/clang.py | python | get_checkers | (clang, plugins) | Get all the available checkers from default and from the plugins.
clang -- the compiler we are using
plugins -- list of plugins which was requested by the user
This method returns a dictionary of all available checkers and status.
{<plugin name>: (<plugin description>, <is active by default>)} | Get all the available checkers from default and from the plugins. | [
"Get",
"all",
"the",
"available",
"checkers",
"from",
"default",
"and",
"from",
"the",
"plugins",
"."
] | def get_checkers(clang, plugins):
""" Get all the available checkers from default and from the plugins.
clang -- the compiler we are using
plugins -- list of plugins which was requested by the user
This method returns a dictionary of all available checkers and status.
{<plugin name>: (<plugin description>, <is active by default>)} """
plugins = plugins if plugins else []
def parse_checkers(stream):
""" Parse clang -analyzer-checker-help output.
Below the line 'CHECKERS:' are there the name description pairs.
Many of them are in one line, but some long named plugins has the
name and the description in separate lines.
The plugin name is always prefixed with two space character. The
name contains no whitespaces. Then followed by newline (if it's
too long) or other space characters comes the description of the
plugin. The description ends with a newline character. """
# find checkers header
for line in stream:
if re.match(r'^CHECKERS:', line):
break
# find entries
state = None
for line in stream:
if state and not re.match(r'^\s\s\S', line):
yield (state, line.strip())
state = None
elif re.match(r'^\s\s\S+$', line.rstrip()):
state = line.strip()
else:
pattern = re.compile(r'^\s\s(?P<key>\S*)\s*(?P<value>.*)')
match = pattern.match(line.rstrip())
if match:
current = match.groupdict()
yield (current['key'], current['value'])
def is_active(actives, entry):
""" Returns true if plugin name is matching the active plugin names.
actives -- set of active plugin names (or prefixes).
entry -- the current plugin name to judge.
The active plugin names are specific plugin names or prefix of some
names. One example for prefix, when it say 'unix' and it shall match
on 'unix.API', 'unix.Malloc' and 'unix.MallocSizeof'. """
return any(re.match(r'^' + a + r'(\.|$)', entry) for a in actives)
actives = get_active_checkers(clang, plugins)
load = [elem for plugin in plugins for elem in ['-load', plugin]]
cmd = [clang, '-cc1'] + load + ['-analyzer-checker-help']
logging.debug('exec command: %s', ' '.join(cmd))
child = subprocess.Popen(cmd,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
checkers = {
k: (v, is_active(actives, k))
for k, v in parse_checkers(child.stdout)
}
child.stdout.close()
child.wait()
if child.returncode == 0 and len(checkers):
return checkers
else:
raise Exception('Could not query Clang for available checkers.') | [
"def",
"get_checkers",
"(",
"clang",
",",
"plugins",
")",
":",
"plugins",
"=",
"plugins",
"if",
"plugins",
"else",
"[",
"]",
"def",
"parse_checkers",
"(",
"stream",
")",
":",
"\"\"\" Parse clang -analyzer-checker-help output.\n\n Below the line 'CHECKERS:' are ther... | https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/tools/scan-build-py/libscanbuild/clang.py#L82-L156 | ||
RoboJackets/robocup-software | bce13ce53ddb2ecb9696266d980722c34617dc15 | rj_gameplay/stp/role/__init__.py | python | CostFn.unassigned_cost_fn | (
self, prev_results: Optional["RoleResult"], world_state: stp.rc.WorldState
) | Given the previous role assigment and current world state,
returns the cost of not assigning any robot.
:param prev_result: The previous role assignment result.
:param world_state: The current world state.
:return: cost of not assigning | Given the previous role assigment and current world state,
returns the cost of not assigning any robot.
:param prev_result: The previous role assignment result.
:param world_state: The current world state.
:return: cost of not assigning | [
"Given",
"the",
"previous",
"role",
"assigment",
"and",
"current",
"world",
"state",
"returns",
"the",
"cost",
"of",
"not",
"assigning",
"any",
"robot",
".",
":",
"param",
"prev_result",
":",
"The",
"previous",
"role",
"assignment",
"result",
".",
":",
"para... | def unassigned_cost_fn(
self, prev_results: Optional["RoleResult"], world_state: stp.rc.WorldState
) -> float:
"""Given the previous role assigment and current world state,
returns the cost of not assigning any robot.
:param prev_result: The previous role assignment result.
:param world_state: The current world state.
:return: cost of not assigning
"""
... | [
"def",
"unassigned_cost_fn",
"(",
"self",
",",
"prev_results",
":",
"Optional",
"[",
"\"RoleResult\"",
"]",
",",
"world_state",
":",
"stp",
".",
"rc",
".",
"WorldState",
")",
"->",
"float",
":",
"..."
] | https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/stp/role/__init__.py#L69-L78 | ||
HKUST-Aerial-Robotics/Fast-Planner | 2ddd7793eecd573dbb5b47e2c985aa06606df3cf | uav_simulator/Utils/odom_visualization/build/catkin_generated/installspace/_setup_util.py | python | find_env_hooks | (environ, cmake_prefix_path) | return lines | Generate shell code with found environment hooks
for the all workspaces. | Generate shell code with found environment hooks
for the all workspaces. | [
"Generate",
"shell",
"code",
"with",
"found",
"environment",
"hooks",
"for",
"the",
"all",
"workspaces",
"."
] | def find_env_hooks(environ, cmake_prefix_path):
'''
Generate shell code with found environment hooks
for the all workspaces.
'''
lines = []
lines.append(comment('found environment hooks in workspaces'))
generic_env_hooks = []
generic_env_hooks_workspace = []
specific_env_hooks = []
specific_env_hooks_workspace = []
generic_env_hooks_by_filename = {}
specific_env_hooks_by_filename = {}
generic_env_hook_ext = 'bat' if IS_WINDOWS else 'sh'
specific_env_hook_ext = environ['CATKIN_SHELL'] if not IS_WINDOWS and 'CATKIN_SHELL' in environ and environ['CATKIN_SHELL'] else None
# remove non-workspace paths
workspaces = [path for path in cmake_prefix_path.split(os.pathsep) if path and os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE))]
for workspace in reversed(workspaces):
env_hook_dir = os.path.join(workspace, 'etc', 'catkin', 'profile.d')
if os.path.isdir(env_hook_dir):
for filename in sorted(os.listdir(env_hook_dir)):
if filename.endswith('.%s' % generic_env_hook_ext):
# remove previous env hook with same name if present
if filename in generic_env_hooks_by_filename:
i = generic_env_hooks.index(generic_env_hooks_by_filename[filename])
generic_env_hooks.pop(i)
generic_env_hooks_workspace.pop(i)
# append env hook
generic_env_hooks.append(os.path.join(env_hook_dir, filename))
generic_env_hooks_workspace.append(workspace)
generic_env_hooks_by_filename[filename] = generic_env_hooks[-1]
elif specific_env_hook_ext is not None and filename.endswith('.%s' % specific_env_hook_ext):
# remove previous env hook with same name if present
if filename in specific_env_hooks_by_filename:
i = specific_env_hooks.index(specific_env_hooks_by_filename[filename])
specific_env_hooks.pop(i)
specific_env_hooks_workspace.pop(i)
# append env hook
specific_env_hooks.append(os.path.join(env_hook_dir, filename))
specific_env_hooks_workspace.append(workspace)
specific_env_hooks_by_filename[filename] = specific_env_hooks[-1]
env_hooks = generic_env_hooks + specific_env_hooks
env_hooks_workspace = generic_env_hooks_workspace + specific_env_hooks_workspace
count = len(env_hooks)
lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_COUNT', count))
for i in range(count):
lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d' % i, env_hooks[i]))
lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d_WORKSPACE' % i, env_hooks_workspace[i]))
return lines | [
"def",
"find_env_hooks",
"(",
"environ",
",",
"cmake_prefix_path",
")",
":",
"lines",
"=",
"[",
"]",
"lines",
".",
"append",
"(",
"comment",
"(",
"'found environment hooks in workspaces'",
")",
")",
"generic_env_hooks",
"=",
"[",
"]",
"generic_env_hooks_workspace",
... | https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/odom_visualization/build/catkin_generated/installspace/_setup_util.py#L195-L244 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/codecs.py | python | IncrementalEncoder.encode | (self, input, final=False) | Encodes input and returns the resulting object. | Encodes input and returns the resulting object. | [
"Encodes",
"input",
"and",
"returns",
"the",
"resulting",
"object",
"."
] | def encode(self, input, final=False):
"""
Encodes input and returns the resulting object.
"""
raise NotImplementedError | [
"def",
"encode",
"(",
"self",
",",
"input",
",",
"final",
"=",
"False",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/codecs.py#L197-L201 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/factorization/python/ops/gmm_ops.py | python | GmmAlgorithm._define_distance_to_clusters | (self, data) | Defines the Mahalanobis distance to the assigned Gaussian. | Defines the Mahalanobis distance to the assigned Gaussian. | [
"Defines",
"the",
"Mahalanobis",
"distance",
"to",
"the",
"assigned",
"Gaussian",
"."
] | def _define_distance_to_clusters(self, data):
"""Defines the Mahalanobis distance to the assigned Gaussian."""
# TODO(xavigonzalvo): reuse (input - mean) * cov^-1 * (input -
# mean) from log probability function.
self._all_scores = []
for shard in data:
all_scores = []
shard = array_ops.expand_dims(shard, 0)
for c in xrange(self._num_classes):
if self._covariance_type == FULL_COVARIANCE:
cov = self._covs[c, :, :]
elif self._covariance_type == DIAG_COVARIANCE:
cov = array_ops.diag(self._covs[c, :])
inverse = linalg_ops.matrix_inverse(cov + self._min_var)
inv_cov = array_ops.tile(
array_ops.expand_dims(inverse, 0),
array_ops.stack([self._num_examples, 1, 1]))
diff = array_ops.transpose(shard - self._means[c, :, :], perm=[1, 0, 2])
m_left = math_ops.matmul(diff, inv_cov)
all_scores.append(
math_ops.sqrt(
math_ops.matmul(
m_left, array_ops.transpose(
diff, perm=[0, 2, 1]))))
self._all_scores.append(
array_ops.reshape(
array_ops.concat(all_scores, 1),
array_ops.stack([self._num_examples, self._num_classes])))
# Distance to the associated class.
self._all_scores = array_ops.concat(self._all_scores, 0)
assignments = array_ops.concat(self.assignments(), 0)
rows = math_ops.to_int64(math_ops.range(0, self._num_examples))
indices = array_ops.concat(
[array_ops.expand_dims(rows, 1), array_ops.expand_dims(assignments, 1)],
1)
self._scores = array_ops.gather_nd(self._all_scores, indices) | [
"def",
"_define_distance_to_clusters",
"(",
"self",
",",
"data",
")",
":",
"# TODO(xavigonzalvo): reuse (input - mean) * cov^-1 * (input -",
"# mean) from log probability function.",
"self",
".",
"_all_scores",
"=",
"[",
"]",
"for",
"shard",
"in",
"data",
":",
"all_scores",... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L443-L479 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/instrument.py | python | Instrument.option_strike_pcnt | (self, option_strike_pcnt) | Sets the option_strike_pcnt of this Instrument.
:param option_strike_pcnt: The option_strike_pcnt of this Instrument. # noqa: E501
:type: float | Sets the option_strike_pcnt of this Instrument. | [
"Sets",
"the",
"option_strike_pcnt",
"of",
"this",
"Instrument",
"."
] | def option_strike_pcnt(self, option_strike_pcnt):
"""Sets the option_strike_pcnt of this Instrument.
:param option_strike_pcnt: The option_strike_pcnt of this Instrument. # noqa: E501
:type: float
"""
self._option_strike_pcnt = option_strike_pcnt | [
"def",
"option_strike_pcnt",
"(",
"self",
",",
"option_strike_pcnt",
")",
":",
"self",
".",
"_option_strike_pcnt",
"=",
"option_strike_pcnt"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/instrument.py#L824-L832 | ||
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | third-party/benchmark/tools/gbench/report.py | python | calculate_geomean | (json) | return gmean(times) if times else array([]) | Extract all real/cpu times from all the benchmarks as seconds,
and calculate their geomean. | Extract all real/cpu times from all the benchmarks as seconds,
and calculate their geomean. | [
"Extract",
"all",
"real",
"/",
"cpu",
"times",
"from",
"all",
"the",
"benchmarks",
"as",
"seconds",
"and",
"calculate",
"their",
"geomean",
"."
] | def calculate_geomean(json):
"""
Extract all real/cpu times from all the benchmarks as seconds,
and calculate their geomean.
"""
times = []
for benchmark in json['benchmarks']:
if 'run_type' in benchmark and benchmark['run_type'] == 'aggregate':
continue
times.append([get_timedelta_field_as_seconds(benchmark, 'real_time'),
get_timedelta_field_as_seconds(benchmark, 'cpu_time')])
return gmean(times) if times else array([]) | [
"def",
"calculate_geomean",
"(",
"json",
")",
":",
"times",
"=",
"[",
"]",
"for",
"benchmark",
"in",
"json",
"[",
"'benchmarks'",
"]",
":",
"if",
"'run_type'",
"in",
"benchmark",
"and",
"benchmark",
"[",
"'run_type'",
"]",
"==",
"'aggregate'",
":",
"contin... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/third-party/benchmark/tools/gbench/report.py#L165-L176 | |
networkit/networkit | 695b7a786a894a303fa8587597d5ef916e797729 | scripts/webgraph.py | python | getLocations | (nodes, urls) | Given a collection of nodes, return a set of net locations (domains) to which they belong | Given a collection of nodes, return a set of net locations (domains) to which they belong | [
"Given",
"a",
"collection",
"of",
"nodes",
"return",
"a",
"set",
"of",
"net",
"locations",
"(",
"domains",
")",
"to",
"which",
"they",
"belong"
] | def getLocations(nodes, urls):
""" Given a collection of nodes, return a set of net locations (domains) to which they belong"""
theurls = dict((u, urls[u]) for u in nodes)
loclist = [urllib.parse.urlparse(url).netloc for url in theurls] | [
"def",
"getLocations",
"(",
"nodes",
",",
"urls",
")",
":",
"theurls",
"=",
"dict",
"(",
"(",
"u",
",",
"urls",
"[",
"u",
"]",
")",
"for",
"u",
"in",
"nodes",
")",
"loclist",
"=",
"[",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"... | https://github.com/networkit/networkit/blob/695b7a786a894a303fa8587597d5ef916e797729/scripts/webgraph.py#L52-L55 | ||
microsoft/ELL | a1d6bacc37a14879cc025d9be2ba40b1a0632315 | tools/importers/common/converters.py | python | LookupTable.set_owning_node_for_output | (self, output_id: str, ell_node: ell.nodes.Node) | Sets the mapping for the ELL node that owns the output identified
by output_id. | Sets the mapping for the ELL node that owns the output identified
by output_id. | [
"Sets",
"the",
"mapping",
"for",
"the",
"ELL",
"node",
"that",
"owns",
"the",
"output",
"identified",
"by",
"output_id",
"."
] | def set_owning_node_for_output(self, output_id: str, ell_node: ell.nodes.Node):
"""
Sets the mapping for the ELL node that owns the output identified
by output_id.
"""
self.output_id_to_ell_ids[output_id] = ell_node.GetId() | [
"def",
"set_owning_node_for_output",
"(",
"self",
",",
"output_id",
":",
"str",
",",
"ell_node",
":",
"ell",
".",
"nodes",
".",
"Node",
")",
":",
"self",
".",
"output_id_to_ell_ids",
"[",
"output_id",
"]",
"=",
"ell_node",
".",
"GetId",
"(",
")"
] | https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/common/converters.py#L296-L301 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/__init__.py | python | CreateJarBuilder | (env) | return java_jar | The Jar builder expects a list of class files
which it can package into a jar file.
The jar tool provides an interface for passing other types
of java files such as .java, directories or swig interfaces
and will build them to class files in which it can package
into the jar. | The Jar builder expects a list of class files
which it can package into a jar file. | [
"The",
"Jar",
"builder",
"expects",
"a",
"list",
"of",
"class",
"files",
"which",
"it",
"can",
"package",
"into",
"a",
"jar",
"file",
"."
] | def CreateJarBuilder(env):
"""The Jar builder expects a list of class files
which it can package into a jar file.
The jar tool provides an interface for passing other types
of java files such as .java, directories or swig interfaces
and will build them to class files in which it can package
into the jar.
"""
try:
java_jar = env['BUILDERS']['JarFile']
except KeyError:
fs = SCons.Node.FS.get_default_fs()
jar_com = SCons.Action.Action('$JARCOM', '$JARCOMSTR')
java_jar = SCons.Builder.Builder(action=jar_com,
suffix='$JARSUFFIX',
src_suffix='$JAVACLASSSUFFIX',
src_builder='JavaClassFile',
source_factory=fs.Entry)
env['BUILDERS']['JarFile'] = java_jar
return java_jar | [
"def",
"CreateJarBuilder",
"(",
"env",
")",
":",
"try",
":",
"java_jar",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'JarFile'",
"]",
"except",
"KeyError",
":",
"fs",
"=",
"SCons",
".",
"Node",
".",
"FS",
".",
"get_default_fs",
"(",
")",
"jar_com",
"=",
... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/__init__.py#L970-L990 | |
tensorflow/deepmath | b5b721f54de1d5d6a02d78f5da5995237f9995f9 | deepmath/guidance/jagged.py | python | unjagged | (value) | return None, value | Split a Tensor or Jagged into (sizes, flat).
This routine is for generic code that might be running on either jagged
or rectangular input. For example,
sizes, flat = unjagged(data)
flat = tf.nn.relu(flat)
data = jagged(sizes, falt)
Args:
value: Possibly Jagged array to split.
Returns:
sizes: value.sizes for Jagged input, otherwise None.
flat: value.flat for Jagged input, otherwise value. | Split a Tensor or Jagged into (sizes, flat). | [
"Split",
"a",
"Tensor",
"or",
"Jagged",
"into",
"(",
"sizes",
"flat",
")",
"."
] | def unjagged(value):
"""Split a Tensor or Jagged into (sizes, flat).
This routine is for generic code that might be running on either jagged
or rectangular input. For example,
sizes, flat = unjagged(data)
flat = tf.nn.relu(flat)
data = jagged(sizes, falt)
Args:
value: Possibly Jagged array to split.
Returns:
sizes: value.sizes for Jagged input, otherwise None.
flat: value.flat for Jagged input, otherwise value.
"""
if isinstance(value, Jagged):
return value.sizes, value.flat
return None, value | [
"def",
"unjagged",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Jagged",
")",
":",
"return",
"value",
".",
"sizes",
",",
"value",
".",
"flat",
"return",
"None",
",",
"value"
] | https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/guidance/jagged.py#L123-L142 | |
ucbrise/clipper | 9f25e3fc7f8edc891615e81c5b80d3d8aed72608 | clipper_admin/clipper_admin/docker/docker_metric_utils.py | python | run_metric_image | (metric_frontend_name, docker_client, common_labels,
prometheus_port, prom_config_path, log_config,
extra_container_kwargs) | Run the prometheus image.
:param metric_frontend_name: container name
:param docker_client: The docker client object
:param common_labels: Labels to pass in
:param prom_config_path: Where config file lives
:param extra_container_kwargs: Kwargs to pass in.
:return: None | Run the prometheus image.
:param metric_frontend_name: container name
:param docker_client: The docker client object
:param common_labels: Labels to pass in
:param prom_config_path: Where config file lives
:param extra_container_kwargs: Kwargs to pass in.
:return: None | [
"Run",
"the",
"prometheus",
"image",
".",
":",
"param",
"metric_frontend_name",
":",
"container",
"name",
":",
"param",
"docker_client",
":",
"The",
"docker",
"client",
"object",
":",
"param",
"common_labels",
":",
"Labels",
"to",
"pass",
"in",
":",
"param",
... | def run_metric_image(metric_frontend_name, docker_client, common_labels,
prometheus_port, prom_config_path, log_config,
extra_container_kwargs):
"""
Run the prometheus image.
:param metric_frontend_name: container name
:param docker_client: The docker client object
:param common_labels: Labels to pass in
:param prom_config_path: Where config file lives
:param extra_container_kwargs: Kwargs to pass in.
:return: None
"""
# CMD comes from https://github.com/prometheus/prometheus/blob/release-2.1/Dockerfile
metric_cmd = [
"--config.file=/etc/prometheus/prometheus.yml",
"--storage.tsdb.path=/prometheus",
"--web.console.libraries=/etc/prometheus/console_libraries",
"--web.console.templates=/etc/prometheus/consoles",
"--web.enable-lifecycle"
]
metric_labels = common_labels.copy()
run_container(
docker_client=docker_client,
image="prom/prometheus:{}".format(PROM_VERSION),
cmd=metric_cmd,
name=metric_frontend_name,
ports={'9090/tcp': prometheus_port},
log_config=log_config,
volumes={
prom_config_path: {
'bind': '/etc/prometheus/prometheus.yml',
'mode': 'ro'
}
},
user='root', # prom use nobody by default but it can't access config.
labels=metric_labels,
extra_container_kwargs=extra_container_kwargs) | [
"def",
"run_metric_image",
"(",
"metric_frontend_name",
",",
"docker_client",
",",
"common_labels",
",",
"prometheus_port",
",",
"prom_config_path",
",",
"log_config",
",",
"extra_container_kwargs",
")",
":",
"# CMD comes from https://github.com/prometheus/prometheus/blob/release... | https://github.com/ucbrise/clipper/blob/9f25e3fc7f8edc891615e81c5b80d3d8aed72608/clipper_admin/clipper_admin/docker/docker_metric_utils.py#L76-L114 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | ConfigBase.GetNumberOfGroups | (*args, **kwargs) | return _misc_.ConfigBase_GetNumberOfGroups(*args, **kwargs) | GetNumberOfGroups(self, bool recursive=False) -> size_t
Get the number of subgroups in the current group, with or without its
subgroups. | GetNumberOfGroups(self, bool recursive=False) -> size_t | [
"GetNumberOfGroups",
"(",
"self",
"bool",
"recursive",
"=",
"False",
")",
"-",
">",
"size_t"
] | def GetNumberOfGroups(*args, **kwargs):
"""
GetNumberOfGroups(self, bool recursive=False) -> size_t
Get the number of subgroups in the current group, with or without its
subgroups.
"""
return _misc_.ConfigBase_GetNumberOfGroups(*args, **kwargs) | [
"def",
"GetNumberOfGroups",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"ConfigBase_GetNumberOfGroups",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L3214-L3221 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/ttk.py | python | Treeview.selection_toggle | (self, *items) | Toggle the selection state of each specified item. | Toggle the selection state of each specified item. | [
"Toggle",
"the",
"selection",
"state",
"of",
"each",
"specified",
"item",
"."
] | def selection_toggle(self, *items):
"""Toggle the selection state of each specified item."""
self._selection("toggle", items) | [
"def",
"selection_toggle",
"(",
"self",
",",
"*",
"items",
")",
":",
"self",
".",
"_selection",
"(",
"\"toggle\"",
",",
"items",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/ttk.py#L1471-L1473 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/jinja2/debug.py | python | ProcessedTraceback.render_as_text | (self, limit=None) | return ''.join(lines).rstrip() | Return a string with the traceback. | Return a string with the traceback. | [
"Return",
"a",
"string",
"with",
"the",
"traceback",
"."
] | def render_as_text(self, limit=None):
"""Return a string with the traceback."""
lines = traceback.format_exception(self.exc_type, self.exc_value,
self.frames[0], limit=limit)
return ''.join(lines).rstrip() | [
"def",
"render_as_text",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"lines",
"=",
"traceback",
".",
"format_exception",
"(",
"self",
".",
"exc_type",
",",
"self",
".",
"exc_value",
",",
"self",
".",
"frames",
"[",
"0",
"]",
",",
"limit",
"=",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/debug.py#L97-L101 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/DNSFlippingRatioCorr.py | python | DNSFlippingRatioCorr.category | (self) | return 'Workflow\\MLZ\\DNS;;CorrectionFunctions\\SpecialCorrections' | Returns category | Returns category | [
"Returns",
"category"
] | def category(self):
"""
Returns category
"""
return 'Workflow\\MLZ\\DNS;;CorrectionFunctions\\SpecialCorrections' | [
"def",
"category",
"(",
"self",
")",
":",
"return",
"'Workflow\\\\MLZ\\\\DNS;;CorrectionFunctions\\\\SpecialCorrections'"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/DNSFlippingRatioCorr.py#L34-L38 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Tool/JavaCommon.py | python | get_java_install_dirs | (platform, version=None) | return sorted(paths) | Find the java jdk installation directories.
This list is intended to supply as "default paths" for use when looking
up actual java binaries.
:param platform: selector for search algorithm.
:param version: If specified, only look for java sdk's of this version
:return: list of default paths for java. | Find the java jdk installation directories. | [
"Find",
"the",
"java",
"jdk",
"installation",
"directories",
"."
] | def get_java_install_dirs(platform, version=None):
"""
Find the java jdk installation directories.
This list is intended to supply as "default paths" for use when looking
up actual java binaries.
:param platform: selector for search algorithm.
:param version: If specified, only look for java sdk's of this version
:return: list of default paths for java.
"""
paths = []
if platform == 'win32':
if version:
paths = glob.glob(java_win32_version_dir_glob % version)
else:
paths = glob.glob(java_win32_dir_glob)
else:
# other platforms, do nothing for now
pass
return sorted(paths) | [
"def",
"get_java_install_dirs",
"(",
"platform",
",",
"version",
"=",
"None",
")",
":",
"paths",
"=",
"[",
"]",
"if",
"platform",
"==",
"'win32'",
":",
"if",
"version",
":",
"paths",
"=",
"glob",
".",
"glob",
"(",
"java_win32_version_dir_glob",
"%",
"versi... | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Tool/JavaCommon.py#L446-L468 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/training/server_lib.py | python | ClusterSpec.job_tasks | (self, job_name) | return ret | Returns a mapping from task ID to address in the given job.
NOTE: For backwards compatibility, this method returns a list. If
the given job was defined with a sparse set of task indices, the
length of this list may not reflect the number of tasks defined in
this job. Use the [`num_tasks()`](#ClusterSpec.num_tasks) method
to find the number of tasks defined in a particular job.
Args:
job_name: The string name of a job in this cluster.
Returns:
A list of task addresses, where the index in the list
corresponds to the task index of each task. The list may contain
`None` if the job was defined with a sparse set of task indices.
Raises:
ValueError: If `job_name` does not name a job in this cluster. | Returns a mapping from task ID to address in the given job. | [
"Returns",
"a",
"mapping",
"from",
"task",
"ID",
"to",
"address",
"in",
"the",
"given",
"job",
"."
] | def job_tasks(self, job_name):
"""Returns a mapping from task ID to address in the given job.
NOTE: For backwards compatibility, this method returns a list. If
the given job was defined with a sparse set of task indices, the
length of this list may not reflect the number of tasks defined in
this job. Use the [`num_tasks()`](#ClusterSpec.num_tasks) method
to find the number of tasks defined in a particular job.
Args:
job_name: The string name of a job in this cluster.
Returns:
A list of task addresses, where the index in the list
corresponds to the task index of each task. The list may contain
`None` if the job was defined with a sparse set of task indices.
Raises:
ValueError: If `job_name` does not name a job in this cluster.
"""
try:
job = self._cluster_spec[job_name]
except KeyError:
raise ValueError("No such job in cluster: %r" % job_name)
ret = [None for _ in range(max(job.keys()) + 1)]
for i, task in job.items():
ret[i] = task
return ret | [
"def",
"job_tasks",
"(",
"self",
",",
"job_name",
")",
":",
"try",
":",
"job",
"=",
"self",
".",
"_cluster_spec",
"[",
"job_name",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"No such job in cluster: %r\"",
"%",
"job_name",
")",
"ret",
"=",... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/server_lib.py#L418-L445 | |
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/trader/gateway.py | python | BaseGateway.on_position | (self, position: PositionData) | Position event push.
Position event of a specific vt_symbol is also pushed. | Position event push.
Position event of a specific vt_symbol is also pushed. | [
"Position",
"event",
"push",
".",
"Position",
"event",
"of",
"a",
"specific",
"vt_symbol",
"is",
"also",
"pushed",
"."
] | def on_position(self, position: PositionData) -> None:
"""
Position event push.
Position event of a specific vt_symbol is also pushed.
"""
self.on_event(EVENT_POSITION, position)
self.on_event(EVENT_POSITION + position.vt_symbol, position) | [
"def",
"on_position",
"(",
"self",
",",
"position",
":",
"PositionData",
")",
"->",
"None",
":",
"self",
".",
"on_event",
"(",
"EVENT_POSITION",
",",
"position",
")",
"self",
".",
"on_event",
"(",
"EVENT_POSITION",
"+",
"position",
".",
"vt_symbol",
",",
"... | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/gateway.py#L120-L126 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/incubate/fleet/base/role_maker.py | python | MPISymetricRoleMaker.is_worker | (self) | return False | return whether current process is worker assigned by role maker | return whether current process is worker assigned by role maker | [
"return",
"whether",
"current",
"process",
"is",
"worker",
"assigned",
"by",
"role",
"maker"
] | def is_worker(self):
"""
return whether current process is worker assigned by role maker
"""
if self._check_role_generation():
return self._node_type == 1
return False | [
"def",
"is_worker",
"(",
"self",
")",
":",
"if",
"self",
".",
"_check_role_generation",
"(",
")",
":",
"return",
"self",
".",
"_node_type",
"==",
"1",
"return",
"False"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/base/role_maker.py#L365-L371 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/sparse/construct.py | python | hstack | (blocks, format=None, dtype=None) | return bmat([blocks], format=format, dtype=dtype) | Stack sparse matrices horizontally (column wise)
Parameters
----------
blocks
sequence of sparse matrices with compatible shapes
format : str
sparse format of the result (e.g. "csr")
by default an appropriate sparse matrix format is returned.
This choice is subject to change.
dtype : dtype, optional
The data-type of the output matrix. If not given, the dtype is
determined from that of `blocks`.
See Also
--------
vstack : stack sparse matrices vertically (row wise)
Examples
--------
>>> from scipy.sparse import coo_matrix, hstack
>>> A = coo_matrix([[1, 2], [3, 4]])
>>> B = coo_matrix([[5], [6]])
>>> hstack([A,B]).toarray()
array([[1, 2, 5],
[3, 4, 6]]) | Stack sparse matrices horizontally (column wise) | [
"Stack",
"sparse",
"matrices",
"horizontally",
"(",
"column",
"wise",
")"
] | def hstack(blocks, format=None, dtype=None):
"""
Stack sparse matrices horizontally (column wise)
Parameters
----------
blocks
sequence of sparse matrices with compatible shapes
format : str
sparse format of the result (e.g. "csr")
by default an appropriate sparse matrix format is returned.
This choice is subject to change.
dtype : dtype, optional
The data-type of the output matrix. If not given, the dtype is
determined from that of `blocks`.
See Also
--------
vstack : stack sparse matrices vertically (row wise)
Examples
--------
>>> from scipy.sparse import coo_matrix, hstack
>>> A = coo_matrix([[1, 2], [3, 4]])
>>> B = coo_matrix([[5], [6]])
>>> hstack([A,B]).toarray()
array([[1, 2, 5],
[3, 4, 6]])
"""
return bmat([blocks], format=format, dtype=dtype) | [
"def",
"hstack",
"(",
"blocks",
",",
"format",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"return",
"bmat",
"(",
"[",
"blocks",
"]",
",",
"format",
"=",
"format",
",",
"dtype",
"=",
"dtype",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/sparse/construct.py#L428-L458 | |
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | examples/faster-rcnn/lib/fast_rcnn/train.py | python | SolverWrapper.__init__ | (self, solver_prototxt, roidb, output_dir,
pretrained_model=None) | Initialize the SolverWrapper. | Initialize the SolverWrapper. | [
"Initialize",
"the",
"SolverWrapper",
"."
] | def __init__(self, solver_prototxt, roidb, output_dir,
pretrained_model=None):
"""Initialize the SolverWrapper."""
self.output_dir = output_dir
if (cfg.TRAIN.HAS_RPN and cfg.TRAIN.BBOX_REG and
cfg.TRAIN.BBOX_NORMALIZE_TARGETS):
# RPN can only use precomputed normalization because there are no
# fixed statistics to compute a priori
assert cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED
if cfg.TRAIN.BBOX_REG:
print 'Computing bounding-box regression targets...'
self.bbox_means, self.bbox_stds = \
rdl_roidb.add_bbox_regression_targets(roidb)
print 'done'
self.solver = caffe.SGDSolver(solver_prototxt)
if pretrained_model is not None:
print ('Loading pretrained model '
'weights from {:s}').format(pretrained_model)
self.solver.net.copy_from(pretrained_model)
self.solver_param = caffe_pb2.SolverParameter()
with open(solver_prototxt, 'rt') as f:
pb2.text_format.Merge(f.read(), self.solver_param)
self.solver.net.layers[0].set_roidb(roidb) | [
"def",
"__init__",
"(",
"self",
",",
"solver_prototxt",
",",
"roidb",
",",
"output_dir",
",",
"pretrained_model",
"=",
"None",
")",
":",
"self",
".",
"output_dir",
"=",
"output_dir",
"if",
"(",
"cfg",
".",
"TRAIN",
".",
"HAS_RPN",
"and",
"cfg",
".",
"TRA... | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/faster-rcnn/lib/fast_rcnn/train.py#L27-L54 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/cookies.py | python | RequestsCookieJar.itervalues | (self) | Dict-like itervalues() that returns an iterator of values of cookies
from the jar.
.. seealso:: iterkeys() and iteritems(). | Dict-like itervalues() that returns an iterator of values of cookies
from the jar. | [
"Dict",
"-",
"like",
"itervalues",
"()",
"that",
"returns",
"an",
"iterator",
"of",
"values",
"of",
"cookies",
"from",
"the",
"jar",
"."
] | def itervalues(self):
"""Dict-like itervalues() that returns an iterator of values of cookies
from the jar.
.. seealso:: iterkeys() and iteritems().
"""
for cookie in iter(self):
yield cookie.value | [
"def",
"itervalues",
"(",
"self",
")",
":",
"for",
"cookie",
"in",
"iter",
"(",
"self",
")",
":",
"yield",
"cookie",
".",
"value"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/cookies.py#L235-L242 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py | python | Decimal.same_quantum | (self, other, context=None) | return self._exp == other._exp | Return True if self and other have the same exponent; otherwise
return False.
If either operand is a special value, the following rules are used:
* return True if both operands are infinities
* return True if both operands are NaNs
* otherwise, return False. | Return True if self and other have the same exponent; otherwise
return False. | [
"Return",
"True",
"if",
"self",
"and",
"other",
"have",
"the",
"same",
"exponent",
";",
"otherwise",
"return",
"False",
"."
] | def same_quantum(self, other, context=None):
"""Return True if self and other have the same exponent; otherwise
return False.
If either operand is a special value, the following rules are used:
* return True if both operands are infinities
* return True if both operands are NaNs
* otherwise, return False.
"""
other = _convert_other(other, raiseit=True)
if self._is_special or other._is_special:
return (self.is_nan() and other.is_nan() or
self.is_infinite() and other.is_infinite())
return self._exp == other._exp | [
"def",
"same_quantum",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
",",
"raiseit",
"=",
"True",
")",
"if",
"self",
".",
"_is_special",
"or",
"other",
".",
"_is_special",
":",
"return",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py#L2597-L2610 | |
LiXizhi/NPLRuntime | a42720e5fe9a6960e0a9ce40bbbcd809192906be | Client/trunk/externals/freetype-2.8.1/src/tools/docmaker/sources.py | python | SourceBlockFormat.__init__ | ( self, id, start, column, end ) | Create a block pattern, used to recognize special documentation
blocks. | Create a block pattern, used to recognize special documentation
blocks. | [
"Create",
"a",
"block",
"pattern",
"used",
"to",
"recognize",
"special",
"documentation",
"blocks",
"."
] | def __init__( self, id, start, column, end ):
"""Create a block pattern, used to recognize special documentation
blocks."""
self.id = id
self.start = re.compile( start, re.VERBOSE )
self.column = re.compile( column, re.VERBOSE )
self.end = re.compile( end, re.VERBOSE ) | [
"def",
"__init__",
"(",
"self",
",",
"id",
",",
"start",
",",
"column",
",",
"end",
")",
":",
"self",
".",
"id",
"=",
"id",
"self",
".",
"start",
"=",
"re",
".",
"compile",
"(",
"start",
",",
"re",
".",
"VERBOSE",
")",
"self",
".",
"column",
"=... | https://github.com/LiXizhi/NPLRuntime/blob/a42720e5fe9a6960e0a9ce40bbbcd809192906be/Client/trunk/externals/freetype-2.8.1/src/tools/docmaker/sources.py#L50-L56 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py | python | SpectraToFoilPeriodMap.get_foilout_periods | (self, spectrum_no) | return self.get_foil_periods(spectrum_no, state=0) | Returns a list of the foil-out periods for the given
spectrum number. Note that these start from 1 not zero
@param spectrum_no :: A spectrum number (1->nspectra)
@returns A list of period numbers for foil out state | Returns a list of the foil-out periods for the given
spectrum number. Note that these start from 1 not zero | [
"Returns",
"a",
"list",
"of",
"the",
"foil",
"-",
"out",
"periods",
"for",
"the",
"given",
"spectrum",
"number",
".",
"Note",
"that",
"these",
"start",
"from",
"1",
"not",
"zero"
] | def get_foilout_periods(self, spectrum_no):
"""Returns a list of the foil-out periods for the given
spectrum number. Note that these start from 1 not zero
@param spectrum_no :: A spectrum number (1->nspectra)
@returns A list of period numbers for foil out state
"""
return self.get_foil_periods(spectrum_no, state=0) | [
"def",
"get_foilout_periods",
"(",
"self",
",",
"spectrum_no",
")",
":",
"return",
"self",
".",
"get_foil_periods",
"(",
"spectrum_no",
",",
"state",
"=",
"0",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py#L1084-L1090 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/sliding-window-median.py | python | Solution.medianSlidingWindow | (self, nums, k) | return result | :type nums: List[int]
:type k: int
:rtype: List[float] | :type nums: List[int]
:type k: int
:rtype: List[float] | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"List",
"[",
"float",
"]"
] | def medianSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[float]
"""
sl = SortedList(float(nums[i])for i in xrange(k))
result = [(sl[k//2]+sl[k//2-(1-k%2)])/2]
for i in xrange(k, len(nums)):
sl.add(float(nums[i]))
sl.remove(nums[i-k])
result.append((sl[k//2]+sl[k//2-(1-k%2)])/2)
return result | [
"def",
"medianSlidingWindow",
"(",
"self",
",",
"nums",
",",
"k",
")",
":",
"sl",
"=",
"SortedList",
"(",
"float",
"(",
"nums",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"k",
")",
")",
"result",
"=",
"[",
"(",
"sl",
"[",
"k",
"//",
... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/sliding-window-median.py#L8-L20 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/monitored_session.py | python | _MonitoredSession._tf_sess | (self) | return self._coordinated_creator.tf_sess | Return underlying tf.compat.v1.Session object.
Warning: accessing the returned object in user code is likely to cause races
or "flaky tests".
Returns:
A tf.compat.v1.Session object. | Return underlying tf.compat.v1.Session object. | [
"Return",
"underlying",
"tf",
".",
"compat",
".",
"v1",
".",
"Session",
"object",
"."
] | def _tf_sess(self):
"""Return underlying tf.compat.v1.Session object.
Warning: accessing the returned object in user code is likely to cause races
or "flaky tests".
Returns:
A tf.compat.v1.Session object.
"""
return self._coordinated_creator.tf_sess | [
"def",
"_tf_sess",
"(",
"self",
")",
":",
"return",
"self",
".",
"_coordinated_creator",
".",
"tf_sess"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/monitored_session.py#L917-L926 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | PageSetupDialogData.EnablePrinter | (*args, **kwargs) | return _windows_.PageSetupDialogData_EnablePrinter(*args, **kwargs) | EnablePrinter(self, bool flag) | EnablePrinter(self, bool flag) | [
"EnablePrinter",
"(",
"self",
"bool",
"flag",
")"
] | def EnablePrinter(*args, **kwargs):
"""EnablePrinter(self, bool flag)"""
return _windows_.PageSetupDialogData_EnablePrinter(*args, **kwargs) | [
"def",
"EnablePrinter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PageSetupDialogData_EnablePrinter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L4882-L4884 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/filters.py | python | do_int | (value: t.Any, default: int = 0, base: int = 10) | Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter. You
can also override the default base (10) in the second
parameter, which handles input with prefixes such as
0b, 0o and 0x for bases 2, 8 and 16 respectively.
The base is ignored for decimal numbers and non-string values. | Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter. You
can also override the default base (10) in the second
parameter, which handles input with prefixes such as
0b, 0o and 0x for bases 2, 8 and 16 respectively.
The base is ignored for decimal numbers and non-string values. | [
"Convert",
"the",
"value",
"into",
"an",
"integer",
".",
"If",
"the",
"conversion",
"doesn",
"t",
"work",
"it",
"will",
"return",
"0",
".",
"You",
"can",
"override",
"this",
"default",
"using",
"the",
"first",
"parameter",
".",
"You",
"can",
"also",
"ove... | def do_int(value: t.Any, default: int = 0, base: int = 10) -> int:
"""Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter. You
can also override the default base (10) in the second
parameter, which handles input with prefixes such as
0b, 0o and 0x for bases 2, 8 and 16 respectively.
The base is ignored for decimal numbers and non-string values.
"""
try:
if isinstance(value, str):
return int(value, base)
return int(value)
except (TypeError, ValueError):
# this quirk is necessary so that "42.23"|int gives 42.
try:
return int(float(value))
except (TypeError, ValueError):
return default | [
"def",
"do_int",
"(",
"value",
":",
"t",
".",
"Any",
",",
"default",
":",
"int",
"=",
"0",
",",
"base",
":",
"int",
"=",
"10",
")",
"->",
"int",
":",
"try",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"int",
"(",
"v... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/filters.py#L967-L986 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/errcheck.py | python | enhance_lib | () | modify existing classes and methods | modify existing classes and methods | [
"modify",
"existing",
"classes",
"and",
"methods"
] | def enhance_lib():
"""
modify existing classes and methods
"""
for m in meths_typos:
replace(m)
# catch '..' in ant_glob patterns
def ant_glob(self, *k, **kw):
if k:
lst=Utils.to_list(k[0])
for pat in lst:
if '..' in pat.split('/'):
Logs.error("In ant_glob pattern %r: '..' means 'two dots', not 'parent directory'" % k[0])
if kw.get('remove', True):
try:
if self.is_child_of(self.ctx.bldnode) and not kw.get('quiet', False):
Logs.error('Using ant_glob on the build folder (%r) is dangerous (quiet=True to disable this warning)' % self)
except AttributeError:
pass
return self.old_ant_glob(*k, **kw)
Node.Node.old_ant_glob = Node.Node.ant_glob
Node.Node.ant_glob = ant_glob
# catch conflicting ext_in/ext_out/before/after declarations
old = Task.is_before
def is_before(t1, t2):
ret = old(t1, t2)
if ret and old(t2, t1):
Logs.error('Contradictory order constraints in classes %r %r' % (t1, t2))
return ret
Task.is_before = is_before
# check for bld(feature='cshlib') where no 'c' is given - this can be either a mistake or on purpose
# so we only issue a warning
def check_err_features(self):
lst = self.to_list(self.features)
if 'shlib' in lst:
Logs.error('feature shlib -> cshlib, dshlib or cxxshlib')
for x in ('c', 'cxx', 'd', 'fc'):
if not x in lst and lst and lst[0] in [x+y for y in ('program', 'shlib', 'stlib')]:
Logs.error('%r features is probably missing %r' % (self, x))
TaskGen.feature('*')(check_err_features)
# check for erroneous order constraints
def check_err_order(self):
if not hasattr(self, 'rule') and not 'subst' in Utils.to_list(self.features):
for x in ('before', 'after', 'ext_in', 'ext_out'):
if hasattr(self, x):
Logs.warn('Erroneous order constraint %r on non-rule based task generator %r' % (x, self))
else:
for x in ('before', 'after'):
for y in self.to_list(getattr(self, x, [])):
if not Task.classes.get(y, None):
Logs.error('Erroneous order constraint %s=%r on %r (no such class)' % (x, y, self))
TaskGen.feature('*')(check_err_order)
# check for @extension used with @feature/@before_method/@after_method
def check_compile(self):
check_invalid_constraints(self)
try:
ret = self.orig_compile()
finally:
check_same_targets(self)
return ret
Build.BuildContext.orig_compile = Build.BuildContext.compile
Build.BuildContext.compile = check_compile
# check for invalid build groups #914
def use_rec(self, name, **kw):
try:
y = self.bld.get_tgen_by_name(name)
except Errors.WafError:
pass
else:
idx = self.bld.get_group_idx(self)
odx = self.bld.get_group_idx(y)
if odx > idx:
msg = "Invalid 'use' across build groups:"
if Logs.verbose > 1:
msg += '\n target %r\n uses:\n %r' % (self, y)
else:
msg += " %r uses %r (try 'waf -v -v' for the full error)" % (self.name, name)
raise Errors.WafError(msg)
self.orig_use_rec(name, **kw)
TaskGen.task_gen.orig_use_rec = TaskGen.task_gen.use_rec
TaskGen.task_gen.use_rec = use_rec
# check for env.append
def getattri(self, name, default=None):
if name == 'append' or name == 'add':
raise Errors.WafError('env.append and env.add do not exist: use env.append_value/env.append_unique')
elif name == 'prepend':
raise Errors.WafError('env.prepend does not exist: use env.prepend_value')
if name in self.__slots__:
return object.__getattr__(self, name, default)
else:
return self[name]
ConfigSet.ConfigSet.__getattr__ = getattri | [
"def",
"enhance_lib",
"(",
")",
":",
"for",
"m",
"in",
"meths_typos",
":",
"replace",
"(",
"m",
")",
"# catch '..' in ant_glob patterns",
"def",
"ant_glob",
"(",
"self",
",",
"*",
"k",
",",
"*",
"*",
"kw",
")",
":",
"if",
"k",
":",
"lst",
"=",
"Utils... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/errcheck.py#L111-L209 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xmlTextReader.XmlVersion | (self) | return ret | Determine the XML version of the document being read. | Determine the XML version of the document being read. | [
"Determine",
"the",
"XML",
"version",
"of",
"the",
"document",
"being",
"read",
"."
] | def XmlVersion(self):
"""Determine the XML version of the document being read. """
ret = libxml2mod.xmlTextReaderConstXmlVersion(self._o)
return ret | [
"def",
"XmlVersion",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlTextReaderConstXmlVersion",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L6949-L6952 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBTypeEnumMember.__str__ | (self) | return _lldb.SBTypeEnumMember___str__(self) | __str__(SBTypeEnumMember self) -> PyObject * | __str__(SBTypeEnumMember self) -> PyObject * | [
"__str__",
"(",
"SBTypeEnumMember",
"self",
")",
"-",
">",
"PyObject",
"*"
] | def __str__(self):
"""__str__(SBTypeEnumMember self) -> PyObject *"""
return _lldb.SBTypeEnumMember___str__(self) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBTypeEnumMember___str__",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L13367-L13369 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-server/gen-py/sdhashsrv/sdhashsrv.py | python | Client.displaySet | (self, num1) | return self.recv_displaySet() | Parameters:
- num1 | Parameters:
- num1 | [
"Parameters",
":",
"-",
"num1"
] | def displaySet(self, num1):
"""
Parameters:
- num1
"""
self.send_displaySet(num1)
return self.recv_displaySet() | [
"def",
"displaySet",
"(",
"self",
",",
"num1",
")",
":",
"self",
".",
"send_displaySet",
"(",
"num1",
")",
"return",
"self",
".",
"recv_displaySet",
"(",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-server/gen-py/sdhashsrv/sdhashsrv.py#L234-L240 | |
Cantera/cantera | 0119484b261967ccb55a0066c020599cacc312e4 | site_scons/buildutils.py | python | ipdb | () | Break execution and drop into an IPython debug shell at the point
where this function is called. | Break execution and drop into an IPython debug shell at the point
where this function is called. | [
"Break",
"execution",
"and",
"drop",
"into",
"an",
"IPython",
"debug",
"shell",
"at",
"the",
"point",
"where",
"this",
"function",
"is",
"called",
"."
] | def ipdb():
"""
Break execution and drop into an IPython debug shell at the point
where this function is called.
"""
from IPython.core.debugger import Pdb
from IPython.core import getipython
ip = getipython.get_ipython()
def_colors = ip.colors
Pdb(def_colors).set_trace(sys._getframe().f_back) | [
"def",
"ipdb",
"(",
")",
":",
"from",
"IPython",
".",
"core",
".",
"debugger",
"import",
"Pdb",
"from",
"IPython",
".",
"core",
"import",
"getipython",
"ip",
"=",
"getipython",
".",
"get_ipython",
"(",
")",
"def_colors",
"=",
"ip",
".",
"colors",
"Pdb",
... | https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/site_scons/buildutils.py#L1126-L1136 | ||
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py | python | File.changed | (self, node=None, allowcache=False) | return has_changed | Returns if the node is up-to-date with respect to the BuildInfo
stored last time it was built.
For File nodes this is basically a wrapper around Node.changed(),
but we allow the return value to get cached after the reference
to the Executor got released in release_target_info().
@see: Node.changed() | Returns if the node is up-to-date with respect to the BuildInfo
stored last time it was built. | [
"Returns",
"if",
"the",
"node",
"is",
"up",
"-",
"to",
"-",
"date",
"with",
"respect",
"to",
"the",
"BuildInfo",
"stored",
"last",
"time",
"it",
"was",
"built",
"."
] | def changed(self, node=None, allowcache=False):
"""
Returns if the node is up-to-date with respect to the BuildInfo
stored last time it was built.
For File nodes this is basically a wrapper around Node.changed(),
but we allow the return value to get cached after the reference
to the Executor got released in release_target_info().
@see: Node.changed()
"""
if node is None:
try:
return self._memo['changed']
except KeyError:
pass
has_changed = SCons.Node.Node.changed(self, node)
if allowcache:
self._memo['changed'] = has_changed
return has_changed | [
"def",
"changed",
"(",
"self",
",",
"node",
"=",
"None",
",",
"allowcache",
"=",
"False",
")",
":",
"if",
"node",
"is",
"None",
":",
"try",
":",
"return",
"self",
".",
"_memo",
"[",
"'changed'",
"]",
"except",
"KeyError",
":",
"pass",
"has_changed",
... | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py#L3206-L3226 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Image.SetAlpha | (*args, **kwargs) | return _core_.Image_SetAlpha(*args, **kwargs) | SetAlpha(self, int x, int y, byte alpha)
Sets the alpha value for the given pixel. This function should only be
called if the image has alpha channel data, use `HasAlpha` to check
for this. | SetAlpha(self, int x, int y, byte alpha) | [
"SetAlpha",
"(",
"self",
"int",
"x",
"int",
"y",
"byte",
"alpha",
")"
] | def SetAlpha(*args, **kwargs):
"""
SetAlpha(self, int x, int y, byte alpha)
Sets the alpha value for the given pixel. This function should only be
called if the image has alpha channel data, use `HasAlpha` to check
for this.
"""
return _core_.Image_SetAlpha(*args, **kwargs) | [
"def",
"SetAlpha",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_SetAlpha",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L3044-L3052 | |
Caffe-MPI/Caffe-MPI.github.io | df5992af571a2a19981b69635115c393f18d1c76 | python/caffe/draw.py | python | draw_net_to_file | (caffe_net, filename, rankdir='LR') | Draws a caffe net, and saves it to file using the format given as the
file extension. Use '.raw' to output raw text that you can manually feed
to graphviz to draw graphs.
Parameters
----------
caffe_net : a caffe.proto.caffe_pb2.NetParameter protocol buffer.
filename : string
The path to a file where the networks visualization will be stored.
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout. | Draws a caffe net, and saves it to file using the format given as the
file extension. Use '.raw' to output raw text that you can manually feed
to graphviz to draw graphs. | [
"Draws",
"a",
"caffe",
"net",
"and",
"saves",
"it",
"to",
"file",
"using",
"the",
"format",
"given",
"as",
"the",
"file",
"extension",
".",
"Use",
".",
"raw",
"to",
"output",
"raw",
"text",
"that",
"you",
"can",
"manually",
"feed",
"to",
"graphviz",
"t... | def draw_net_to_file(caffe_net, filename, rankdir='LR'):
"""Draws a caffe net, and saves it to file using the format given as the
file extension. Use '.raw' to output raw text that you can manually feed
to graphviz to draw graphs.
Parameters
----------
caffe_net : a caffe.proto.caffe_pb2.NetParameter protocol buffer.
filename : string
The path to a file where the networks visualization will be stored.
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
"""
ext = filename[filename.rfind('.')+1:]
with open(filename, 'wb') as fid:
fid.write(draw_net(caffe_net, rankdir, ext)) | [
"def",
"draw_net_to_file",
"(",
"caffe_net",
",",
"filename",
",",
"rankdir",
"=",
"'LR'",
")",
":",
"ext",
"=",
"filename",
"[",
"filename",
".",
"rfind",
"(",
"'.'",
")",
"+",
"1",
":",
"]",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
... | https://github.com/Caffe-MPI/Caffe-MPI.github.io/blob/df5992af571a2a19981b69635115c393f18d1c76/python/caffe/draw.py#L207-L222 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/smtplib.py | python | SMTP.auth | (self, mechanism, authobject, *, initial_response_ok=True) | Authentication command - requires response processing.
'mechanism' specifies which authentication mechanism is to
be used - the valid values are those listed in the 'auth'
element of 'esmtp_features'.
'authobject' must be a callable object taking a single argument:
data = authobject(challenge)
It will be called to process the server's challenge response; the
challenge argument it is passed will be a bytes. It should return
an ASCII string that will be base64 encoded and sent to the server.
Keyword arguments:
- initial_response_ok: Allow sending the RFC 4954 initial-response
to the AUTH command, if the authentication methods supports it. | Authentication command - requires response processing. | [
"Authentication",
"command",
"-",
"requires",
"response",
"processing",
"."
] | def auth(self, mechanism, authobject, *, initial_response_ok=True):
"""Authentication command - requires response processing.
'mechanism' specifies which authentication mechanism is to
be used - the valid values are those listed in the 'auth'
element of 'esmtp_features'.
'authobject' must be a callable object taking a single argument:
data = authobject(challenge)
It will be called to process the server's challenge response; the
challenge argument it is passed will be a bytes. It should return
an ASCII string that will be base64 encoded and sent to the server.
Keyword arguments:
- initial_response_ok: Allow sending the RFC 4954 initial-response
to the AUTH command, if the authentication methods supports it.
"""
# RFC 4954 allows auth methods to provide an initial response. Not all
# methods support it. By definition, if they return something other
# than None when challenge is None, then they do. See issue #15014.
mechanism = mechanism.upper()
initial_response = (authobject() if initial_response_ok else None)
if initial_response is not None:
response = encode_base64(initial_response.encode('ascii'), eol='')
(code, resp) = self.docmd("AUTH", mechanism + " " + response)
self._auth_challenge_count = 1
else:
(code, resp) = self.docmd("AUTH", mechanism)
self._auth_challenge_count = 0
# If server responds with a challenge, send the response.
while code == 334:
self._auth_challenge_count += 1
challenge = base64.decodebytes(resp)
response = encode_base64(
authobject(challenge).encode('ascii'), eol='')
(code, resp) = self.docmd(response)
# If server keeps sending challenges, something is wrong.
if self._auth_challenge_count > _MAXCHALLENGE:
raise SMTPException(
"Server AUTH mechanism infinite loop. Last response: "
+ repr((code, resp))
)
if code in (235, 503):
return (code, resp)
raise SMTPAuthenticationError(code, resp) | [
"def",
"auth",
"(",
"self",
",",
"mechanism",
",",
"authobject",
",",
"*",
",",
"initial_response_ok",
"=",
"True",
")",
":",
"# RFC 4954 allows auth methods to provide an initial response. Not all",
"# methods support it. By definition, if they return something other",
"# than... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/smtplib.py#L616-L662 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/msvc.py | python | SystemInfo.WindowsSdkVersion | (self) | Microsoft Windows SDK versions for specified MSVC++ version.
Return
------
tuple of str
versions | Microsoft Windows SDK versions for specified MSVC++ version. | [
"Microsoft",
"Windows",
"SDK",
"versions",
"for",
"specified",
"MSVC",
"++",
"version",
"."
] | def WindowsSdkVersion(self):
"""
Microsoft Windows SDK versions for specified MSVC++ version.
Return
------
tuple of str
versions
"""
if self.vs_ver <= 9.0:
return '7.0', '6.1', '6.0a'
elif self.vs_ver == 10.0:
return '7.1', '7.0a'
elif self.vs_ver == 11.0:
return '8.0', '8.0a'
elif self.vs_ver == 12.0:
return '8.1', '8.1a'
elif self.vs_ver >= 14.0:
return '10.0', '8.1' | [
"def",
"WindowsSdkVersion",
"(",
"self",
")",
":",
"if",
"self",
".",
"vs_ver",
"<=",
"9.0",
":",
"return",
"'7.0'",
",",
"'6.1'",
",",
"'6.0a'",
"elif",
"self",
".",
"vs_ver",
"==",
"10.0",
":",
"return",
"'7.1'",
",",
"'7.0a'",
"elif",
"self",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/msvc.py#L748-L766 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_style.py | python | StyleItem.__eq__ | (self, other) | return unicode(self) == unicode(other) | Defines the == operator for the StyleItem Class
@param other: style item to compare to
@return: whether the two items are equal | Defines the == operator for the StyleItem Class
@param other: style item to compare to
@return: whether the two items are equal | [
"Defines",
"the",
"==",
"operator",
"for",
"the",
"StyleItem",
"Class",
"@param",
"other",
":",
"style",
"item",
"to",
"compare",
"to",
"@return",
":",
"whether",
"the",
"two",
"items",
"are",
"equal"
] | def __eq__(self, other):
"""Defines the == operator for the StyleItem Class
@param other: style item to compare to
@return: whether the two items are equal
"""
return unicode(self) == unicode(other) | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"return",
"unicode",
"(",
"self",
")",
"==",
"unicode",
"(",
"other",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_style.py#L85-L91 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGridInterface.RefreshGrid | (*args, **kwargs) | return _propgrid.PropertyGridInterface_RefreshGrid(*args, **kwargs) | RefreshGrid(self, state=None) | RefreshGrid(self, state=None) | [
"RefreshGrid",
"(",
"self",
"state",
"=",
"None",
")"
] | def RefreshGrid(*args, **kwargs):
"""RefreshGrid(self, state=None)"""
return _propgrid.PropertyGridInterface_RefreshGrid(*args, **kwargs) | [
"def",
"RefreshGrid",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridInterface_RefreshGrid",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L1337-L1339 | |
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py | python | SpawnBase.readlines | (self, sizehint=-1) | return lines | This reads until EOF using readline() and returns a list containing
the lines thus read. The optional 'sizehint' argument is ignored.
Remember, because this reads until EOF that means the child
process should have closed its stdout. If you run this method on
a child that is still running with its stdout open then this
method will block until it timesout. | This reads until EOF using readline() and returns a list containing
the lines thus read. The optional 'sizehint' argument is ignored.
Remember, because this reads until EOF that means the child
process should have closed its stdout. If you run this method on
a child that is still running with its stdout open then this
method will block until it timesout. | [
"This",
"reads",
"until",
"EOF",
"using",
"readline",
"()",
"and",
"returns",
"a",
"list",
"containing",
"the",
"lines",
"thus",
"read",
".",
"The",
"optional",
"sizehint",
"argument",
"is",
"ignored",
".",
"Remember",
"because",
"this",
"reads",
"until",
"E... | def readlines(self, sizehint=-1):
'''This reads until EOF using readline() and returns a list containing
the lines thus read. The optional 'sizehint' argument is ignored.
Remember, because this reads until EOF that means the child
process should have closed its stdout. If you run this method on
a child that is still running with its stdout open then this
method will block until it timesout.'''
lines = []
while True:
line = self.readline()
if not line:
break
lines.append(line)
return lines | [
"def",
"readlines",
"(",
"self",
",",
"sizehint",
"=",
"-",
"1",
")",
":",
"lines",
"=",
"[",
"]",
"while",
"True",
":",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"lines",
".",
"append",
"(",
"line",
")",
... | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py#L485-L499 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/urllib3/util/connection.py | python | allowed_gai_family | () | return family | This function is designed to work in the context of
getaddrinfo, where family=socket.AF_UNSPEC is the default and
will perform a DNS search for both IPv6 and IPv4 records. | This function is designed to work in the context of
getaddrinfo, where family=socket.AF_UNSPEC is the default and
will perform a DNS search for both IPv6 and IPv4 records. | [
"This",
"function",
"is",
"designed",
"to",
"work",
"in",
"the",
"context",
"of",
"getaddrinfo",
"where",
"family",
"=",
"socket",
".",
"AF_UNSPEC",
"is",
"the",
"default",
"and",
"will",
"perform",
"a",
"DNS",
"search",
"for",
"both",
"IPv6",
"and",
"IPv4... | def allowed_gai_family():
"""This function is designed to work in the context of
getaddrinfo, where family=socket.AF_UNSPEC is the default and
will perform a DNS search for both IPv6 and IPv4 records."""
family = socket.AF_INET
if HAS_IPV6:
family = socket.AF_UNSPEC
return family | [
"def",
"allowed_gai_family",
"(",
")",
":",
"family",
"=",
"socket",
".",
"AF_INET",
"if",
"HAS_IPV6",
":",
"family",
"=",
"socket",
".",
"AF_UNSPEC",
"return",
"family"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/urllib3/util/connection.py#L93-L101 | |
strukturag/libheif | 0082fea96ee70a20c8906a0373bedec0c01777bc | scripts/cpplint.py | python | _CppLintState.SetFilters | (self, filters) | Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" | Sets the error-message filters. | [
"Sets",
"the",
"error",
"-",
"message",
"filters",
"."
] | def SetFilters(self, filters):
"""Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
"""
# Default filters always have less priority than the flag ones.
self.filters = _DEFAULT_FILTERS[:]
self.AddFilters(filters) | [
"def",
"SetFilters",
"(",
"self",
",",
"filters",
")",
":",
"# Default filters always have less priority than the flag ones.",
"self",
".",
"filters",
"=",
"_DEFAULT_FILTERS",
"[",
":",
"]",
"self",
".",
"AddFilters",
"(",
"filters",
")"
] | https://github.com/strukturag/libheif/blob/0082fea96ee70a20c8906a0373bedec0c01777bc/scripts/cpplint.py#L859-L875 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/nn_impl.py | python | depthwise_conv2d | (input,
filter,
strides,
padding,
rate=None,
name=None,
data_format=None) | Depthwise 2-D convolution.
Given a 4D input tensor ('NHWC' or 'NCHW' data formats)
and a filter tensor of shape
`[filter_height, filter_width, in_channels, channel_multiplier]`
containing `in_channels` convolutional filters of depth 1, `depthwise_conv2d`
applies a different filter to each input channel (expanding from 1 channel
to `channel_multiplier` channels for each), then concatenates the results
together. The output has `in_channels * channel_multiplier` channels.
In detail,
output[b, i, j, k * channel_multiplier + q] = sum_{di, dj}
filter[di, dj, k, q] * input[b, strides[1] * i + rate[0] * di,
strides[2] * j + rate[1] * dj, k]
Must have `strides[0] = strides[3] = 1`. For the most common case of the
same horizontal and vertical strides, `strides = [1, stride, stride, 1]`.
If any value in `rate` is greater than 1, we perform atrous depthwise
convolution, in which case all values in the `strides` tensor must be equal
to 1.
Args:
input: 4-D with shape according to `data_format`.
filter: 4-D with shape
`[filter_height, filter_width, in_channels, channel_multiplier]`.
strides: 1-D of size 4. The stride of the sliding window for each
dimension of `input`.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
See the @{tf.nn.convolution$comment here}
rate: 1-D of size 2. The dilation rate in which we sample input values
across the `height` and `width` dimensions in atrous convolution. If it is
greater than 1, then all values of strides must be 1.
name: A name for this operation (optional).
data_format: The data format for input. Either "NHWC" (default) or "NCHW".
Returns:
A 4-D `Tensor` with shape according to `data_format`. E.g., for
"NHWC" format, shape is
`[batch, out_height, out_width, in_channels * channel_multiplier].` | Depthwise 2-D convolution. | [
"Depthwise",
"2",
"-",
"D",
"convolution",
"."
] | def depthwise_conv2d(input,
filter,
strides,
padding,
rate=None,
name=None,
data_format=None):
"""Depthwise 2-D convolution.
Given a 4D input tensor ('NHWC' or 'NCHW' data formats)
and a filter tensor of shape
`[filter_height, filter_width, in_channels, channel_multiplier]`
containing `in_channels` convolutional filters of depth 1, `depthwise_conv2d`
applies a different filter to each input channel (expanding from 1 channel
to `channel_multiplier` channels for each), then concatenates the results
together. The output has `in_channels * channel_multiplier` channels.
In detail,
output[b, i, j, k * channel_multiplier + q] = sum_{di, dj}
filter[di, dj, k, q] * input[b, strides[1] * i + rate[0] * di,
strides[2] * j + rate[1] * dj, k]
Must have `strides[0] = strides[3] = 1`. For the most common case of the
same horizontal and vertical strides, `strides = [1, stride, stride, 1]`.
If any value in `rate` is greater than 1, we perform atrous depthwise
convolution, in which case all values in the `strides` tensor must be equal
to 1.
Args:
input: 4-D with shape according to `data_format`.
filter: 4-D with shape
`[filter_height, filter_width, in_channels, channel_multiplier]`.
strides: 1-D of size 4. The stride of the sliding window for each
dimension of `input`.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
See the @{tf.nn.convolution$comment here}
rate: 1-D of size 2. The dilation rate in which we sample input values
across the `height` and `width` dimensions in atrous convolution. If it is
greater than 1, then all values of strides must be 1.
name: A name for this operation (optional).
data_format: The data format for input. Either "NHWC" (default) or "NCHW".
Returns:
A 4-D `Tensor` with shape according to `data_format`. E.g., for
"NHWC" format, shape is
`[batch, out_height, out_width, in_channels * channel_multiplier].`
"""
with ops.name_scope(name, "depthwise", [input, filter]) as name:
input = ops.convert_to_tensor(input, name="tensor_in")
filter = ops.convert_to_tensor(filter, name="filter_in")
if rate is None:
rate = [1, 1]
def op(input_converted, _, padding):
return nn_ops.depthwise_conv2d_native(
input=input_converted,
filter=filter,
strides=strides,
padding=padding,
data_format=data_format,
name=name)
return nn_ops.with_space_to_batch(
input=input,
filter_shape=array_ops.shape(filter),
dilation_rate=rate,
padding=padding,
data_format=data_format,
op=op) | [
"def",
"depthwise_conv2d",
"(",
"input",
",",
"filter",
",",
"strides",
",",
"padding",
",",
"rate",
"=",
"None",
",",
"name",
"=",
"None",
",",
"data_format",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"depthwise\"",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/nn_impl.py#L369-L438 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_menu.py | python | EdMenu.InsertBefore | (self, item_id, id_, label=u'', helpstr=u'',
kind=wx.ITEM_NORMAL, use_bmp=True) | return mitem | Inserts the given item before the specified item id in
the menu. If the id cannot be found then the item will appended
to the end of the menu.
@param item_id: Menu ID to insert new item before
@param id_: New MenuItem ID
@keyword label: Menu Label
@keyword helpstr: Help String
@keyword kind: MenuItem type
@keyword use_bmp: try and set a bitmap if an appropriate one is
available in the ArtProvider
@return: menu item that was inserted | Inserts the given item before the specified item id in
the menu. If the id cannot be found then the item will appended
to the end of the menu.
@param item_id: Menu ID to insert new item before
@param id_: New MenuItem ID
@keyword label: Menu Label
@keyword helpstr: Help String
@keyword kind: MenuItem type
@keyword use_bmp: try and set a bitmap if an appropriate one is
available in the ArtProvider
@return: menu item that was inserted | [
"Inserts",
"the",
"given",
"item",
"before",
"the",
"specified",
"item",
"id",
"in",
"the",
"menu",
".",
"If",
"the",
"id",
"cannot",
"be",
"found",
"then",
"the",
"item",
"will",
"appended",
"to",
"the",
"end",
"of",
"the",
"menu",
".",
"@param",
"ite... | def InsertBefore(self, item_id, id_, label=u'', helpstr=u'',
kind=wx.ITEM_NORMAL, use_bmp=True):
"""Inserts the given item before the specified item id in
the menu. If the id cannot be found then the item will appended
to the end of the menu.
@param item_id: Menu ID to insert new item before
@param id_: New MenuItem ID
@keyword label: Menu Label
@keyword helpstr: Help String
@keyword kind: MenuItem type
@keyword use_bmp: try and set a bitmap if an appropriate one is
available in the ArtProvider
@return: menu item that was inserted
"""
pos = None
for item in xrange(self.GetMenuItemCount()):
mitem = self.FindItemByPosition(item)
if mitem.GetId() == item_id:
pos = item
break
if pos:
mitem = self.Insert(pos, id_, label, helpstr, kind, use_bmp)
else:
mitem = self.Append(id_, label, helpstr, kind, use_bmp)
return mitem | [
"def",
"InsertBefore",
"(",
"self",
",",
"item_id",
",",
"id_",
",",
"label",
"=",
"u''",
",",
"helpstr",
"=",
"u''",
",",
"kind",
"=",
"wx",
".",
"ITEM_NORMAL",
",",
"use_bmp",
"=",
"True",
")",
":",
"pos",
"=",
"None",
"for",
"item",
"in",
"xrang... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_menu.py#L135-L160 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/html5lib/treeadapters/sax.py | python | to_sax | (walker, handler) | Call SAX-like content handler based on treewalker walker
:arg walker: the treewalker to use to walk the tree to convert it
:arg handler: SAX handler to use | Call SAX-like content handler based on treewalker walker | [
"Call",
"SAX",
"-",
"like",
"content",
"handler",
"based",
"on",
"treewalker",
"walker"
] | def to_sax(walker, handler):
"""Call SAX-like content handler based on treewalker walker
:arg walker: the treewalker to use to walk the tree to convert it
:arg handler: SAX handler to use
"""
handler.startDocument()
for prefix, namespace in prefix_mapping.items():
handler.startPrefixMapping(prefix, namespace)
for token in walker:
type = token["type"]
if type == "Doctype":
continue
elif type in ("StartTag", "EmptyTag"):
attrs = AttributesNSImpl(token["data"],
unadjustForeignAttributes)
handler.startElementNS((token["namespace"], token["name"]),
token["name"],
attrs)
if type == "EmptyTag":
handler.endElementNS((token["namespace"], token["name"]),
token["name"])
elif type == "EndTag":
handler.endElementNS((token["namespace"], token["name"]),
token["name"])
elif type in ("Characters", "SpaceCharacters"):
handler.characters(token["data"])
elif type == "Comment":
pass
else:
assert False, "Unknown token type"
for prefix, namespace in prefix_mapping.items():
handler.endPrefixMapping(prefix)
handler.endDocument() | [
"def",
"to_sax",
"(",
"walker",
",",
"handler",
")",
":",
"handler",
".",
"startDocument",
"(",
")",
"for",
"prefix",
",",
"namespace",
"in",
"prefix_mapping",
".",
"items",
"(",
")",
":",
"handler",
".",
"startPrefixMapping",
"(",
"prefix",
",",
"namespac... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/html5lib/treeadapters/sax.py#L13-L50 | ||
dmlc/nnvm | dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38 | python/nnvm/frontend/darknet.py | python | _darknet_shortcut | (inputs, attrs) | return sym, out_name | Process the shortcut operation. | Process the shortcut operation. | [
"Process",
"the",
"shortcut",
"operation",
"."
] | def _darknet_shortcut(inputs, attrs):
"""Process the shortcut operation."""
op_name, new_attrs = 'elemwise_add', {}
input_0 = inputs[0]
input_1 = inputs[1]
input_0_channel = int(attrs['out_channel'])
input_1_channel = int(attrs['add_out_channel'])
input_0_size = int(attrs['out_size'])
input_1_size = int(attrs['add_out_size'])
if input_0_size > input_1_size:
scale = int(input_0_size/input_1_size)
input_1 = _sym.upsampling(input_1, scale=scale, name="_upsampling")
elif input_0_size < input_1_size:
stride = int(input_1_size/input_0_size)
input_1 = _sym.avg_pool2d(input_1, pool_size=(1, 1),
strides=(stride, stride), padding=(0, 0), name="_downsampling")
if input_0_channel != input_1_channel:
pad_channel = input_0_channel - input_1_channel
input_1 = _sym.pad(input_1, pad_width=((0, 0), (0, pad_channel), (0, 0), (0, 0)),
pad_value=0.)
new_inputs = _as_list([input_0, input_1])
sym = _darknet_get_nnvm_op(op_name)(*new_inputs, **new_attrs)
out_name = sym.list_output_names()[0].replace('_output', '')
if 'activation' in attrs:
new_attrs['activation'] = attrs['activation']
sym, _ = _darknet_activations(sym, new_attrs)
return sym, out_name | [
"def",
"_darknet_shortcut",
"(",
"inputs",
",",
"attrs",
")",
":",
"op_name",
",",
"new_attrs",
"=",
"'elemwise_add'",
",",
"{",
"}",
"input_0",
"=",
"inputs",
"[",
"0",
"]",
"input_1",
"=",
"inputs",
"[",
"1",
"]",
"input_0_channel",
"=",
"int",
"(",
... | https://github.com/dmlc/nnvm/blob/dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38/python/nnvm/frontend/darknet.py#L194-L223 | |
facebook/proxygen | a9ca025af207787815cb01eee1971cd572c7a81e | build/fbcode_builder/getdeps/fetcher.py | python | ShipitPathMap._minimize_roots | (self) | compute the de-duplicated set of roots within fbsource.
We take the shortest common directory prefix to make this
determination | compute the de-duplicated set of roots within fbsource.
We take the shortest common directory prefix to make this
determination | [
"compute",
"the",
"de",
"-",
"duplicated",
"set",
"of",
"roots",
"within",
"fbsource",
".",
"We",
"take",
"the",
"shortest",
"common",
"directory",
"prefix",
"to",
"make",
"this",
"determination"
] | def _minimize_roots(self):
"""compute the de-duplicated set of roots within fbsource.
We take the shortest common directory prefix to make this
determination"""
self.roots.sort(key=len)
minimized = []
for r in self.roots:
add_this_entry = True
for existing in minimized:
if r.startswith(existing + "/"):
add_this_entry = False
break
if add_this_entry:
minimized.append(r)
self.roots = minimized | [
"def",
"_minimize_roots",
"(",
"self",
")",
":",
"self",
".",
"roots",
".",
"sort",
"(",
"key",
"=",
"len",
")",
"minimized",
"=",
"[",
"]",
"for",
"r",
"in",
"self",
".",
"roots",
":",
"add_this_entry",
"=",
"True",
"for",
"existing",
"in",
"minimiz... | https://github.com/facebook/proxygen/blob/a9ca025af207787815cb01eee1971cd572c7a81e/build/fbcode_builder/getdeps/fetcher.py#L411-L427 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/ValidationKit/common/utils.py | python | __installShUtilHacks | (shutil) | return True | Installs the shutil buffer size hacks. | Installs the shutil buffer size hacks. | [
"Installs",
"the",
"shutil",
"buffer",
"size",
"hacks",
"."
] | def __installShUtilHacks(shutil):
""" Installs the shutil buffer size hacks. """
global g_fnOriginalShCopyFileObj;
if g_fnOriginalShCopyFileObj is None:
g_fnOriginalShCopyFileObj = shutil.copyfileobj;
shutil.copyfileobj = __myshutilcopyfileobj;
return True; | [
"def",
"__installShUtilHacks",
"(",
"shutil",
")",
":",
"global",
"g_fnOriginalShCopyFileObj",
"if",
"g_fnOriginalShCopyFileObj",
"is",
"None",
":",
"g_fnOriginalShCopyFileObj",
"=",
"shutil",
".",
"copyfileobj",
"shutil",
".",
"copyfileobj",
"=",
"__myshutilcopyfileobj",... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/ValidationKit/common/utils.py#L510-L516 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py | python | BuildInfoBase.merge | (self, other) | Merge the fields of another object into this object. Already existing
information is overwritten by the other instance's data.
WARNING: If a '__dict__' slot is added, it should be updated instead of
replaced. | Merge the fields of another object into this object. Already existing
information is overwritten by the other instance's data.
WARNING: If a '__dict__' slot is added, it should be updated instead of
replaced. | [
"Merge",
"the",
"fields",
"of",
"another",
"object",
"into",
"this",
"object",
".",
"Already",
"existing",
"information",
"is",
"overwritten",
"by",
"the",
"other",
"instance",
"s",
"data",
".",
"WARNING",
":",
"If",
"a",
"__dict__",
"slot",
"is",
"added",
... | def merge(self, other):
"""
Merge the fields of another object into this object. Already existing
information is overwritten by the other instance's data.
WARNING: If a '__dict__' slot is added, it should be updated instead of
replaced.
"""
state = other.__getstate__()
self.__setstate__(state) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"state",
"=",
"other",
".",
"__getstate__",
"(",
")",
"self",
".",
"__setstate__",
"(",
"state",
")"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py#L450-L458 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/sas/sasreader.py | python | read_sas | (
filepath_or_buffer,
format=None,
index=None,
encoding=None,
chunksize=None,
iterator=False,
) | return data | Read SAS files stored as either XPORT or SAS7BDAT format files.
Parameters
----------
filepath_or_buffer : str, path object or file-like object
Any valid string path is acceptable. The string could be a URL. Valid
URL schemes include http, ftp, s3, and file. For file URLs, a host is
expected. A local file could be:
``file://localhost/path/to/table.sas``.
If you want to pass in a path object, pandas accepts any
``os.PathLike``.
By file-like object, we refer to objects with a ``read()`` method,
such as a file handler (e.g. via builtin ``open`` function)
or ``StringIO``.
format : str {'xport', 'sas7bdat'} or None
If None, file format is inferred from file extension. If 'xport' or
'sas7bdat', uses the corresponding format.
index : identifier of index column, defaults to None
Identifier of column that should be used as index of the DataFrame.
encoding : str, default is None
Encoding for text data. If None, text data are stored as raw bytes.
chunksize : int
Read file `chunksize` lines at a time, returns iterator.
iterator : bool, defaults to False
If True, returns an iterator for reading the file incrementally.
Returns
-------
DataFrame if iterator=False and chunksize=None, else SAS7BDATReader
or XportReader | Read SAS files stored as either XPORT or SAS7BDAT format files. | [
"Read",
"SAS",
"files",
"stored",
"as",
"either",
"XPORT",
"or",
"SAS7BDAT",
"format",
"files",
"."
] | def read_sas(
filepath_or_buffer,
format=None,
index=None,
encoding=None,
chunksize=None,
iterator=False,
):
"""
Read SAS files stored as either XPORT or SAS7BDAT format files.
Parameters
----------
filepath_or_buffer : str, path object or file-like object
Any valid string path is acceptable. The string could be a URL. Valid
URL schemes include http, ftp, s3, and file. For file URLs, a host is
expected. A local file could be:
``file://localhost/path/to/table.sas``.
If you want to pass in a path object, pandas accepts any
``os.PathLike``.
By file-like object, we refer to objects with a ``read()`` method,
such as a file handler (e.g. via builtin ``open`` function)
or ``StringIO``.
format : str {'xport', 'sas7bdat'} or None
If None, file format is inferred from file extension. If 'xport' or
'sas7bdat', uses the corresponding format.
index : identifier of index column, defaults to None
Identifier of column that should be used as index of the DataFrame.
encoding : str, default is None
Encoding for text data. If None, text data are stored as raw bytes.
chunksize : int
Read file `chunksize` lines at a time, returns iterator.
iterator : bool, defaults to False
If True, returns an iterator for reading the file incrementally.
Returns
-------
DataFrame if iterator=False and chunksize=None, else SAS7BDATReader
or XportReader
"""
if format is None:
buffer_error_msg = (
"If this is a buffer object rather "
"than a string name, you must specify "
"a format string"
)
filepath_or_buffer = stringify_path(filepath_or_buffer)
if not isinstance(filepath_or_buffer, str):
raise ValueError(buffer_error_msg)
fname = filepath_or_buffer.lower()
if fname.endswith(".xpt"):
format = "xport"
elif fname.endswith(".sas7bdat"):
format = "sas7bdat"
else:
raise ValueError("unable to infer format of SAS file")
if format.lower() == "xport":
from pandas.io.sas.sas_xport import XportReader
reader = XportReader(
filepath_or_buffer, index=index, encoding=encoding, chunksize=chunksize
)
elif format.lower() == "sas7bdat":
from pandas.io.sas.sas7bdat import SAS7BDATReader
reader = SAS7BDATReader(
filepath_or_buffer, index=index, encoding=encoding, chunksize=chunksize
)
else:
raise ValueError("unknown SAS format")
if iterator or chunksize:
return reader
data = reader.read()
reader.close()
return data | [
"def",
"read_sas",
"(",
"filepath_or_buffer",
",",
"format",
"=",
"None",
",",
"index",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"iterator",
"=",
"False",
",",
")",
":",
"if",
"format",
"is",
"None",
":",
"buffer_e... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/sas/sasreader.py#L7-L86 | |
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/cpplint_1.4.5/cpplint.py | python | ProcessFileData | (filename, file_extension, lines, error,
extra_check_functions=None) | Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Performs lint checks and reports any errors to the given error function. | [
"Performs",
"lint",
"checks",
"and",
"reports",
"any",
"errors",
"to",
"the",
"given",
"error",
"function",
"."
] | def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=None):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
ProcessGlobalSuppresions(lines)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
if IsHeaderExtension(file_extension):
CheckForHeaderGuard(filename, clean_lines, error)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
FlagCxx11Features(filename, clean_lines, line, error)
nesting_state.CheckCompletedBlocks(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# Check that the .cc file has included its header if it exists.
if _IsSourceExtension(file_extension):
CheckHeaderFileIncluded(filename, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForBadCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error) | [
"def",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"error",
",",
"extra_check_functions",
"=",
"None",
")",
":",
"lines",
"=",
"(",
"[",
"'// marker so line numbers and indices both start at 1'",
"]",
"+",
"lines",
"+",
"[",
"'// ... | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/cpplint_1.4.5/cpplint.py#L6181-L6230 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py | python | Flag.Type | (self) | return self.parser.Type() | Returns: a string that describes the type of this Flag. | Returns: a string that describes the type of this Flag. | [
"Returns",
":",
"a",
"string",
"that",
"describes",
"the",
"type",
"of",
"this",
"Flag",
"."
] | def Type(self):
"""Returns: a string that describes the type of this Flag."""
# NOTE: we use strings, and not the types.*Type constants because
# our flags can have more exotic types, e.g., 'comma separated list
# of strings', 'whitespace separated list of strings', etc.
return self.parser.Type() | [
"def",
"Type",
"(",
"self",
")",
":",
"# NOTE: we use strings, and not the types.*Type constants because",
"# our flags can have more exotic types, e.g., 'comma separated list",
"# of strings', 'whitespace separated list of strings', etc.",
"return",
"self",
".",
"parser",
".",
"Type",
... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L1930-L1935 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/vae-gan/vaegan_mxnet.py | python | DiscriminatorLayerLoss | () | return dloss | Calculate the discriminator layer loss | Calculate the discriminator layer loss | [
"Calculate",
"the",
"discriminator",
"layer",
"loss"
] | def DiscriminatorLayerLoss():
'''Calculate the discriminator layer loss
'''
data = mx.sym.Variable('data')
label = mx.sym.Variable('label')
data = mx.sym.Flatten(data)
label = mx.sym.Flatten(label)
label = mx.sym.BlockGrad(label)
zeros = mx.sym.zeros_like(data)
output = -GaussianLogDensity(label, data, zeros)
dloss = mx.symbol.MakeLoss(mx.symbol.mean(output),name='lloss')
return dloss | [
"def",
"DiscriminatorLayerLoss",
"(",
")",
":",
"data",
"=",
"mx",
".",
"sym",
".",
"Variable",
"(",
"'data'",
")",
"label",
"=",
"mx",
".",
"sym",
".",
"Variable",
"(",
"'label'",
")",
"data",
"=",
"mx",
".",
"sym",
".",
"Flatten",
"(",
"data",
")... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/vae-gan/vaegan_mxnet.py#L173-L192 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/bsddb/dbtables.py | python | bsdTableDB.ListTableColumns | (self, table) | Return a list of columns in the given table.
[] if the table doesn't exist. | Return a list of columns in the given table.
[] if the table doesn't exist. | [
"Return",
"a",
"list",
"of",
"columns",
"in",
"the",
"given",
"table",
".",
"[]",
"if",
"the",
"table",
"doesn",
"t",
"exist",
"."
] | def ListTableColumns(self, table):
"""Return a list of columns in the given table.
[] if the table doesn't exist.
"""
assert isinstance(table, str)
if contains_metastrings(table):
raise ValueError, "bad table name: contains reserved metastrings"
columnlist_key = _columns_key(table)
if not getattr(self.db, "has_key")(columnlist_key):
return []
pickledcolumnlist = getattr(self.db, "get_bytes",
self.db.get)(columnlist_key)
if pickledcolumnlist:
return pickle.loads(pickledcolumnlist)
else:
return [] | [
"def",
"ListTableColumns",
"(",
"self",
",",
"table",
")",
":",
"assert",
"isinstance",
"(",
"table",
",",
"str",
")",
"if",
"contains_metastrings",
"(",
"table",
")",
":",
"raise",
"ValueError",
",",
"\"bad table name: contains reserved metastrings\"",
"columnlist_... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/bsddb/dbtables.py#L341-L357 | ||
JoseExposito/touchegg | 1f3fda214358d071c05da4bf17c070c33d67b5eb | cmake/cpplint.py | python | NestingState.InAsmBlock | (self) | return self.stack and self.stack[-1].inline_asm != _NO_ASM | Check if we are currently one level inside an inline ASM block.
Returns:
True if the top of the stack is a block containing inline ASM. | Check if we are currently one level inside an inline ASM block. | [
"Check",
"if",
"we",
"are",
"currently",
"one",
"level",
"inside",
"an",
"inline",
"ASM",
"block",
"."
] | def InAsmBlock(self):
"""Check if we are currently one level inside an inline ASM block.
Returns:
True if the top of the stack is a block containing inline ASM.
"""
return self.stack and self.stack[-1].inline_asm != _NO_ASM | [
"def",
"InAsmBlock",
"(",
"self",
")",
":",
"return",
"self",
".",
"stack",
"and",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"inline_asm",
"!=",
"_NO_ASM"
] | https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L2465-L2471 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/request_track.py | python | ShortName | (url) | Returns a shortened version of a URL. | Returns a shortened version of a URL. | [
"Returns",
"a",
"shortened",
"version",
"of",
"a",
"URL",
"."
] | def ShortName(url):
"""Returns a shortened version of a URL."""
parsed = urlparse.urlparse(url)
path = parsed.path
hostname = parsed.hostname if parsed.hostname else '?.?.?'
if path != '' and path != '/':
last_path = parsed.path.split('/')[-1]
if len(last_path) < 10:
if len(path) < 10:
return hostname + '/' + path
else:
return hostname + '/..' + parsed.path[-10:]
else:
return hostname + '/..' + last_path[:5]
else:
return hostname | [
"def",
"ShortName",
"(",
"url",
")",
":",
"parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"path",
"=",
"parsed",
".",
"path",
"hostname",
"=",
"parsed",
".",
"hostname",
"if",
"parsed",
".",
"hostname",
"else",
"'?.?.?'",
"if",
"path",
"!=... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/request_track.py#L81-L96 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py | python | ScriptWriter.get_header | (cls, script_text="", executable=None) | return cmd.as_header() | Create a #! line, getting options (if any) from script_text | Create a #! line, getting options (if any) from script_text | [
"Create",
"a",
"#!",
"line",
"getting",
"options",
"(",
"if",
"any",
")",
"from",
"script_text"
] | def get_header(cls, script_text="", executable=None):
"""Create a #! line, getting options (if any) from script_text"""
cmd = cls.command_spec_class.best().from_param(executable)
cmd.install_options(script_text)
return cmd.as_header() | [
"def",
"get_header",
"(",
"cls",
",",
"script_text",
"=",
"\"\"",
",",
"executable",
"=",
"None",
")",
":",
"cmd",
"=",
"cls",
".",
"command_spec_class",
".",
"best",
"(",
")",
".",
"from_param",
"(",
"executable",
")",
"cmd",
".",
"install_options",
"("... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py#L2156-L2160 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/llvm/utils/llvm-build/llvmbuild/main.py | python | mk_quote_string_for_target | (value) | return value.replace(":", "\\:") | mk_quote_string_for_target(target_name) -> str
Return a quoted form of the given target_name suitable for including in a
Makefile as a target name. | mk_quote_string_for_target(target_name) -> str | [
"mk_quote_string_for_target",
"(",
"target_name",
")",
"-",
">",
"str"
] | def mk_quote_string_for_target(value):
"""
mk_quote_string_for_target(target_name) -> str
Return a quoted form of the given target_name suitable for including in a
Makefile as a target name.
"""
# The only quoting we currently perform is for ':', to support msys users.
return value.replace(":", "\\:") | [
"def",
"mk_quote_string_for_target",
"(",
"value",
")",
":",
"# The only quoting we currently perform is for ':', to support msys users.",
"return",
"value",
".",
"replace",
"(",
"\":\"",
",",
"\"\\\\:\"",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/llvm/utils/llvm-build/llvmbuild/main.py#L41-L50 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/generator/make.py | python | Compilable | (filename) | return False | Return true if the file is compilable (should be in OBJS). | Return true if the file is compilable (should be in OBJS). | [
"Return",
"true",
"if",
"the",
"file",
"is",
"compilable",
"(",
"should",
"be",
"in",
"OBJS",
")",
"."
] | def Compilable(filename):
"""Return true if the file is compilable (should be in OBJS)."""
for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS):
if res:
return True
return False | [
"def",
"Compilable",
"(",
"filename",
")",
":",
"for",
"res",
"in",
"(",
"filename",
".",
"endswith",
"(",
"e",
")",
"for",
"e",
"in",
"COMPILABLE_EXTENSIONS",
")",
":",
"if",
"res",
":",
"return",
"True",
"return",
"False"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/generator/make.py#L564-L569 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.