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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CanalTP/navitia | cb84ce9859070187e708818b058e6a7e0b7f891b | source/tyr/tyr/binarisation.py | python | osm2mimir | (self, autocomplete_instance, filename, job_id, dataset_uid, autocomplete_version) | launch osm2mimir | launch osm2mimir | [
"launch",
"osm2mimir"
] | def osm2mimir(self, autocomplete_instance, filename, job_id, dataset_uid, autocomplete_version):
""" launch osm2mimir """
executable = "osm2mimir" if autocomplete_version == 2 else "osm2mimir7"
autocomplete_instance = models.db.session.merge(autocomplete_instance) # reatache the object
logger = get_autocomplete_instance_logger(autocomplete_instance, task_id=job_id)
logger.debug('running {} for {}'.format(executable, job_id))
job = models.Job.query.get(job_id)
data_filename = unzip_if_needed(filename)
custom_config = "custom_config"
working_directory = os.path.dirname(data_filename)
custom_config_config_toml = '{}/{}.toml'.format(working_directory, custom_config)
data = autocomplete_instance.config_toml.encode("utf-8")
with open(custom_config_config_toml, 'w') as f:
f.write(data)
params = get_osm2mimir_params(
autocomplete_instance, data_filename, working_directory, custom_config, autocomplete_version
)
try:
res = launch_exec(executable, params, logger)
if res != 0:
# @TODO: exception
raise ValueError('{} failed'.format(executable))
except:
logger.exception('')
job.state = 'failed'
models.db.session.commit()
raise | [
"def",
"osm2mimir",
"(",
"self",
",",
"autocomplete_instance",
",",
"filename",
",",
"job_id",
",",
"dataset_uid",
",",
"autocomplete_version",
")",
":",
"executable",
"=",
"\"osm2mimir\"",
"if",
"autocomplete_version",
"==",
"2",
"else",
"\"osm2mimir7\"",
"autocomp... | https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/tyr/tyr/binarisation.py#L791-L817 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/io_ops.py | python | _SaveSlicesShape | (op) | return [] | Shape function for SaveSlices op. | Shape function for SaveSlices op. | [
"Shape",
"function",
"for",
"SaveSlices",
"op",
"."
] | def _SaveSlicesShape(op):
"""Shape function for SaveSlices op."""
# Validate input shapes.
unused_filename = op.inputs[0].get_shape().merge_with(tensor_shape.scalar())
data_count = len(op.inputs) - 3
unused_tensor_names_shape = op.inputs[1].get_shape().merge_with(
tensor_shape.vector(data_count))
unused_shapes_and_slices_shape = op.inputs[2].get_shape().merge_with(
tensor_shape.vector(data_count))
# TODO(mrry): Attempt to parse the shapes_and_slices values and use
# them to constrain the shape of the remaining inputs.
return [] | [
"def",
"_SaveSlicesShape",
"(",
"op",
")",
":",
"# Validate input shapes.",
"unused_filename",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"tensor_shape",
".",
"scalar",
"(",
")",
")",
"data_count",
"=",
"le... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/io_ops.py#L244-L255 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/resources/list_unused_grit_header.py | python | NeedsGritInclude | (grit_header, resources, filename) | Return whether a file needs a given grit header or not.
Args:
grit_header: The grit header file name.
resources: The list of resource names in grit_header.
filename: The file to scan.
Returns:
True if the file should include the grit header. | Return whether a file needs a given grit header or not. | [
"Return",
"whether",
"a",
"file",
"needs",
"a",
"given",
"grit",
"header",
"or",
"not",
"."
] | def NeedsGritInclude(grit_header, resources, filename):
"""Return whether a file needs a given grit header or not.
Args:
grit_header: The grit header file name.
resources: The list of resource names in grit_header.
filename: The file to scan.
Returns:
True if the file should include the grit header.
"""
# A list of special keywords that implies the file needs grit headers.
# To be more thorough, one would need to run a pre-processor.
SPECIAL_KEYWORDS = (
'#include "ui_localizer_table.h"', # ui_localizer.mm
'DEFINE_RESOURCE_ID', # chrome/browser/android/resource_mapper.cc
)
with open(filename, 'rb') as f:
grit_header_line = grit_header + '"\n'
has_grit_header = False
while True:
line = f.readline()
if not line:
break
if line.endswith(grit_header_line):
has_grit_header = True
break
if not has_grit_header:
return True
rest_of_the_file = f.read()
return (any(resource in rest_of_the_file for resource in resources) or
any(keyword in rest_of_the_file for keyword in SPECIAL_KEYWORDS)) | [
"def",
"NeedsGritInclude",
"(",
"grit_header",
",",
"resources",
",",
"filename",
")",
":",
"# A list of special keywords that implies the file needs grit headers.",
"# To be more thorough, one would need to run a pre-processor.",
"SPECIAL_KEYWORDS",
"=",
"(",
"'#include \"ui_localizer... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/resources/list_unused_grit_header.py#L157-L189 | ||
rdiankov/openrave | d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7 | python/databases/__init__.py | python | DatabaseGenerator.CreateOptionParser | (useManipulator=True) | return parser | set basic option parsing options for using databasers through the command line | set basic option parsing options for using databasers through the command line | [
"set",
"basic",
"option",
"parsing",
"options",
"for",
"using",
"databasers",
"through",
"the",
"command",
"line"
] | def CreateOptionParser(useManipulator=True):
"""set basic option parsing options for using databasers through the command line
"""
from optparse import OptionParser, OptionGroup
parser = OptionParser(description='OpenRAVE Database Generator.')
OpenRAVEGlobalArguments.addOptions(parser)
dbgroup = OptionGroup(parser,"OpenRAVE Database Generator General Options")
dbgroup.add_option('--show',action='store_true',dest='show',default=False,
help='Graphically shows the built model')
dbgroup.add_option('--getfilename',action="store_true",dest='getfilename',default=False,
help='If set, will return the final database filename where all data is stored')
dbgroup.add_option('--gethas',action="store_true",dest='gethas',default=False,
help='If set, will exit with 0 if datafile is generated and up to date, otherwise will return a 1. This will require loading the model and checking versions, so might be a little slow.')
dbgroup.add_option('--robot',action='store',type='string',dest='robot',default=getenv('OPENRAVE_ROBOT',default='robots/barrettsegway.robot.xml'),
help='OpenRAVE robot to load (default=%default)')
dbgroup.add_option('--numthreads',action='store',type='int',dest='numthreads',default=1,
help='number of threads to compute the database with (default=%default)')
if useManipulator:
dbgroup.add_option('--manipname',action='store',type='string',dest='manipname',default=None,
help='The name of the manipulator on the robot to use')
parser.add_option_group(dbgroup)
return parser | [
"def",
"CreateOptionParser",
"(",
"useManipulator",
"=",
"True",
")",
":",
"from",
"optparse",
"import",
"OptionParser",
",",
"OptionGroup",
"parser",
"=",
"OptionParser",
"(",
"description",
"=",
"'OpenRAVE Database Generator.'",
")",
"OpenRAVEGlobalArguments",
".",
... | https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/databases/__init__.py#L149-L170 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/generator.py | python | Generator.__init__ | (self, outfp, mangle_from_=None, maxheaderlen=None, *,
policy=None) | Create the generator for message flattening.
outfp is the output file-like object for writing the message to. It
must have a write() method.
Optional mangle_from_ is a flag that, when True (the default if policy
is not set), escapes From_ lines in the body of the message by putting
a `>' in front of them.
Optional maxheaderlen specifies the longest length for a non-continued
header. When a header line is longer (in characters, with tabs
expanded to 8 spaces) than maxheaderlen, the header will split as
defined in the Header class. Set maxheaderlen to zero to disable
header wrapping. The default is 78, as recommended (but not required)
by RFC 2822.
The policy keyword specifies a policy object that controls a number of
aspects of the generator's operation. If no policy is specified,
the policy associated with the Message object passed to the
flatten method is used. | Create the generator for message flattening. | [
"Create",
"the",
"generator",
"for",
"message",
"flattening",
"."
] | def __init__(self, outfp, mangle_from_=None, maxheaderlen=None, *,
policy=None):
"""Create the generator for message flattening.
outfp is the output file-like object for writing the message to. It
must have a write() method.
Optional mangle_from_ is a flag that, when True (the default if policy
is not set), escapes From_ lines in the body of the message by putting
a `>' in front of them.
Optional maxheaderlen specifies the longest length for a non-continued
header. When a header line is longer (in characters, with tabs
expanded to 8 spaces) than maxheaderlen, the header will split as
defined in the Header class. Set maxheaderlen to zero to disable
header wrapping. The default is 78, as recommended (but not required)
by RFC 2822.
The policy keyword specifies a policy object that controls a number of
aspects of the generator's operation. If no policy is specified,
the policy associated with the Message object passed to the
flatten method is used.
"""
if mangle_from_ is None:
mangle_from_ = True if policy is None else policy.mangle_from_
self._fp = outfp
self._mangle_from_ = mangle_from_
self.maxheaderlen = maxheaderlen
self.policy = policy | [
"def",
"__init__",
"(",
"self",
",",
"outfp",
",",
"mangle_from_",
"=",
"None",
",",
"maxheaderlen",
"=",
"None",
",",
"*",
",",
"policy",
"=",
"None",
")",
":",
"if",
"mangle_from_",
"is",
"None",
":",
"mangle_from_",
"=",
"True",
"if",
"policy",
"is"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/generator.py#L36-L66 | ||
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | llvm/utils/lit/lit/LitConfig.py | python | LitConfig.maxIndividualTestTime | (self) | return self._maxIndividualTestTime | Interface for getting maximum time to spend executing
a single test | Interface for getting maximum time to spend executing
a single test | [
"Interface",
"for",
"getting",
"maximum",
"time",
"to",
"spend",
"executing",
"a",
"single",
"test"
] | def maxIndividualTestTime(self):
"""
Interface for getting maximum time to spend executing
a single test
"""
return self._maxIndividualTestTime | [
"def",
"maxIndividualTestTime",
"(",
"self",
")",
":",
"return",
"self",
".",
"_maxIndividualTestTime"
] | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/llvm/utils/lit/lit/LitConfig.py#L71-L76 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | Grid.GetLabelTextColour | (*args, **kwargs) | return _grid.Grid_GetLabelTextColour(*args, **kwargs) | GetLabelTextColour(self) -> Colour | GetLabelTextColour(self) -> Colour | [
"GetLabelTextColour",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetLabelTextColour(*args, **kwargs):
"""GetLabelTextColour(self) -> Colour"""
return _grid.Grid_GetLabelTextColour(*args, **kwargs) | [
"def",
"GetLabelTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_GetLabelTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L1490-L1492 | |
apple/swift-clang | d7403439fc6641751840b723e7165fb02f52db95 | bindings/python/clang/cindex.py | python | SourceLocation.from_offset | (tu, file, offset) | return conf.lib.clang_getLocationForOffset(tu, file, offset) | Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file | Retrieve a SourceLocation from a given character offset. | [
"Retrieve",
"a",
"SourceLocation",
"from",
"a",
"given",
"character",
"offset",
"."
] | def from_offset(tu, file, offset):
"""Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file
"""
return conf.lib.clang_getLocationForOffset(tu, file, offset) | [
"def",
"from_offset",
"(",
"tu",
",",
"file",
",",
"offset",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getLocationForOffset",
"(",
"tu",
",",
"file",
",",
"offset",
")"
] | https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/bindings/python/clang/cindex.py#L260-L267 | |
GoSSIP-SJTU/Armariris | ad5d868482956b2194a77b39c8d543c7c2318200 | tools/clang/bindings/python/clang/cindex.py | python | Cursor.displayname | (self) | return self._displayname | Return the display name for the entity referenced by this cursor.
The display name contains extra information that helps identify the
cursor, such as the parameters of a function or template or the
arguments of a class template specialization. | Return the display name for the entity referenced by this cursor. | [
"Return",
"the",
"display",
"name",
"for",
"the",
"entity",
"referenced",
"by",
"this",
"cursor",
"."
] | def displayname(self):
"""
Return the display name for the entity referenced by this cursor.
The display name contains extra information that helps identify the
cursor, such as the parameters of a function or template or the
arguments of a class template specialization.
"""
if not hasattr(self, '_displayname'):
self._displayname = conf.lib.clang_getCursorDisplayName(self)
return self._displayname | [
"def",
"displayname",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_displayname'",
")",
":",
"self",
".",
"_displayname",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorDisplayName",
"(",
"self",
")",
"return",
"self",
".",
"_displayna... | https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/bindings/python/clang/cindex.py#L1282-L1293 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/common.py | python | pipe | (obj, func, *args, **kwargs) | Apply a function ``func`` to object ``obj`` either by passing obj as the
first argument to the function or, in the case that the func is a tuple,
interpret the first element of the tuple as a function and pass the obj to
that function as a keyword argument whose key is the value of the second
element of the tuple.
Parameters
----------
func : callable or tuple of (callable, str)
Function to apply to this object or, alternatively, a
``(callable, data_keyword)`` tuple where ``data_keyword`` is a
string indicating the keyword of `callable`` that expects the
object.
*args : iterable, optional
Positional arguments passed into ``func``.
**kwargs : dict, optional
A dictionary of keyword arguments passed into ``func``.
Returns
-------
object : the return type of ``func``. | Apply a function ``func`` to object ``obj`` either by passing obj as the
first argument to the function or, in the case that the func is a tuple,
interpret the first element of the tuple as a function and pass the obj to
that function as a keyword argument whose key is the value of the second
element of the tuple. | [
"Apply",
"a",
"function",
"func",
"to",
"object",
"obj",
"either",
"by",
"passing",
"obj",
"as",
"the",
"first",
"argument",
"to",
"the",
"function",
"or",
"in",
"the",
"case",
"that",
"the",
"func",
"is",
"a",
"tuple",
"interpret",
"the",
"first",
"elem... | def pipe(obj, func, *args, **kwargs):
"""
Apply a function ``func`` to object ``obj`` either by passing obj as the
first argument to the function or, in the case that the func is a tuple,
interpret the first element of the tuple as a function and pass the obj to
that function as a keyword argument whose key is the value of the second
element of the tuple.
Parameters
----------
func : callable or tuple of (callable, str)
Function to apply to this object or, alternatively, a
``(callable, data_keyword)`` tuple where ``data_keyword`` is a
string indicating the keyword of `callable`` that expects the
object.
*args : iterable, optional
Positional arguments passed into ``func``.
**kwargs : dict, optional
A dictionary of keyword arguments passed into ``func``.
Returns
-------
object : the return type of ``func``.
"""
if isinstance(func, tuple):
func, target = func
if target in kwargs:
msg = f"{target} is both the pipe target and a keyword argument"
raise ValueError(msg)
kwargs[target] = obj
return func(*args, **kwargs)
else:
return func(obj, *args, **kwargs) | [
"def",
"pipe",
"(",
"obj",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"tuple",
")",
":",
"func",
",",
"target",
"=",
"func",
"if",
"target",
"in",
"kwargs",
":",
"msg",
"=",
"f\"{target... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/common.py#L429-L461 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/process-restricted-friend-requests.py | python | Solution.friendRequests | (self, n, restrictions, requests) | return result | :type n: int
:type restrictions: List[List[int]]
:type requests: List[List[int]]
:rtype: List[bool] | :type n: int
:type restrictions: List[List[int]]
:type requests: List[List[int]]
:rtype: List[bool] | [
":",
"type",
"n",
":",
"int",
":",
"type",
"restrictions",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"type",
"requests",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"List",
"[",
"bool",
"]"
] | def friendRequests(self, n, restrictions, requests):
"""
:type n: int
:type restrictions: List[List[int]]
:type requests: List[List[int]]
:rtype: List[bool]
"""
result = []
uf = UnionFind(n)
for u, v in requests:
pu, pv = uf.find_set(u), uf.find_set(v)
ok = True
for x, y in restrictions:
px, py = uf.find_set(x), uf.find_set(y)
if {px, py} == {pu, pv}:
ok = False
break
result.append(ok)
if ok:
uf.union_set(u, v)
return result | [
"def",
"friendRequests",
"(",
"self",
",",
"n",
",",
"restrictions",
",",
"requests",
")",
":",
"result",
"=",
"[",
"]",
"uf",
"=",
"UnionFind",
"(",
"n",
")",
"for",
"u",
",",
"v",
"in",
"requests",
":",
"pu",
",",
"pv",
"=",
"uf",
".",
"find_se... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/process-restricted-friend-requests.py#L31-L51 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/google/protobuf-py/google/protobuf/descriptor.py | python | _ParseOptions | (message, string) | return message | Parses serialized options.
This helper function is used to parse serialized options in generated
proto2 files. It must not be used outside proto2. | Parses serialized options. | [
"Parses",
"serialized",
"options",
"."
] | def _ParseOptions(message, string):
"""Parses serialized options.
This helper function is used to parse serialized options in generated
proto2 files. It must not be used outside proto2.
"""
message.ParseFromString(string)
return message | [
"def",
"_ParseOptions",
"(",
"message",
",",
"string",
")",
":",
"message",
".",
"ParseFromString",
"(",
"string",
")",
"return",
"message"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/descriptor.py#L590-L597 | |
microsoft/AirSim | 8057725712c0cd46979135396381784075ffc0f3 | PythonClient/airsim/client.py | python | VehicleClient.simSetSegmentationObjectID | (self, mesh_name, object_id, is_name_regex = False) | return self.client.call('simSetSegmentationObjectID', mesh_name, object_id, is_name_regex) | Set segmentation ID for specific objects
See https://microsoft.github.io/AirSim/image_apis/#segmentation for details
Args:
mesh_name (str): Name of the mesh to set the ID of (supports regex)
object_id (int): Object ID to be set, range 0-255
RBG values for IDs can be seen at https://microsoft.github.io/AirSim/seg_rgbs.txt
is_name_regex (bool, optional): Whether the mesh name is a regex
Returns:
bool: If the mesh was found | Set segmentation ID for specific objects | [
"Set",
"segmentation",
"ID",
"for",
"specific",
"objects"
] | def simSetSegmentationObjectID(self, mesh_name, object_id, is_name_regex = False):
"""
Set segmentation ID for specific objects
See https://microsoft.github.io/AirSim/image_apis/#segmentation for details
Args:
mesh_name (str): Name of the mesh to set the ID of (supports regex)
object_id (int): Object ID to be set, range 0-255
RBG values for IDs can be seen at https://microsoft.github.io/AirSim/seg_rgbs.txt
is_name_regex (bool, optional): Whether the mesh name is a regex
Returns:
bool: If the mesh was found
"""
return self.client.call('simSetSegmentationObjectID', mesh_name, object_id, is_name_regex) | [
"def",
"simSetSegmentationObjectID",
"(",
"self",
",",
"mesh_name",
",",
"object_id",
",",
"is_name_regex",
"=",
"False",
")",
":",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'simSetSegmentationObjectID'",
",",
"mesh_name",
",",
"object_id",
",",
"is_na... | https://github.com/microsoft/AirSim/blob/8057725712c0cd46979135396381784075ffc0f3/PythonClient/airsim/client.py#L604-L620 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | SpinCtrlDouble.SetValue | (*args, **kwargs) | return _controls_.SpinCtrlDouble_SetValue(*args, **kwargs) | SetValue(self, double value) | SetValue(self, double value) | [
"SetValue",
"(",
"self",
"double",
"value",
")"
] | def SetValue(*args, **kwargs):
"""SetValue(self, double value)"""
return _controls_.SpinCtrlDouble_SetValue(*args, **kwargs) | [
"def",
"SetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"SpinCtrlDouble_SetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L2512-L2514 | |
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/generators/formatters.py | python | Formatters.opcodeStemNameValidate | (self, id, cmd_name_list) | return True | Called for generation of the mod_ac_msg.h
code file. If there are repeated stem
names than through exception and stop
everything.
@param cmd_name_list: list of command function names.
@return: TRUE if all command stem names are unique, else raise an exception. | Called for generation of the mod_ac_msg.h
code file. If there are repeated stem
names than through exception and stop
everything. | [
"Called",
"for",
"generation",
"of",
"the",
"mod_ac_msg",
".",
"h",
"code",
"file",
".",
"If",
"there",
"are",
"repeated",
"stem",
"names",
"than",
"through",
"exception",
"and",
"stop",
"everything",
"."
] | def opcodeStemNameValidate(self, id, cmd_name_list):
"""
Called for generation of the mod_ac_msg.h
code file. If there are repeated stem
names than through exception and stop
everything.
@param cmd_name_list: list of command function names.
@return: TRUE if all command stem names are unique, else raise an exception.
"""
cmds = list()
for c in cmd_name_list:
cmds.append(self.opcodeStemName(id, c))
for c in cmds:
if sum([int(x == c) for x in cmds]) > 1:
PRINT.info("ERROR: DETECTED %s COMMAND STEM NAME REPEATED." % c)
raise Exception("Error detected repeated command stem name.")
return True | [
"def",
"opcodeStemNameValidate",
"(",
"self",
",",
"id",
",",
"cmd_name_list",
")",
":",
"cmds",
"=",
"list",
"(",
")",
"for",
"c",
"in",
"cmd_name_list",
":",
"cmds",
".",
"append",
"(",
"self",
".",
"opcodeStemName",
"(",
"id",
",",
"c",
")",
")",
... | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/formatters.py#L714-L732 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/ensemble/_gb.py | python | BaseGradientBoosting._clear_state | (self) | Clear the state of the gradient boosting model. | Clear the state of the gradient boosting model. | [
"Clear",
"the",
"state",
"of",
"the",
"gradient",
"boosting",
"model",
"."
] | def _clear_state(self):
"""Clear the state of the gradient boosting model. """
if hasattr(self, 'estimators_'):
self.estimators_ = np.empty((0, 0), dtype=np.object)
if hasattr(self, 'train_score_'):
del self.train_score_
if hasattr(self, 'oob_improvement_'):
del self.oob_improvement_
if hasattr(self, 'init_'):
del self.init_
if hasattr(self, '_rng'):
del self._rng | [
"def",
"_clear_state",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'estimators_'",
")",
":",
"self",
".",
"estimators_",
"=",
"np",
".",
"empty",
"(",
"(",
"0",
",",
"0",
")",
",",
"dtype",
"=",
"np",
".",
"object",
")",
"if",
"has... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/ensemble/_gb.py#L1359-L1370 | ||
redpony/cdec | f7c4899b174d86bc70b40b1cae68dcad364615cb | python/cdec/configobj.py | python | ConfigObj.write | (self, outfile=None, section=None) | Write the current ConfigObj as a file
tekNico: FIXME: use StringIO instead of real files
>>> filename = a.filename
>>> a.filename = 'test.ini'
>>> a.write()
>>> a.filename = filename
>>> a == ConfigObj('test.ini', raise_errors=True)
1
>>> import os
>>> os.remove('test.ini') | Write the current ConfigObj as a file
tekNico: FIXME: use StringIO instead of real files
>>> filename = a.filename
>>> a.filename = 'test.ini'
>>> a.write()
>>> a.filename = filename
>>> a == ConfigObj('test.ini', raise_errors=True)
1
>>> import os
>>> os.remove('test.ini') | [
"Write",
"the",
"current",
"ConfigObj",
"as",
"a",
"file",
"tekNico",
":",
"FIXME",
":",
"use",
"StringIO",
"instead",
"of",
"real",
"files",
">>>",
"filename",
"=",
"a",
".",
"filename",
">>>",
"a",
".",
"filename",
"=",
"test",
".",
"ini",
">>>",
"a"... | def write(self, outfile=None, section=None):
"""
Write the current ConfigObj as a file
tekNico: FIXME: use StringIO instead of real files
>>> filename = a.filename
>>> a.filename = 'test.ini'
>>> a.write()
>>> a.filename = filename
>>> a == ConfigObj('test.ini', raise_errors=True)
1
>>> import os
>>> os.remove('test.ini')
"""
if self.indent_type is None:
# this can be true if initialised from a dictionary
self.indent_type = DEFAULT_INDENT_TYPE
out = []
cs = self._a_to_u('#')
csp = self._a_to_u('# ')
if section is None:
int_val = self.interpolation
self.interpolation = False
section = self
for line in self.initial_comment:
line = self._decode_element(line)
stripped_line = line.strip()
if stripped_line and not stripped_line.startswith(cs):
line = csp + line
out.append(line)
indent_string = self.indent_type * section.depth
for entry in (section.scalars + section.sections):
if entry in section.defaults:
# don't write out default values
continue
for comment_line in section.comments[entry]:
comment_line = self._decode_element(comment_line.lstrip())
if comment_line and not comment_line.startswith(cs):
comment_line = csp + comment_line
out.append(indent_string + comment_line)
this_entry = section[entry]
comment = self._handle_comment(section.inline_comments[entry])
if isinstance(this_entry, dict):
# a section
out.append(self._write_marker(
indent_string,
this_entry.depth,
entry,
comment))
out.extend(self.write(section=this_entry))
else:
out.append(self._write_line(
indent_string,
entry,
this_entry,
comment))
if section is self:
for line in self.final_comment:
line = self._decode_element(line)
stripped_line = line.strip()
if stripped_line and not stripped_line.startswith(cs):
line = csp + line
out.append(line)
self.interpolation = int_val
if section is not self:
return out
if (self.filename is None) and (outfile is None):
# output a list of lines
# might need to encode
# NOTE: This will *screw* UTF16, each line will start with the BOM
if self.encoding:
out = [l.encode(self.encoding) for l in out]
if (self.BOM and ((self.encoding is None) or
(BOM_LIST.get(self.encoding.lower()) == 'utf_8'))):
# Add the UTF8 BOM
if not out:
out.append('')
out[0] = BOM_UTF8 + out[0]
return out
# Turn the list to a string, joined with correct newlines
newline = self.newlines or os.linesep
if (getattr(outfile, 'mode', None) is not None and outfile.mode == 'w'
and sys.platform == 'win32' and newline == '\r\n'):
# Windows specific hack to avoid writing '\r\r\n'
newline = '\n'
output = self._a_to_u(newline).join(out)
if self.encoding:
output = output.encode(self.encoding)
if self.BOM and ((self.encoding is None) or match_utf8(self.encoding)):
# Add the UTF8 BOM
output = BOM_UTF8 + output
if not output.endswith(newline):
output += newline
if outfile is not None:
outfile.write(output)
else:
h = open(self.filename, 'wb')
h.write(output)
h.close() | [
"def",
"write",
"(",
"self",
",",
"outfile",
"=",
"None",
",",
"section",
"=",
"None",
")",
":",
"if",
"self",
".",
"indent_type",
"is",
"None",
":",
"# this can be true if initialised from a dictionary",
"self",
".",
"indent_type",
"=",
"DEFAULT_INDENT_TYPE",
"... | https://github.com/redpony/cdec/blob/f7c4899b174d86bc70b40b1cae68dcad364615cb/python/cdec/configobj.py#L2006-L2113 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | PyApp.GetMacAboutMenuItemId | (*args, **kwargs) | return _core_.PyApp_GetMacAboutMenuItemId(*args, **kwargs) | GetMacAboutMenuItemId() -> long | GetMacAboutMenuItemId() -> long | [
"GetMacAboutMenuItemId",
"()",
"-",
">",
"long"
] | def GetMacAboutMenuItemId(*args, **kwargs):
"""GetMacAboutMenuItemId() -> long"""
return _core_.PyApp_GetMacAboutMenuItemId(*args, **kwargs) | [
"def",
"GetMacAboutMenuItemId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"PyApp_GetMacAboutMenuItemId",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L8145-L8147 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextBuffer.GetBatchedCommand | (*args, **kwargs) | return _richtext.RichTextBuffer_GetBatchedCommand(*args, **kwargs) | GetBatchedCommand(self) -> RichTextCommand | GetBatchedCommand(self) -> RichTextCommand | [
"GetBatchedCommand",
"(",
"self",
")",
"-",
">",
"RichTextCommand"
] | def GetBatchedCommand(*args, **kwargs):
"""GetBatchedCommand(self) -> RichTextCommand"""
return _richtext.RichTextBuffer_GetBatchedCommand(*args, **kwargs) | [
"def",
"GetBatchedCommand",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_GetBatchedCommand",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2285-L2287 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_stretch.py | python | Stretch.numericInput | (self, numx, numy, numz) | Validate the entry fields in the user interface.
This function is called by the toolbar or taskpanel interface
when valid x, y, and z have been entered in the input fields. | Validate the entry fields in the user interface. | [
"Validate",
"the",
"entry",
"fields",
"in",
"the",
"user",
"interface",
"."
] | def numericInput(self, numx, numy, numz):
"""Validate the entry fields in the user interface.
This function is called by the toolbar or taskpanel interface
when valid x, y, and z have been entered in the input fields.
"""
point = App.Vector(numx, numy, numz)
self.addPoint(point) | [
"def",
"numericInput",
"(",
"self",
",",
"numx",
",",
"numy",
",",
"numz",
")",
":",
"point",
"=",
"App",
".",
"Vector",
"(",
"numx",
",",
"numy",
",",
"numz",
")",
"self",
".",
"addPoint",
"(",
"point",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_stretch.py#L248-L255 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py | python | TopologicallySorted | (graph, get_edges) | return ordered_nodes | r"""Topologically sort based on a user provided edge definition.
Args:
graph: A list of node names.
get_edges: A function mapping from node name to a hashable collection
of node names which this node has outgoing edges to.
Returns:
A list containing all of the node in graph in topological order.
It is assumed that calling get_edges once for each node and caching is
cheaper than repeatedly calling get_edges.
Raises:
CycleError in the event of a cycle.
Example:
graph = {'a': '$(b) $(c)', 'b': 'hi', 'c': '$(b)'}
def GetEdges(node):
return re.findall(r'\$\(([^))]\)', graph[node])
print TopologicallySorted(graph.keys(), GetEdges)
==>
['a', 'c', b'] | r"""Topologically sort based on a user provided edge definition. | [
"r",
"Topologically",
"sort",
"based",
"on",
"a",
"user",
"provided",
"edge",
"definition",
"."
] | def TopologicallySorted(graph, get_edges):
r"""Topologically sort based on a user provided edge definition.
Args:
graph: A list of node names.
get_edges: A function mapping from node name to a hashable collection
of node names which this node has outgoing edges to.
Returns:
A list containing all of the node in graph in topological order.
It is assumed that calling get_edges once for each node and caching is
cheaper than repeatedly calling get_edges.
Raises:
CycleError in the event of a cycle.
Example:
graph = {'a': '$(b) $(c)', 'b': 'hi', 'c': '$(b)'}
def GetEdges(node):
return re.findall(r'\$\(([^))]\)', graph[node])
print TopologicallySorted(graph.keys(), GetEdges)
==>
['a', 'c', b']
"""
get_edges = memoize(get_edges)
visited = set()
visiting = set()
ordered_nodes = []
def Visit(node):
if node in visiting:
raise CycleError(visiting)
if node in visited:
return
visited.add(node)
visiting.add(node)
for neighbor in get_edges(node):
Visit(neighbor)
visiting.remove(node)
ordered_nodes.insert(0, node)
for node in sorted(graph):
Visit(node)
return ordered_nodes | [
"def",
"TopologicallySorted",
"(",
"graph",
",",
"get_edges",
")",
":",
"get_edges",
"=",
"memoize",
"(",
"get_edges",
")",
"visited",
"=",
"set",
"(",
")",
"visiting",
"=",
"set",
"(",
")",
"ordered_nodes",
"=",
"[",
"]",
"def",
"Visit",
"(",
"node",
... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py#L576-L614 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/factorization/python/ops/factorization_ops.py | python | WALSModel._create_gramian | (n_components, name) | return variable_scope.variable(
array_ops.zeros([n_components, n_components]),
dtype=dtypes.float32,
name=name) | Helper function to create the gramian variable.
Args:
n_components: number of dimensions of the factors from which the gramian
will be calculated.
name: name for the new Variables.
Returns:
A gramian Tensor with shape of [n_components, n_components]. | Helper function to create the gramian variable. | [
"Helper",
"function",
"to",
"create",
"the",
"gramian",
"variable",
"."
] | def _create_gramian(n_components, name):
"""Helper function to create the gramian variable.
Args:
n_components: number of dimensions of the factors from which the gramian
will be calculated.
name: name for the new Variables.
Returns:
A gramian Tensor with shape of [n_components, n_components].
"""
return variable_scope.variable(
array_ops.zeros([n_components, n_components]),
dtype=dtypes.float32,
name=name) | [
"def",
"_create_gramian",
"(",
"n_components",
",",
"name",
")",
":",
"return",
"variable_scope",
".",
"variable",
"(",
"array_ops",
".",
"zeros",
"(",
"[",
"n_components",
",",
"n_components",
"]",
")",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
",",
"n... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/factorization/python/ops/factorization_ops.py#L403-L417 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_utils.py | python | split_training_and_validation_data | (x, y, sample_weights, validation_split) | return x, y, sample_weights, val_x, val_y, val_sample_weights | Split input data into train/eval section based on validation_split. | Split input data into train/eval section based on validation_split. | [
"Split",
"input",
"data",
"into",
"train",
"/",
"eval",
"section",
"based",
"on",
"validation_split",
"."
] | def split_training_and_validation_data(x, y, sample_weights, validation_split):
"""Split input data into train/eval section based on validation_split."""
if has_symbolic_tensors(x):
raise ValueError('If your data is in the form of symbolic tensors, '
'you cannot use `validation_split`.')
if hasattr(x[0], 'shape'):
split_at = int(x[0].shape[0] * (1. - validation_split))
else:
split_at = int(len(x[0]) * (1. - validation_split))
x, val_x = (generic_utils.slice_arrays(x, 0, split_at),
generic_utils.slice_arrays(x, split_at))
y, val_y = (generic_utils.slice_arrays(y, 0, split_at),
generic_utils.slice_arrays(y, split_at))
if sample_weights:
sample_weights, val_sample_weights = (
generic_utils.slice_arrays(sample_weights, 0, split_at),
generic_utils.slice_arrays(sample_weights, split_at),
)
else:
val_sample_weights = None
return x, y, sample_weights, val_x, val_y, val_sample_weights | [
"def",
"split_training_and_validation_data",
"(",
"x",
",",
"y",
",",
"sample_weights",
",",
"validation_split",
")",
":",
"if",
"has_symbolic_tensors",
"(",
"x",
")",
":",
"raise",
"ValueError",
"(",
"'If your data is in the form of symbolic tensors, '",
"'you cannot use... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_utils.py#L1865-L1885 | |
muccc/gr-iridium | d0e7efcb6ee55a35042acd267d65af90847e5475 | docs/doxygen/update_pydoc.py | python | argParse | () | return parser.parse_args() | Parses commandline args. | Parses commandline args. | [
"Parses",
"commandline",
"args",
"."
] | def argParse():
"""Parses commandline args."""
desc='Scrape the doxygen generated xml for docstrings to insert into python bindings'
parser = ArgumentParser(description=desc)
parser.add_argument("function", help="Operation to perform on docstrings", choices=["scrape","sub","copy"])
parser.add_argument("--xml_path")
parser.add_argument("--bindings_dir")
parser.add_argument("--output_dir")
parser.add_argument("--json_path")
parser.add_argument("--filter", default=None)
return parser.parse_args() | [
"def",
"argParse",
"(",
")",
":",
"desc",
"=",
"'Scrape the doxygen generated xml for docstrings to insert into python bindings'",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"desc",
")",
"parser",
".",
"add_argument",
"(",
"\"function\"",
",",
"help",
"="... | https://github.com/muccc/gr-iridium/blob/d0e7efcb6ee55a35042acd267d65af90847e5475/docs/doxygen/update_pydoc.py#L314-L327 | |
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/YouCompleteMe/third_party/requests/requests/packages/urllib3/util.py | python | split_first | (s, delims) | return s[:min_idx], s[min_idx+1:], min_delim | Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example: ::
>>> split_first('foo/bar?baz', '?/=')
('foo', 'bar?baz', '/')
>>> split_first('foo/bar?baz', '123')
('foo/bar?baz', '', None)
Scales linearly with number of delims. Not ideal for large number of delims. | Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter. | [
"Given",
"a",
"string",
"and",
"an",
"iterable",
"of",
"delimiters",
"split",
"on",
"the",
"first",
"found",
"delimiter",
".",
"Return",
"two",
"split",
"parts",
"and",
"the",
"matched",
"delimiter",
"."
] | def split_first(s, delims):
"""
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example: ::
>>> split_first('foo/bar?baz', '?/=')
('foo', 'bar?baz', '/')
>>> split_first('foo/bar?baz', '123')
('foo/bar?baz', '', None)
Scales linearly with number of delims. Not ideal for large number of delims.
"""
min_idx = None
min_delim = None
for d in delims:
idx = s.find(d)
if idx < 0:
continue
if min_idx is None or idx < min_idx:
min_idx = idx
min_delim = d
if min_idx is None or min_idx < 0:
return s, '', None
return s[:min_idx], s[min_idx+1:], min_delim | [
"def",
"split_first",
"(",
"s",
",",
"delims",
")",
":",
"min_idx",
"=",
"None",
"min_delim",
"=",
"None",
"for",
"d",
"in",
"delims",
":",
"idx",
"=",
"s",
".",
"find",
"(",
"d",
")",
"if",
"idx",
"<",
"0",
":",
"continue",
"if",
"min_idx",
"is"... | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/requests/requests/packages/urllib3/util.py#L298-L328 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | PNEANet.EdgeAttrIsDeleted | (self, *args) | return _snap.PNEANet_EdgeAttrIsDeleted(self, *args) | EdgeAttrIsDeleted(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const & | EdgeAttrIsDeleted(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool | [
"EdgeAttrIsDeleted",
"(",
"PNEANet",
"self",
"int",
"const",
"&",
"EId",
"TStrIntPrH",
"::",
"TIter",
"const",
"&",
"EdgeHI",
")",
"-",
">",
"bool"
] | def EdgeAttrIsDeleted(self, *args):
"""
EdgeAttrIsDeleted(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_EdgeAttrIsDeleted(self, *args) | [
"def",
"EdgeAttrIsDeleted",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"PNEANet_EdgeAttrIsDeleted",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L24431-L24440 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | xmlNode.setSpacePreserve | (self, val) | Set (or reset) the space preserving behaviour of a node,
i.e. the value of the xml:space attribute. | Set (or reset) the space preserving behaviour of a node,
i.e. the value of the xml:space attribute. | [
"Set",
"(",
"or",
"reset",
")",
"the",
"space",
"preserving",
"behaviour",
"of",
"a",
"node",
"i",
".",
"e",
".",
"the",
"value",
"of",
"the",
"xml",
":",
"space",
"attribute",
"."
] | def setSpacePreserve(self, val):
"""Set (or reset) the space preserving behaviour of a node,
i.e. the value of the xml:space attribute. """
libxml2mod.xmlNodeSetSpacePreserve(self._o, val) | [
"def",
"setSpacePreserve",
"(",
"self",
",",
"val",
")",
":",
"libxml2mod",
".",
"xmlNodeSetSpacePreserve",
"(",
"self",
".",
"_o",
",",
"val",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L2802-L2805 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemComputeFarm/v1/Harness/dictionary_sorter/merge.py | python | handler | (config, task, updater, main_input, path_input, merge_inputs) | return {
'zip_name': out_zip_name,
'tail': path_input[-1] if len(path_input) else None
} | A simple example of a merge handler that downloads sorted segments of a dictionary from S3, merges them together
into a single sorted dictionary, and uploads the results back to S3. | A simple example of a merge handler that downloads sorted segments of a dictionary from S3, merges them together
into a single sorted dictionary, and uploads the results back to S3. | [
"A",
"simple",
"example",
"of",
"a",
"merge",
"handler",
"that",
"downloads",
"sorted",
"segments",
"of",
"a",
"dictionary",
"from",
"S3",
"merges",
"them",
"together",
"into",
"a",
"single",
"sorted",
"dictionary",
"and",
"uploads",
"the",
"results",
"back",
... | def handler(config, task, updater, main_input, path_input, merge_inputs):
"""
A simple example of a merge handler that downloads sorted segments of a dictionary from S3, merges them together
into a single sorted dictionary, and uploads the results back to S3.
"""
s3_dir = main_input['s3_dir']
s3_file = main_input['s3_file']
merge_sources = []
for idx, input in enumerate(merge_inputs):
updater.post_task_update("Downloading chunk %d of %d from S3" % (idx + 1, len(merge_inputs)))
zip_name = input['zip_name']
text_name = zip_name[:-3] + "txt"
local_zip_path = os.path.join(tempfile.gettempdir(), zip_name)
config.s3_resource.meta.client.download_file(
Bucket=config.config_bucket,
Key=util.s3_key_join(s3_dir, zip_name),
Filename=local_zip_path
)
with zipfile.ZipFile(local_zip_path, "r") as zp:
with zp.open(text_name, "r") as fp:
lines = fp.readlines()
merge_sources.append(LineSource(lines, len(merge_sources)))
updater.post_task_update("Merging %d data sources" % len(merge_inputs))
out_lines = []
# Merge the multiple independently-sorted sources by popping the minimum off of each stack until there are none left
while len(merge_sources) > 1:
# Determine which source has the minimum value, and append its line to the output
min_source = min(merge_sources, key=lambda x: x.current)
out_lines.append(min_source.lines[min_source.index])
# Advance that source to the next line
if not min_source.advance():
# We are out of lines remaining in this source, so discard it
del merge_sources[min_source.list_position]
# Renumber the remaining sources
for idx, src in enumerate(merge_sources):
src.list_position = idx
# With only one source left, we can just dump the remaining lines from it to the output
out_lines.extend(merge_sources[0].lines[merge_sources[0].index:])
# Write the output to a file
out_basename = "%s_sorted%s" % (s3_file, "".join([str(x) for x in path_input]))
out_zip_name = out_basename + ".zip"
out_txt_name = out_basename + ".txt"
out_zip_path = os.path.join(tempfile.gettempdir(), out_zip_name)
with zipfile.ZipFile(out_zip_path, "w", zipfile.ZIP_DEFLATED) as zp:
with zp.open(out_txt_name, "w") as fp:
fp.write(b"".join(out_lines))
updater.post_task_update("Uploading results to S3")
config.s3_resource.meta.client.upload_file(
Filename=out_zip_path,
Bucket=config.config_bucket,
Key=util.s3_key_join(s3_dir, out_zip_name)
)
return {
'zip_name': out_zip_name,
'tail': path_input[-1] if len(path_input) else None
} | [
"def",
"handler",
"(",
"config",
",",
"task",
",",
"updater",
",",
"main_input",
",",
"path_input",
",",
"merge_inputs",
")",
":",
"s3_dir",
"=",
"main_input",
"[",
"'s3_dir'",
"]",
"s3_file",
"=",
"main_input",
"[",
"'s3_file'",
"]",
"merge_sources",
"=",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemComputeFarm/v1/Harness/dictionary_sorter/merge.py#L37-L109 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | tools/caffe_converter/convert_caffe_modelzoo.py | python | download_caffe_model | (model_name, meta_info, dst_dir='./model') | return (prototxt, caffemodel, mean) | Download caffe model into disk by the given meta info | Download caffe model into disk by the given meta info | [
"Download",
"caffe",
"model",
"into",
"disk",
"by",
"the",
"given",
"meta",
"info"
] | def download_caffe_model(model_name, meta_info, dst_dir='./model'):
"""Download caffe model into disk by the given meta info """
if not os.path.isdir(dst_dir):
os.mkdir(dst_dir)
model_name = os.path.join(dst_dir, model_name)
assert 'prototxt' in meta_info, "missing prototxt url"
proto_url, proto_sha1 = meta_info['prototxt']
prototxt = mx.gluon.utils.download(proto_url,
model_name+'_deploy.prototxt',
sha1_hash=proto_sha1)
assert 'caffemodel' in meta_info, "mssing caffemodel url"
caffemodel_url, caffemodel_sha1 = meta_info['caffemodel']
caffemodel = mx.gluon.utils.download(caffemodel_url,
model_name+'.caffemodel',
sha1_hash=caffemodel_sha1)
assert 'mean' in meta_info, 'no mean info'
mean = meta_info['mean']
if isinstance(mean[0], str):
mean_url, mean_sha1 = mean
mean = mx.gluon.utils.download(mean_url,
model_name+'_mean.binaryproto',
sha1_hash=mean_sha1)
return (prototxt, caffemodel, mean) | [
"def",
"download_caffe_model",
"(",
"model_name",
",",
"meta_info",
",",
"dst_dir",
"=",
"'./model'",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dst_dir",
")",
":",
"os",
".",
"mkdir",
"(",
"dst_dir",
")",
"model_name",
"=",
"os",
".... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/tools/caffe_converter/convert_caffe_modelzoo.py#L118-L142 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/the-time-when-the-network-becomes-idle.py | python | Solution.networkBecomesIdle | (self, edges, patience) | return 1+result | :type edges: List[List[int]]
:type patience: List[int]
:rtype: int | :type edges: List[List[int]]
:type patience: List[int]
:rtype: int | [
":",
"type",
"edges",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"type",
"patience",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def networkBecomesIdle(self, edges, patience):
"""
:type edges: List[List[int]]
:type patience: List[int]
:rtype: int
"""
adj = [[] for _ in xrange(len(patience))]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
q = [0]
lookup = [False]*len(patience)
lookup[0] = True
step = 1
result = 0
while q:
new_q = []
for u in q:
for v in adj[u]:
if lookup[v]:
continue
lookup[v] = True
new_q.append(v)
result = max(result, ((step*2)-1)//patience[v]*patience[v] + (step*2))
q = new_q
step += 1
return 1+result | [
"def",
"networkBecomesIdle",
"(",
"self",
",",
"edges",
",",
"patience",
")",
":",
"adj",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"xrange",
"(",
"len",
"(",
"patience",
")",
")",
"]",
"for",
"u",
",",
"v",
"in",
"edges",
":",
"adj",
"[",
"u",
"]"... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/the-time-when-the-network-becomes-idle.py#L5-L31 | |
p4lang/p4c | 3272e79369f20813cc1a555a5eb26f44432f84a4 | tools/cpplint.py | python | FlagCxx11Features | (filename, clean_lines, linenum, error) | Flag those c++11 features that we only allow in certain places.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Flag those c++11 features that we only allow in certain places. | [
"Flag",
"those",
"c",
"++",
"11",
"features",
"that",
"we",
"only",
"allow",
"in",
"certain",
"places",
"."
] | def FlagCxx11Features(filename, clean_lines, linenum, error):
"""Flag those c++11 features that we only allow in certain places.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
# Flag unapproved C++ TR1 headers.
if include and include.group(1).startswith('tr1/'):
error(filename, linenum, 'build/c++tr1', 5,
('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
# Flag unapproved C++11 headers.
if include and include.group(1) in ('cfenv',
'condition_variable',
'fenv.h',
'future',
'mutex',
'thread',
'chrono',
'ratio',
'regex',
'system_error',
):
error(filename, linenum, 'build/c++11', 5,
('<%s> is an unapproved C++11 header.') % include.group(1))
# The only place where we need to worry about C++11 keywords and library
# features in preprocessor directives is in macro definitions.
if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
# These are classes and free functions. The classes are always
# mentioned as std::*, but we only catch the free functions if
# they're not found by ADL. They're alphabetical by header.
for top_name in (
# type_traits
'alignment_of',
'aligned_union',
):
if Search(r'\bstd::%s\b' % top_name, line):
error(filename, linenum, 'build/c++11', 5,
('std::%s is an unapproved C++11 class or function. Send c-style '
'an example of where it would make your code more readable, and '
'they may let you use it.') % top_name) | [
"def",
"FlagCxx11Features",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"include",
"=",
"Match",
"(",
"r'\\s*#\\s*include\\s+[<\"]([^<\"]+)[\">]'",
",",
"line",
")",... | https://github.com/p4lang/p4c/blob/3272e79369f20813cc1a555a5eb26f44432f84a4/tools/cpplint.py#L6413-L6462 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | RegionIterator.GetWidth | (*args, **kwargs) | return _gdi_.RegionIterator_GetWidth(*args, **kwargs) | GetWidth(self) -> int | GetWidth(self) -> int | [
"GetWidth",
"(",
"self",
")",
"-",
">",
"int"
] | def GetWidth(*args, **kwargs):
"""GetWidth(self) -> int"""
return _gdi_.RegionIterator_GetWidth(*args, **kwargs) | [
"def",
"GetWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"RegionIterator_GetWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L1682-L1684 | |
facebook/folly | 744a0a698074d1b013813065fe60f545aa2c9b94 | build/fbcode_builder/getdeps/manifest.py | python | ManifestParser.update_hash | (self, hasher, ctx) | Compute a hash over the configuration for the given
context. The goal is for the hash to change if the config
for that context changes, but not if a change is made to
the config only for a different platform than that expressed
by ctx. The hash is intended to be used to help invalidate
a future cache for the third party build products.
The hasher argument is a hash object returned from hashlib. | Compute a hash over the configuration for the given
context. The goal is for the hash to change if the config
for that context changes, but not if a change is made to
the config only for a different platform than that expressed
by ctx. The hash is intended to be used to help invalidate
a future cache for the third party build products.
The hasher argument is a hash object returned from hashlib. | [
"Compute",
"a",
"hash",
"over",
"the",
"configuration",
"for",
"the",
"given",
"context",
".",
"The",
"goal",
"is",
"for",
"the",
"hash",
"to",
"change",
"if",
"the",
"config",
"for",
"that",
"context",
"changes",
"but",
"not",
"if",
"a",
"change",
"is",... | def update_hash(self, hasher, ctx):
"""Compute a hash over the configuration for the given
context. The goal is for the hash to change if the config
for that context changes, but not if a change is made to
the config only for a different platform than that expressed
by ctx. The hash is intended to be used to help invalidate
a future cache for the third party build products.
The hasher argument is a hash object returned from hashlib."""
for section in sorted(SCHEMA.keys()):
hasher.update(section.encode("utf-8"))
# Note: at the time of writing, nothing in the implementation
# relies on keys in any config section being ordered.
# In theory we could have conflicting flags in different
# config sections and later flags override earlier flags.
# For the purposes of computing a hash we're not super
# concerned about this: manifest changes should be rare
# enough and we'd rather that this trigger an invalidation
# than strive for a cache hit at this time.
pairs = self.get_section_as_ordered_pairs(section, ctx)
pairs.sort(key=lambda pair: pair[0])
for key, value in pairs:
hasher.update(key.encode("utf-8"))
if value is not None:
hasher.update(value.encode("utf-8")) | [
"def",
"update_hash",
"(",
"self",
",",
"hasher",
",",
"ctx",
")",
":",
"for",
"section",
"in",
"sorted",
"(",
"SCHEMA",
".",
"keys",
"(",
")",
")",
":",
"hasher",
".",
"update",
"(",
"section",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"# Note: at ... | https://github.com/facebook/folly/blob/744a0a698074d1b013813065fe60f545aa2c9b94/build/fbcode_builder/getdeps/manifest.py#L329-L353 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | media/tools/constrained_network_server/cns.py | python | PortAllocator._SetupPort | (self, port, **kwargs) | Setup network constraints on port using the requested parameters.
Args:
port: The port number to setup network constraints on.
**kwargs: Network constraints to set up on the port.
Returns:
True if setting the network constraints on the port was successful, false
otherwise. | Setup network constraints on port using the requested parameters. | [
"Setup",
"network",
"constraints",
"on",
"port",
"using",
"the",
"requested",
"parameters",
"."
] | def _SetupPort(self, port, **kwargs):
"""Setup network constraints on port using the requested parameters.
Args:
port: The port number to setup network constraints on.
**kwargs: Network constraints to set up on the port.
Returns:
True if setting the network constraints on the port was successful, false
otherwise.
"""
kwargs['port'] = port
try:
cherrypy.log('Setting up port %d' % port)
traffic_control.CreateConstrainedPort(kwargs)
return True
except traffic_control.TrafficControlError as e:
cherrypy.log('Error: %s\nOutput: %s' % (e.msg, e.error))
return False | [
"def",
"_SetupPort",
"(",
"self",
",",
"port",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'port'",
"]",
"=",
"port",
"try",
":",
"cherrypy",
".",
"log",
"(",
"'Setting up port %d'",
"%",
"port",
")",
"traffic_control",
".",
"CreateConstrainedPort",... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/media/tools/constrained_network_server/cns.py#L111-L129 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_vehicle.py | python | VehicleDomain.dispatchTaxi | (self, vehID, reservations) | dispatchTaxi(string, list(string)) -> None
dispatches the taxi with the given id to service the given reservations.
If only a single reservation is given, this implies pickup and drop-off
If multiple reservations are given, each reservation id must occur twice
(once for pickup and once for drop-off) and the list encodes ride
sharing of passengers (in pickup and drop-off order) | dispatchTaxi(string, list(string)) -> None
dispatches the taxi with the given id to service the given reservations.
If only a single reservation is given, this implies pickup and drop-off
If multiple reservations are given, each reservation id must occur twice
(once for pickup and once for drop-off) and the list encodes ride
sharing of passengers (in pickup and drop-off order) | [
"dispatchTaxi",
"(",
"string",
"list",
"(",
"string",
"))",
"-",
">",
"None",
"dispatches",
"the",
"taxi",
"with",
"the",
"given",
"id",
"to",
"service",
"the",
"given",
"reservations",
".",
"If",
"only",
"a",
"single",
"reservation",
"is",
"given",
"this"... | def dispatchTaxi(self, vehID, reservations):
"""dispatchTaxi(string, list(string)) -> None
dispatches the taxi with the given id to service the given reservations.
If only a single reservation is given, this implies pickup and drop-off
If multiple reservations are given, each reservation id must occur twice
(once for pickup and once for drop-off) and the list encodes ride
sharing of passengers (in pickup and drop-off order)
"""
self._setCmd(tc.CMD_TAXI_DISPATCH, vehID, "l", reservations) | [
"def",
"dispatchTaxi",
"(",
"self",
",",
"vehID",
",",
"reservations",
")",
":",
"self",
".",
"_setCmd",
"(",
"tc",
".",
"CMD_TAXI_DISPATCH",
",",
"vehID",
",",
"\"l\"",
",",
"reservations",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L1598-L1606 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/setobj.py | python | SetInstance._pyapi_get_hash_value | (self, pyapi, context, builder, item) | return retval | Python API compatible version of `get_hash_value()`. | Python API compatible version of `get_hash_value()`. | [
"Python",
"API",
"compatible",
"version",
"of",
"get_hash_value",
"()",
"."
] | def _pyapi_get_hash_value(self, pyapi, context, builder, item):
"""Python API compatible version of `get_hash_value()`.
"""
def emit_wrapper(resty, argtypes):
# Because `get_hash_value()` could raise a nopython exception,
# we need to wrap it in a function that has nopython
# calling convention.
fnty = context.call_conv.get_function_type(resty, argtypes)
mod = builder.module
fn = ir.Function(
mod, fnty, name=mod.get_unique_name('.set_hash_item'),
)
fn.linkage = 'internal'
inner_builder = ir.IRBuilder(fn.append_basic_block())
[inner_item] = context.call_conv.decode_arguments(
inner_builder, argtypes, fn,
)
# Call get_hash_value()
h = get_hash_value(
context, inner_builder, self._ty.dtype, inner_item,
)
context.call_conv.return_value(inner_builder, h)
return fn
argtypes = [self._ty.dtype]
resty = types.intp
fn = emit_wrapper(resty, argtypes)
# Call wrapper function
status, retval = context.call_conv.call_function(
builder, fn, resty, argtypes, [item],
)
# Handle return status
with builder.if_then(builder.not_(status.is_ok), likely=False):
# Raise nopython exception as a Python exception
context.call_conv.raise_error(builder, pyapi, status)
builder.ret(pyapi.get_null_object())
return retval | [
"def",
"_pyapi_get_hash_value",
"(",
"self",
",",
"pyapi",
",",
"context",
",",
"builder",
",",
"item",
")",
":",
"def",
"emit_wrapper",
"(",
"resty",
",",
"argtypes",
")",
":",
"# Because `get_hash_value()` could raise a nopython exception,",
"# we need to wrap it in a... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/setobj.py#L490-L527 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexers.py | python | is_empty_indexer | (indexer, arr_value: np.ndarray) | return False | Check if we have an empty indexer.
Parameters
----------
indexer : object
arr_value : np.ndarray
Returns
-------
bool | Check if we have an empty indexer. | [
"Check",
"if",
"we",
"have",
"an",
"empty",
"indexer",
"."
] | def is_empty_indexer(indexer, arr_value: np.ndarray) -> bool:
"""
Check if we have an empty indexer.
Parameters
----------
indexer : object
arr_value : np.ndarray
Returns
-------
bool
"""
if is_list_like(indexer) and not len(indexer):
return True
if arr_value.ndim == 1:
if not isinstance(indexer, tuple):
indexer = tuple([indexer])
return any(isinstance(idx, np.ndarray) and len(idx) == 0 for idx in indexer)
return False | [
"def",
"is_empty_indexer",
"(",
"indexer",
",",
"arr_value",
":",
"np",
".",
"ndarray",
")",
"->",
"bool",
":",
"if",
"is_list_like",
"(",
"indexer",
")",
"and",
"not",
"len",
"(",
"indexer",
")",
":",
"return",
"True",
"if",
"arr_value",
".",
"ndim",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexers.py#L54-L73 | |
D-X-Y/caffe-faster-rcnn | eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb | python/caffe/net_spec.py | python | to_proto | (*tops) | return net | Generate a NetParameter that contains all layers needed to compute
all arguments. | Generate a NetParameter that contains all layers needed to compute
all arguments. | [
"Generate",
"a",
"NetParameter",
"that",
"contains",
"all",
"layers",
"needed",
"to",
"compute",
"all",
"arguments",
"."
] | def to_proto(*tops):
"""Generate a NetParameter that contains all layers needed to compute
all arguments."""
layers = OrderedDict()
autonames = Counter()
for top in tops:
top.fn._to_proto(layers, {}, autonames)
net = caffe_pb2.NetParameter()
net.layer.extend(layers.values())
return net | [
"def",
"to_proto",
"(",
"*",
"tops",
")",
":",
"layers",
"=",
"OrderedDict",
"(",
")",
"autonames",
"=",
"Counter",
"(",
")",
"for",
"top",
"in",
"tops",
":",
"top",
".",
"fn",
".",
"_to_proto",
"(",
"layers",
",",
"{",
"}",
",",
"autonames",
")",
... | https://github.com/D-X-Y/caffe-faster-rcnn/blob/eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb/python/caffe/net_spec.py#L43-L53 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | example/gluon/image_classification.py | python | update_learning_rate | (lr, trainer, epoch, ratio, steps) | return trainer | Set the learning rate to the initial value decayed by ratio every N epochs. | Set the learning rate to the initial value decayed by ratio every N epochs. | [
"Set",
"the",
"learning",
"rate",
"to",
"the",
"initial",
"value",
"decayed",
"by",
"ratio",
"every",
"N",
"epochs",
"."
] | def update_learning_rate(lr, trainer, epoch, ratio, steps):
"""Set the learning rate to the initial value decayed by ratio every N epochs."""
new_lr = lr * (ratio ** int(np.sum(np.array(steps) < epoch)))
trainer.set_learning_rate(new_lr)
return trainer | [
"def",
"update_learning_rate",
"(",
"lr",
",",
"trainer",
",",
"epoch",
",",
"ratio",
",",
"steps",
")",
":",
"new_lr",
"=",
"lr",
"*",
"(",
"ratio",
"**",
"int",
"(",
"np",
".",
"sum",
"(",
"np",
".",
"array",
"(",
"steps",
")",
"<",
"epoch",
")... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/example/gluon/image_classification.py#L174-L178 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.GetLastKeydownProcessed | (*args, **kwargs) | return _stc.StyledTextCtrl_GetLastKeydownProcessed(*args, **kwargs) | GetLastKeydownProcessed(self) -> bool | GetLastKeydownProcessed(self) -> bool | [
"GetLastKeydownProcessed",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetLastKeydownProcessed(*args, **kwargs):
"""GetLastKeydownProcessed(self) -> bool"""
return _stc.StyledTextCtrl_GetLastKeydownProcessed(*args, **kwargs) | [
"def",
"GetLastKeydownProcessed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetLastKeydownProcessed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L6645-L6647 | |
quarkslab/arybo | 89d9a4266fa51c1a560f6c4a66f65d1ffde5f093 | arybo/lib/mba_if.py | python | MBAVariable.simplify | (self) | return simplify(self) | Simplify the expression | Simplify the expression | [
"Simplify",
"the",
"expression"
] | def simplify(self):
''' Simplify the expression '''
return simplify(self) | [
"def",
"simplify",
"(",
"self",
")",
":",
"return",
"simplify",
"(",
"self",
")"
] | https://github.com/quarkslab/arybo/blob/89d9a4266fa51c1a560f6c4a66f65d1ffde5f093/arybo/lib/mba_if.py#L322-L324 | |
berndpfrommer/tagslam | 406562abfb27ec0f409d7bd27dd6c45dabd9965d | src/rpp.py | python | compute_polynomial | (FTF) | return f, g, h | E_os(beta_t) = (1+beta_t^2)^{-2} * mu^T * (F^T * F) * mu
where mu = [1, beta_t, beta_t^2]^T
now express E_os(beta_t) and derivates as polynomials in beta_t
E_os = (1+beta^2)^{-2} * (sum_{i=0^n} f[n-i] beta^i)
E_os' = (1+beta^2)^{-3} * (sum_{i=0^n} g[n-i] beta^i)
E_os'' = (1+beta^2)^{-4} * (sum_{i=0^n} h[n-i] beta^i)
NOTE: ordering is opposite to the c++ code!!!
i.e. f[0] is x^4 order in python!!! | E_os(beta_t) = (1+beta_t^2)^{-2} * mu^T * (F^T * F) * mu
where mu = [1, beta_t, beta_t^2]^T
now express E_os(beta_t) and derivates as polynomials in beta_t
E_os = (1+beta^2)^{-2} * (sum_{i=0^n} f[n-i] beta^i)
E_os' = (1+beta^2)^{-3} * (sum_{i=0^n} g[n-i] beta^i)
E_os'' = (1+beta^2)^{-4} * (sum_{i=0^n} h[n-i] beta^i) | [
"E_os",
"(",
"beta_t",
")",
"=",
"(",
"1",
"+",
"beta_t^2",
")",
"^",
"{",
"-",
"2",
"}",
"*",
"mu^T",
"*",
"(",
"F^T",
"*",
"F",
")",
"*",
"mu",
"where",
"mu",
"=",
"[",
"1",
"beta_t",
"beta_t^2",
"]",
"^T",
"now",
"express",
"E_os",
"(",
... | def compute_polynomial(FTF):
"""
E_os(beta_t) = (1+beta_t^2)^{-2} * mu^T * (F^T * F) * mu
where mu = [1, beta_t, beta_t^2]^T
now express E_os(beta_t) and derivates as polynomials in beta_t
E_os = (1+beta^2)^{-2} * (sum_{i=0^n} f[n-i] beta^i)
E_os' = (1+beta^2)^{-3} * (sum_{i=0^n} g[n-i] beta^i)
E_os'' = (1+beta^2)^{-4} * (sum_{i=0^n} h[n-i] beta^i)
NOTE: ordering is opposite to the c++ code!!!
i.e. f[0] is x^4 order in python!!!
"""
# zeroth order deriv poly
f = np.asarray([FTF[2, 2],
FTF[1, 2] + FTF[2, 1],
FTF[0, 2] + FTF[1, 1] + FTF[2, 0],
FTF[0, 1] + FTF[1, 0],
FTF[0, 0]])
# first deriv polynomial
g = np.asarray([-f[1], 4*f[0]-2*f[2], 3*(f[1]-f[3]), 2*f[2]-4*f[4], f[3]])
# second deriv polynomial
h = np.asarray([2*f[1], # 5
6 *f[2] - 12*f[0], # 4
12*f[3] - 16*f[1], # 3
20*f[4] - 16*f[2] + 12*f[0], # 2
-12*f[3] + 6*f[1], # 1
-4*f[4] + 2*f[2]])
return f, g, h | [
"def",
"compute_polynomial",
"(",
"FTF",
")",
":",
"# zeroth order deriv poly",
"f",
"=",
"np",
".",
"asarray",
"(",
"[",
"FTF",
"[",
"2",
",",
"2",
"]",
",",
"FTF",
"[",
"1",
",",
"2",
"]",
"+",
"FTF",
"[",
"2",
",",
"1",
"]",
",",
"FTF",
"[",... | https://github.com/berndpfrommer/tagslam/blob/406562abfb27ec0f409d7bd27dd6c45dabd9965d/src/rpp.py#L151-L181 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/generator/eclipse.py | python | GenerateClasspathFile | (target_list, target_dicts, toplevel_dir,
toplevel_build, out_name) | Generates a classpath file suitable for symbol navigation and code
completion of Java code (such as in Android projects) by finding all
.java and .jar files used as action inputs. | Generates a classpath file suitable for symbol navigation and code
completion of Java code (such as in Android projects) by finding all
.java and .jar files used as action inputs. | [
"Generates",
"a",
"classpath",
"file",
"suitable",
"for",
"symbol",
"navigation",
"and",
"code",
"completion",
"of",
"Java",
"code",
"(",
"such",
"as",
"in",
"Android",
"projects",
")",
"by",
"finding",
"all",
".",
"java",
"and",
".",
"jar",
"files",
"used... | def GenerateClasspathFile(target_list, target_dicts, toplevel_dir,
toplevel_build, out_name):
'''Generates a classpath file suitable for symbol navigation and code
completion of Java code (such as in Android projects) by finding all
.java and .jar files used as action inputs.'''
gyp.common.EnsureDirExists(out_name)
result = ET.Element('classpath')
def AddElements(kind, paths):
# First, we need to normalize the paths so they are all relative to the
# toplevel dir.
rel_paths = set()
for path in paths:
if os.path.isabs(path):
rel_paths.add(os.path.relpath(path, toplevel_dir))
else:
rel_paths.add(path)
for path in sorted(rel_paths):
entry_element = ET.SubElement(result, 'classpathentry')
entry_element.set('kind', kind)
entry_element.set('path', path)
AddElements('lib', GetJavaJars(target_list, target_dicts, toplevel_dir))
AddElements('src', GetJavaSourceDirs(target_list, target_dicts, toplevel_dir))
# Include the standard JRE container and a dummy out folder
AddElements('con', ['org.eclipse.jdt.launching.JRE_CONTAINER'])
# Include a dummy out folder so that Eclipse doesn't use the default /bin
# folder in the root of the project.
AddElements('output', [os.path.join(toplevel_build, '.eclipse-java-build')])
ET.ElementTree(result).write(out_name) | [
"def",
"GenerateClasspathFile",
"(",
"target_list",
",",
"target_dicts",
",",
"toplevel_dir",
",",
"toplevel_build",
",",
"out_name",
")",
":",
"gyp",
".",
"common",
".",
"EnsureDirExists",
"(",
"out_name",
")",
"result",
"=",
"ET",
".",
"Element",
"(",
"'clas... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/eclipse.py#L343-L374 | ||
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/tools/grit/grit/node/misc.py | python | GritNode.SetOwnDir | (self, dir) | Informs the 'grit' element of the directory the file it is in resides.
This allows it to calculate relative paths from the input file, which is
what we desire (rather than from the current path).
Args:
dir: r'c:\bla'
Return:
None | Informs the 'grit' element of the directory the file it is in resides.
This allows it to calculate relative paths from the input file, which is
what we desire (rather than from the current path). | [
"Informs",
"the",
"grit",
"element",
"of",
"the",
"directory",
"the",
"file",
"it",
"is",
"in",
"resides",
".",
"This",
"allows",
"it",
"to",
"calculate",
"relative",
"paths",
"from",
"the",
"input",
"file",
"which",
"is",
"what",
"we",
"desire",
"(",
"r... | def SetOwnDir(self, dir):
"""Informs the 'grit' element of the directory the file it is in resides.
This allows it to calculate relative paths from the input file, which is
what we desire (rather than from the current path).
Args:
dir: r'c:\bla'
Return:
None
"""
assert dir
self.base_dir = os.path.normpath(os.path.join(dir, self.attrs['base_dir'])) | [
"def",
"SetOwnDir",
"(",
"self",
",",
"dir",
")",
":",
"assert",
"dir",
"self",
".",
"base_dir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"self",
".",
"attrs",
"[",
"'base_dir'",
"]",
")",
")"... | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/node/misc.py#L428-L440 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/serial/urlhandler/protocol_loop.py | python | Serial.open | (self) | \
Open port with current settings. This may throw a SerialException
if the port cannot be opened. | \
Open port with current settings. This may throw a SerialException
if the port cannot be opened. | [
"\\",
"Open",
"port",
"with",
"current",
"settings",
".",
"This",
"may",
"throw",
"a",
"SerialException",
"if",
"the",
"port",
"cannot",
"be",
"opened",
"."
] | def open(self):
"""\
Open port with current settings. This may throw a SerialException
if the port cannot be opened.
"""
if self.is_open:
raise SerialException("Port is already open.")
self.logger = None
self.queue = queue.Queue(self.buffer_size)
if self._port is None:
raise SerialException("Port must be configured before it can be used.")
# not that there is anything to open, but the function applies the
# options found in the URL
self.from_url(self.port)
# not that there anything to configure...
self._reconfigure_port()
# all things set up get, now a clean start
self.is_open = True
if not self._dsrdtr:
self._update_dtr_state()
if not self._rtscts:
self._update_rts_state()
self.reset_input_buffer()
self.reset_output_buffer() | [
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_open",
":",
"raise",
"SerialException",
"(",
"\"Port is already open.\"",
")",
"self",
".",
"logger",
"=",
"None",
"self",
".",
"queue",
"=",
"queue",
".",
"Queue",
"(",
"self",
".",
"buffer_si... | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/urlhandler/protocol_loop.py#L52-L77 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Pygments/py2/pygments/lexers/__init__.py | python | _fn_matches | (fn, glob) | return _pattern_cache[glob].match(fn) | Return whether the supplied file name fn matches pattern filename. | Return whether the supplied file name fn matches pattern filename. | [
"Return",
"whether",
"the",
"supplied",
"file",
"name",
"fn",
"matches",
"pattern",
"filename",
"."
] | def _fn_matches(fn, glob):
"""Return whether the supplied file name fn matches pattern filename."""
if glob not in _pattern_cache:
pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob))
return pattern.match(fn)
return _pattern_cache[glob].match(fn) | [
"def",
"_fn_matches",
"(",
"fn",
",",
"glob",
")",
":",
"if",
"glob",
"not",
"in",
"_pattern_cache",
":",
"pattern",
"=",
"_pattern_cache",
"[",
"glob",
"]",
"=",
"re",
".",
"compile",
"(",
"fnmatch",
".",
"translate",
"(",
"glob",
")",
")",
"return",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py2/pygments/lexers/__init__.py#L35-L40 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/robotsim.py | python | RobotPoser.set | (self, q) | return _robotsim.RobotPoser_set(self, q) | set(RobotPoser self, doubleVector q) | set(RobotPoser self, doubleVector q) | [
"set",
"(",
"RobotPoser",
"self",
"doubleVector",
"q",
")"
] | def set(self, q):
"""
set(RobotPoser self, doubleVector q)
"""
return _robotsim.RobotPoser_set(self, q) | [
"def",
"set",
"(",
"self",
",",
"q",
")",
":",
"return",
"_robotsim",
".",
"RobotPoser_set",
"(",
"self",
",",
"q",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L3388-L3395 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/utils/utils.py | python | getIndex | (seq, f) | return idx | TODO DOCUMENTME. | TODO DOCUMENTME. | [
"TODO",
"DOCUMENTME",
"."
] | def getIndex(seq, f):
"""TODO DOCUMENTME."""
pg.error('getIndex in use?')
# DEPRECATED_SLOW
idx = []
if isinstance(seq, pg.Vector):
for i, _ in enumerate(seq):
v = seq[i]
if f(v):
idx.append(i)
else:
for i, d in enumerate(seq):
if f(d):
idx.append(i)
return idx | [
"def",
"getIndex",
"(",
"seq",
",",
"f",
")",
":",
"pg",
".",
"error",
"(",
"'getIndex in use?'",
")",
"# DEPRECATED_SLOW",
"idx",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"seq",
",",
"pg",
".",
"Vector",
")",
":",
"for",
"i",
",",
"_",
"in",
"enume... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/utils/utils.py#L527-L541 | |
nlohmann/json | eb2182414749825be086c825edb5229e5c28503d | third_party/cpplint/cpplint.py | python | ResetNolintSuppressions | () | Resets the set of NOLINT suppressions to empty. | Resets the set of NOLINT suppressions to empty. | [
"Resets",
"the",
"set",
"of",
"NOLINT",
"suppressions",
"to",
"empty",
"."
] | def ResetNolintSuppressions():
"""Resets the set of NOLINT suppressions to empty."""
_error_suppressions.clear()
_global_error_suppressions.clear() | [
"def",
"ResetNolintSuppressions",
"(",
")",
":",
"_error_suppressions",
".",
"clear",
"(",
")",
"_global_error_suppressions",
".",
"clear",
"(",
")"
] | https://github.com/nlohmann/json/blob/eb2182414749825be086c825edb5229e5c28503d/third_party/cpplint/cpplint.py#L1005-L1008 | ||
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/transmute/chainsolve.py | python | Transmuter.transmute | (self, x, t=None, phi=None, tol=None, log=None, *args, **kwargs) | return y | Transmutes a material into its daughters.
Parameters
----------
x : Material or similar
Input material for transmutation.
t : float
Transmutations time [sec].
phi : float or array of floats
Neutron flux vector [n/cm^2/sec]. Currently this must either be
a scalar or match the group structure of EAF.
tol : float
Tolerance level for chain truncation.
log : file-like or None
The log file object should be written. A None imples the log is
not desired.
Returns
-------
y : Material
The output material post-transmutation. | Transmutes a material into its daughters. | [
"Transmutes",
"a",
"material",
"into",
"its",
"daughters",
"."
] | def transmute(self, x, t=None, phi=None, tol=None, log=None, *args, **kwargs):
"""Transmutes a material into its daughters.
Parameters
----------
x : Material or similar
Input material for transmutation.
t : float
Transmutations time [sec].
phi : float or array of floats
Neutron flux vector [n/cm^2/sec]. Currently this must either be
a scalar or match the group structure of EAF.
tol : float
Tolerance level for chain truncation.
log : file-like or None
The log file object should be written. A None imples the log is
not desired.
Returns
-------
y : Material
The output material post-transmutation.
"""
if not isinstance(x, Material):
x = Material(x)
if t is not None:
self.t = t
if phi is not None:
self.phi = phi
if log is not None:
self.log = log
if tol is not None:
self.tol = tol
x_atoms = x.to_atom_frac()
y_atoms = {}
for nuc, adens in x_atoms.items():
# Find output for root of unit density and scale all output by
# actual nuclide density and add to final output.
partial = self._transmute_partial(nuc)
for part_nuc, part_adens in partial.items():
y_atoms[part_nuc] = part_adens * adens + y_atoms.get(part_nuc, 0.0)
mw_x = x.molecular_mass()
y = from_atom_frac(y_atoms, atoms_per_molecule=x.atoms_per_molecule)
# even though it doesn't look like it, the following line is actually
# mass_y = MW_y * mass_x / MW_x
y.mass *= x.mass / mw_x
return y | [
"def",
"transmute",
"(",
"self",
",",
"x",
",",
"t",
"=",
"None",
",",
"phi",
"=",
"None",
",",
"tol",
"=",
"None",
",",
"log",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"Mater... | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/transmute/chainsolve.py#L100-L148 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextFileHandler.GetExtension | (*args, **kwargs) | return _richtext.RichTextFileHandler_GetExtension(*args, **kwargs) | GetExtension(self) -> String | GetExtension(self) -> String | [
"GetExtension",
"(",
"self",
")",
"-",
">",
"String"
] | def GetExtension(*args, **kwargs):
"""GetExtension(self) -> String"""
return _richtext.RichTextFileHandler_GetExtension(*args, **kwargs) | [
"def",
"GetExtension",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextFileHandler_GetExtension",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2801-L2803 | |
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/models/Port.py | python | Port.get_return | (self) | Return a tuple of (type, modifier). If (None,None) return None. | Return a tuple of (type, modifier). If (None,None) return None. | [
"Return",
"a",
"tuple",
"of",
"(",
"type",
"modifier",
")",
".",
"If",
"(",
"None",
"None",
")",
"return",
"None",
"."
] | def get_return(self):
"""
Return a tuple of (type, modifier). If (None,None) return None.
"""
if (self.__return_modifier is None) and (self.__return_type is None):
return None
else:
return (self.__return_type, self.__return_modifier) | [
"def",
"get_return",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"__return_modifier",
"is",
"None",
")",
"and",
"(",
"self",
".",
"__return_type",
"is",
"None",
")",
":",
"return",
"None",
"else",
":",
"return",
"(",
"self",
".",
"__return_type",
",... | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/models/Port.py#L120-L127 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/v8/tools/stats-viewer.py | python | UiCounter.__init__ | (self, var, format) | Creates a new ui counter.
Args:
var: the Tkinter string variable for updating the ui
format: the format string used to format this counter | Creates a new ui counter. | [
"Creates",
"a",
"new",
"ui",
"counter",
"."
] | def __init__(self, var, format):
"""Creates a new ui counter.
Args:
var: the Tkinter string variable for updating the ui
format: the format string used to format this counter
"""
self.var = var
self.format = format
self.last_value = None | [
"def",
"__init__",
"(",
"self",
",",
"var",
",",
"format",
")",
":",
"self",
".",
"var",
"=",
"var",
"self",
".",
"format",
"=",
"format",
"self",
".",
"last_value",
"=",
"None"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/tools/stats-viewer.py#L274-L283 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/mirrored_strategy.py | python | MirroredExtended._global_batch_size | (self) | return True | `make_dataset_iterator` and `make_numpy_iterator` use global batch size.
`make_input_fn_iterator` assumes per-replica batching.
Returns:
Boolean. | `make_dataset_iterator` and `make_numpy_iterator` use global batch size. | [
"make_dataset_iterator",
"and",
"make_numpy_iterator",
"use",
"global",
"batch",
"size",
"."
] | def _global_batch_size(self):
"""`make_dataset_iterator` and `make_numpy_iterator` use global batch size.
`make_input_fn_iterator` assumes per-replica batching.
Returns:
Boolean.
"""
return True | [
"def",
"_global_batch_size",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/mirrored_strategy.py#L788-L796 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLSumForeground.py | python | ReflectometryILLSumForeground.category | (self) | return 'ILL\\Reflectometry;Workflow\\Reflectometry' | Return algorithm's categories. | Return algorithm's categories. | [
"Return",
"algorithm",
"s",
"categories",
"."
] | def category(self):
"""Return algorithm's categories."""
return 'ILL\\Reflectometry;Workflow\\Reflectometry' | [
"def",
"category",
"(",
"self",
")",
":",
"return",
"'ILL\\\\Reflectometry;Workflow\\\\Reflectometry'"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLSumForeground.py#L43-L45 | |
google/shaka-player-embedded | dabbeb5b47cc257b37b9a254661546352aaf0afe | shaka/tools/parse_makefile.py | python | Makefile._ExecStatement | (self, stmt) | Executes the given Makefile statement. | Executes the given Makefile statement. | [
"Executes",
"the",
"given",
"Makefile",
"statement",
"."
] | def _ExecStatement(self, stmt):
"""Executes the given Makefile statement."""
assert isinstance(stmt, pymake.parserdata.Statement)
if isinstance(stmt, pymake.parserdata.Rule):
name = stmt.targetexp.resolvestr(self._makefile, self._makefile.variables)
value = stmt.depexp.resolvestr(self._makefile, self._makefile.variables)
self._dependencies[name] = value
elif (isinstance(stmt, pymake.parserdata.StaticPatternRule) or
isinstance(stmt, pymake.parserdata.Command) or
isinstance(stmt, pymake.parserdata.EmptyDirective)):
pass # Ignore commands
elif isinstance(stmt, pymake.parserdata.Include):
pass # Ignore includes
elif isinstance(stmt, pymake.parserdata.SetVariable):
stmt.execute(self._makefile, None)
elif isinstance(stmt, pymake.parserdata.ConditionBlock):
for cond, children in stmt:
if cond.evaluate(self._makefile):
for s in children:
self._ExecStatement(s)
break
else:
assert False, 'Unknown type of statement %s' % stmt | [
"def",
"_ExecStatement",
"(",
"self",
",",
"stmt",
")",
":",
"assert",
"isinstance",
"(",
"stmt",
",",
"pymake",
".",
"parserdata",
".",
"Statement",
")",
"if",
"isinstance",
"(",
"stmt",
",",
"pymake",
".",
"parserdata",
".",
"Rule",
")",
":",
"name",
... | https://github.com/google/shaka-player-embedded/blob/dabbeb5b47cc257b37b9a254661546352aaf0afe/shaka/tools/parse_makefile.py#L66-L88 | ||
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/ma/core.py | python | MaskedArray.min | (self, axis=None, out=None, fill_value=None) | return out | Return the minimum along a given axis.
Parameters
----------
axis : {None, int}, optional
Axis along which to operate. By default, ``axis`` is None and the
flattened input is used.
out : array_like, optional
Alternative output array in which to place the result. Must be of
the same shape and buffer length as the expected output.
fill_value : {var}, optional
Value used to fill in the masked values.
If None, use the output of `minimum_fill_value`.
Returns
-------
amin : array_like
New array holding the result.
If ``out`` was specified, ``out`` is returned.
See Also
--------
minimum_fill_value
Returns the minimum filling value for a given datatype. | Return the minimum along a given axis. | [
"Return",
"the",
"minimum",
"along",
"a",
"given",
"axis",
"."
] | def min(self, axis=None, out=None, fill_value=None):
"""
Return the minimum along a given axis.
Parameters
----------
axis : {None, int}, optional
Axis along which to operate. By default, ``axis`` is None and the
flattened input is used.
out : array_like, optional
Alternative output array in which to place the result. Must be of
the same shape and buffer length as the expected output.
fill_value : {var}, optional
Value used to fill in the masked values.
If None, use the output of `minimum_fill_value`.
Returns
-------
amin : array_like
New array holding the result.
If ``out`` was specified, ``out`` is returned.
See Also
--------
minimum_fill_value
Returns the minimum filling value for a given datatype.
"""
_mask = ndarray.__getattribute__(self, '_mask')
newmask = _check_mask_axis(_mask, axis)
if fill_value is None:
fill_value = minimum_fill_value(self)
# No explicit output
if out is None:
result = self.filled(fill_value).min(axis=axis, out=out).view(type(self))
if result.ndim:
# Set the mask
result.__setmask__(newmask)
# Get rid of Infs
if newmask.ndim:
np.putmask(result, newmask, result.fill_value)
elif newmask:
result = masked
return result
# Explicit output
result = self.filled(fill_value).min(axis=axis, out=out)
if isinstance(out, MaskedArray):
outmask = getattr(out, '_mask', nomask)
if (outmask is nomask):
outmask = out._mask = make_mask_none(out.shape)
outmask.flat = newmask
else:
if out.dtype.kind in 'biu':
errmsg = "Masked data information would be lost in one or more"\
" location."
raise MaskError(errmsg)
np.putmask(out, newmask, np.nan)
return out | [
"def",
"min",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"out",
"=",
"None",
",",
"fill_value",
"=",
"None",
")",
":",
"_mask",
"=",
"ndarray",
".",
"__getattribute__",
"(",
"self",
",",
"'_mask'",
")",
"newmask",
"=",
"_check_mask_axis",
"(",
"_mask"... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/core.py#L5022-L5079 | |
zetavm/zetavm | 61af9cd317fa5629f570b30b61ea8c7ffc375e59 | espresso/e_parser.py | python | parse_float | (input_handler, literal) | return FloatExpr(literal) | Parse a float | Parse a float | [
"Parse",
"a",
"float"
] | def parse_float(input_handler, literal):
"""Parse a float"""
while True:
next_ch = input_handler.peek_ch()
if next_ch.isdigit() or next_ch == 'e' or next_ch == '.':
literal += input_handler.read_ch()
else:
break
input_handler.expect('f')
return FloatExpr(literal) | [
"def",
"parse_float",
"(",
"input_handler",
",",
"literal",
")",
":",
"while",
"True",
":",
"next_ch",
"=",
"input_handler",
".",
"peek_ch",
"(",
")",
"if",
"next_ch",
".",
"isdigit",
"(",
")",
"or",
"next_ch",
"==",
"'e'",
"or",
"next_ch",
"==",
"'.'",
... | https://github.com/zetavm/zetavm/blob/61af9cd317fa5629f570b30b61ea8c7ffc375e59/espresso/e_parser.py#L22-L31 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/indexes/base.py | python | Index._join_level | (self, other, level, how='left', return_indexers=False,
keep_order=True) | The join method *only* affects the level of the resulting
MultiIndex. Otherwise it just exactly aligns the Index data to the
labels of the level in the MultiIndex.
If ```keep_order == True```, the order of the data indexed by the
MultiIndex will not be changed; otherwise, it will tie out
with `other`. | The join method *only* affects the level of the resulting
MultiIndex. Otherwise it just exactly aligns the Index data to the
labels of the level in the MultiIndex. | [
"The",
"join",
"method",
"*",
"only",
"*",
"affects",
"the",
"level",
"of",
"the",
"resulting",
"MultiIndex",
".",
"Otherwise",
"it",
"just",
"exactly",
"aligns",
"the",
"Index",
"data",
"to",
"the",
"labels",
"of",
"the",
"level",
"in",
"the",
"MultiIndex... | def _join_level(self, other, level, how='left', return_indexers=False,
keep_order=True):
"""
The join method *only* affects the level of the resulting
MultiIndex. Otherwise it just exactly aligns the Index data to the
labels of the level in the MultiIndex.
If ```keep_order == True```, the order of the data indexed by the
MultiIndex will not be changed; otherwise, it will tie out
with `other`.
"""
from .multi import MultiIndex
def _get_leaf_sorter(labels):
"""
Returns sorter for the inner most level while preserving the
order of higher levels.
"""
if labels[0].size == 0:
return np.empty(0, dtype='int64')
if len(labels) == 1:
lab = ensure_int64(labels[0])
sorter, _ = libalgos.groupsort_indexer(lab, 1 + lab.max())
return sorter
# find indexers of beginning of each set of
# same-key labels w.r.t all but last level
tic = labels[0][:-1] != labels[0][1:]
for lab in labels[1:-1]:
tic |= lab[:-1] != lab[1:]
starts = np.hstack(([True], tic, [True])).nonzero()[0]
lab = ensure_int64(labels[-1])
return lib.get_level_sorter(lab, ensure_int64(starts))
if isinstance(self, MultiIndex) and isinstance(other, MultiIndex):
raise TypeError('Join on level between two MultiIndex objects '
'is ambiguous')
left, right = self, other
flip_order = not isinstance(self, MultiIndex)
if flip_order:
left, right = right, left
how = {'right': 'left', 'left': 'right'}.get(how, how)
level = left._get_level_number(level)
old_level = left.levels[level]
if not right.is_unique:
raise NotImplementedError('Index._join_level on non-unique index '
'is not implemented')
new_level, left_lev_indexer, right_lev_indexer = \
old_level.join(right, how=how, return_indexers=True)
if left_lev_indexer is None:
if keep_order or len(left) == 0:
left_indexer = None
join_index = left
else: # sort the leaves
left_indexer = _get_leaf_sorter(left.codes[:level + 1])
join_index = left[left_indexer]
else:
left_lev_indexer = ensure_int64(left_lev_indexer)
rev_indexer = lib.get_reverse_indexer(left_lev_indexer,
len(old_level))
new_lev_codes = algos.take_nd(rev_indexer, left.codes[level],
allow_fill=False)
new_codes = list(left.codes)
new_codes[level] = new_lev_codes
new_levels = list(left.levels)
new_levels[level] = new_level
if keep_order: # just drop missing values. o.w. keep order
left_indexer = np.arange(len(left), dtype=np.intp)
mask = new_lev_codes != -1
if not mask.all():
new_codes = [lab[mask] for lab in new_codes]
left_indexer = left_indexer[mask]
else: # tie out the order with other
if level == 0: # outer most level, take the fast route
ngroups = 1 + new_lev_codes.max()
left_indexer, counts = libalgos.groupsort_indexer(
new_lev_codes, ngroups)
# missing values are placed first; drop them!
left_indexer = left_indexer[counts[0]:]
new_codes = [lab[left_indexer] for lab in new_codes]
else: # sort the leaves
mask = new_lev_codes != -1
mask_all = mask.all()
if not mask_all:
new_codes = [lab[mask] for lab in new_codes]
left_indexer = _get_leaf_sorter(new_codes[:level + 1])
new_codes = [lab[left_indexer] for lab in new_codes]
# left_indexers are w.r.t masked frame.
# reverse to original frame!
if not mask_all:
left_indexer = mask.nonzero()[0][left_indexer]
join_index = MultiIndex(levels=new_levels, codes=new_codes,
names=left.names, verify_integrity=False)
if right_lev_indexer is not None:
right_indexer = algos.take_nd(right_lev_indexer,
join_index.codes[level],
allow_fill=False)
else:
right_indexer = join_index.codes[level]
if flip_order:
left_indexer, right_indexer = right_indexer, left_indexer
if return_indexers:
left_indexer = (None if left_indexer is None
else ensure_platform_int(left_indexer))
right_indexer = (None if right_indexer is None
else ensure_platform_int(right_indexer))
return join_index, left_indexer, right_indexer
else:
return join_index | [
"def",
"_join_level",
"(",
"self",
",",
"other",
",",
"level",
",",
"how",
"=",
"'left'",
",",
"return_indexers",
"=",
"False",
",",
"keep_order",
"=",
"True",
")",
":",
"from",
".",
"multi",
"import",
"MultiIndex",
"def",
"_get_leaf_sorter",
"(",
"labels"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/indexes/base.py#L3424-L3554 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/pyserial/serial/rfc2217.py | python | TelnetSubnegotiation.__repr__ | (self) | return "%s:%s" % (self.name, self.state) | String for debug outputs. | String for debug outputs. | [
"String",
"for",
"debug",
"outputs",
"."
] | def __repr__(self):
"""String for debug outputs."""
return "%s:%s" % (self.name, self.state) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"%s:%s\"",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"state",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/rfc2217.py#L307-L309 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/control/robotinterfaceutils.py | python | OmniRobotInterface.setPartJointLimits | (self, part : str, qmin='auto', qmax='auto', op='clamp') | Activates a joint limit filter.
If qmin/qmax are 'auto', these are read from the klampt robot model
or the properties.
If op is...
* 'clamp' then commands are silently clamped to their limits.
* 'stop' a soft-stop is raised.
* 'warn' a warning is printed and the robot silently ignores the
command. | Activates a joint limit filter.
If qmin/qmax are 'auto', these are read from the klampt robot model
or the properties. | [
"Activates",
"a",
"joint",
"limit",
"filter",
".",
"If",
"qmin",
"/",
"qmax",
"are",
"auto",
"these",
"are",
"read",
"from",
"the",
"klampt",
"robot",
"model",
"or",
"the",
"properties",
"."
] | def setPartJointLimits(self, part : str, qmin='auto', qmax='auto', op='clamp'):
"""Activates a joint limit filter.
If qmin/qmax are 'auto', these are read from the klampt robot model
or the properties.
If op is...
* 'clamp' then commands are silently clamped to their limits.
* 'stop' a soft-stop is raised.
* 'warn' a warning is printed and the robot silently ignores the
command.
"""
indices = self.indices(part)
#need to limit to hardware values
hw_qmin,hw_qmax = self.properties.get('joint_limits',(None,None))
if hw_qmin is not None:
hw_qmin = [hw_qmin[i] for i in indices]
hw_qmax = [hw_qmax[i] for i in indices]
self._emulator.setJointLimits(indices,qmin,qmax,op,hw_qmin,hw_qmax) | [
"def",
"setPartJointLimits",
"(",
"self",
",",
"part",
":",
"str",
",",
"qmin",
"=",
"'auto'",
",",
"qmax",
"=",
"'auto'",
",",
"op",
"=",
"'clamp'",
")",
":",
"indices",
"=",
"self",
".",
"indices",
"(",
"part",
")",
"#need to limit to hardware values",
... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterfaceutils.py#L2028-L2048 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/six.py | python | _import_module | (name) | return sys.modules[name] | Import module, returning the module after the last dot. | Import module, returning the module after the last dot. | [
"Import",
"module",
"returning",
"the",
"module",
"after",
"the",
"last",
"dot",
"."
] | def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name] | [
"def",
"_import_module",
"(",
"name",
")",
":",
"__import__",
"(",
"name",
")",
"return",
"sys",
".",
"modules",
"[",
"name",
"]"
] | 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/six.py#L80-L83 | |
intel-iot-devkit/how-to-code-samples | b4ea616f36bbfa2e042beb1698f968cfd651d79f | alarm-clock/python/iot_alarm_clock/hardware/dfrobot.py | python | DfrobotBoard.change_background | (self, color) | Change LCD screen background color.
No effect on the dfrobot. | Change LCD screen background color.
No effect on the dfrobot. | [
"Change",
"LCD",
"screen",
"background",
"color",
".",
"No",
"effect",
"on",
"the",
"dfrobot",
"."
] | def change_background(self, color):
"""
Change LCD screen background color.
No effect on the dfrobot.
"""
pass | [
"def",
"change_background",
"(",
"self",
",",
"color",
")",
":",
"pass"
] | https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/alarm-clock/python/iot_alarm_clock/hardware/dfrobot.py#L130-L137 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.BeginURL | (*args, **kwargs) | return _richtext.RichTextCtrl_BeginURL(*args, **kwargs) | BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool
Begin URL. | BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool | [
"BeginURL",
"(",
"self",
"String",
"url",
"String",
"characterStyle",
"=",
"wxEmptyString",
")",
"-",
">",
"bool"
] | def BeginURL(*args, **kwargs):
"""
BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool
Begin URL.
"""
return _richtext.RichTextCtrl_BeginURL(*args, **kwargs) | [
"def",
"BeginURL",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_BeginURL",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3613-L3619 | |
apple/swift | 469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893 | utils/gyb_syntax_support/Node.py | python | Node.requires_validation | (self) | return self.is_buildable() | Returns `True` if this node should have a `validate` method associated. | Returns `True` if this node should have a `validate` method associated. | [
"Returns",
"True",
"if",
"this",
"node",
"should",
"have",
"a",
"validate",
"method",
"associated",
"."
] | def requires_validation(self):
"""
Returns `True` if this node should have a `validate` method associated.
"""
return self.is_buildable() | [
"def",
"requires_validation",
"(",
"self",
")",
":",
"return",
"self",
".",
"is_buildable",
"(",
")"
] | https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/gyb_syntax_support/Node.py#L65-L69 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/bisect_utils.py | python | RunRepoSyncAtTimestamp | (timestamp) | return RunRepo(cmd) | Syncs all git depots to the timestamp specified using repo forall.
Args:
params: Unix timestamp to sync to.
Returns:
The return code of the call. | Syncs all git depots to the timestamp specified using repo forall. | [
"Syncs",
"all",
"git",
"depots",
"to",
"the",
"timestamp",
"specified",
"using",
"repo",
"forall",
"."
] | def RunRepoSyncAtTimestamp(timestamp):
"""Syncs all git depots to the timestamp specified using repo forall.
Args:
params: Unix timestamp to sync to.
Returns:
The return code of the call.
"""
repo_sync = REPO_SYNC_COMMAND % timestamp
cmd = ['forall', '-c', REPO_SYNC_COMMAND % timestamp]
return RunRepo(cmd) | [
"def",
"RunRepoSyncAtTimestamp",
"(",
"timestamp",
")",
":",
"repo_sync",
"=",
"REPO_SYNC_COMMAND",
"%",
"timestamp",
"cmd",
"=",
"[",
"'forall'",
",",
"'-c'",
",",
"REPO_SYNC_COMMAND",
"%",
"timestamp",
"]",
"return",
"RunRepo",
"(",
"cmd",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/bisect_utils.py#L195-L206 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/layer/embedding.py | python | EmbeddingLookup.__init__ | (self, vocab_size, embedding_size, param_init='normal',
target='CPU', slice_mode='batch_slice', manual_shapes=None,
max_norm=None, sparse=True, vocab_cache_size=0) | Initialize EmbeddingLookup. | Initialize EmbeddingLookup. | [
"Initialize",
"EmbeddingLookup",
"."
] | def __init__(self, vocab_size, embedding_size, param_init='normal',
target='CPU', slice_mode='batch_slice', manual_shapes=None,
max_norm=None, sparse=True, vocab_cache_size=0):
"""Initialize EmbeddingLookup."""
super(EmbeddingLookup, self).__init__()
validator.check_value_type('sparse', sparse, [bool], self.cls_name)
self.vocab_size = validator.check_positive_int(vocab_size, 'vocab_size')
self.vocab_cache_size = validator.check_non_negative_int(vocab_cache_size, 'vocab_cache_size')
self.target = target
self.sparse = sparse
self.cache_enable = self.vocab_cache_size > 0
self.forward_unique = False
validator.check_string(target, ['CPU', 'DEVICE'], 'target', self.cls_name)
if not sparse and target == 'CPU':
raise ValueError(f"For '{self.cls_name}', 'sparse' must be True when 'target' is \"CPU\", "
f"but got 'sparse': {sparse} and 'target': {target}")
if sparse:
self.gatherv2 = P.SparseGatherV2()
else:
self.gatherv2 = P.Gather()
self.embeddinglookup = P.EmbeddingLookup().add_prim_attr('primitive_target', 'CPU')
enable_ps = _get_ps_context("enable_ps")
if enable_ps:
self._process_vocab_cache(slice_mode)
self.embedding_size = validator.check_positive_int(embedding_size, 'embedding_size', self.cls_name)
self.embedding_table = Parameter(initializer(param_init, [self.vocab_size, self.embedding_size]),
name='embedding_table')
parallel_mode = _get_parallel_mode()
is_auto_parallel = parallel_mode in (ParallelMode.SEMI_AUTO_PARALLEL, ParallelMode.AUTO_PARALLEL)
self.gather_revert = P.Gather()
self.reshape_first = P.Reshape()
self.reshape = P.Reshape()
self.unique = P.Unique()
self.shape = P.Shape()
if is_auto_parallel:
self.unique = P.Unique().shard(((1,),))
if self.cache_enable and enable_ps:
self._set_voacb_cache_enable_for_ps(vocab_cache_size, embedding_size, vocab_size)
if is_auto_parallel:
self.unique.add_prim_attr('cache_enable', True)
indices_shape_size = 2
if slice_mode == "field_slice" and is_auto_parallel:
if not manual_shapes:
raise ValueError(f"For '{self.cls_name}', the 'manual_shapes' should not be none "
f"when the 'slice_mode' is \"filed_slice\", but got {manual_shapes}.")
if not isinstance(manual_shapes, tuple):
raise TypeError(f"For '{self.cls_name}', the type of 'manual_shapes' must be tuple(int), "
f"but got {type(manual_shapes).__name__}!")
for dim in manual_shapes:
validator.check_positive_int(dim, 'manual shape dim', self.cls_name)
self.gatherv2.add_prim_attr("manual_split", manual_shapes)
self.embeddinglookup.add_prim_attr("manual_split", manual_shapes)
self.gatherv2.shard(((get_group_size(), 1), (1, get_group_size())))
self.embeddinglookup.shard(((get_group_size(), 1), (1, get_group_size())))
elif slice_mode == "table_row_slice" and is_auto_parallel:
full_batch = _get_full_batch()
if (target == 'DEVICE' and not full_batch) or (self.cache_enable and enable_ps and sparse):
indices_shape_size = 1
self.gather_revert.shard(((1, 1), (get_group_size(),)))
self.forward_unique = True
indices_strategy = (1,)*indices_shape_size
self.gatherv2.shard(((get_group_size(), 1), indices_strategy))
self.embeddinglookup.shard(((get_group_size(), 1), indices_strategy))
elif slice_mode == "table_column_slice" and is_auto_parallel:
if target == 'DEVICE':
indices_shape_size = 1
self.gather_revert.shard(((1, get_group_size()), (1,)))
self.forward_unique = True
indices_strategy = (1,)*indices_shape_size
self.gatherv2.shard(((1, get_group_size()), indices_strategy))
self.embeddinglookup.shard(((1, get_group_size()), indices_strategy))
elif slice_mode == "batch_slice" and is_auto_parallel:
indices_strategy = [get_group_size()]
indices_strategy.extend([1]*(indices_shape_size - 1))
indices_strategy = tuple(indices_strategy)
self.gatherv2.shard(((1, 1), indices_strategy))
self.embeddinglookup.shard(((1, 1), indices_strategy))
else:
if is_auto_parallel:
support_mode = ["field_slice", "table_row_slice", "table_column_slice", "batch_slice"]
raise ValueError("For '{}', the 'slice_mode' must be in {}, "
"but got \"{}\".".format(self.cls_name, support_mode, slice_mode))
if self.cache_enable and not enable_ps:
raise ValueError(f"For '{self.cls_name}', haven't supported cache enable for not ps mode.")
self.embedding_table.unique = self.forward_unique
self.max_norm = max_norm
if self.max_norm is not None:
self.max_norm = validator.check_positive_float(self.max_norm, 'max_norm', self.cls_name)
self.max_norm = Tensor(self.max_norm, dtype=mstype.float32) | [
"def",
"__init__",
"(",
"self",
",",
"vocab_size",
",",
"embedding_size",
",",
"param_init",
"=",
"'normal'",
",",
"target",
"=",
"'CPU'",
",",
"slice_mode",
"=",
"'batch_slice'",
",",
"manual_shapes",
"=",
"None",
",",
"max_norm",
"=",
"None",
",",
"sparse"... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/embedding.py#L223-L311 | ||
synfig/synfig | a5ec91db5b751dc12e4400ccfb5c063fd6d2d928 | synfig-studio/plugins/lottie-exporter/common/misc.py | python | get_time | (waypoint) | return parse_time(waypoint.attrib["time"]) | Given a waypoint, it parses the string time to float time
Args:
waypoint (lxml.etree._Element) : Synfig format waypoint
Returns:
(float) : the time in seconds at which the waypoint is present | Given a waypoint, it parses the string time to float time | [
"Given",
"a",
"waypoint",
"it",
"parses",
"the",
"string",
"time",
"to",
"float",
"time"
] | def get_time(waypoint):
"""
Given a waypoint, it parses the string time to float time
Args:
waypoint (lxml.etree._Element) : Synfig format waypoint
Returns:
(float) : the time in seconds at which the waypoint is present
"""
return parse_time(waypoint.attrib["time"]) | [
"def",
"get_time",
"(",
"waypoint",
")",
":",
"return",
"parse_time",
"(",
"waypoint",
".",
"attrib",
"[",
"\"time\"",
"]",
")"
] | https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/misc.py#L326-L336 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TStrUtil_GetShorStr | (*args) | return _snap.TStrUtil_GetShorStr(*args) | GetShorStr(TChA LongStr, int const MaxLen=50) -> TChA
Parameters:
LongStr: TChA const &
MaxLen: int const
TStrUtil_GetShorStr(TChA LongStr) -> TChA
Parameters:
LongStr: TChA const & | GetShorStr(TChA LongStr, int const MaxLen=50) -> TChA | [
"GetShorStr",
"(",
"TChA",
"LongStr",
"int",
"const",
"MaxLen",
"=",
"50",
")",
"-",
">",
"TChA"
] | def TStrUtil_GetShorStr(*args):
"""
GetShorStr(TChA LongStr, int const MaxLen=50) -> TChA
Parameters:
LongStr: TChA const &
MaxLen: int const
TStrUtil_GetShorStr(TChA LongStr) -> TChA
Parameters:
LongStr: TChA const &
"""
return _snap.TStrUtil_GetShorStr(*args) | [
"def",
"TStrUtil_GetShorStr",
"(",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TStrUtil_GetShorStr",
"(",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L7321-L7335 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/learn_io/dask_io.py | python | extract_dask_data | (data) | Extract data from dask.Series or dask.DataFrame for predictors.
Given a distributed dask.DataFrame or dask.Series containing columns or names
for one or more predictors, this operation returns a single dask.DataFrame or
dask.Series that can be iterated over.
Args:
data: A distributed dask.DataFrame or dask.Series.
Returns:
A dask.DataFrame or dask.Series that can be iterated over.
If the supplied argument is neither a dask.DataFrame nor a dask.Series this
operation returns it without modification. | Extract data from dask.Series or dask.DataFrame for predictors. | [
"Extract",
"data",
"from",
"dask",
".",
"Series",
"or",
"dask",
".",
"DataFrame",
"for",
"predictors",
"."
] | def extract_dask_data(data):
"""Extract data from dask.Series or dask.DataFrame for predictors.
Given a distributed dask.DataFrame or dask.Series containing columns or names
for one or more predictors, this operation returns a single dask.DataFrame or
dask.Series that can be iterated over.
Args:
data: A distributed dask.DataFrame or dask.Series.
Returns:
A dask.DataFrame or dask.Series that can be iterated over.
If the supplied argument is neither a dask.DataFrame nor a dask.Series this
operation returns it without modification.
"""
if isinstance(data, allowed_classes):
return _construct_dask_df_with_divisions(data)
else:
return data | [
"def",
"extract_dask_data",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"allowed_classes",
")",
":",
"return",
"_construct_dask_df_with_divisions",
"(",
"data",
")",
"else",
":",
"return",
"data"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/learn_io/dask_io.py#L71-L89 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/tools/gyp/pylib/gyp/__init__.py | python | RegenerateFlags | (options) | return flags | Given a parsed options object, and taking the environment variables into
account, returns a list of flags that should regenerate an equivalent options
object (even in the absence of the environment variables.)
Any path options will be normalized relative to depth.
The format flag is not included, as it is assumed the calling generator will
set that as appropriate. | Given a parsed options object, and taking the environment variables into
account, returns a list of flags that should regenerate an equivalent options
object (even in the absence of the environment variables.) | [
"Given",
"a",
"parsed",
"options",
"object",
"and",
"taking",
"the",
"environment",
"variables",
"into",
"account",
"returns",
"a",
"list",
"of",
"flags",
"that",
"should",
"regenerate",
"an",
"equivalent",
"options",
"object",
"(",
"even",
"in",
"the",
"absen... | def RegenerateFlags(options):
"""Given a parsed options object, and taking the environment variables into
account, returns a list of flags that should regenerate an equivalent options
object (even in the absence of the environment variables.)
Any path options will be normalized relative to depth.
The format flag is not included, as it is assumed the calling generator will
set that as appropriate.
"""
def FixPath(path):
path = gyp.common.FixIfRelativePath(path, options.depth)
if not path:
return os.path.curdir
return path
def Noop(value):
return value
# We always want to ignore the environment when regenerating, to avoid
# duplicate or changed flags in the environment at the time of regeneration.
flags = ['--ignore-environment']
for name, metadata in options._regeneration_metadata.iteritems():
opt = metadata['opt']
value = getattr(options, name)
value_predicate = metadata['type'] == 'path' and FixPath or Noop
action = metadata['action']
env_name = metadata['env_name']
if action == 'append':
flags.extend(RegenerateAppendFlag(opt, value, value_predicate,
env_name, options))
elif action in ('store', None): # None is a synonym for 'store'.
if value:
flags.append(FormatOpt(opt, value_predicate(value)))
elif options.use_environment and env_name and os.environ.get(env_name):
flags.append(FormatOpt(opt, value_predicate(os.environ.get(env_name))))
elif action in ('store_true', 'store_false'):
if ((action == 'store_true' and value) or
(action == 'store_false' and not value)):
flags.append(opt)
elif options.use_environment and env_name:
print >>sys.stderr, ('Warning: environment regeneration unimplemented '
'for %s flag %r env_name %r' % (action, opt,
env_name))
else:
print >>sys.stderr, ('Warning: regeneration unimplemented for action %r '
'flag %r' % (action, opt))
return flags | [
"def",
"RegenerateFlags",
"(",
"options",
")",
":",
"def",
"FixPath",
"(",
"path",
")",
":",
"path",
"=",
"gyp",
".",
"common",
".",
"FixIfRelativePath",
"(",
"path",
",",
"options",
".",
"depth",
")",
"if",
"not",
"path",
":",
"return",
"os",
".",
"... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/__init__.py#L190-L238 | |
yuxng/PoseCNN | 9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04 | lib/gt_data_layer/layer.py | python | GtDataLayer._get_next_minibatch_inds | (self) | return db_inds_reorder | Return the roidb indices for the next minibatch. | Return the roidb indices for the next minibatch. | [
"Return",
"the",
"roidb",
"indices",
"for",
"the",
"next",
"minibatch",
"."
] | def _get_next_minibatch_inds(self):
"""Return the roidb indices for the next minibatch."""
num_steps = cfg.TRAIN.NUM_STEPS
ims_per_batch = cfg.TRAIN.IMS_PER_BATCH
db_inds = np.zeros(num_steps * ims_per_batch, dtype=np.int32)
interval = 1
count = 0
while count < ims_per_batch:
ind = self._perm[self._cur]
if ind + (num_steps - 1) * interval < len(self._roidb) and self._roidb[ind]['video_id'] == self._roidb[ind + (num_steps-1) * interval]['video_id']:
db_inds[count * num_steps : (count+1) * num_steps] = range(ind, ind + num_steps * interval, interval)
count += 1
self._cur += 1
if self._cur >= len(self._roidb):
self._shuffle_roidb_inds()
db_inds_reorder = np.zeros(num_steps * ims_per_batch, dtype=np.int32)
count = 0
for i in xrange(num_steps):
for j in xrange(ims_per_batch):
db_inds_reorder[count] = db_inds[j * num_steps + i]
count = count + 1
return db_inds_reorder | [
"def",
"_get_next_minibatch_inds",
"(",
"self",
")",
":",
"num_steps",
"=",
"cfg",
".",
"TRAIN",
".",
"NUM_STEPS",
"ims_per_batch",
"=",
"cfg",
".",
"TRAIN",
".",
"IMS_PER_BATCH",
"db_inds",
"=",
"np",
".",
"zeros",
"(",
"num_steps",
"*",
"ims_per_batch",
",... | https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/gt_data_layer/layer.py#L31-L55 | |
LiXizhi/NPLRuntime | a42720e5fe9a6960e0a9ce40bbbcd809192906be | Client/trunk/externals/assimp-4.0.0/port/PyAssimp/scripts/transformations.py | python | arcball_map_to_sphere | (point, center, radius) | return v | Return unit sphere coordinates from window coordinates. | Return unit sphere coordinates from window coordinates. | [
"Return",
"unit",
"sphere",
"coordinates",
"from",
"window",
"coordinates",
"."
] | def arcball_map_to_sphere(point, center, radius):
"""Return unit sphere coordinates from window coordinates."""
v = numpy.array(((point[0] - center[0]) / radius,
(center[1] - point[1]) / radius,
0.0), dtype=numpy.float64)
n = v[0]*v[0] + v[1]*v[1]
if n > 1.0:
v /= math.sqrt(n) # position outside of sphere
else:
v[2] = math.sqrt(1.0 - n)
return v | [
"def",
"arcball_map_to_sphere",
"(",
"point",
",",
"center",
",",
"radius",
")",
":",
"v",
"=",
"numpy",
".",
"array",
"(",
"(",
"(",
"point",
"[",
"0",
"]",
"-",
"center",
"[",
"0",
"]",
")",
"/",
"radius",
",",
"(",
"center",
"[",
"1",
"]",
"... | https://github.com/LiXizhi/NPLRuntime/blob/a42720e5fe9a6960e0a9ce40bbbcd809192906be/Client/trunk/externals/assimp-4.0.0/port/PyAssimp/scripts/transformations.py#L1472-L1482 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/training/basic_session_run_hooks.py | python | GlobalStepWaiterHook.__init__ | (self, wait_until_step) | Initializes a `GlobalStepWaiterHook`.
Args:
wait_until_step: an `int` shows until which global step should we wait. | Initializes a `GlobalStepWaiterHook`. | [
"Initializes",
"a",
"GlobalStepWaiterHook",
"."
] | def __init__(self, wait_until_step):
"""Initializes a `GlobalStepWaiterHook`.
Args:
wait_until_step: an `int` shows until which global step should we wait.
"""
self._wait_until_step = wait_until_step | [
"def",
"__init__",
"(",
"self",
",",
"wait_until_step",
")",
":",
"self",
".",
"_wait_until_step",
"=",
"wait_until_step"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/basic_session_run_hooks.py#L703-L709 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/tools/stats-viewer.py | python | StatsViewer.CleanUp | (self) | Cleans up the memory mapped file if necessary. | Cleans up the memory mapped file if necessary. | [
"Cleans",
"up",
"the",
"memory",
"mapped",
"file",
"if",
"necessary",
"."
] | def CleanUp(self):
"""Cleans up the memory mapped file if necessary."""
if self.shared_mmap:
self.shared_mmap.close() | [
"def",
"CleanUp",
"(",
"self",
")",
":",
"if",
"self",
".",
"shared_mmap",
":",
"self",
".",
"shared_mmap",
".",
"close",
"(",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/tools/stats-viewer.py#L132-L135 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/ma/core.py | python | MaskedArray.soften_mask | (self) | return self | Force the mask to soft.
Whether the mask of a masked array is hard or soft is determined by
its `~ma.MaskedArray.hardmask` property. `soften_mask` sets
`~ma.MaskedArray.hardmask` to ``False``.
See Also
--------
ma.MaskedArray.hardmask | Force the mask to soft. | [
"Force",
"the",
"mask",
"to",
"soft",
"."
] | def soften_mask(self):
"""
Force the mask to soft.
Whether the mask of a masked array is hard or soft is determined by
its `~ma.MaskedArray.hardmask` property. `soften_mask` sets
`~ma.MaskedArray.hardmask` to ``False``.
See Also
--------
ma.MaskedArray.hardmask
"""
self._hardmask = False
return self | [
"def",
"soften_mask",
"(",
"self",
")",
":",
"self",
".",
"_hardmask",
"=",
"False",
"return",
"self"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/core.py#L3557-L3571 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/platforms/compile_settings_clang.py | python | load_release_clang_settings | (conf) | Setup all compiler/linker flags with are shared over all targets using the clang compiler
for the "release" configuration | Setup all compiler/linker flags with are shared over all targets using the clang compiler
for the "release" configuration | [
"Setup",
"all",
"compiler",
"/",
"linker",
"flags",
"with",
"are",
"shared",
"over",
"all",
"targets",
"using",
"the",
"clang",
"compiler",
"for",
"the",
"release",
"configuration"
] | def load_release_clang_settings(conf):
"""
Setup all compiler/linker flags with are shared over all targets using the clang compiler
for the "release" configuration
"""
# v = conf.env
# load_clang_common_settings(conf)
# Moved to common.clang.json
"""
COMPILER_FLAGS = [
'-O2',
]
v['CFLAGS'] += COMPILER_FLAGS
v['CXXFLAGS'] += COMPILER_FLAGS
"""
pass | [
"def",
"load_release_clang_settings",
"(",
"conf",
")",
":",
"# v = conf.env",
"# load_clang_common_settings(conf)",
"# Moved to common.clang.json",
"\"\"\"\n COMPILER_FLAGS = [\n '-O2',\n ]\n\n v['CFLAGS'] += COMPILER_FLAGS\n v['CXXFLAGS'] += COMPILER_FLAGS\n \"\"\"",
"pas... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/platforms/compile_settings_clang.py#L236-L253 | ||
cornell-zhang/heterocl | 6d9e4b4acc2ee2707b2d25b27298c0335bccedfd | python/heterocl/nparray.py | python | pack_np | (np_in, dtype_in, dtype_out) | return np.array(np_out) | Pack a NumPy array according to the specified data types.
Now we only support packing and unpacking for a 1-dimensional array.
Parameters
----------
np_in : ndarray
The array to be packed
dtype_in : Type
The data type of the input array
dtype_out : Type
The target data type
Returns
-------
ndarray
Examples
--------
.. code-block:: python
a = numpy.random.randint(16, size=(10,))
packed_a = hcl.pack_np(np_in, hcl.UInt(8), hcl.UInt(32)) | Pack a NumPy array according to the specified data types. | [
"Pack",
"a",
"NumPy",
"array",
"according",
"to",
"the",
"specified",
"data",
"types",
"."
] | def pack_np(np_in, dtype_in, dtype_out):
"""Pack a NumPy array according to the specified data types.
Now we only support packing and unpacking for a 1-dimensional array.
Parameters
----------
np_in : ndarray
The array to be packed
dtype_in : Type
The data type of the input array
dtype_out : Type
The target data type
Returns
-------
ndarray
Examples
--------
.. code-block:: python
a = numpy.random.randint(16, size=(10,))
packed_a = hcl.pack_np(np_in, hcl.UInt(8), hcl.UInt(32))
"""
factor = dtype_out.bits / dtype_in.bits
fracs = dtype_in.fracs
shape = np_in.shape
np_out = []
signed = True
if isinstance(dtype_in, (types.UInt, types.UFixed)):
signed = False
for i in range(0, shape[0]/factor):
num = 0
for j in range(0, factor):
val = int(np_in[i*factor + j] * (1 << fracs))
if signed:
val = val if val >= 0 else val + (1 << dtype_in.bits)
num += val << (j * dtype_in.bits)
np_out.append(num)
return np.array(np_out) | [
"def",
"pack_np",
"(",
"np_in",
",",
"dtype_in",
",",
"dtype_out",
")",
":",
"factor",
"=",
"dtype_out",
".",
"bits",
"/",
"dtype_in",
".",
"bits",
"fracs",
"=",
"dtype_in",
".",
"fracs",
"shape",
"=",
"np_in",
".",
"shape",
"np_out",
"=",
"[",
"]",
... | https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/nparray.py#L85-L128 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/generate_playthrough.py | python | playthrough_lines | (game_string, alsologtostdout=False, action_sequence=None,
observation_params_string=None,
seed: Optional[int] = None) | return lines | Returns a playthrough of the specified game as a list of lines.
Actions are selected uniformly at random, including chance actions.
Args:
game_string: string, e.g. 'markov_soccer' or 'kuhn_poker(players=4)'.
alsologtostdout: Whether to also print the trace to stdout. This can be
useful when an error occurs, to still be able to get context information.
action_sequence: A (possibly partial) list of action choices to make.
observation_params_string: Optional observation parameters for constructing
an observer.
seed: A(n optional) seed to initialize the random number generator from. | Returns a playthrough of the specified game as a list of lines. | [
"Returns",
"a",
"playthrough",
"of",
"the",
"specified",
"game",
"as",
"a",
"list",
"of",
"lines",
"."
] | def playthrough_lines(game_string, alsologtostdout=False, action_sequence=None,
observation_params_string=None,
seed: Optional[int] = None):
"""Returns a playthrough of the specified game as a list of lines.
Actions are selected uniformly at random, including chance actions.
Args:
game_string: string, e.g. 'markov_soccer' or 'kuhn_poker(players=4)'.
alsologtostdout: Whether to also print the trace to stdout. This can be
useful when an error occurs, to still be able to get context information.
action_sequence: A (possibly partial) list of action choices to make.
observation_params_string: Optional observation parameters for constructing
an observer.
seed: A(n optional) seed to initialize the random number generator from.
"""
should_display_state_fn = ShouldDisplayStateTracker()
lines = []
action_sequence = action_sequence or []
should_display = True
def add_line(v, force=False):
if force or should_display:
if alsologtostdout:
print(v)
lines.append(v)
game = pyspiel.load_game(game_string)
add_line("game: {}".format(game_string))
if observation_params_string:
add_line("observation_params: {}".format(observation_params_string))
if seed is None:
seed = np.random.randint(2**32 - 1)
game_type = game.get_type()
default_observation = None
try:
observation_params = pyspiel.game_parameters_from_string(
observation_params_string) if observation_params_string else None
default_observation = make_observation(
game,
imperfect_information_observation_type=None,
params=observation_params)
except (RuntimeError, ValueError) as e:
print("Warning: unable to build an observation: ", e)
infostate_observation = None
# TODO(author11) reinstate this restriction
# if game_type.information in (pyspiel.IMPERFECT_INFORMATION,
# pyspiel.ONE_SHOT):
try:
infostate_observation = make_observation(
game, pyspiel.IIGObservationType(perfect_recall=True))
except (RuntimeError, ValueError):
pass
public_observation = None
private_observation = None
# Instantiate factored observations only for imperfect information games,
# as it would yield unncessarily redundant information for perfect info games.
# The default observation is the same as the public observation, while private
# observations are always empty.
if game_type.information == pyspiel.GameType.Information.IMPERFECT_INFORMATION:
try:
public_observation = make_observation(
game,
pyspiel.IIGObservationType(
public_info=True,
perfect_recall=False,
private_info=pyspiel.PrivateInfoType.NONE))
except (RuntimeError, ValueError):
pass
try:
private_observation = make_observation(
game,
pyspiel.IIGObservationType(
public_info=False,
perfect_recall=False,
private_info=pyspiel.PrivateInfoType.SINGLE_PLAYER))
except (RuntimeError, ValueError):
pass
add_line("")
add_line("GameType.chance_mode = {}".format(game_type.chance_mode))
add_line("GameType.dynamics = {}".format(game_type.dynamics))
add_line("GameType.information = {}".format(game_type.information))
add_line("GameType.long_name = {}".format('"{}"'.format(game_type.long_name)))
add_line("GameType.max_num_players = {}".format(game_type.max_num_players))
add_line("GameType.min_num_players = {}".format(game_type.min_num_players))
add_line("GameType.parameter_specification = {}".format("[{}]".format(
", ".join('"{}"'.format(param)
for param in sorted(game_type.parameter_specification)))))
add_line("GameType.provides_information_state_string = {}".format(
game_type.provides_information_state_string))
add_line("GameType.provides_information_state_tensor = {}".format(
game_type.provides_information_state_tensor))
add_line("GameType.provides_observation_string = {}".format(
game_type.provides_observation_string))
add_line("GameType.provides_observation_tensor = {}".format(
game_type.provides_observation_tensor))
add_line("GameType.provides_factored_observation_string = {}".format(
game_type.provides_factored_observation_string))
add_line("GameType.reward_model = {}".format(game_type.reward_model))
add_line("GameType.short_name = {}".format('"{}"'.format(
game_type.short_name)))
add_line("GameType.utility = {}".format(game_type.utility))
add_line("")
add_line("NumDistinctActions() = {}".format(game.num_distinct_actions()))
add_line("PolicyTensorShape() = {}".format(game.policy_tensor_shape()))
add_line("MaxChanceOutcomes() = {}".format(game.max_chance_outcomes()))
add_line("GetParameters() = {}".format(_format_params(game.get_parameters())))
add_line("NumPlayers() = {}".format(game.num_players()))
add_line("MinUtility() = {:.5}".format(game.min_utility()))
add_line("MaxUtility() = {:.5}".format(game.max_utility()))
try:
utility_sum = game.utility_sum()
except RuntimeError:
utility_sum = None
add_line("UtilitySum() = {}".format(utility_sum))
if infostate_observation and infostate_observation.tensor is not None:
add_line("InformationStateTensorShape() = {}".format(
format_shapes(infostate_observation.dict)))
add_line("InformationStateTensorLayout() = {}".format(
game.information_state_tensor_layout()))
add_line("InformationStateTensorSize() = {}".format(
len(infostate_observation.tensor)))
if default_observation and default_observation.tensor is not None:
add_line("ObservationTensorShape() = {}".format(
format_shapes(default_observation.dict)))
add_line("ObservationTensorLayout() = {}".format(
game.observation_tensor_layout()))
add_line("ObservationTensorSize() = {}".format(
len(default_observation.tensor)))
add_line("MaxGameLength() = {}".format(game.max_game_length()))
add_line('ToString() = "{}"'.format(str(game)))
players = list(range(game.num_players()))
# Arbitrarily pick the last possible initial states (for all games
# but multi-population MFGs, there will be a single initial state).
state = game.new_initial_states()[-1]
state_idx = 0
rng = np.random.RandomState(seed)
while True:
should_display = should_display_state_fn(state)
add_line("", force=True)
add_line("# State {}".format(state_idx), force=True)
for line in str(state).splitlines():
add_line("# {}".format(line).rstrip())
add_line("IsTerminal() = {}".format(state.is_terminal()))
add_line("History() = {}".format([int(a) for a in state.history()]))
add_line('HistoryString() = "{}"'.format(state.history_str()))
add_line("IsChanceNode() = {}".format(state.is_chance_node()))
add_line("IsSimultaneousNode() = {}".format(state.is_simultaneous_node()))
add_line("CurrentPlayer() = {}".format(state.current_player()))
if infostate_observation:
for player in players:
s = infostate_observation.string_from(state, player)
if s is not None:
add_line(f'InformationStateString({player}) = "{_escape(s)}"')
if infostate_observation and infostate_observation.tensor is not None:
for player in players:
infostate_observation.set_from(state, player)
for name, tensor in infostate_observation.dict.items():
label = f"InformationStateTensor({player})"
label += f".{name}" if name != "info_state" else ""
for line in _format_tensor(tensor, label):
add_line(line)
if default_observation:
for player in players:
s = default_observation.string_from(state, player)
if s is not None:
add_line(f'ObservationString({player}) = "{_escape(s)}"')
if public_observation:
s = public_observation.string_from(state, 0)
if s is not None:
add_line('PublicObservationString() = "{}"'.format(_escape(s)))
for player in players:
s = private_observation.string_from(state, player)
if s is not None:
add_line(f'PrivateObservationString({player}) = "{_escape(s)}"')
if default_observation and default_observation.tensor is not None:
for player in players:
default_observation.set_from(state, player)
for name, tensor in default_observation.dict.items():
label = f"ObservationTensor({player})"
label += f".{name}" if name != "observation" else ""
for line in _format_tensor(tensor, label):
add_line(line)
if game_type.chance_mode == pyspiel.GameType.ChanceMode.SAMPLED_STOCHASTIC:
add_line('SerializeState() = "{}"'.format(_escape(state.serialize())))
if not state.is_chance_node():
add_line("Rewards() = {}".format(state.rewards()))
add_line("Returns() = {}".format(state.returns()))
if state.is_terminal():
break
if state.is_chance_node():
add_line("ChanceOutcomes() = {}".format(state.chance_outcomes()))
if state.is_mean_field_node():
add_line("DistributionSupport() = {}".format(
state.distribution_support()))
num_states = len(state.distribution_support())
state.update_distribution(
[1. / num_states] * num_states if num_states else [])
if state_idx < len(action_sequence):
assert action_sequence[state_idx] == "update_distribution", (
f"Unexpected action at MFG node: {action_sequence[state_idx]}, "
f"state: {state}, action_sequence: {action_sequence}")
add_line("")
add_line("# Set mean field distribution to be uniform", force=True)
add_line("action: update_distribution", force=True)
elif state.is_simultaneous_node():
for player in players:
add_line("LegalActions({}) = [{}]".format(
player, ", ".join(str(x) for x in state.legal_actions(player))))
for player in players:
add_line("StringLegalActions({}) = [{}]".format(
player, ", ".join('"{}"'.format(state.action_to_string(player, x))
for x in state.legal_actions(player))))
if state_idx < len(action_sequence):
actions = action_sequence[state_idx]
else:
actions = []
for pl in players:
legal_actions = state.legal_actions(pl)
actions.append(0 if not legal_actions else rng.choice(legal_actions))
add_line("")
add_line("# Apply joint action [{}]".format(
format(", ".join(
'"{}"'.format(state.action_to_string(player, action))
for player, action in enumerate(actions)))), force=True)
add_line("actions: [{}]".format(", ".join(
str(action) for action in actions)), force=True)
state.apply_actions(actions)
else:
add_line("LegalActions() = [{}]".format(", ".join(
str(x) for x in state.legal_actions())))
add_line("StringLegalActions() = [{}]".format(", ".join(
'"{}"'.format(state.action_to_string(state.current_player(), x))
for x in state.legal_actions())))
if state_idx < len(action_sequence):
action = action_sequence[state_idx]
else:
action = rng.choice(state.legal_actions())
add_line("")
add_line('# Apply action "{}"'.format(
state.action_to_string(state.current_player(), action)), force=True)
add_line("action: {}".format(action), force=True)
state.apply_action(action)
state_idx += 1
return lines | [
"def",
"playthrough_lines",
"(",
"game_string",
",",
"alsologtostdout",
"=",
"False",
",",
"action_sequence",
"=",
"None",
",",
"observation_params_string",
"=",
"None",
",",
"seed",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
":",
"should_display_state_... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/generate_playthrough.py#L187-L439 | |
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/trader/ui/mainwindow.py | python | MainWindow.load_window_setting | (self, name: str) | Load previous window size and state by trader path and setting name. | Load previous window size and state by trader path and setting name. | [
"Load",
"previous",
"window",
"size",
"and",
"state",
"by",
"trader",
"path",
"and",
"setting",
"name",
"."
] | def load_window_setting(self, name: str) -> None:
"""
Load previous window size and state by trader path and setting name.
"""
settings = QtCore.QSettings(self.window_title, name)
state = settings.value("state")
geometry = settings.value("geometry")
if isinstance(state, QtCore.QByteArray):
self.restoreState(state)
self.restoreGeometry(geometry) | [
"def",
"load_window_setting",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"None",
":",
"settings",
"=",
"QtCore",
".",
"QSettings",
"(",
"self",
".",
"window_title",
",",
"name",
")",
"state",
"=",
"settings",
".",
"value",
"(",
"\"state\"",
")",
... | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/ui/mainwindow.py#L298-L308 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/resmokelib/core/network.py | python | PortAllocator.max_test_port | (cls, job_num) | return next_range_start - 1 | For the given job, returns the highest port that is reserved
for use by tests.
Raises a PortAllocationError if that port is higher than the
maximum port. | For the given job, returns the highest port that is reserved
for use by tests. | [
"For",
"the",
"given",
"job",
"returns",
"the",
"highest",
"port",
"that",
"is",
"reserved",
"for",
"use",
"by",
"tests",
"."
] | def max_test_port(cls, job_num):
"""
For the given job, returns the highest port that is reserved
for use by tests.
Raises a PortAllocationError if that port is higher than the
maximum port.
"""
next_range_start = config.BASE_PORT + ((job_num + 1) * cls._PORTS_PER_JOB)
return next_range_start - 1 | [
"def",
"max_test_port",
"(",
"cls",
",",
"job_num",
")",
":",
"next_range_start",
"=",
"config",
".",
"BASE_PORT",
"+",
"(",
"(",
"job_num",
"+",
"1",
")",
"*",
"cls",
".",
"_PORTS_PER_JOB",
")",
"return",
"next_range_start",
"-",
"1"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/resmokelib/core/network.py#L105-L114 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/compatibility/ngraph/utils/input_validation.py | python | assert_list_of_ints | (value_list: Iterable[int], message: str) | Verify that the provided value is an iterable of integers. | Verify that the provided value is an iterable of integers. | [
"Verify",
"that",
"the",
"provided",
"value",
"is",
"an",
"iterable",
"of",
"integers",
"."
] | def assert_list_of_ints(value_list: Iterable[int], message: str) -> None:
"""Verify that the provided value is an iterable of integers."""
try:
for value in value_list:
if not isinstance(value, int):
raise TypeError
except TypeError:
log.warning(message)
raise UserInputError(message, value_list) | [
"def",
"assert_list_of_ints",
"(",
"value_list",
":",
"Iterable",
"[",
"int",
"]",
",",
"message",
":",
"str",
")",
"->",
"None",
":",
"try",
":",
"for",
"value",
"in",
"value_list",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/utils/input_validation.py#L16-L24 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | xmlNode.getSpacePreserve | (self) | return ret | Searches the space preserving behaviour of a node, i.e. the
values of the xml:space attribute or the one carried by the
nearest ancestor. | Searches the space preserving behaviour of a node, i.e. the
values of the xml:space attribute or the one carried by the
nearest ancestor. | [
"Searches",
"the",
"space",
"preserving",
"behaviour",
"of",
"a",
"node",
"i",
".",
"e",
".",
"the",
"values",
"of",
"the",
"xml",
":",
"space",
"attribute",
"or",
"the",
"one",
"carried",
"by",
"the",
"nearest",
"ancestor",
"."
] | def getSpacePreserve(self):
"""Searches the space preserving behaviour of a node, i.e. the
values of the xml:space attribute or the one carried by the
nearest ancestor. """
ret = libxml2mod.xmlNodeGetSpacePreserve(self._o)
return ret | [
"def",
"getSpacePreserve",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNodeGetSpacePreserve",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L3265-L3270 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/queues.py | python | Queue.empty | (self) | return not self._queue | Return True if the queue is empty, False otherwise. | Return True if the queue is empty, False otherwise. | [
"Return",
"True",
"if",
"the",
"queue",
"is",
"empty",
"False",
"otherwise",
"."
] | def empty(self):
"""Return True if the queue is empty, False otherwise."""
return not self._queue | [
"def",
"empty",
"(",
"self",
")",
":",
"return",
"not",
"self",
".",
"_queue"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/queues.py#L96-L98 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py | python | fix_lines | (source_lines, options, filename='') | return ''.join(normalize_line_endings(sio.readlines(), original_newline)) | Return fixed source code. | Return fixed source code. | [
"Return",
"fixed",
"source",
"code",
"."
] | def fix_lines(source_lines, options, filename=''):
"""Return fixed source code."""
# Transform everything to line feed. Then change them back to original
# before returning fixed source code.
original_newline = find_newline(source_lines)
tmp_source = ''.join(normalize_line_endings(source_lines, '\n'))
# Keep a history to break out of cycles.
previous_hashes = set()
if options.line_range:
fixed_source = apply_local_fixes(tmp_source, options)
else:
# Apply global fixes only once (for efficiency).
fixed_source = apply_global_fixes(tmp_source, options)
passes = 0
long_line_ignore_cache = set()
while hash(fixed_source) not in previous_hashes:
if options.pep8_passes >= 0 and passes > options.pep8_passes:
break
passes += 1
previous_hashes.add(hash(fixed_source))
tmp_source = copy.copy(fixed_source)
fix = FixPEP8(
filename,
options,
contents=tmp_source,
long_line_ignore_cache=long_line_ignore_cache)
fixed_source = fix.fix()
sio = io.StringIO(fixed_source)
return ''.join(normalize_line_endings(sio.readlines(), original_newline)) | [
"def",
"fix_lines",
"(",
"source_lines",
",",
"options",
",",
"filename",
"=",
"''",
")",
":",
"# Transform everything to line feed. Then change them back to original",
"# before returning fixed source code.",
"original_newline",
"=",
"find_newline",
"(",
"source_lines",
")",
... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py#L2828-L2864 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/aui.py | python | AuiPaneInfo.IsMovable | (*args, **kwargs) | return _aui.AuiPaneInfo_IsMovable(*args, **kwargs) | IsMovable(self) -> bool | IsMovable(self) -> bool | [
"IsMovable",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsMovable(*args, **kwargs):
"""IsMovable(self) -> bool"""
return _aui.AuiPaneInfo_IsMovable(*args, **kwargs) | [
"def",
"IsMovable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_IsMovable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L289-L291 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/database.py | python | _Cache.add | (self, dist) | Add a distribution to the cache.
:param dist: The distribution to add. | Add a distribution to the cache.
:param dist: The distribution to add. | [
"Add",
"a",
"distribution",
"to",
"the",
"cache",
".",
":",
"param",
"dist",
":",
"The",
"distribution",
"to",
"add",
"."
] | def add(self, dist):
"""
Add a distribution to the cache.
:param dist: The distribution to add.
"""
if dist.path not in self.path:
self.path[dist.path] = dist
self.name.setdefault(dist.key, []).append(dist) | [
"def",
"add",
"(",
"self",
",",
"dist",
")",
":",
"if",
"dist",
".",
"path",
"not",
"in",
"self",
".",
"path",
":",
"self",
".",
"path",
"[",
"dist",
".",
"path",
"]",
"=",
"dist",
"self",
".",
"name",
".",
"setdefault",
"(",
"dist",
".",
"key"... | 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/distlib/database.py#L65-L72 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/thumbnailctrl.py | python | ScrolledThumbnail.EnableToolTips | (self, enable=True) | Globally enables/disables thumbnail file information.
:param `enable`: ``True`` to enable thumbnail file information, ``False`` to disable it. | Globally enables/disables thumbnail file information. | [
"Globally",
"enables",
"/",
"disables",
"thumbnail",
"file",
"information",
"."
] | def EnableToolTips(self, enable=True):
"""
Globally enables/disables thumbnail file information.
:param `enable`: ``True`` to enable thumbnail file information, ``False`` to disable it.
"""
self._enabletooltip = enable
if not enable and hasattr(self, "_tipwindow"):
self._tipwindow.Enable(False) | [
"def",
"EnableToolTips",
"(",
"self",
",",
"enable",
"=",
"True",
")",
":",
"self",
".",
"_enabletooltip",
"=",
"enable",
"if",
"not",
"enable",
"and",
"hasattr",
"(",
"self",
",",
"\"_tipwindow\"",
")",
":",
"self",
".",
"_tipwindow",
".",
"Enable",
"("... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/thumbnailctrl.py#L1405-L1415 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/poplib.py | python | POP3.apop | (self, user, secret) | return self._shortcmd('APOP %s %s' % (user, digest)) | Authorisation
- only possible if server has supplied a timestamp in initial greeting.
Args:
user - mailbox user;
secret - secret shared between client and server.
NB: mailbox is locked by server from here to 'quit()' | Authorisation | [
"Authorisation"
] | def apop(self, user, secret):
"""Authorisation
- only possible if server has supplied a timestamp in initial greeting.
Args:
user - mailbox user;
secret - secret shared between client and server.
NB: mailbox is locked by server from here to 'quit()'
"""
m = self.timestamp.match(self.welcome)
if not m:
raise error_proto('-ERR APOP not supported by server')
import hashlib
digest = hashlib.md5(m.group(1)+secret).digest()
digest = ''.join(map(lambda x:'%02x'%ord(x), digest))
return self._shortcmd('APOP %s %s' % (user, digest)) | [
"def",
"apop",
"(",
"self",
",",
"user",
",",
"secret",
")",
":",
"m",
"=",
"self",
".",
"timestamp",
".",
"match",
"(",
"self",
".",
"welcome",
")",
"if",
"not",
"m",
":",
"raise",
"error_proto",
"(",
"'-ERR APOP not supported by server'",
")",
"import"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/poplib.py#L271-L288 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/sparse/construct.py | python | _compressed_sparse_stack | (blocks, axis) | Stacking fast path for CSR/CSC matrices
(i) vstack for CSR, (ii) hstack for CSC. | Stacking fast path for CSR/CSC matrices
(i) vstack for CSR, (ii) hstack for CSC. | [
"Stacking",
"fast",
"path",
"for",
"CSR",
"/",
"CSC",
"matrices",
"(",
"i",
")",
"vstack",
"for",
"CSR",
"(",
"ii",
")",
"hstack",
"for",
"CSC",
"."
] | def _compressed_sparse_stack(blocks, axis):
"""
Stacking fast path for CSR/CSC matrices
(i) vstack for CSR, (ii) hstack for CSC.
"""
other_axis = 1 if axis == 0 else 0
data = np.concatenate([b.data for b in blocks])
indices = np.concatenate([b.indices for b in blocks])
indptr = []
last_indptr = 0
constant_dim = blocks[0].shape[other_axis]
sum_dim = 0
for b in blocks:
if b.shape[other_axis] != constant_dim:
raise ValueError('incompatible dimensions for axis %d' % other_axis)
sum_dim += b.shape[axis]
indptr.append(b.indptr[:-1] + last_indptr)
last_indptr += b.indptr[-1]
indptr.append([last_indptr])
indptr = np.concatenate(indptr)
if axis == 0:
return csr_matrix((data, indices, indptr),
shape=(sum_dim, constant_dim))
else:
return csc_matrix((data, indices, indptr),
shape=(constant_dim, sum_dim)) | [
"def",
"_compressed_sparse_stack",
"(",
"blocks",
",",
"axis",
")",
":",
"other_axis",
"=",
"1",
"if",
"axis",
"==",
"0",
"else",
"0",
"data",
"=",
"np",
".",
"concatenate",
"(",
"[",
"b",
".",
"data",
"for",
"b",
"in",
"blocks",
"]",
")",
"indices",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/sparse/construct.py#L400-L425 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/opsworks/layer1.py | python | OpsWorksConnection.register_instance | (self, stack_id, hostname=None, public_ip=None,
private_ip=None, rsa_public_key=None,
rsa_public_key_fingerprint=None,
instance_identity=None) | return self.make_request(action='RegisterInstance',
body=json.dumps(params)) | Registers instances with a specified stack that were created
outside of AWS OpsWorks.
We do not recommend using this action to register instances.
The complete registration operation has two primary steps,
installing the AWS OpsWorks agent on the instance and
registering the instance with the stack. `RegisterInstance`
handles only the second step. You should instead use the AWS
CLI `register` command, which performs the entire registration
operation.
**Required Permissions**: To use this action, an IAM user must
have a Manage permissions level for the stack or an attached
policy that explicitly grants permissions. For more
information on user permissions, see `Managing User
Permissions`_.
:type stack_id: string
:param stack_id: The ID of the stack that the instance is to be
registered with.
:type hostname: string
:param hostname: The instance's hostname.
:type public_ip: string
:param public_ip: The instance's public IP address.
:type private_ip: string
:param private_ip: The instance's private IP address.
:type rsa_public_key: string
:param rsa_public_key: The instances public RSA key. This key is used
to encrypt communication between the instance and the service.
:type rsa_public_key_fingerprint: string
:param rsa_public_key_fingerprint: The instances public RSA key
fingerprint.
:type instance_identity: dict
:param instance_identity: An InstanceIdentity object that contains the
instance's identity. | Registers instances with a specified stack that were created
outside of AWS OpsWorks. | [
"Registers",
"instances",
"with",
"a",
"specified",
"stack",
"that",
"were",
"created",
"outside",
"of",
"AWS",
"OpsWorks",
"."
] | def register_instance(self, stack_id, hostname=None, public_ip=None,
private_ip=None, rsa_public_key=None,
rsa_public_key_fingerprint=None,
instance_identity=None):
"""
Registers instances with a specified stack that were created
outside of AWS OpsWorks.
We do not recommend using this action to register instances.
The complete registration operation has two primary steps,
installing the AWS OpsWorks agent on the instance and
registering the instance with the stack. `RegisterInstance`
handles only the second step. You should instead use the AWS
CLI `register` command, which performs the entire registration
operation.
**Required Permissions**: To use this action, an IAM user must
have a Manage permissions level for the stack or an attached
policy that explicitly grants permissions. For more
information on user permissions, see `Managing User
Permissions`_.
:type stack_id: string
:param stack_id: The ID of the stack that the instance is to be
registered with.
:type hostname: string
:param hostname: The instance's hostname.
:type public_ip: string
:param public_ip: The instance's public IP address.
:type private_ip: string
:param private_ip: The instance's private IP address.
:type rsa_public_key: string
:param rsa_public_key: The instances public RSA key. This key is used
to encrypt communication between the instance and the service.
:type rsa_public_key_fingerprint: string
:param rsa_public_key_fingerprint: The instances public RSA key
fingerprint.
:type instance_identity: dict
:param instance_identity: An InstanceIdentity object that contains the
instance's identity.
"""
params = {'StackId': stack_id, }
if hostname is not None:
params['Hostname'] = hostname
if public_ip is not None:
params['PublicIp'] = public_ip
if private_ip is not None:
params['PrivateIp'] = private_ip
if rsa_public_key is not None:
params['RsaPublicKey'] = rsa_public_key
if rsa_public_key_fingerprint is not None:
params['RsaPublicKeyFingerprint'] = rsa_public_key_fingerprint
if instance_identity is not None:
params['InstanceIdentity'] = instance_identity
return self.make_request(action='RegisterInstance',
body=json.dumps(params)) | [
"def",
"register_instance",
"(",
"self",
",",
"stack_id",
",",
"hostname",
"=",
"None",
",",
"public_ip",
"=",
"None",
",",
"private_ip",
"=",
"None",
",",
"rsa_public_key",
"=",
"None",
",",
"rsa_public_key_fingerprint",
"=",
"None",
",",
"instance_identity",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/opsworks/layer1.py#L2045-L2107 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | TextAttr.HasTextEffects | (*args, **kwargs) | return _controls_.TextAttr_HasTextEffects(*args, **kwargs) | HasTextEffects(self) -> bool | HasTextEffects(self) -> bool | [
"HasTextEffects",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasTextEffects(*args, **kwargs):
"""HasTextEffects(self) -> bool"""
return _controls_.TextAttr_HasTextEffects(*args, **kwargs) | [
"def",
"HasTextEffects",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_HasTextEffects",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L1876-L1878 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/site_compare/command_line.py | python | CommandLine.GetUsageString | (self) | return "Type '%s help' for usage." % self.prog | Returns simple usage instructions. | Returns simple usage instructions. | [
"Returns",
"simple",
"usage",
"instructions",
"."
] | def GetUsageString(self):
"""Returns simple usage instructions."""
return "Type '%s help' for usage." % self.prog | [
"def",
"GetUsageString",
"(",
"self",
")",
":",
"return",
"\"Type '%s help' for usage.\"",
"%",
"self",
".",
"prog"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/site_compare/command_line.py#L550-L552 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py | python | EncodedFile | (file, data_encoding, file_encoding=None, errors='strict') | return sr | Return a wrapped version of file which provides transparent
encoding translation.
Strings written to the wrapped file are interpreted according
to the given data_encoding and then written to the original
file as string using file_encoding. The intermediate encoding
will usually be Unicode but depends on the specified codecs.
Strings are read from the file using file_encoding and then
passed back to the caller as string using data_encoding.
If file_encoding is not given, it defaults to data_encoding.
errors may be given to define the error handling. It defaults
to 'strict' which causes ValueErrors to be raised in case an
encoding error occurs.
The returned wrapped file object provides two extra attributes
.data_encoding and .file_encoding which reflect the given
parameters of the same name. The attributes can be used for
introspection by Python programs. | Return a wrapped version of file which provides transparent
encoding translation. | [
"Return",
"a",
"wrapped",
"version",
"of",
"file",
"which",
"provides",
"transparent",
"encoding",
"translation",
"."
] | def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):
""" Return a wrapped version of file which provides transparent
encoding translation.
Strings written to the wrapped file are interpreted according
to the given data_encoding and then written to the original
file as string using file_encoding. The intermediate encoding
will usually be Unicode but depends on the specified codecs.
Strings are read from the file using file_encoding and then
passed back to the caller as string using data_encoding.
If file_encoding is not given, it defaults to data_encoding.
errors may be given to define the error handling. It defaults
to 'strict' which causes ValueErrors to be raised in case an
encoding error occurs.
The returned wrapped file object provides two extra attributes
.data_encoding and .file_encoding which reflect the given
parameters of the same name. The attributes can be used for
introspection by Python programs.
"""
if file_encoding is None:
file_encoding = data_encoding
data_info = lookup(data_encoding)
file_info = lookup(file_encoding)
sr = StreamRecoder(file, data_info.encode, data_info.decode,
file_info.streamreader, file_info.streamwriter, errors)
# Add attributes to simplify introspection
sr.data_encoding = data_encoding
sr.file_encoding = file_encoding
return sr | [
"def",
"EncodedFile",
"(",
"file",
",",
"data_encoding",
",",
"file_encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"file_encoding",
"is",
"None",
":",
"file_encoding",
"=",
"data_encoding",
"data_info",
"=",
"lookup",
"(",
"data_encodi... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py#L890-L924 | |
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | isapi/samples/advanced.py | python | status_handler | (options, log, arg) | Query the status of something | Query the status of something | [
"Query",
"the",
"status",
"of",
"something"
] | def status_handler(options, log, arg):
"Query the status of something"
print("Everything seems to be fine!") | [
"def",
"status_handler",
"(",
"options",
",",
"log",
",",
"arg",
")",
":",
"print",
"(",
"\"Everything seems to be fine!\"",
")"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/isapi/samples/advanced.py#L169-L171 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | FindDialogEvent.GetDialog | (*args, **kwargs) | return _windows_.FindDialogEvent_GetDialog(*args, **kwargs) | GetDialog(self) -> FindReplaceDialog
Return the pointer to the dialog which generated this event. | GetDialog(self) -> FindReplaceDialog | [
"GetDialog",
"(",
"self",
")",
"-",
">",
"FindReplaceDialog"
] | def GetDialog(*args, **kwargs):
"""
GetDialog(self) -> FindReplaceDialog
Return the pointer to the dialog which generated this event.
"""
return _windows_.FindDialogEvent_GetDialog(*args, **kwargs) | [
"def",
"GetDialog",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"FindDialogEvent_GetDialog",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L3839-L3845 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/depends.py | python | Require.full_name | (self) | return self.name | Return full package/distribution name, w/version | Return full package/distribution name, w/version | [
"Return",
"full",
"package",
"/",
"distribution",
"name",
"w",
"/",
"version"
] | def full_name(self):
"""Return full package/distribution name, w/version"""
if self.requested_version is not None:
return '%s-%s' % (self.name, self.requested_version)
return self.name | [
"def",
"full_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"requested_version",
"is",
"not",
"None",
":",
"return",
"'%s-%s'",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"requested_version",
")",
"return",
"self",
".",
"name"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/depends.py#L35-L39 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/cubecolourdialog.py | python | CustomPanel.OnEraseBackground | (self, event) | Handles the ``wx.EVT_ERASE_BACKGROUND`` for :class:`CustomPanel`.
:param `event`: a :class:`EraseEvent` event to be processed.
:note: This is intentionally empty to reduce flicker. | Handles the ``wx.EVT_ERASE_BACKGROUND`` for :class:`CustomPanel`. | [
"Handles",
"the",
"wx",
".",
"EVT_ERASE_BACKGROUND",
"for",
":",
"class",
":",
"CustomPanel",
"."
] | def OnEraseBackground(self, event):
"""
Handles the ``wx.EVT_ERASE_BACKGROUND`` for :class:`CustomPanel`.
:param `event`: a :class:`EraseEvent` event to be processed.
:note: This is intentionally empty to reduce flicker.
"""
pass | [
"def",
"OnEraseBackground",
"(",
"self",
",",
"event",
")",
":",
"pass"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/cubecolourdialog.py#L2703-L2712 | ||
traveller59/spconv | 647927ce6b64dc51fbec4eb50c7194f8ca5007e5 | spconv/pytorch/utils.py | python | gather_features_by_pc_voxel_id | (seg_res_features: torch.Tensor, pc_voxel_id: torch.Tensor, invalid_value: Union[int, float] = 0) | return res | This function is used to gather segmentation result to match origin pc. | This function is used to gather segmentation result to match origin pc. | [
"This",
"function",
"is",
"used",
"to",
"gather",
"segmentation",
"result",
"to",
"match",
"origin",
"pc",
"."
] | def gather_features_by_pc_voxel_id(seg_res_features: torch.Tensor, pc_voxel_id: torch.Tensor, invalid_value: Union[int, float] = 0):
"""This function is used to gather segmentation result to match origin pc.
"""
if seg_res_features.device != pc_voxel_id.device:
pc_voxel_id = pc_voxel_id.to(seg_res_features.device)
res_feature_shape = (pc_voxel_id.shape[0], *seg_res_features.shape[1:])
if invalid_value == 0:
res = torch.zeros(res_feature_shape, dtype=seg_res_features.dtype, device=seg_res_features.device)
else:
res = torch.full(res_feature_shape, invalid_value, dtype=seg_res_features.dtype, device=seg_res_features.device)
pc_voxel_id_valid = pc_voxel_id != -1
pc_voxel_id_valid_ids = torch.nonzero(pc_voxel_id_valid).view(-1)
seg_res_features_valid = seg_res_features[pc_voxel_id[pc_voxel_id_valid_ids]]
res[pc_voxel_id_valid_ids] = seg_res_features_valid
return res | [
"def",
"gather_features_by_pc_voxel_id",
"(",
"seg_res_features",
":",
"torch",
".",
"Tensor",
",",
"pc_voxel_id",
":",
"torch",
".",
"Tensor",
",",
"invalid_value",
":",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"0",
")",
":",
"if",
"seg_res_features",
"... | https://github.com/traveller59/spconv/blob/647927ce6b64dc51fbec4eb50c7194f8ca5007e5/spconv/pytorch/utils.py#L160-L174 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/smtplib.py | python | SMTP.__init__ | (self, host='', port=0, local_hostname=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None) | Initialize a new instance.
If specified, `host` is the name of the remote host to which to
connect. If specified, `port` specifies the port to which to connect.
By default, smtplib.SMTP_PORT is used. If a host is specified the
connect method is called, and if it returns anything other than a
success code an SMTPConnectError is raised. If specified,
`local_hostname` is used as the FQDN of the local host in the HELO/EHLO
command. Otherwise, the local hostname is found using
socket.getfqdn(). The `source_address` parameter takes a 2-tuple (host,
port) for the socket to bind to as its source address before
connecting. If the host is '' and port is 0, the OS default behavior
will be used. | Initialize a new instance. | [
"Initialize",
"a",
"new",
"instance",
"."
] | def __init__(self, host='', port=0, local_hostname=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None):
"""Initialize a new instance.
If specified, `host` is the name of the remote host to which to
connect. If specified, `port` specifies the port to which to connect.
By default, smtplib.SMTP_PORT is used. If a host is specified the
connect method is called, and if it returns anything other than a
success code an SMTPConnectError is raised. If specified,
`local_hostname` is used as the FQDN of the local host in the HELO/EHLO
command. Otherwise, the local hostname is found using
socket.getfqdn(). The `source_address` parameter takes a 2-tuple (host,
port) for the socket to bind to as its source address before
connecting. If the host is '' and port is 0, the OS default behavior
will be used.
"""
self._host = host
self.timeout = timeout
self.esmtp_features = {}
self.command_encoding = 'ascii'
self.source_address = source_address
self._auth_challenge_count = 0
if host:
(code, msg) = self.connect(host, port)
if code != 220:
self.close()
raise SMTPConnectError(code, msg)
if local_hostname is not None:
self.local_hostname = local_hostname
else:
# RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and
# if that can't be calculated, that we should use a domain literal
# instead (essentially an encoded IP address like [A.B.C.D]).
fqdn = socket.getfqdn()
if '.' in fqdn:
self.local_hostname = fqdn
else:
# We can't find an fqdn hostname, so use a domain literal
addr = '127.0.0.1'
try:
addr = socket.gethostbyname(socket.gethostname())
except socket.gaierror:
pass
self.local_hostname = '[%s]' % addr | [
"def",
"__init__",
"(",
"self",
",",
"host",
"=",
"''",
",",
"port",
"=",
"0",
",",
"local_hostname",
"=",
"None",
",",
"timeout",
"=",
"socket",
".",
"_GLOBAL_DEFAULT_TIMEOUT",
",",
"source_address",
"=",
"None",
")",
":",
"self",
".",
"_host",
"=",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/smtplib.py#L229-L275 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.