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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/core/jasper_process.py | python | Process.__init__ | ( # pylint: disable=too-many-arguments
self, logger, args, env=None, env_vars=None, job_num=None, test_id=None) | Initialize the process with the specified logger, arguments, and environment. | Initialize the process with the specified logger, arguments, and environment. | [
"Initialize",
"the",
"process",
"with",
"the",
"specified",
"logger",
"arguments",
"and",
"environment",
"."
] | def __init__( # pylint: disable=too-many-arguments
self, logger, args, env=None, env_vars=None, job_num=None, test_id=None):
"""Initialize the process with the specified logger, arguments, and environment."""
_process.Process.__init__(self, logger, args, env=env, env_vars=env_vars)
self._id = None
self.job_num = job_num
self.test_id = test_id
self._stub = self.rpc.JasperProcessManagerStub(
grpc.insecure_channel(config.JASPER_CONNECTION_STR))
self._return_code = None | [
"def",
"__init__",
"(",
"# pylint: disable=too-many-arguments",
"self",
",",
"logger",
",",
"args",
",",
"env",
"=",
"None",
",",
"env_vars",
"=",
"None",
",",
"job_num",
"=",
"None",
",",
"test_id",
"=",
"None",
")",
":",
"_process",
".",
"Process",
".",
"__init__",
"(",
"self",
",",
"logger",
",",
"args",
",",
"env",
"=",
"env",
",",
"env_vars",
"=",
"env_vars",
")",
"self",
".",
"_id",
"=",
"None",
"self",
".",
"job_num",
"=",
"job_num",
"self",
".",
"test_id",
"=",
"test_id",
"self",
".",
"_stub",
"=",
"self",
".",
"rpc",
".",
"JasperProcessManagerStub",
"(",
"grpc",
".",
"insecure_channel",
"(",
"config",
".",
"JASPER_CONNECTION_STR",
")",
")",
"self",
".",
"_return_code",
"=",
"None"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/core/jasper_process.py#L29-L38 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/turtle.py | python | TurtleScreen.mode | (self, mode=None) | Set turtle-mode ('standard', 'logo' or 'world') and perform reset.
Optional argument:
mode -- one of the strings 'standard', 'logo' or 'world'
Mode 'standard' is compatible with turtle.py.
Mode 'logo' is compatible with most Logo-Turtle-Graphics.
Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in
this mode angles appear distorted if x/y unit-ratio doesn't equal 1.
If mode is not given, return the current mode.
Mode Initial turtle heading positive angles
------------|-------------------------|-------------------
'standard' to the right (east) counterclockwise
'logo' upward (north) clockwise
Examples:
>>> mode('logo') # resets turtle heading to north
>>> mode()
'logo' | Set turtle-mode ('standard', 'logo' or 'world') and perform reset. | [
"Set",
"turtle",
"-",
"mode",
"(",
"standard",
"logo",
"or",
"world",
")",
"and",
"perform",
"reset",
"."
] | def mode(self, mode=None):
"""Set turtle-mode ('standard', 'logo' or 'world') and perform reset.
Optional argument:
mode -- one of the strings 'standard', 'logo' or 'world'
Mode 'standard' is compatible with turtle.py.
Mode 'logo' is compatible with most Logo-Turtle-Graphics.
Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in
this mode angles appear distorted if x/y unit-ratio doesn't equal 1.
If mode is not given, return the current mode.
Mode Initial turtle heading positive angles
------------|-------------------------|-------------------
'standard' to the right (east) counterclockwise
'logo' upward (north) clockwise
Examples:
>>> mode('logo') # resets turtle heading to north
>>> mode()
'logo'
"""
if mode is None:
return self._mode
mode = mode.lower()
if mode not in ["standard", "logo", "world"]:
raise TurtleGraphicsError("No turtle-graphics-mode %s" % mode)
self._mode = mode
if mode in ["standard", "logo"]:
self._setscrollregion(-self.canvwidth//2, -self.canvheight//2,
self.canvwidth//2, self.canvheight//2)
self.xscale = self.yscale = 1.0
self.reset() | [
"def",
"mode",
"(",
"self",
",",
"mode",
"=",
"None",
")",
":",
"if",
"mode",
"is",
"None",
":",
"return",
"self",
".",
"_mode",
"mode",
"=",
"mode",
".",
"lower",
"(",
")",
"if",
"mode",
"not",
"in",
"[",
"\"standard\"",
",",
"\"logo\"",
",",
"\"world\"",
"]",
":",
"raise",
"TurtleGraphicsError",
"(",
"\"No turtle-graphics-mode %s\"",
"%",
"mode",
")",
"self",
".",
"_mode",
"=",
"mode",
"if",
"mode",
"in",
"[",
"\"standard\"",
",",
"\"logo\"",
"]",
":",
"self",
".",
"_setscrollregion",
"(",
"-",
"self",
".",
"canvwidth",
"//",
"2",
",",
"-",
"self",
".",
"canvheight",
"//",
"2",
",",
"self",
".",
"canvwidth",
"//",
"2",
",",
"self",
".",
"canvheight",
"//",
"2",
")",
"self",
".",
"xscale",
"=",
"self",
".",
"yscale",
"=",
"1.0",
"self",
".",
"reset",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L1035-L1067 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | StandardPaths.GetUserDataDir | (*args, **kwargs) | return _misc_.StandardPaths_GetUserDataDir(*args, **kwargs) | GetUserDataDir(self) -> String
Return the directory for the user-dependent application data files:
$HOME/.appname under Unix, c:/Documents and
Settings/username/Application Data/appname under Windows and
~/Library/Application Support/appname under Mac | GetUserDataDir(self) -> String | [
"GetUserDataDir",
"(",
"self",
")",
"-",
">",
"String"
] | def GetUserDataDir(*args, **kwargs):
"""
GetUserDataDir(self) -> String
Return the directory for the user-dependent application data files:
$HOME/.appname under Unix, c:/Documents and
Settings/username/Application Data/appname under Windows and
~/Library/Application Support/appname under Mac
"""
return _misc_.StandardPaths_GetUserDataDir(*args, **kwargs) | [
"def",
"GetUserDataDir",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"StandardPaths_GetUserDataDir",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L6353-L6362 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | version | () | return "%s %s (classic)" % (wx.VERSION_STRING, port) | Returns a string containing version and port info | Returns a string containing version and port info | [
"Returns",
"a",
"string",
"containing",
"version",
"and",
"port",
"info"
] | def version():
"""Returns a string containing version and port info"""
if wx.Platform == '__WXMSW__':
port = 'msw'
elif wx.Platform == '__WXMAC__':
if 'wxOSX-carbon' in wx.PlatformInfo:
port = 'osx-carbon'
else:
port = 'osx-cocoa'
elif wx.Platform == '__WXGTK__':
port = 'gtk'
if 'gtk2' in wx.PlatformInfo:
port = 'gtk2'
elif 'gtk3' in wx.PlatformInfo:
port = 'gtk3'
else:
port = '?'
return "%s %s (classic)" % (wx.VERSION_STRING, port) | [
"def",
"version",
"(",
")",
":",
"if",
"wx",
".",
"Platform",
"==",
"'__WXMSW__'",
":",
"port",
"=",
"'msw'",
"elif",
"wx",
".",
"Platform",
"==",
"'__WXMAC__'",
":",
"if",
"'wxOSX-carbon'",
"in",
"wx",
".",
"PlatformInfo",
":",
"port",
"=",
"'osx-carbon'",
"else",
":",
"port",
"=",
"'osx-cocoa'",
"elif",
"wx",
".",
"Platform",
"==",
"'__WXGTK__'",
":",
"port",
"=",
"'gtk'",
"if",
"'gtk2'",
"in",
"wx",
".",
"PlatformInfo",
":",
"port",
"=",
"'gtk2'",
"elif",
"'gtk3'",
"in",
"wx",
".",
"PlatformInfo",
":",
"port",
"=",
"'gtk3'",
"else",
":",
"port",
"=",
"'?'",
"return",
"\"%s %s (classic)\"",
"%",
"(",
"wx",
".",
"VERSION_STRING",
",",
"port",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L16640-L16658 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/contrib/onnx/onnx2mx/_op_translations.py | python | reciprocal | (attrs, inputs, proto_obj) | return 'reciprocal', attrs, inputs | Returns the reciprocal of the argument, element-wise. | Returns the reciprocal of the argument, element-wise. | [
"Returns",
"the",
"reciprocal",
"of",
"the",
"argument",
"element",
"-",
"wise",
"."
] | def reciprocal(attrs, inputs, proto_obj):
"""Returns the reciprocal of the argument, element-wise."""
return 'reciprocal', attrs, inputs | [
"def",
"reciprocal",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"return",
"'reciprocal'",
",",
"attrs",
",",
"inputs"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L561-L563 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | native_client_sdk/src/build_tools/buildbot_common.py | python | Move | (src, dst) | Move the path src to dst. | Move the path src to dst. | [
"Move",
"the",
"path",
"src",
"to",
"dst",
"."
] | def Move(src, dst):
"""Move the path src to dst."""
print 'mv -f %s %s' % (src, dst)
oshelpers.Move(['-f', src, dst]) | [
"def",
"Move",
"(",
"src",
",",
"dst",
")",
":",
"print",
"'mv -f %s %s'",
"%",
"(",
"src",
",",
"dst",
")",
"oshelpers",
".",
"Move",
"(",
"[",
"'-f'",
",",
"src",
",",
"dst",
"]",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/build_tools/buildbot_common.py#L76-L79 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tools/saved_model_cli.py | python | run | (args) | Function triggered by run command.
Args:
args: A namespace parsed from command line.
Raises:
AttributeError: An error when neither --inputs nor --input_exprs is passed
to run command. | Function triggered by run command. | [
"Function",
"triggered",
"by",
"run",
"command",
"."
] | def run(args):
"""Function triggered by run command.
Args:
args: A namespace parsed from command line.
Raises:
AttributeError: An error when neither --inputs nor --input_exprs is passed
to run command.
"""
if not args.inputs and not args.input_exprs and not args.input_examples:
raise AttributeError(
'At least one of --inputs, --input_exprs or --input_examples must be '
'required')
tensor_key_feed_dict = load_inputs_from_input_arg_string(
args.inputs, args.input_exprs, args.input_examples)
run_saved_model_with_feed_dict(args.dir, args.tag_set, args.signature_def,
tensor_key_feed_dict, args.outdir,
args.overwrite, worker=args.worker,
init_tpu=args.init_tpu, tf_debug=args.tf_debug) | [
"def",
"run",
"(",
"args",
")",
":",
"if",
"not",
"args",
".",
"inputs",
"and",
"not",
"args",
".",
"input_exprs",
"and",
"not",
"args",
".",
"input_examples",
":",
"raise",
"AttributeError",
"(",
"'At least one of --inputs, --input_exprs or --input_examples must be '",
"'required'",
")",
"tensor_key_feed_dict",
"=",
"load_inputs_from_input_arg_string",
"(",
"args",
".",
"inputs",
",",
"args",
".",
"input_exprs",
",",
"args",
".",
"input_examples",
")",
"run_saved_model_with_feed_dict",
"(",
"args",
".",
"dir",
",",
"args",
".",
"tag_set",
",",
"args",
".",
"signature_def",
",",
"tensor_key_feed_dict",
",",
"args",
".",
"outdir",
",",
"args",
".",
"overwrite",
",",
"worker",
"=",
"args",
".",
"worker",
",",
"init_tpu",
"=",
"args",
".",
"init_tpu",
",",
"tf_debug",
"=",
"args",
".",
"tf_debug",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tools/saved_model_cli.py#L705-L724 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/handlers.py | python | SysLogHandler.__init__ | (self, address=('localhost', SYSLOG_UDP_PORT),
facility=LOG_USER, socktype=None) | Initialize a handler.
If address is specified as a string, a UNIX socket is used. To log to a
local syslogd, "SysLogHandler(address="/dev/log")" can be used.
If facility is not specified, LOG_USER is used. If socktype is
specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
socket type will be used. For Unix sockets, you can also specify a
socktype of None, in which case socket.SOCK_DGRAM will be used, falling
back to socket.SOCK_STREAM. | Initialize a handler. | [
"Initialize",
"a",
"handler",
"."
] | def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
facility=LOG_USER, socktype=None):
"""
Initialize a handler.
If address is specified as a string, a UNIX socket is used. To log to a
local syslogd, "SysLogHandler(address="/dev/log")" can be used.
If facility is not specified, LOG_USER is used. If socktype is
specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
socket type will be used. For Unix sockets, you can also specify a
socktype of None, in which case socket.SOCK_DGRAM will be used, falling
back to socket.SOCK_STREAM.
"""
logging.Handler.__init__(self)
self.address = address
self.facility = facility
self.socktype = socktype
if isinstance(address, str):
self.unixsocket = True
# Syslog server may be unavailable during handler initialisation.
# C's openlog() function also ignores connection errors.
# Moreover, we ignore these errors while logging, so it not worse
# to ignore it also here.
try:
self._connect_unixsocket(address)
except OSError:
pass
else:
self.unixsocket = False
if socktype is None:
socktype = socket.SOCK_DGRAM
host, port = address
ress = socket.getaddrinfo(host, port, 0, socktype)
if not ress:
raise OSError("getaddrinfo returns an empty list")
for res in ress:
af, socktype, proto, _, sa = res
err = sock = None
try:
sock = socket.socket(af, socktype, proto)
if socktype == socket.SOCK_STREAM:
sock.connect(sa)
break
except OSError as exc:
err = exc
if sock is not None:
sock.close()
if err is not None:
raise err
self.socket = sock
self.socktype = socktype | [
"def",
"__init__",
"(",
"self",
",",
"address",
"=",
"(",
"'localhost'",
",",
"SYSLOG_UDP_PORT",
")",
",",
"facility",
"=",
"LOG_USER",
",",
"socktype",
"=",
"None",
")",
":",
"logging",
".",
"Handler",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"address",
"=",
"address",
"self",
".",
"facility",
"=",
"facility",
"self",
".",
"socktype",
"=",
"socktype",
"if",
"isinstance",
"(",
"address",
",",
"str",
")",
":",
"self",
".",
"unixsocket",
"=",
"True",
"# Syslog server may be unavailable during handler initialisation.",
"# C's openlog() function also ignores connection errors.",
"# Moreover, we ignore these errors while logging, so it not worse",
"# to ignore it also here.",
"try",
":",
"self",
".",
"_connect_unixsocket",
"(",
"address",
")",
"except",
"OSError",
":",
"pass",
"else",
":",
"self",
".",
"unixsocket",
"=",
"False",
"if",
"socktype",
"is",
"None",
":",
"socktype",
"=",
"socket",
".",
"SOCK_DGRAM",
"host",
",",
"port",
"=",
"address",
"ress",
"=",
"socket",
".",
"getaddrinfo",
"(",
"host",
",",
"port",
",",
"0",
",",
"socktype",
")",
"if",
"not",
"ress",
":",
"raise",
"OSError",
"(",
"\"getaddrinfo returns an empty list\"",
")",
"for",
"res",
"in",
"ress",
":",
"af",
",",
"socktype",
",",
"proto",
",",
"_",
",",
"sa",
"=",
"res",
"err",
"=",
"sock",
"=",
"None",
"try",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"af",
",",
"socktype",
",",
"proto",
")",
"if",
"socktype",
"==",
"socket",
".",
"SOCK_STREAM",
":",
"sock",
".",
"connect",
"(",
"sa",
")",
"break",
"except",
"OSError",
"as",
"exc",
":",
"err",
"=",
"exc",
"if",
"sock",
"is",
"not",
"None",
":",
"sock",
".",
"close",
"(",
")",
"if",
"err",
"is",
"not",
"None",
":",
"raise",
"err",
"self",
".",
"socket",
"=",
"sock",
"self",
".",
"socktype",
"=",
"socktype"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/handlers.py#L795-L847 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/util/__init__.py | python | _get_temp_file_location | () | return cache_dir | Returns user specified temporary file location.
The temporary location is specified through:
>>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...) | Returns user specified temporary file location.
The temporary location is specified through: | [
"Returns",
"user",
"specified",
"temporary",
"file",
"location",
".",
"The",
"temporary",
"location",
"is",
"specified",
"through",
":"
] | def _get_temp_file_location():
"""
Returns user specified temporary file location.
The temporary location is specified through:
>>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...)
"""
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
cache_dir = _convert_slashes(unity.get_current_cache_file_location())
if not _os.path.exists(cache_dir):
_os.makedirs(cache_dir)
return cache_dir | [
"def",
"_get_temp_file_location",
"(",
")",
":",
"from",
".",
".",
"_connect",
"import",
"main",
"as",
"_glconnect",
"unity",
"=",
"_glconnect",
".",
"get_unity",
"(",
")",
"cache_dir",
"=",
"_convert_slashes",
"(",
"unity",
".",
"get_current_cache_file_location",
"(",
")",
")",
"if",
"not",
"_os",
".",
"path",
".",
"exists",
"(",
"cache_dir",
")",
":",
"_os",
".",
"makedirs",
"(",
"cache_dir",
")",
"return",
"cache_dir"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/util/__init__.py#L409-L423 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/io/pytables.py | python | LegacyTable.read | (self, where=None, columns=None, **kwargs) | return wp | we have n indexable columns, with an arbitrary number of data
axes | we have n indexable columns, with an arbitrary number of data
axes | [
"we",
"have",
"n",
"indexable",
"columns",
"with",
"an",
"arbitrary",
"number",
"of",
"data",
"axes"
] | def read(self, where=None, columns=None, **kwargs):
"""we have n indexable columns, with an arbitrary number of data
axes
"""
if not self.read_axes(where=where, **kwargs):
return None
lst_vals = [a.values for a in self.index_axes]
labels, levels = _factorize_from_iterables(lst_vals)
# labels and levels are tuples but lists are expected
labels = list(labels)
levels = list(levels)
N = [len(lvl) for lvl in levels]
# compute the key
key = _factor_indexer(N[1:], labels)
objs = []
if len(unique(key)) == len(key):
sorter, _ = algos.groupsort_indexer(
ensure_int64(key), np.prod(N))
sorter = ensure_platform_int(sorter)
# create the objs
for c in self.values_axes:
# the data need to be sorted
sorted_values = c.take_data().take(sorter, axis=0)
if sorted_values.ndim == 1:
sorted_values = sorted_values.reshape(
(sorted_values.shape[0], 1))
take_labels = [l.take(sorter) for l in labels]
items = Index(c.values)
block = _block2d_to_blocknd(
values=sorted_values, placement=np.arange(len(items)),
shape=tuple(N), labels=take_labels, ref_items=items)
# create the object
mgr = BlockManager([block], [items] + levels)
obj = self.obj_type(mgr)
# permute if needed
if self.is_transposed:
obj = obj.transpose(
*tuple(Series(self.data_orientation).argsort()))
objs.append(obj)
else:
warnings.warn(duplicate_doc, DuplicateWarning, stacklevel=5)
# reconstruct
long_index = MultiIndex.from_arrays(
[i.values for i in self.index_axes])
for c in self.values_axes:
lp = DataFrame(c.data, index=long_index, columns=c.values)
# need a better algorithm
tuple_index = long_index.values
unique_tuples = unique(tuple_index)
unique_tuples = com.asarray_tuplesafe(unique_tuples)
indexer = match(unique_tuples, tuple_index)
indexer = ensure_platform_int(indexer)
new_index = long_index.take(indexer)
new_values = lp.values.take(indexer, axis=0)
lp = DataFrame(new_values, index=new_index, columns=lp.columns)
objs.append(lp.to_panel())
# create the composite object
if len(objs) == 1:
wp = objs[0]
else:
wp = concat(objs, axis=0, verify_integrity=False)._consolidate()
# apply the selection filters & axis orderings
wp = self.process_axes(wp, columns=columns)
return wp | [
"def",
"read",
"(",
"self",
",",
"where",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"read_axes",
"(",
"where",
"=",
"where",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"None",
"lst_vals",
"=",
"[",
"a",
".",
"values",
"for",
"a",
"in",
"self",
".",
"index_axes",
"]",
"labels",
",",
"levels",
"=",
"_factorize_from_iterables",
"(",
"lst_vals",
")",
"# labels and levels are tuples but lists are expected",
"labels",
"=",
"list",
"(",
"labels",
")",
"levels",
"=",
"list",
"(",
"levels",
")",
"N",
"=",
"[",
"len",
"(",
"lvl",
")",
"for",
"lvl",
"in",
"levels",
"]",
"# compute the key",
"key",
"=",
"_factor_indexer",
"(",
"N",
"[",
"1",
":",
"]",
",",
"labels",
")",
"objs",
"=",
"[",
"]",
"if",
"len",
"(",
"unique",
"(",
"key",
")",
")",
"==",
"len",
"(",
"key",
")",
":",
"sorter",
",",
"_",
"=",
"algos",
".",
"groupsort_indexer",
"(",
"ensure_int64",
"(",
"key",
")",
",",
"np",
".",
"prod",
"(",
"N",
")",
")",
"sorter",
"=",
"ensure_platform_int",
"(",
"sorter",
")",
"# create the objs",
"for",
"c",
"in",
"self",
".",
"values_axes",
":",
"# the data need to be sorted",
"sorted_values",
"=",
"c",
".",
"take_data",
"(",
")",
".",
"take",
"(",
"sorter",
",",
"axis",
"=",
"0",
")",
"if",
"sorted_values",
".",
"ndim",
"==",
"1",
":",
"sorted_values",
"=",
"sorted_values",
".",
"reshape",
"(",
"(",
"sorted_values",
".",
"shape",
"[",
"0",
"]",
",",
"1",
")",
")",
"take_labels",
"=",
"[",
"l",
".",
"take",
"(",
"sorter",
")",
"for",
"l",
"in",
"labels",
"]",
"items",
"=",
"Index",
"(",
"c",
".",
"values",
")",
"block",
"=",
"_block2d_to_blocknd",
"(",
"values",
"=",
"sorted_values",
",",
"placement",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"items",
")",
")",
",",
"shape",
"=",
"tuple",
"(",
"N",
")",
",",
"labels",
"=",
"take_labels",
",",
"ref_items",
"=",
"items",
")",
"# create the object",
"mgr",
"=",
"BlockManager",
"(",
"[",
"block",
"]",
",",
"[",
"items",
"]",
"+",
"levels",
")",
"obj",
"=",
"self",
".",
"obj_type",
"(",
"mgr",
")",
"# permute if needed",
"if",
"self",
".",
"is_transposed",
":",
"obj",
"=",
"obj",
".",
"transpose",
"(",
"*",
"tuple",
"(",
"Series",
"(",
"self",
".",
"data_orientation",
")",
".",
"argsort",
"(",
")",
")",
")",
"objs",
".",
"append",
"(",
"obj",
")",
"else",
":",
"warnings",
".",
"warn",
"(",
"duplicate_doc",
",",
"DuplicateWarning",
",",
"stacklevel",
"=",
"5",
")",
"# reconstruct",
"long_index",
"=",
"MultiIndex",
".",
"from_arrays",
"(",
"[",
"i",
".",
"values",
"for",
"i",
"in",
"self",
".",
"index_axes",
"]",
")",
"for",
"c",
"in",
"self",
".",
"values_axes",
":",
"lp",
"=",
"DataFrame",
"(",
"c",
".",
"data",
",",
"index",
"=",
"long_index",
",",
"columns",
"=",
"c",
".",
"values",
")",
"# need a better algorithm",
"tuple_index",
"=",
"long_index",
".",
"values",
"unique_tuples",
"=",
"unique",
"(",
"tuple_index",
")",
"unique_tuples",
"=",
"com",
".",
"asarray_tuplesafe",
"(",
"unique_tuples",
")",
"indexer",
"=",
"match",
"(",
"unique_tuples",
",",
"tuple_index",
")",
"indexer",
"=",
"ensure_platform_int",
"(",
"indexer",
")",
"new_index",
"=",
"long_index",
".",
"take",
"(",
"indexer",
")",
"new_values",
"=",
"lp",
".",
"values",
".",
"take",
"(",
"indexer",
",",
"axis",
"=",
"0",
")",
"lp",
"=",
"DataFrame",
"(",
"new_values",
",",
"index",
"=",
"new_index",
",",
"columns",
"=",
"lp",
".",
"columns",
")",
"objs",
".",
"append",
"(",
"lp",
".",
"to_panel",
"(",
")",
")",
"# create the composite object",
"if",
"len",
"(",
"objs",
")",
"==",
"1",
":",
"wp",
"=",
"objs",
"[",
"0",
"]",
"else",
":",
"wp",
"=",
"concat",
"(",
"objs",
",",
"axis",
"=",
"0",
",",
"verify_integrity",
"=",
"False",
")",
".",
"_consolidate",
"(",
")",
"# apply the selection filters & axis orderings",
"wp",
"=",
"self",
".",
"process_axes",
"(",
"wp",
",",
"columns",
"=",
"columns",
")",
"return",
"wp"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/pytables.py#L3895-L3980 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/TemplatePyMod/DocumentObject.py | python | ViewProvider.toString | (self) | return self.__vobject__.toString() | returns a string representation of the coin node of this object | returns a string representation of the coin node of this object | [
"returns",
"a",
"string",
"representation",
"of",
"the",
"coin",
"node",
"of",
"this",
"object"
] | def toString(self):
"returns a string representation of the coin node of this object"
return self.__vobject__.toString() | [
"def",
"toString",
"(",
"self",
")",
":",
"return",
"self",
".",
"__vobject__",
".",
"toString",
"(",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/TemplatePyMod/DocumentObject.py#L197-L199 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | UIActionSimulator.Char | (*args, **kwargs) | return _misc_.UIActionSimulator_Char(*args, **kwargs) | Char(self, int keycode, int modifiers=MOD_NONE) -> bool | Char(self, int keycode, int modifiers=MOD_NONE) -> bool | [
"Char",
"(",
"self",
"int",
"keycode",
"int",
"modifiers",
"=",
"MOD_NONE",
")",
"-",
">",
"bool"
] | def Char(*args, **kwargs):
"""Char(self, int keycode, int modifiers=MOD_NONE) -> bool"""
return _misc_.UIActionSimulator_Char(*args, **kwargs) | [
"def",
"Char",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"UIActionSimulator_Char",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L6995-L6997 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/package/_importlib.py | python | _calc___package__ | (globals) | return package | Calculate what __package__ should be.
__package__ is not guaranteed to be defined or could be set to None
to represent that its proper value is unknown. | Calculate what __package__ should be. | [
"Calculate",
"what",
"__package__",
"should",
"be",
"."
] | def _calc___package__(globals):
"""Calculate what __package__ should be.
__package__ is not guaranteed to be defined or could be set to None
to represent that its proper value is unknown.
"""
package = globals.get("__package__")
spec = globals.get("__spec__")
if package is not None:
if spec is not None and package != spec.parent:
_warnings.warn(
"__package__ != __spec__.parent " f"({package!r} != {spec.parent!r})",
ImportWarning,
stacklevel=3,
)
return package
elif spec is not None:
return spec.parent
else:
_warnings.warn(
"can't resolve package from __spec__ or __package__, "
"falling back on __name__ and __path__",
ImportWarning,
stacklevel=3,
)
package = globals["__name__"]
if "__path__" not in globals:
package = package.rpartition(".")[0]
return package | [
"def",
"_calc___package__",
"(",
"globals",
")",
":",
"package",
"=",
"globals",
".",
"get",
"(",
"\"__package__\"",
")",
"spec",
"=",
"globals",
".",
"get",
"(",
"\"__spec__\"",
")",
"if",
"package",
"is",
"not",
"None",
":",
"if",
"spec",
"is",
"not",
"None",
"and",
"package",
"!=",
"spec",
".",
"parent",
":",
"_warnings",
".",
"warn",
"(",
"\"__package__ != __spec__.parent \"",
"f\"({package!r} != {spec.parent!r})\"",
",",
"ImportWarning",
",",
"stacklevel",
"=",
"3",
",",
")",
"return",
"package",
"elif",
"spec",
"is",
"not",
"None",
":",
"return",
"spec",
".",
"parent",
"else",
":",
"_warnings",
".",
"warn",
"(",
"\"can't resolve package from __spec__ or __package__, \"",
"\"falling back on __name__ and __path__\"",
",",
"ImportWarning",
",",
"stacklevel",
"=",
"3",
",",
")",
"package",
"=",
"globals",
"[",
"\"__name__\"",
"]",
"if",
"\"__path__\"",
"not",
"in",
"globals",
":",
"package",
"=",
"package",
".",
"rpartition",
"(",
"\".\"",
")",
"[",
"0",
"]",
"return",
"package"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/package/_importlib.py#L53-L82 | |
leela-zero/leela-zero | e3ed6310d33d75078ba74c3adf887d18439fc2e3 | scripts/cpplint.py | python | IsBlankLine | (line) | return not line or line.isspace() | Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank. | Returns true if the given line is blank. | [
"Returns",
"true",
"if",
"the",
"given",
"line",
"is",
"blank",
"."
] | def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace() | [
"def",
"IsBlankLine",
"(",
"line",
")",
":",
"return",
"not",
"line",
"or",
"line",
".",
"isspace",
"(",
")"
] | https://github.com/leela-zero/leela-zero/blob/e3ed6310d33d75078ba74c3adf887d18439fc2e3/scripts/cpplint.py#L2802-L2814 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/min.py | python | min.sign_from_args | (self) | return (self.args[0].is_nonneg(), self.args[0].is_nonpos()) | Returns sign (is positive, is negative) of the expression. | Returns sign (is positive, is negative) of the expression. | [
"Returns",
"sign",
"(",
"is",
"positive",
"is",
"negative",
")",
"of",
"the",
"expression",
"."
] | def sign_from_args(self) -> Tuple[bool, bool]:
"""Returns sign (is positive, is negative) of the expression.
"""
# Same as argument.
return (self.args[0].is_nonneg(), self.args[0].is_nonpos()) | [
"def",
"sign_from_args",
"(",
"self",
")",
"->",
"Tuple",
"[",
"bool",
",",
"bool",
"]",
":",
"# Same as argument.",
"return",
"(",
"self",
".",
"args",
"[",
"0",
"]",
".",
"is_nonneg",
"(",
")",
",",
"self",
".",
"args",
"[",
"0",
"]",
".",
"is_nonpos",
"(",
")",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/min.py#L68-L72 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Environment.py | python | Base.AppendENVPath | (self, name, newpath, envname = 'ENV',
sep = os.pathsep, delete_existing=0) | Append path elements to the path 'name' in the 'ENV'
dictionary for this environment. Will only add any particular
path once, and will normpath and normcase all paths to help
assure this. This can also handle the case where the env
variable is a list instead of a string.
If delete_existing is 0, a newpath which is already in the path
will not be moved to the end (it will be left where it is). | Append path elements to the path 'name' in the 'ENV'
dictionary for this environment. Will only add any particular
path once, and will normpath and normcase all paths to help
assure this. This can also handle the case where the env
variable is a list instead of a string. | [
"Append",
"path",
"elements",
"to",
"the",
"path",
"name",
"in",
"the",
"ENV",
"dictionary",
"for",
"this",
"environment",
".",
"Will",
"only",
"add",
"any",
"particular",
"path",
"once",
"and",
"will",
"normpath",
"and",
"normcase",
"all",
"paths",
"to",
"help",
"assure",
"this",
".",
"This",
"can",
"also",
"handle",
"the",
"case",
"where",
"the",
"env",
"variable",
"is",
"a",
"list",
"instead",
"of",
"a",
"string",
"."
] | def AppendENVPath(self, name, newpath, envname = 'ENV',
sep = os.pathsep, delete_existing=0):
"""Append path elements to the path 'name' in the 'ENV'
dictionary for this environment. Will only add any particular
path once, and will normpath and normcase all paths to help
assure this. This can also handle the case where the env
variable is a list instead of a string.
If delete_existing is 0, a newpath which is already in the path
will not be moved to the end (it will be left where it is).
"""
orig = ''
if envname in self._dict and name in self._dict[envname]:
orig = self._dict[envname][name]
nv = SCons.Util.AppendPath(orig, newpath, sep, delete_existing,
canonicalize=self._canonicalize)
if envname not in self._dict:
self._dict[envname] = {}
self._dict[envname][name] = nv | [
"def",
"AppendENVPath",
"(",
"self",
",",
"name",
",",
"newpath",
",",
"envname",
"=",
"'ENV'",
",",
"sep",
"=",
"os",
".",
"pathsep",
",",
"delete_existing",
"=",
"0",
")",
":",
"orig",
"=",
"''",
"if",
"envname",
"in",
"self",
".",
"_dict",
"and",
"name",
"in",
"self",
".",
"_dict",
"[",
"envname",
"]",
":",
"orig",
"=",
"self",
".",
"_dict",
"[",
"envname",
"]",
"[",
"name",
"]",
"nv",
"=",
"SCons",
".",
"Util",
".",
"AppendPath",
"(",
"orig",
",",
"newpath",
",",
"sep",
",",
"delete_existing",
",",
"canonicalize",
"=",
"self",
".",
"_canonicalize",
")",
"if",
"envname",
"not",
"in",
"self",
".",
"_dict",
":",
"self",
".",
"_dict",
"[",
"envname",
"]",
"=",
"{",
"}",
"self",
".",
"_dict",
"[",
"envname",
"]",
"[",
"name",
"]",
"=",
"nv"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Environment.py#L1248-L1270 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/cr/cr/plugin.py | python | Plugin.UnorderedPlugins | (cls) | Returns all enabled plugins of type cls, in undefined order. | Returns all enabled plugins of type cls, in undefined order. | [
"Returns",
"all",
"enabled",
"plugins",
"of",
"type",
"cls",
"in",
"undefined",
"order",
"."
] | def UnorderedPlugins(cls):
"""Returns all enabled plugins of type cls, in undefined order."""
plugin = cls.GetInstance()
if plugin.enabled:
yield plugin
for child in cls.__subclasses__():
for p in child.UnorderedPlugins():
yield p | [
"def",
"UnorderedPlugins",
"(",
"cls",
")",
":",
"plugin",
"=",
"cls",
".",
"GetInstance",
"(",
")",
"if",
"plugin",
".",
"enabled",
":",
"yield",
"plugin",
"for",
"child",
"in",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"for",
"p",
"in",
"child",
".",
"UnorderedPlugins",
"(",
")",
":",
"yield",
"p"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/cr/cr/plugin.py#L226-L233 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | Log_GetTraceMask | (*args) | return _misc_.Log_GetTraceMask(*args) | Log_GetTraceMask() -> TraceMask | Log_GetTraceMask() -> TraceMask | [
"Log_GetTraceMask",
"()",
"-",
">",
"TraceMask"
] | def Log_GetTraceMask(*args):
"""Log_GetTraceMask() -> TraceMask"""
return _misc_.Log_GetTraceMask(*args) | [
"def",
"Log_GetTraceMask",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"Log_GetTraceMask",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1720-L1722 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_pytorch/example/resnet18_qat.py | python | accuracy | (output, target, topk=(1,)) | Computes the accuracy over the k top predictions for the specified values of k | Computes the accuracy over the k top predictions for the specified values of k | [
"Computes",
"the",
"accuracy",
"over",
"the",
"k",
"top",
"predictions",
"for",
"the",
"specified",
"values",
"of",
"k"
] | def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].flatten().float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res | [
"def",
"accuracy",
"(",
"output",
",",
"target",
",",
"topk",
"=",
"(",
"1",
",",
")",
")",
":",
"with",
"torch",
".",
"no_grad",
"(",
")",
":",
"maxk",
"=",
"max",
"(",
"topk",
")",
"batch_size",
"=",
"target",
".",
"size",
"(",
"0",
")",
"_",
",",
"pred",
"=",
"output",
".",
"topk",
"(",
"maxk",
",",
"1",
",",
"True",
",",
"True",
")",
"pred",
"=",
"pred",
".",
"t",
"(",
")",
"correct",
"=",
"pred",
".",
"eq",
"(",
"target",
".",
"view",
"(",
"1",
",",
"-",
"1",
")",
".",
"expand_as",
"(",
"pred",
")",
")",
"res",
"=",
"[",
"]",
"for",
"k",
"in",
"topk",
":",
"correct_k",
"=",
"correct",
"[",
":",
"k",
"]",
".",
"flatten",
"(",
")",
".",
"float",
"(",
")",
".",
"sum",
"(",
"0",
",",
"keepdim",
"=",
"True",
")",
"res",
".",
"append",
"(",
"correct_k",
".",
"mul_",
"(",
"100.0",
"/",
"batch_size",
")",
")",
"return",
"res"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_pytorch/example/resnet18_qat.py#L490-L504 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/math_grad.py | python | _SquaredDifferenceGrad | (op, grad) | return (gx, gy) | Returns the gradient for (x-y)^2. | Returns the gradient for (x-y)^2. | [
"Returns",
"the",
"gradient",
"for",
"(",
"x",
"-",
"y",
")",
"^2",
"."
] | def _SquaredDifferenceGrad(op, grad):
"""Returns the gradient for (x-y)^2."""
x = op.inputs[0]
y = op.inputs[1]
skip_input_indices = None
try:
skip_input_indices = op.skip_input_indices
except AttributeError:
# No gradient skipping, so do the full gradient computation
pass
with ops.control_dependencies([grad]):
# The parens ensure that if grad is IndexedSlices, it'll get multiplied by
# Tensor (not a number like 2.0) which causes it to convert to Tensor.
x_grad = math_ops.scalar_mul(2.0, grad) * (x - y)
if (isinstance(grad, ops.Tensor) and
_ShapesFullySpecifiedAndEqual(x, y, grad)):
return x_grad, -x_grad
(sx, rx, must_reduce_x), (sy, ry, must_reduce_y) = (
SmartBroadcastGradientArgs(x, y, grad))
if skip_input_indices is not None and 0 in skip_input_indices:
gx = None
elif must_reduce_x:
gx = array_ops.reshape(math_ops.reduce_sum(x_grad, rx), sx)
else:
gx = x_grad
if skip_input_indices is not None and 1 in skip_input_indices:
gy = None
elif must_reduce_y:
gy = -array_ops.reshape(math_ops.reduce_sum(x_grad, ry), sy)
else:
gy = -x_grad
return (gx, gy) | [
"def",
"_SquaredDifferenceGrad",
"(",
"op",
",",
"grad",
")",
":",
"x",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"y",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
"skip_input_indices",
"=",
"None",
"try",
":",
"skip_input_indices",
"=",
"op",
".",
"skip_input_indices",
"except",
"AttributeError",
":",
"# No gradient skipping, so do the full gradient computation",
"pass",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"grad",
"]",
")",
":",
"# The parens ensure that if grad is IndexedSlices, it'll get multiplied by",
"# Tensor (not a number like 2.0) which causes it to convert to Tensor.",
"x_grad",
"=",
"math_ops",
".",
"scalar_mul",
"(",
"2.0",
",",
"grad",
")",
"*",
"(",
"x",
"-",
"y",
")",
"if",
"(",
"isinstance",
"(",
"grad",
",",
"ops",
".",
"Tensor",
")",
"and",
"_ShapesFullySpecifiedAndEqual",
"(",
"x",
",",
"y",
",",
"grad",
")",
")",
":",
"return",
"x_grad",
",",
"-",
"x_grad",
"(",
"sx",
",",
"rx",
",",
"must_reduce_x",
")",
",",
"(",
"sy",
",",
"ry",
",",
"must_reduce_y",
")",
"=",
"(",
"SmartBroadcastGradientArgs",
"(",
"x",
",",
"y",
",",
"grad",
")",
")",
"if",
"skip_input_indices",
"is",
"not",
"None",
"and",
"0",
"in",
"skip_input_indices",
":",
"gx",
"=",
"None",
"elif",
"must_reduce_x",
":",
"gx",
"=",
"array_ops",
".",
"reshape",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"x_grad",
",",
"rx",
")",
",",
"sx",
")",
"else",
":",
"gx",
"=",
"x_grad",
"if",
"skip_input_indices",
"is",
"not",
"None",
"and",
"1",
"in",
"skip_input_indices",
":",
"gy",
"=",
"None",
"elif",
"must_reduce_y",
":",
"gy",
"=",
"-",
"array_ops",
".",
"reshape",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"x_grad",
",",
"ry",
")",
",",
"sy",
")",
"else",
":",
"gy",
"=",
"-",
"x_grad",
"return",
"(",
"gx",
",",
"gy",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_grad.py#L1604-L1640 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/externals/funcsigs.py | python | Signature.replace | (self, parameters=_void, return_annotation=_void) | return type(self)(parameters,
return_annotation=return_annotation) | Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy. | Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy. | [
"Creates",
"a",
"customized",
"copy",
"of",
"the",
"Signature",
".",
"Pass",
"parameters",
"and",
"/",
"or",
"return_annotation",
"arguments",
"to",
"override",
"them",
"in",
"the",
"new",
"copy",
"."
] | def replace(self, parameters=_void, return_annotation=_void):
'''Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
'''
if parameters is _void:
parameters = self.parameters.values()
if return_annotation is _void:
return_annotation = self._return_annotation
return type(self)(parameters,
return_annotation=return_annotation) | [
"def",
"replace",
"(",
"self",
",",
"parameters",
"=",
"_void",
",",
"return_annotation",
"=",
"_void",
")",
":",
"if",
"parameters",
"is",
"_void",
":",
"parameters",
"=",
"self",
".",
"parameters",
".",
"values",
"(",
")",
"if",
"return_annotation",
"is",
"_void",
":",
"return_annotation",
"=",
"self",
".",
"_return_annotation",
"return",
"type",
"(",
"self",
")",
"(",
"parameters",
",",
"return_annotation",
"=",
"return_annotation",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/externals/funcsigs.py#L596-L609 | |
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | third_party/Python/module/ptyprocess-0.6.0/ptyprocess/_fork_pty.py | python | fork_pty | () | return pid, parent_fd | This implements a substitute for the forkpty system call. This
should be more portable than the pty.fork() function. Specifically,
this should work on Solaris.
Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
resolve the issue with Python's pty.fork() not supporting Solaris,
particularly ssh. Based on patch to posixmodule.c authored by Noah
Spurrier::
http://mail.python.org/pipermail/python-dev/2003-May/035281.html | This implements a substitute for the forkpty system call. This
should be more portable than the pty.fork() function. Specifically,
this should work on Solaris. | [
"This",
"implements",
"a",
"substitute",
"for",
"the",
"forkpty",
"system",
"call",
".",
"This",
"should",
"be",
"more",
"portable",
"than",
"the",
"pty",
".",
"fork",
"()",
"function",
".",
"Specifically",
"this",
"should",
"work",
"on",
"Solaris",
"."
] | def fork_pty():
'''This implements a substitute for the forkpty system call. This
should be more portable than the pty.fork() function. Specifically,
this should work on Solaris.
Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
resolve the issue with Python's pty.fork() not supporting Solaris,
particularly ssh. Based on patch to posixmodule.c authored by Noah
Spurrier::
http://mail.python.org/pipermail/python-dev/2003-May/035281.html
'''
parent_fd, child_fd = os.openpty()
if parent_fd < 0 or child_fd < 0:
raise OSError("os.openpty() failed")
pid = os.fork()
if pid == CHILD:
# Child.
os.close(parent_fd)
pty_make_controlling_tty(child_fd)
os.dup2(child_fd, STDIN_FILENO)
os.dup2(child_fd, STDOUT_FILENO)
os.dup2(child_fd, STDERR_FILENO)
else:
# Parent.
os.close(child_fd)
return pid, parent_fd | [
"def",
"fork_pty",
"(",
")",
":",
"parent_fd",
",",
"child_fd",
"=",
"os",
".",
"openpty",
"(",
")",
"if",
"parent_fd",
"<",
"0",
"or",
"child_fd",
"<",
"0",
":",
"raise",
"OSError",
"(",
"\"os.openpty() failed\"",
")",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
"==",
"CHILD",
":",
"# Child.",
"os",
".",
"close",
"(",
"parent_fd",
")",
"pty_make_controlling_tty",
"(",
"child_fd",
")",
"os",
".",
"dup2",
"(",
"child_fd",
",",
"STDIN_FILENO",
")",
"os",
".",
"dup2",
"(",
"child_fd",
",",
"STDOUT_FILENO",
")",
"os",
".",
"dup2",
"(",
"child_fd",
",",
"STDERR_FILENO",
")",
"else",
":",
"# Parent.",
"os",
".",
"close",
"(",
"child_fd",
")",
"return",
"pid",
",",
"parent_fd"
] | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/_fork_pty.py#L9-L41 | |
Tencent/TNN | 7acca99f54c55747b415a4c57677403eebc7b706 | third_party/flatbuffers/grpc/examples/python/greeter/models/HelloReply.py | python | HelloReplyAddMessage | (builder, message) | return AddMessage(builder, message) | This method is deprecated. Please switch to AddMessage. | This method is deprecated. Please switch to AddMessage. | [
"This",
"method",
"is",
"deprecated",
".",
"Please",
"switch",
"to",
"AddMessage",
"."
] | def HelloReplyAddMessage(builder, message):
"""This method is deprecated. Please switch to AddMessage."""
return AddMessage(builder, message) | [
"def",
"HelloReplyAddMessage",
"(",
"builder",
",",
"message",
")",
":",
"return",
"AddMessage",
"(",
"builder",
",",
"message",
")"
] | https://github.com/Tencent/TNN/blob/7acca99f54c55747b415a4c57677403eebc7b706/third_party/flatbuffers/grpc/examples/python/greeter/models/HelloReply.py#L39-L41 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/math/se3.py | python | homogeneous | (T) | return [[R[0],R[3],R[6],t[0]],
[R[1],R[4],R[7],t[1]],
[R[2],R[5],R[8],t[2]],
[0.,0.,0.,1.]] | Returns the 4x4 homogeneous transform corresponding to T | Returns the 4x4 homogeneous transform corresponding to T | [
"Returns",
"the",
"4x4",
"homogeneous",
"transform",
"corresponding",
"to",
"T"
] | def homogeneous(T):
"""Returns the 4x4 homogeneous transform corresponding to T"""
(R,t) = T
return [[R[0],R[3],R[6],t[0]],
[R[1],R[4],R[7],t[1]],
[R[2],R[5],R[8],t[2]],
[0.,0.,0.,1.]] | [
"def",
"homogeneous",
"(",
"T",
")",
":",
"(",
"R",
",",
"t",
")",
"=",
"T",
"return",
"[",
"[",
"R",
"[",
"0",
"]",
",",
"R",
"[",
"3",
"]",
",",
"R",
"[",
"6",
"]",
",",
"t",
"[",
"0",
"]",
"]",
",",
"[",
"R",
"[",
"1",
"]",
",",
"R",
"[",
"4",
"]",
",",
"R",
"[",
"7",
"]",
",",
"t",
"[",
"1",
"]",
"]",
",",
"[",
"R",
"[",
"2",
"]",
",",
"R",
"[",
"5",
"]",
",",
"R",
"[",
"8",
"]",
",",
"t",
"[",
"2",
"]",
"]",
",",
"[",
"0.",
",",
"0.",
",",
"0.",
",",
"1.",
"]",
"]"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/se3.py#L67-L73 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/moosesqa/check_requirements.py | python | RequirementLogHelper._colorTestInfo | (req, filename, name, line) | return '{}:{}:{}\n'.format(filename, name, line) | Helper for creating first line of message with file:test:line information | Helper for creating first line of message with file:test:line information | [
"Helper",
"for",
"creating",
"first",
"line",
"of",
"message",
"with",
"file",
":",
"test",
":",
"line",
"information"
] | def _colorTestInfo(req, filename, name, line):
"""Helper for creating first line of message with file:test:line information"""
filename = filename or req.filename
name = mooseutils.colorText(name or req.name, 'MAGENTA', colored=RequirementLogHelper.COLOR_TEXT)
line = mooseutils.colorText(str(line if (line is not None) else req.line), 'CYAN', colored=RequirementLogHelper.COLOR_TEXT)
return '{}:{}:{}\n'.format(filename, name, line) | [
"def",
"_colorTestInfo",
"(",
"req",
",",
"filename",
",",
"name",
",",
"line",
")",
":",
"filename",
"=",
"filename",
"or",
"req",
".",
"filename",
"name",
"=",
"mooseutils",
".",
"colorText",
"(",
"name",
"or",
"req",
".",
"name",
",",
"'MAGENTA'",
",",
"colored",
"=",
"RequirementLogHelper",
".",
"COLOR_TEXT",
")",
"line",
"=",
"mooseutils",
".",
"colorText",
"(",
"str",
"(",
"line",
"if",
"(",
"line",
"is",
"not",
"None",
")",
"else",
"req",
".",
"line",
")",
",",
"'CYAN'",
",",
"colored",
"=",
"RequirementLogHelper",
".",
"COLOR_TEXT",
")",
"return",
"'{}:{}:{}\\n'",
".",
"format",
"(",
"filename",
",",
"name",
",",
"line",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/moosesqa/check_requirements.py#L30-L35 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py | python | NDFrame.add_prefix | (self: FrameOrSeries, prefix: str) | return self.rename(**mapper) | Prefix labels with string `prefix`.
For Series, the row labels are prefixed.
For DataFrame, the column labels are prefixed.
Parameters
----------
prefix : str
The string to add before each label.
Returns
-------
Series or DataFrame
New Series or DataFrame with updated labels.
See Also
--------
Series.add_suffix: Suffix row labels with string `suffix`.
DataFrame.add_suffix: Suffix column labels with string `suffix`.
Examples
--------
>>> s = pd.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.add_prefix('item_')
item_0 1
item_1 2
item_2 3
item_3 4
dtype: int64
>>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
>>> df
A B
0 1 3
1 2 4
2 3 5
3 4 6
>>> df.add_prefix('col_')
col_A col_B
0 1 3
1 2 4
2 3 5
3 4 6 | Prefix labels with string `prefix`. | [
"Prefix",
"labels",
"with",
"string",
"prefix",
"."
] | def add_prefix(self: FrameOrSeries, prefix: str) -> FrameOrSeries:
"""
Prefix labels with string `prefix`.
For Series, the row labels are prefixed.
For DataFrame, the column labels are prefixed.
Parameters
----------
prefix : str
The string to add before each label.
Returns
-------
Series or DataFrame
New Series or DataFrame with updated labels.
See Also
--------
Series.add_suffix: Suffix row labels with string `suffix`.
DataFrame.add_suffix: Suffix column labels with string `suffix`.
Examples
--------
>>> s = pd.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.add_prefix('item_')
item_0 1
item_1 2
item_2 3
item_3 4
dtype: int64
>>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
>>> df
A B
0 1 3
1 2 4
2 3 5
3 4 6
>>> df.add_prefix('col_')
col_A col_B
0 1 3
1 2 4
2 3 5
3 4 6
"""
f = functools.partial("{prefix}{}".format, prefix=prefix)
mapper = {self._info_axis_name: f}
return self.rename(**mapper) | [
"def",
"add_prefix",
"(",
"self",
":",
"FrameOrSeries",
",",
"prefix",
":",
"str",
")",
"->",
"FrameOrSeries",
":",
"f",
"=",
"functools",
".",
"partial",
"(",
"\"{prefix}{}\"",
".",
"format",
",",
"prefix",
"=",
"prefix",
")",
"mapper",
"=",
"{",
"self",
".",
"_info_axis_name",
":",
"f",
"}",
"return",
"self",
".",
"rename",
"(",
"*",
"*",
"mapper",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py#L4015-L4072 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/framemanager.py | python | AuiManager.DoDropNonFloatingPane | (self, docks, panes, target, pt) | return self.ProcessDockResult(target, drop) | Handles the situation in which the dropped pane is not floating.
:param `docks`: a list of :class:`AuiDockInfo` classes;
:param `panes`: a list of :class:`AuiPaneInfo` instances;
:param AuiPaneInfo `target`: the target pane containing the toolbar;
:param Point `pt`: a mouse position to check for a drop operation. | Handles the situation in which the dropped pane is not floating. | [
"Handles",
"the",
"situation",
"in",
"which",
"the",
"dropped",
"pane",
"is",
"not",
"floating",
"."
] | def DoDropNonFloatingPane(self, docks, panes, target, pt):
"""
Handles the situation in which the dropped pane is not floating.
:param `docks`: a list of :class:`AuiDockInfo` classes;
:param `panes`: a list of :class:`AuiPaneInfo` instances;
:param AuiPaneInfo `target`: the target pane containing the toolbar;
:param Point `pt`: a mouse position to check for a drop operation.
"""
screenPt = self._frame.ClientToScreen(pt)
clientSize = self._frame.GetClientSize()
frameRect = GetInternalFrameRect(self._frame, self._docks)
drop = self.CopyTarget(target)
# The result should always be shown
drop.Show()
part = self.HitTest(pt.x, pt.y)
if not part:
return False, target
if part.type == AuiDockUIPart.typeDockSizer:
if len(part.dock.panes) != 1:
return False, target
part = self.GetPanePart(part.dock.panes[0].window)
if not part:
return False, target
if not part.pane:
return False, target
part = self.GetPanePart(part.pane.window)
if not part:
return False, target
insert_dock_row = False
insert_row = part.pane.dock_row
insert_dir = part.pane.dock_direction
insert_layer = part.pane.dock_layer
direction = part.pane.dock_direction
if direction == AUI_DOCK_TOP:
if pt.y >= part.rect.y and pt.y < part.rect.y+auiInsertRowPixels:
insert_dock_row = True
elif direction == AUI_DOCK_BOTTOM:
if pt.y > part.rect.y+part.rect.height-auiInsertRowPixels and \
pt.y <= part.rect.y + part.rect.height:
insert_dock_row = True
elif direction == AUI_DOCK_LEFT:
if pt.x >= part.rect.x and pt.x < part.rect.x+auiInsertRowPixels:
insert_dock_row = True
elif direction == AUI_DOCK_RIGHT:
if pt.x > part.rect.x+part.rect.width-auiInsertRowPixels and \
pt.x <= part.rect.x+part.rect.width:
insert_dock_row = True
elif direction == AUI_DOCK_CENTER:
# "new row pixels" will be set to the default, but
# must never exceed 20% of the window size
new_row_pixels_x = auiNewRowPixels
new_row_pixels_y = auiNewRowPixels
if new_row_pixels_x > (part.rect.width*20)/100:
new_row_pixels_x = (part.rect.width*20)/100
if new_row_pixels_y > (part.rect.height*20)/100:
new_row_pixels_y = (part.rect.height*20)/100
# determine if the mouse pointer is in a location that
# will cause a new row to be inserted. The hot spot positions
# are along the borders of the center pane
insert_layer = 0
insert_dock_row = True
pr = part.rect
if pt.x >= pr.x and pt.x < pr.x + new_row_pixels_x:
insert_dir = AUI_DOCK_LEFT
elif pt.y >= pr.y and pt.y < pr.y + new_row_pixels_y:
insert_dir = AUI_DOCK_TOP
elif pt.x >= pr.x + pr.width - new_row_pixels_x and pt.x < pr.x + pr.width:
insert_dir = AUI_DOCK_RIGHT
elif pt.y >= pr.y+ pr.height - new_row_pixels_y and pt.y < pr.y + pr.height:
insert_dir = AUI_DOCK_BOTTOM
else:
return False, target
insert_row = GetMaxRow(panes, insert_dir, insert_layer) + 1
if insert_dock_row:
panes = DoInsertDockRow(panes, insert_dir, insert_layer, insert_row)
drop.Dock().Direction(insert_dir).Layer(insert_layer). \
Row(insert_row).Position(0)
return self.ProcessDockResult(target, drop)
# determine the mouse offset and the pane size, both in the
# direction of the dock itself, and perpendicular to the dock
if part.orientation == wx.VERTICAL:
offset = pt.y - part.rect.y
size = part.rect.GetHeight()
else:
offset = pt.x - part.rect.x
size = part.rect.GetWidth()
drop_position = part.pane.dock_pos
# if we are in the top/left part of the pane,
# insert the pane before the pane being hovered over
if offset <= size/2:
drop_position = part.pane.dock_pos
panes = DoInsertPane(panes,
part.pane.dock_direction,
part.pane.dock_layer,
part.pane.dock_row,
part.pane.dock_pos)
# if we are in the bottom/right part of the pane,
# insert the pane before the pane being hovered over
if offset > size/2:
drop_position = part.pane.dock_pos+1
panes = DoInsertPane(panes,
part.pane.dock_direction,
part.pane.dock_layer,
part.pane.dock_row,
part.pane.dock_pos+1)
drop.Dock(). \
Direction(part.dock.dock_direction). \
Layer(part.dock.dock_layer).Row(part.dock.dock_row). \
Position(drop_position)
return self.ProcessDockResult(target, drop) | [
"def",
"DoDropNonFloatingPane",
"(",
"self",
",",
"docks",
",",
"panes",
",",
"target",
",",
"pt",
")",
":",
"screenPt",
"=",
"self",
".",
"_frame",
".",
"ClientToScreen",
"(",
"pt",
")",
"clientSize",
"=",
"self",
".",
"_frame",
".",
"GetClientSize",
"(",
")",
"frameRect",
"=",
"GetInternalFrameRect",
"(",
"self",
".",
"_frame",
",",
"self",
".",
"_docks",
")",
"drop",
"=",
"self",
".",
"CopyTarget",
"(",
"target",
")",
"# The result should always be shown",
"drop",
".",
"Show",
"(",
")",
"part",
"=",
"self",
".",
"HitTest",
"(",
"pt",
".",
"x",
",",
"pt",
".",
"y",
")",
"if",
"not",
"part",
":",
"return",
"False",
",",
"target",
"if",
"part",
".",
"type",
"==",
"AuiDockUIPart",
".",
"typeDockSizer",
":",
"if",
"len",
"(",
"part",
".",
"dock",
".",
"panes",
")",
"!=",
"1",
":",
"return",
"False",
",",
"target",
"part",
"=",
"self",
".",
"GetPanePart",
"(",
"part",
".",
"dock",
".",
"panes",
"[",
"0",
"]",
".",
"window",
")",
"if",
"not",
"part",
":",
"return",
"False",
",",
"target",
"if",
"not",
"part",
".",
"pane",
":",
"return",
"False",
",",
"target",
"part",
"=",
"self",
".",
"GetPanePart",
"(",
"part",
".",
"pane",
".",
"window",
")",
"if",
"not",
"part",
":",
"return",
"False",
",",
"target",
"insert_dock_row",
"=",
"False",
"insert_row",
"=",
"part",
".",
"pane",
".",
"dock_row",
"insert_dir",
"=",
"part",
".",
"pane",
".",
"dock_direction",
"insert_layer",
"=",
"part",
".",
"pane",
".",
"dock_layer",
"direction",
"=",
"part",
".",
"pane",
".",
"dock_direction",
"if",
"direction",
"==",
"AUI_DOCK_TOP",
":",
"if",
"pt",
".",
"y",
">=",
"part",
".",
"rect",
".",
"y",
"and",
"pt",
".",
"y",
"<",
"part",
".",
"rect",
".",
"y",
"+",
"auiInsertRowPixels",
":",
"insert_dock_row",
"=",
"True",
"elif",
"direction",
"==",
"AUI_DOCK_BOTTOM",
":",
"if",
"pt",
".",
"y",
">",
"part",
".",
"rect",
".",
"y",
"+",
"part",
".",
"rect",
".",
"height",
"-",
"auiInsertRowPixels",
"and",
"pt",
".",
"y",
"<=",
"part",
".",
"rect",
".",
"y",
"+",
"part",
".",
"rect",
".",
"height",
":",
"insert_dock_row",
"=",
"True",
"elif",
"direction",
"==",
"AUI_DOCK_LEFT",
":",
"if",
"pt",
".",
"x",
">=",
"part",
".",
"rect",
".",
"x",
"and",
"pt",
".",
"x",
"<",
"part",
".",
"rect",
".",
"x",
"+",
"auiInsertRowPixels",
":",
"insert_dock_row",
"=",
"True",
"elif",
"direction",
"==",
"AUI_DOCK_RIGHT",
":",
"if",
"pt",
".",
"x",
">",
"part",
".",
"rect",
".",
"x",
"+",
"part",
".",
"rect",
".",
"width",
"-",
"auiInsertRowPixels",
"and",
"pt",
".",
"x",
"<=",
"part",
".",
"rect",
".",
"x",
"+",
"part",
".",
"rect",
".",
"width",
":",
"insert_dock_row",
"=",
"True",
"elif",
"direction",
"==",
"AUI_DOCK_CENTER",
":",
"# \"new row pixels\" will be set to the default, but",
"# must never exceed 20% of the window size",
"new_row_pixels_x",
"=",
"auiNewRowPixels",
"new_row_pixels_y",
"=",
"auiNewRowPixels",
"if",
"new_row_pixels_x",
">",
"(",
"part",
".",
"rect",
".",
"width",
"*",
"20",
")",
"/",
"100",
":",
"new_row_pixels_x",
"=",
"(",
"part",
".",
"rect",
".",
"width",
"*",
"20",
")",
"/",
"100",
"if",
"new_row_pixels_y",
">",
"(",
"part",
".",
"rect",
".",
"height",
"*",
"20",
")",
"/",
"100",
":",
"new_row_pixels_y",
"=",
"(",
"part",
".",
"rect",
".",
"height",
"*",
"20",
")",
"/",
"100",
"# determine if the mouse pointer is in a location that",
"# will cause a new row to be inserted. The hot spot positions",
"# are along the borders of the center pane",
"insert_layer",
"=",
"0",
"insert_dock_row",
"=",
"True",
"pr",
"=",
"part",
".",
"rect",
"if",
"pt",
".",
"x",
">=",
"pr",
".",
"x",
"and",
"pt",
".",
"x",
"<",
"pr",
".",
"x",
"+",
"new_row_pixels_x",
":",
"insert_dir",
"=",
"AUI_DOCK_LEFT",
"elif",
"pt",
".",
"y",
">=",
"pr",
".",
"y",
"and",
"pt",
".",
"y",
"<",
"pr",
".",
"y",
"+",
"new_row_pixels_y",
":",
"insert_dir",
"=",
"AUI_DOCK_TOP",
"elif",
"pt",
".",
"x",
">=",
"pr",
".",
"x",
"+",
"pr",
".",
"width",
"-",
"new_row_pixels_x",
"and",
"pt",
".",
"x",
"<",
"pr",
".",
"x",
"+",
"pr",
".",
"width",
":",
"insert_dir",
"=",
"AUI_DOCK_RIGHT",
"elif",
"pt",
".",
"y",
">=",
"pr",
".",
"y",
"+",
"pr",
".",
"height",
"-",
"new_row_pixels_y",
"and",
"pt",
".",
"y",
"<",
"pr",
".",
"y",
"+",
"pr",
".",
"height",
":",
"insert_dir",
"=",
"AUI_DOCK_BOTTOM",
"else",
":",
"return",
"False",
",",
"target",
"insert_row",
"=",
"GetMaxRow",
"(",
"panes",
",",
"insert_dir",
",",
"insert_layer",
")",
"+",
"1",
"if",
"insert_dock_row",
":",
"panes",
"=",
"DoInsertDockRow",
"(",
"panes",
",",
"insert_dir",
",",
"insert_layer",
",",
"insert_row",
")",
"drop",
".",
"Dock",
"(",
")",
".",
"Direction",
"(",
"insert_dir",
")",
".",
"Layer",
"(",
"insert_layer",
")",
".",
"Row",
"(",
"insert_row",
")",
".",
"Position",
"(",
"0",
")",
"return",
"self",
".",
"ProcessDockResult",
"(",
"target",
",",
"drop",
")",
"# determine the mouse offset and the pane size, both in the",
"# direction of the dock itself, and perpendicular to the dock",
"if",
"part",
".",
"orientation",
"==",
"wx",
".",
"VERTICAL",
":",
"offset",
"=",
"pt",
".",
"y",
"-",
"part",
".",
"rect",
".",
"y",
"size",
"=",
"part",
".",
"rect",
".",
"GetHeight",
"(",
")",
"else",
":",
"offset",
"=",
"pt",
".",
"x",
"-",
"part",
".",
"rect",
".",
"x",
"size",
"=",
"part",
".",
"rect",
".",
"GetWidth",
"(",
")",
"drop_position",
"=",
"part",
".",
"pane",
".",
"dock_pos",
"# if we are in the top/left part of the pane,",
"# insert the pane before the pane being hovered over",
"if",
"offset",
"<=",
"size",
"/",
"2",
":",
"drop_position",
"=",
"part",
".",
"pane",
".",
"dock_pos",
"panes",
"=",
"DoInsertPane",
"(",
"panes",
",",
"part",
".",
"pane",
".",
"dock_direction",
",",
"part",
".",
"pane",
".",
"dock_layer",
",",
"part",
".",
"pane",
".",
"dock_row",
",",
"part",
".",
"pane",
".",
"dock_pos",
")",
"# if we are in the bottom/right part of the pane,",
"# insert the pane before the pane being hovered over",
"if",
"offset",
">",
"size",
"/",
"2",
":",
"drop_position",
"=",
"part",
".",
"pane",
".",
"dock_pos",
"+",
"1",
"panes",
"=",
"DoInsertPane",
"(",
"panes",
",",
"part",
".",
"pane",
".",
"dock_direction",
",",
"part",
".",
"pane",
".",
"dock_layer",
",",
"part",
".",
"pane",
".",
"dock_row",
",",
"part",
".",
"pane",
".",
"dock_pos",
"+",
"1",
")",
"drop",
".",
"Dock",
"(",
")",
".",
"Direction",
"(",
"part",
".",
"dock",
".",
"dock_direction",
")",
".",
"Layer",
"(",
"part",
".",
"dock",
".",
"dock_layer",
")",
".",
"Row",
"(",
"part",
".",
"dock",
".",
"dock_row",
")",
".",
"Position",
"(",
"drop_position",
")",
"return",
"self",
".",
"ProcessDockResult",
"(",
"target",
",",
"drop",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L7825-L7975 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py | python | _CudnnRNNNoInputC.__init__ | (self,
num_layers,
num_units,
input_size,
input_mode="linear_input",
direction=CUDNN_RNN_UNIDIRECTION,
dropout=0.,
seed=0) | Creates a Cudnn RNN model from model without hidden-state C.
Args:
num_layers: the number of layers for the RNN model.
num_units: the number of units within the RNN model.
input_size: the size of the input, it could be different from the
num_units.
input_mode: indicate whether there is a linear projection between the
input and The actual computation before the first layer. It could be
'skip_input', 'linear_input' or 'auto_select'.
'skip_input' is only allowed when input_size == num_units;
'auto_select' implies 'skip_input' when input_size == num_units;
otherwise, it implies 'linear_input'.
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
seed: the seed used for initializing dropout.
Raises:
ValueError: if direction is not 'unidirectional' or 'bidirectional'. | Creates a Cudnn RNN model from model without hidden-state C. | [
"Creates",
"a",
"Cudnn",
"RNN",
"model",
"from",
"model",
"without",
"hidden",
"-",
"state",
"C",
"."
] | def __init__(self,
num_layers,
num_units,
input_size,
input_mode="linear_input",
direction=CUDNN_RNN_UNIDIRECTION,
dropout=0.,
seed=0):
"""Creates a Cudnn RNN model from model without hidden-state C.
Args:
num_layers: the number of layers for the RNN model.
num_units: the number of units within the RNN model.
input_size: the size of the input, it could be different from the
num_units.
input_mode: indicate whether there is a linear projection between the
input and The actual computation before the first layer. It could be
'skip_input', 'linear_input' or 'auto_select'.
'skip_input' is only allowed when input_size == num_units;
'auto_select' implies 'skip_input' when input_size == num_units;
otherwise, it implies 'linear_input'.
direction: the direction model that the model operates. Could be either
'unidirectional' or 'bidirectional'
dropout: whether to enable dropout. With it is 0, dropout is disabled.
seed: the seed used for initializing dropout.
Raises:
ValueError: if direction is not 'unidirectional' or 'bidirectional'.
"""
if direction not in (CUDNN_RNN_UNIDIRECTION, CUDNN_RNN_BIDIRECTION):
raise ValueError("Invalid direction: %s", direction)
super(_CudnnRNNNoInputC, self).__init__(
self._rnn_mode,
num_layers,
num_units,
input_size,
input_mode=input_mode,
direction=direction,
dropout=dropout,
seed=seed) | [
"def",
"__init__",
"(",
"self",
",",
"num_layers",
",",
"num_units",
",",
"input_size",
",",
"input_mode",
"=",
"\"linear_input\"",
",",
"direction",
"=",
"CUDNN_RNN_UNIDIRECTION",
",",
"dropout",
"=",
"0.",
",",
"seed",
"=",
"0",
")",
":",
"if",
"direction",
"not",
"in",
"(",
"CUDNN_RNN_UNIDIRECTION",
",",
"CUDNN_RNN_BIDIRECTION",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid direction: %s\"",
",",
"direction",
")",
"super",
"(",
"_CudnnRNNNoInputC",
",",
"self",
")",
".",
"__init__",
"(",
"self",
".",
"_rnn_mode",
",",
"num_layers",
",",
"num_units",
",",
"input_size",
",",
"input_mode",
"=",
"input_mode",
",",
"direction",
"=",
"direction",
",",
"dropout",
"=",
"dropout",
",",
"seed",
"=",
"seed",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py#L751-L792 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/excel/_openpyxl.py | python | _OpenpyxlWriter._convert_to_alignment | (cls, alignment_dict) | return Alignment(**alignment_dict) | Convert ``alignment_dict`` to an openpyxl v2 Alignment object.
Parameters
----------
alignment_dict : dict
A dict with zero or more of the following keys (or their synonyms).
'horizontal'
'vertical'
'text_rotation'
'wrap_text'
'shrink_to_fit'
'indent'
Returns
-------
alignment : openpyxl.styles.Alignment | Convert ``alignment_dict`` to an openpyxl v2 Alignment object. | [
"Convert",
"alignment_dict",
"to",
"an",
"openpyxl",
"v2",
"Alignment",
"object",
"."
] | def _convert_to_alignment(cls, alignment_dict):
"""
Convert ``alignment_dict`` to an openpyxl v2 Alignment object.
Parameters
----------
alignment_dict : dict
A dict with zero or more of the following keys (or their synonyms).
'horizontal'
'vertical'
'text_rotation'
'wrap_text'
'shrink_to_fit'
'indent'
Returns
-------
alignment : openpyxl.styles.Alignment
"""
from openpyxl.styles import Alignment
return Alignment(**alignment_dict) | [
"def",
"_convert_to_alignment",
"(",
"cls",
",",
"alignment_dict",
")",
":",
"from",
"openpyxl",
".",
"styles",
"import",
"Alignment",
"return",
"Alignment",
"(",
"*",
"*",
"alignment_dict",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/excel/_openpyxl.py#L350-L371 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/sparse/linalg/_expm_multiply.py | python | LazyOperatorNormInfo.set_scale | (self,scale) | Set the scale parameter. | Set the scale parameter. | [
"Set",
"the",
"scale",
"parameter",
"."
] | def set_scale(self,scale):
"""
Set the scale parameter.
"""
self._scale = scale | [
"def",
"set_scale",
"(",
"self",
",",
"scale",
")",
":",
"self",
".",
"_scale",
"=",
"scale"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/linalg/_expm_multiply.py#L338-L342 | ||
plasma-umass/Mesh | ad5947577a2dce68eb79e2d6ec8507ef992d2859 | theory/experiment.py | python | experiment | (stringSet = "random", length = 16, numStrings = 100, x = range(1,8), filename = None, meshingList = None, boundList = None, reps = 10, time = False) | return means, std_devs, tmeans, tstd_devs, bound_results | Performs random meshing experiments on a given list of meshing algorithms. Can optionally compute & record runtime of these algorithms
as well as the size of their computed meshings. Must specify properties of random string set (length of strings, number of strings, range of
occupancy values, etc. | Performs random meshing experiments on a given list of meshing algorithms. Can optionally compute & record runtime of these algorithms
as well as the size of their computed meshings. Must specify properties of random string set (length of strings, number of strings, range of
occupancy values, etc. | [
"Performs",
"random",
"meshing",
"experiments",
"on",
"a",
"given",
"list",
"of",
"meshing",
"algorithms",
".",
"Can",
"optionally",
"compute",
"&",
"record",
"runtime",
"of",
"these",
"algorithms",
"as",
"well",
"as",
"the",
"size",
"of",
"their",
"computed",
"meshings",
".",
"Must",
"specify",
"properties",
"of",
"random",
"string",
"set",
"(",
"length",
"of",
"strings",
"number",
"of",
"strings",
"range",
"of",
"occupancy",
"values",
"etc",
"."
] | def experiment(stringSet = "random", length = 16, numStrings = 100, x = range(1,8), filename = None, meshingList = None, boundList = None, reps = 10, time = False):
"""Performs random meshing experiments on a given list of meshing algorithms. Can optionally compute & record runtime of these algorithms
as well as the size of their computed meshings. Must specify properties of random string set (length of strings, number of strings, range of
occupancy values, etc."""
dim = len(x)
meshers = mesherManager(meshingList)
tmeans = None
tstd_devs = None
bound_results = None
if time:
tmeans = np.empty((dim, len(meshingList)))
tstd_devs = np.empty((dim, len(meshingList)))
if boundList:
bounds = boundGenerator(boundList)
bound_results = np.empty((dim, len(boundList)))
means = np.empty((dim, len(meshingList)))
std_devs = np.empty((dim, len(meshingList)))
for i in range(dim):
result = repeatedTrials(stringSet = stringSet, length = length, numStrings = numStrings, numOnes = x[i], meshers = meshers, reps = reps, time = time)
means[i] = np.asarray(result[0])
std_devs[i] = np.asarray(result[1])
if time:
tmeans[i] = np.asarray(result[2])
tstd_devs[i] = np.asarray(result[3])
if boundList:
results = computeBounds(bounds, length, numStrings, x[i])
bound_results[i] = np.asarray(results)
return means, std_devs, tmeans, tstd_devs, bound_results | [
"def",
"experiment",
"(",
"stringSet",
"=",
"\"random\"",
",",
"length",
"=",
"16",
",",
"numStrings",
"=",
"100",
",",
"x",
"=",
"range",
"(",
"1",
",",
"8",
")",
",",
"filename",
"=",
"None",
",",
"meshingList",
"=",
"None",
",",
"boundList",
"=",
"None",
",",
"reps",
"=",
"10",
",",
"time",
"=",
"False",
")",
":",
"dim",
"=",
"len",
"(",
"x",
")",
"meshers",
"=",
"mesherManager",
"(",
"meshingList",
")",
"tmeans",
"=",
"None",
"tstd_devs",
"=",
"None",
"bound_results",
"=",
"None",
"if",
"time",
":",
"tmeans",
"=",
"np",
".",
"empty",
"(",
"(",
"dim",
",",
"len",
"(",
"meshingList",
")",
")",
")",
"tstd_devs",
"=",
"np",
".",
"empty",
"(",
"(",
"dim",
",",
"len",
"(",
"meshingList",
")",
")",
")",
"if",
"boundList",
":",
"bounds",
"=",
"boundGenerator",
"(",
"boundList",
")",
"bound_results",
"=",
"np",
".",
"empty",
"(",
"(",
"dim",
",",
"len",
"(",
"boundList",
")",
")",
")",
"means",
"=",
"np",
".",
"empty",
"(",
"(",
"dim",
",",
"len",
"(",
"meshingList",
")",
")",
")",
"std_devs",
"=",
"np",
".",
"empty",
"(",
"(",
"dim",
",",
"len",
"(",
"meshingList",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"dim",
")",
":",
"result",
"=",
"repeatedTrials",
"(",
"stringSet",
"=",
"stringSet",
",",
"length",
"=",
"length",
",",
"numStrings",
"=",
"numStrings",
",",
"numOnes",
"=",
"x",
"[",
"i",
"]",
",",
"meshers",
"=",
"meshers",
",",
"reps",
"=",
"reps",
",",
"time",
"=",
"time",
")",
"means",
"[",
"i",
"]",
"=",
"np",
".",
"asarray",
"(",
"result",
"[",
"0",
"]",
")",
"std_devs",
"[",
"i",
"]",
"=",
"np",
".",
"asarray",
"(",
"result",
"[",
"1",
"]",
")",
"if",
"time",
":",
"tmeans",
"[",
"i",
"]",
"=",
"np",
".",
"asarray",
"(",
"result",
"[",
"2",
"]",
")",
"tstd_devs",
"[",
"i",
"]",
"=",
"np",
".",
"asarray",
"(",
"result",
"[",
"3",
"]",
")",
"if",
"boundList",
":",
"results",
"=",
"computeBounds",
"(",
"bounds",
",",
"length",
",",
"numStrings",
",",
"x",
"[",
"i",
"]",
")",
"bound_results",
"[",
"i",
"]",
"=",
"np",
".",
"asarray",
"(",
"results",
")",
"return",
"means",
",",
"std_devs",
",",
"tmeans",
",",
"tstd_devs",
",",
"bound_results"
] | https://github.com/plasma-umass/Mesh/blob/ad5947577a2dce68eb79e2d6ec8507ef992d2859/theory/experiment.py#L148-L177 | |
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | dmlc-core/tracker/dmlc_tracker/local.py | python | submit | (args) | Submit function of local jobs. | Submit function of local jobs. | [
"Submit",
"function",
"of",
"local",
"jobs",
"."
] | def submit(args):
"""Submit function of local jobs."""
def mthread_submit(nworker, nserver, envs):
"""
customized submit script, that submit nslave jobs, each must contain args as parameter
note this can be a lambda function containing additional parameters in input
Parameters
----------
nworker: number of slave process to start up
nserver: number of server nodes to start up
envs: enviroment variables to be added to the starting programs
"""
procs = {}
for i in range(nworker + nserver):
if i < nworker:
role = 'worker'
else:
role = 'server'
procs[i] = Thread(target=exec_cmd, args=(args.command, role, i, envs))
procs[i].setDaemon(True)
procs[i].start()
# call submit, with nslave, the commands to run each job and submit function
tracker.submit(args.num_workers, args.num_servers, fun_submit=mthread_submit,
pscmd=(' '.join(args.command))) | [
"def",
"submit",
"(",
"args",
")",
":",
"def",
"mthread_submit",
"(",
"nworker",
",",
"nserver",
",",
"envs",
")",
":",
"\"\"\"\n customized submit script, that submit nslave jobs, each must contain args as parameter\n note this can be a lambda function containing additional parameters in input\n\n Parameters\n ----------\n nworker: number of slave process to start up\n nserver: number of server nodes to start up\n envs: enviroment variables to be added to the starting programs\n \"\"\"",
"procs",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"nworker",
"+",
"nserver",
")",
":",
"if",
"i",
"<",
"nworker",
":",
"role",
"=",
"'worker'",
"else",
":",
"role",
"=",
"'server'",
"procs",
"[",
"i",
"]",
"=",
"Thread",
"(",
"target",
"=",
"exec_cmd",
",",
"args",
"=",
"(",
"args",
".",
"command",
",",
"role",
",",
"i",
",",
"envs",
")",
")",
"procs",
"[",
"i",
"]",
".",
"setDaemon",
"(",
"True",
")",
"procs",
"[",
"i",
"]",
".",
"start",
"(",
")",
"# call submit, with nslave, the commands to run each job and submit function",
"tracker",
".",
"submit",
"(",
"args",
".",
"num_workers",
",",
"args",
".",
"num_servers",
",",
"fun_submit",
"=",
"mthread_submit",
",",
"pscmd",
"=",
"(",
"' '",
".",
"join",
"(",
"args",
".",
"command",
")",
")",
")"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/dmlc-core/tracker/dmlc_tracker/local.py#L58-L83 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | toolkit/crashreporter/tools/symbolstore.py | python | VCSFileInfo.GetFilename | (self) | This method should return the repository-specific filename for the
file or 'None' on failure. | This method should return the repository-specific filename for the
file or 'None' on failure. | [
"This",
"method",
"should",
"return",
"the",
"repository",
"-",
"specific",
"filename",
"for",
"the",
"file",
"or",
"None",
"on",
"failure",
"."
] | def GetFilename(self):
""" This method should return the repository-specific filename for the
file or 'None' on failure. """
raise NotImplementedError | [
"def",
"GetFilename",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/toolkit/crashreporter/tools/symbolstore.py#L111-L114 | ||
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Tool/mslink.py | python | embedManifestDllCheck | (target, source, env) | return 0 | Function run by embedManifestDllCheckAction to check for existence of manifest
and other conditions, and embed the manifest by calling embedManifestDllAction if so. | Function run by embedManifestDllCheckAction to check for existence of manifest
and other conditions, and embed the manifest by calling embedManifestDllAction if so. | [
"Function",
"run",
"by",
"embedManifestDllCheckAction",
"to",
"check",
"for",
"existence",
"of",
"manifest",
"and",
"other",
"conditions",
"and",
"embed",
"the",
"manifest",
"by",
"calling",
"embedManifestDllAction",
"if",
"so",
"."
] | def embedManifestDllCheck(target, source, env):
"""Function run by embedManifestDllCheckAction to check for existence of manifest
and other conditions, and embed the manifest by calling embedManifestDllAction if so."""
if env.get('WINDOWS_EMBED_MANIFEST', 0):
manifestSrc = target[0].get_abspath() + '.manifest'
if os.path.exists(manifestSrc):
ret = embedManifestDllAction([target[0]], None, env)
if ret:
raise SCons.Errors.UserError("Unable to embed manifest into %s" % (target[0]))
return ret
else:
print('(embed: no %s.manifest found; not embedding.)'%str(target[0]))
return 0 | [
"def",
"embedManifestDllCheck",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"if",
"env",
".",
"get",
"(",
"'WINDOWS_EMBED_MANIFEST'",
",",
"0",
")",
":",
"manifestSrc",
"=",
"target",
"[",
"0",
"]",
".",
"get_abspath",
"(",
")",
"+",
"'.manifest'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"manifestSrc",
")",
":",
"ret",
"=",
"embedManifestDllAction",
"(",
"[",
"target",
"[",
"0",
"]",
"]",
",",
"None",
",",
"env",
")",
"if",
"ret",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"\"Unable to embed manifest into %s\"",
"%",
"(",
"target",
"[",
"0",
"]",
")",
")",
"return",
"ret",
"else",
":",
"print",
"(",
"'(embed: no %s.manifest found; not embedding.)'",
"%",
"str",
"(",
"target",
"[",
"0",
"]",
")",
")",
"return",
"0"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Tool/mslink.py#L212-L224 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | clang/bindings/python/clang/cindex.py | python | Cursor.enum_type | (self) | return self._enum_type | Return the integer type of an enum declaration.
Returns a Type corresponding to an integer. If the cursor is not for an
enum, this raises. | Return the integer type of an enum declaration. | [
"Return",
"the",
"integer",
"type",
"of",
"an",
"enum",
"declaration",
"."
] | def enum_type(self):
"""Return the integer type of an enum declaration.
Returns a Type corresponding to an integer. If the cursor is not for an
enum, this raises.
"""
if not hasattr(self, '_enum_type'):
assert self.kind == CursorKind.ENUM_DECL
self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
return self._enum_type | [
"def",
"enum_type",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_enum_type'",
")",
":",
"assert",
"self",
".",
"kind",
"==",
"CursorKind",
".",
"ENUM_DECL",
"self",
".",
"_enum_type",
"=",
"conf",
".",
"lib",
".",
"clang_getEnumDeclIntegerType",
"(",
"self",
")",
"return",
"self",
".",
"_enum_type"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/bindings/python/clang/cindex.py#L1702-L1712 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py | python | Wm.wm_attributes | (self, *args) | return self.tk.call(args) | This subcommand returns or sets platform specific attributes
The first form returns a list of the platform specific flags and
their values. The second form returns the value for the specific
option. The third form sets one or more of the values. The values
are as follows:
On Windows, -disabled gets or sets whether the window is in a
disabled state. -toolwindow gets or sets the style of the window
to toolwindow (as defined in the MSDN). -topmost gets or sets
whether this is a topmost window (displays above all other
windows).
On Macintosh, XXXXX
On Unix, there are currently no special attribute values. | This subcommand returns or sets platform specific attributes | [
"This",
"subcommand",
"returns",
"or",
"sets",
"platform",
"specific",
"attributes"
] | def wm_attributes(self, *args):
"""This subcommand returns or sets platform specific attributes
The first form returns a list of the platform specific flags and
their values. The second form returns the value for the specific
option. The third form sets one or more of the values. The values
are as follows:
On Windows, -disabled gets or sets whether the window is in a
disabled state. -toolwindow gets or sets the style of the window
to toolwindow (as defined in the MSDN). -topmost gets or sets
whether this is a topmost window (displays above all other
windows).
On Macintosh, XXXXX
On Unix, there are currently no special attribute values.
"""
args = ('wm', 'attributes', self._w) + args
return self.tk.call(args) | [
"def",
"wm_attributes",
"(",
"self",
",",
"*",
"args",
")",
":",
"args",
"=",
"(",
"'wm'",
",",
"'attributes'",
",",
"self",
".",
"_w",
")",
"+",
"args",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"args",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L1769-L1788 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | DateTime.IsLaterThan | (*args, **kwargs) | return _misc_.DateTime_IsLaterThan(*args, **kwargs) | IsLaterThan(self, DateTime datetime) -> bool | IsLaterThan(self, DateTime datetime) -> bool | [
"IsLaterThan",
"(",
"self",
"DateTime",
"datetime",
")",
"-",
">",
"bool"
] | def IsLaterThan(*args, **kwargs):
"""IsLaterThan(self, DateTime datetime) -> bool"""
return _misc_.DateTime_IsLaterThan(*args, **kwargs) | [
"def",
"IsLaterThan",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_IsLaterThan",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L4033-L4035 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/examples/python/file_extract.py | python | FileExtract.get_n_uint16 | (self, n, fail_value=0) | Extract "n" uint16_t integers from the binary file at the current file position, returns a list of integers | Extract "n" uint16_t integers from the binary file at the current file position, returns a list of integers | [
"Extract",
"n",
"uint16_t",
"integers",
"from",
"the",
"binary",
"file",
"at",
"the",
"current",
"file",
"position",
"returns",
"a",
"list",
"of",
"integers"
] | def get_n_uint16(self, n, fail_value=0):
'''Extract "n" uint16_t integers from the binary file at the current file position, returns a list of integers'''
s = self.read_size(2 * n)
if s:
return struct.unpack(self.byte_order + ("%u" % n) + 'H', s)
else:
return (fail_value,) * n | [
"def",
"get_n_uint16",
"(",
"self",
",",
"n",
",",
"fail_value",
"=",
"0",
")",
":",
"s",
"=",
"self",
".",
"read_size",
"(",
"2",
"*",
"n",
")",
"if",
"s",
":",
"return",
"struct",
".",
"unpack",
"(",
"self",
".",
"byte_order",
"+",
"(",
"\"%u\"",
"%",
"n",
")",
"+",
"'H'",
",",
"s",
")",
"else",
":",
"return",
"(",
"fail_value",
",",
")",
"*",
"n"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/examples/python/file_extract.py#L188-L194 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/layers/base.py | python | _unique_layer_name | (name) | return name + '_' + str(layer_name_uids[name]) | Makes a layer name (or arbitrary string) unique within a TensorFlow graph.
Arguments:
name: String name to make unique.
Returns:
Unique string name.
Example:
```python
_unique_layer_name('dense') # dense_1
_unique_layer_name('dense') # dense_2
``` | Makes a layer name (or arbitrary string) unique within a TensorFlow graph. | [
"Makes",
"a",
"layer",
"name",
"(",
"or",
"arbitrary",
"string",
")",
"unique",
"within",
"a",
"TensorFlow",
"graph",
"."
] | def _unique_layer_name(name):
"""Makes a layer name (or arbitrary string) unique within a TensorFlow graph.
Arguments:
name: String name to make unique.
Returns:
Unique string name.
Example:
```python
_unique_layer_name('dense') # dense_1
_unique_layer_name('dense') # dense_2
```
"""
graph = ops.get_default_graph()
if graph not in PER_GRAPH_LAYER_NAME_UIDS:
PER_GRAPH_LAYER_NAME_UIDS[graph] = collections.defaultdict(int)
layer_name_uids = PER_GRAPH_LAYER_NAME_UIDS[graph]
layer_name_uids[name] += 1
return name + '_' + str(layer_name_uids[name]) | [
"def",
"_unique_layer_name",
"(",
"name",
")",
":",
"graph",
"=",
"ops",
".",
"get_default_graph",
"(",
")",
"if",
"graph",
"not",
"in",
"PER_GRAPH_LAYER_NAME_UIDS",
":",
"PER_GRAPH_LAYER_NAME_UIDS",
"[",
"graph",
"]",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"layer_name_uids",
"=",
"PER_GRAPH_LAYER_NAME_UIDS",
"[",
"graph",
"]",
"layer_name_uids",
"[",
"name",
"]",
"+=",
"1",
"return",
"name",
"+",
"'_'",
"+",
"str",
"(",
"layer_name_uids",
"[",
"name",
"]",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/layers/base.py#L2345-L2366 | |
physercoe/starquant | c00cad64d1de2da05081b3dc320ef264c6295e08 | cppsrc/fmt-5.3.0/support/rst2md.py | python | convert | (rst_path) | return core.publish_file(source_path=rst_path, writer=MDWriter()) | Converts RST file to Markdown. | Converts RST file to Markdown. | [
"Converts",
"RST",
"file",
"to",
"Markdown",
"."
] | def convert(rst_path):
"""Converts RST file to Markdown."""
return core.publish_file(source_path=rst_path, writer=MDWriter()) | [
"def",
"convert",
"(",
"rst_path",
")",
":",
"return",
"core",
".",
"publish_file",
"(",
"source_path",
"=",
"rst_path",
",",
"writer",
"=",
"MDWriter",
"(",
")",
")"
] | https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/cppsrc/fmt-5.3.0/support/rst2md.py#L153-L155 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/telemetry/core/backends/chrome/cros_browser_backend.py | python | CrOSBrowserBackend._HandleUserImageSelectionScreen | (self) | If we're stuck on the user image selection screen, we click the ok
button. | If we're stuck on the user image selection screen, we click the ok
button. | [
"If",
"we",
"re",
"stuck",
"on",
"the",
"user",
"image",
"selection",
"screen",
"we",
"click",
"the",
"ok",
"button",
"."
] | def _HandleUserImageSelectionScreen(self):
"""If we're stuck on the user image selection screen, we click the ok
button.
"""
oobe = self.oobe
if oobe:
try:
oobe.EvaluateJavaScript("""
var ok = document.getElementById("ok-button");
if (ok) {
ok.click();
}
""")
except (exceptions.TabCrashException):
pass | [
"def",
"_HandleUserImageSelectionScreen",
"(",
"self",
")",
":",
"oobe",
"=",
"self",
".",
"oobe",
"if",
"oobe",
":",
"try",
":",
"oobe",
".",
"EvaluateJavaScript",
"(",
"\"\"\"\n var ok = document.getElementById(\"ok-button\");\n if (ok) {\n ok.click();\n }\n \"\"\"",
")",
"except",
"(",
"exceptions",
".",
"TabCrashException",
")",
":",
"pass"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/core/backends/chrome/cros_browser_backend.py#L332-L346 | ||
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/programs/scripts/internetcontent/nv_python_libs/xsltfunctions/chrisPirillo_api.py | python | OutStreamEncoder.__getattr__ | (self, attr) | return getattr(self.out, attr) | Delegate everything but write to the stream | Delegate everything but write to the stream | [
"Delegate",
"everything",
"but",
"write",
"to",
"the",
"stream"
] | def __getattr__(self, attr):
"""Delegate everything but write to the stream"""
return getattr(self.out, attr) | [
"def",
"__getattr__",
"(",
"self",
",",
"attr",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"out",
",",
"attr",
")"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/xsltfunctions/chrisPirillo_api.py#L56-L58 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | Palette.__init__ | (self, *args, **kwargs) | __init__(self, wxArrayInt red, wxArrayInt green, wxArrayInt blue) -> Palette | __init__(self, wxArrayInt red, wxArrayInt green, wxArrayInt blue) -> Palette | [
"__init__",
"(",
"self",
"wxArrayInt",
"red",
"wxArrayInt",
"green",
"wxArrayInt",
"blue",
")",
"-",
">",
"Palette"
] | def __init__(self, *args, **kwargs):
"""__init__(self, wxArrayInt red, wxArrayInt green, wxArrayInt blue) -> Palette"""
_gdi_.Palette_swiginit(self,_gdi_.new_Palette(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_gdi_",
".",
"Palette_swiginit",
"(",
"self",
",",
"_gdi_",
".",
"new_Palette",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L336-L338 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/genericpath.py | python | _splitext | (p, sep, altsep, extsep) | return p, '' | Split the extension from a pathname.
Extension is everything from the last dot to the end, ignoring
leading dots. Returns "(root, ext)"; ext may be empty. | Split the extension from a pathname. | [
"Split",
"the",
"extension",
"from",
"a",
"pathname",
"."
] | def _splitext(p, sep, altsep, extsep):
"""Split the extension from a pathname.
Extension is everything from the last dot to the end, ignoring
leading dots. Returns "(root, ext)"; ext may be empty."""
sepIndex = p.rfind(sep)
if altsep:
altsepIndex = p.rfind(altsep)
sepIndex = max(sepIndex, altsepIndex)
dotIndex = p.rfind(extsep)
if dotIndex > sepIndex:
# skip all leading dots
filenameIndex = sepIndex + 1
while filenameIndex < dotIndex:
if p[filenameIndex] != extsep:
return p[:dotIndex], p[dotIndex:]
filenameIndex += 1
return p, '' | [
"def",
"_splitext",
"(",
"p",
",",
"sep",
",",
"altsep",
",",
"extsep",
")",
":",
"sepIndex",
"=",
"p",
".",
"rfind",
"(",
"sep",
")",
"if",
"altsep",
":",
"altsepIndex",
"=",
"p",
".",
"rfind",
"(",
"altsep",
")",
"sepIndex",
"=",
"max",
"(",
"sepIndex",
",",
"altsepIndex",
")",
"dotIndex",
"=",
"p",
".",
"rfind",
"(",
"extsep",
")",
"if",
"dotIndex",
">",
"sepIndex",
":",
"# skip all leading dots",
"filenameIndex",
"=",
"sepIndex",
"+",
"1",
"while",
"filenameIndex",
"<",
"dotIndex",
":",
"if",
"p",
"[",
"filenameIndex",
"]",
"!=",
"extsep",
":",
"return",
"p",
"[",
":",
"dotIndex",
"]",
",",
"p",
"[",
"dotIndex",
":",
"]",
"filenameIndex",
"+=",
"1",
"return",
"p",
",",
"''"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/genericpath.py#L85-L105 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_presenter.py | python | BasicFittingPresenter._get_fit_browser_options | (self) | return {"Minimizer": self.model.minimizer, "Evaluation Type": self.model.evaluation_type} | Returns the fitting options to use in the Fit Script Generator interface. | Returns the fitting options to use in the Fit Script Generator interface. | [
"Returns",
"the",
"fitting",
"options",
"to",
"use",
"in",
"the",
"Fit",
"Script",
"Generator",
"interface",
"."
] | def _get_fit_browser_options(self) -> dict:
"""Returns the fitting options to use in the Fit Script Generator interface."""
return {"Minimizer": self.model.minimizer, "Evaluation Type": self.model.evaluation_type} | [
"def",
"_get_fit_browser_options",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"{",
"\"Minimizer\"",
":",
"self",
".",
"model",
".",
"minimizer",
",",
"\"Evaluation Type\"",
":",
"self",
".",
"model",
".",
"evaluation_type",
"}"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_presenter.py#L480-L482 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/vis/glprogram.py | python | GLProgram.closefunc | (self) | return True | Called by the window when it is closed | Called by the window when it is closed | [
"Called",
"by",
"the",
"window",
"when",
"it",
"is",
"closed"
] | def closefunc(self):
"""Called by the window when it is closed"""
return True | [
"def",
"closefunc",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/vis/glprogram.py#L192-L194 | |
Bitcoin-ABC/bitcoin-abc | aff7e41f00bef9d52786c6cffb49faca5c84d32e | contrib/buildbot/phabricator_wrapper.py | python | PhabWrapper.get_object_token | (self, object_PHID) | return tokens[0]["tokenPHID"] | Return the current token set by the current user on target object | Return the current token set by the current user on target object | [
"Return",
"the",
"current",
"token",
"set",
"by",
"the",
"current",
"user",
"on",
"target",
"object"
] | def get_object_token(self, object_PHID):
""" Return the current token set by the current user on target object """
tokens = self.token.given(
authorPHIDs=[self.get_current_user_phid()],
objectPHIDs=[object_PHID],
tokenPHIDs=[],
)
if not tokens:
return ""
# There should be no more than a single token from the same user for the
# same object.
if len(tokens) > 1:
self.logger.info(
"Found {} tokens for user {} on object {}: {}".format(
len(tokens),
self.get_current_user_phid(),
object_PHID,
tokens,
)
)
return tokens[0]["tokenPHID"] | [
"def",
"get_object_token",
"(",
"self",
",",
"object_PHID",
")",
":",
"tokens",
"=",
"self",
".",
"token",
".",
"given",
"(",
"authorPHIDs",
"=",
"[",
"self",
".",
"get_current_user_phid",
"(",
")",
"]",
",",
"objectPHIDs",
"=",
"[",
"object_PHID",
"]",
",",
"tokenPHIDs",
"=",
"[",
"]",
",",
")",
"if",
"not",
"tokens",
":",
"return",
"\"\"",
"# There should be no more than a single token from the same user for the",
"# same object.",
"if",
"len",
"(",
"tokens",
")",
">",
"1",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Found {} tokens for user {} on object {}: {}\"",
".",
"format",
"(",
"len",
"(",
"tokens",
")",
",",
"self",
".",
"get_current_user_phid",
"(",
")",
",",
"object_PHID",
",",
"tokens",
",",
")",
")",
"return",
"tokens",
"[",
"0",
"]",
"[",
"\"tokenPHID\"",
"]"
] | https://github.com/Bitcoin-ABC/bitcoin-abc/blob/aff7e41f00bef9d52786c6cffb49faca5c84d32e/contrib/buildbot/phabricator_wrapper.py#L498-L521 | |
oneapi-src/oneDAL | 73264b7d06f5e4e8d1207c813347d003ea81b379 | docs/dalapi/doxypy/parser/index.py | python | get_required_ns_prefix_defs | (rootNode) | return nsmap, namespacedefs | Get all name space prefix definitions required in this XML doc.
Return a dictionary of definitions and a char string of definitions. | Get all name space prefix definitions required in this XML doc.
Return a dictionary of definitions and a char string of definitions. | [
"Get",
"all",
"name",
"space",
"prefix",
"definitions",
"required",
"in",
"this",
"XML",
"doc",
".",
"Return",
"a",
"dictionary",
"of",
"definitions",
"and",
"a",
"char",
"string",
"of",
"definitions",
"."
] | def get_required_ns_prefix_defs(rootNode):
'''Get all name space prefix definitions required in this XML doc.
Return a dictionary of definitions and a char string of definitions.
'''
nsmap = {
prefix: uri
for node in rootNode.iter()
for (prefix, uri) in node.nsmap.items()
if prefix is not None
}
namespacedefs = ' '.join([
'xmlns:{}="{}"'.format(prefix, uri)
for prefix, uri in nsmap.items()
])
return nsmap, namespacedefs | [
"def",
"get_required_ns_prefix_defs",
"(",
"rootNode",
")",
":",
"nsmap",
"=",
"{",
"prefix",
":",
"uri",
"for",
"node",
"in",
"rootNode",
".",
"iter",
"(",
")",
"for",
"(",
"prefix",
",",
"uri",
")",
"in",
"node",
".",
"nsmap",
".",
"items",
"(",
")",
"if",
"prefix",
"is",
"not",
"None",
"}",
"namespacedefs",
"=",
"' '",
".",
"join",
"(",
"[",
"'xmlns:{}=\"{}\"'",
".",
"format",
"(",
"prefix",
",",
"uri",
")",
"for",
"prefix",
",",
"uri",
"in",
"nsmap",
".",
"items",
"(",
")",
"]",
")",
"return",
"nsmap",
",",
"namespacedefs"
] | https://github.com/oneapi-src/oneDAL/blob/73264b7d06f5e4e8d1207c813347d003ea81b379/docs/dalapi/doxypy/parser/index.py#L1410-L1424 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/_shard/sharded_tensor/__init__.py | python | sharded_op_impl | (func) | return decorator_sharded_func | Provides a way for users to write their own custom sharded operator. This
can be used to override existing ShardedTensor operators or write a new
one not supported by ShardedTensor. If the operator in question is covered
by ``__torch_function__`` dispatch and has a ShardedTensor as any of its
parameters, the function provided will be invoked for that operator.
Example::
>>> @custom_sharded_op(torch.nn.functional.linear)
>>> def my_custom_sharded_linear(types, args, kwargs, process_group):
>>> ....
>>>
>>> input = torch.rand(10, 32)
>>> weight = sharded_tensor.rand(32, 16)
>>> bias = torch.rand(16)
>>> # This will call 'my_custom_sharded_linear'
>>> torch.nn.functional.linear(input, weight, bias)
The types, args and kwargs parameters are the same parameters that are
passed to ``__torch_function__`` dispatch API
(https://pytorch.org/docs/stable/notes/extending.html#extending-torch).
There is an additional ``process_group`` parameter which is the
process_group used for the ShardedTensor and can be used by
implementations for communications within a sharded implementation.
Args:
func(Callable): Torch function for which we want to provide a sharded
implementation (ex: torch.nn.functional.linear) | Provides a way for users to write their own custom sharded operator. This
can be used to override existing ShardedTensor operators or write a new
one not supported by ShardedTensor. If the operator in question is covered
by ``__torch_function__`` dispatch and has a ShardedTensor as any of its
parameters, the function provided will be invoked for that operator. | [
"Provides",
"a",
"way",
"for",
"users",
"to",
"write",
"their",
"own",
"custom",
"sharded",
"operator",
".",
"This",
"can",
"be",
"used",
"to",
"override",
"existing",
"ShardedTensor",
"operators",
"or",
"write",
"a",
"new",
"one",
"not",
"supported",
"by",
"ShardedTensor",
".",
"If",
"the",
"operator",
"in",
"question",
"is",
"covered",
"by",
"__torch_function__",
"dispatch",
"and",
"has",
"a",
"ShardedTensor",
"as",
"any",
"of",
"its",
"parameters",
"the",
"function",
"provided",
"will",
"be",
"invoked",
"for",
"that",
"operator",
"."
] | def sharded_op_impl(func):
"""
Provides a way for users to write their own custom sharded operator. This
can be used to override existing ShardedTensor operators or write a new
one not supported by ShardedTensor. If the operator in question is covered
by ``__torch_function__`` dispatch and has a ShardedTensor as any of its
parameters, the function provided will be invoked for that operator.
Example::
>>> @custom_sharded_op(torch.nn.functional.linear)
>>> def my_custom_sharded_linear(types, args, kwargs, process_group):
>>> ....
>>>
>>> input = torch.rand(10, 32)
>>> weight = sharded_tensor.rand(32, 16)
>>> bias = torch.rand(16)
>>> # This will call 'my_custom_sharded_linear'
>>> torch.nn.functional.linear(input, weight, bias)
The types, args and kwargs parameters are the same parameters that are
passed to ``__torch_function__`` dispatch API
(https://pytorch.org/docs/stable/notes/extending.html#extending-torch).
There is an additional ``process_group`` parameter which is the
process_group used for the ShardedTensor and can be used by
implementations for communications within a sharded implementation.
Args:
func(Callable): Torch function for which we want to provide a sharded
implementation (ex: torch.nn.functional.linear)
"""
def decorator_sharded_func(wrapped_func):
_register_sharded_op(func, wrapped_func)
@functools.wraps(wrapped_func)
def wrapper(*args, **kwargs):
return wrapped_func(*args, **kwargs)
return wrapper
return decorator_sharded_func | [
"def",
"sharded_op_impl",
"(",
"func",
")",
":",
"def",
"decorator_sharded_func",
"(",
"wrapped_func",
")",
":",
"_register_sharded_op",
"(",
"func",
",",
"wrapped_func",
")",
"@",
"functools",
".",
"wraps",
"(",
"wrapped_func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"wrapped_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper",
"return",
"decorator_sharded_func"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/_shard/sharded_tensor/__init__.py#L368-L405 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | GraphicsGradientStops.Item | (*args, **kwargs) | return _gdi_.GraphicsGradientStops_Item(*args, **kwargs) | Item(self, unsigned int n) -> GraphicsGradientStop | Item(self, unsigned int n) -> GraphicsGradientStop | [
"Item",
"(",
"self",
"unsigned",
"int",
"n",
")",
"-",
">",
"GraphicsGradientStop"
] | def Item(*args, **kwargs):
"""Item(self, unsigned int n) -> GraphicsGradientStop"""
return _gdi_.GraphicsGradientStops_Item(*args, **kwargs) | [
"def",
"Item",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"GraphicsGradientStops_Item",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L5937-L5939 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | clang/utils/check_cfc/check_cfc.py | python | flip_dash_g | (args) | Search for -g in args. If it exists then return args without. If not then
add it. | Search for -g in args. If it exists then return args without. If not then
add it. | [
"Search",
"for",
"-",
"g",
"in",
"args",
".",
"If",
"it",
"exists",
"then",
"return",
"args",
"without",
".",
"If",
"not",
"then",
"add",
"it",
"."
] | def flip_dash_g(args):
"""Search for -g in args. If it exists then return args without. If not then
add it."""
if '-g' in args:
# Return args without any -g
return [x for x in args if x != '-g']
else:
# No -g, add one
return args + ['-g'] | [
"def",
"flip_dash_g",
"(",
"args",
")",
":",
"if",
"'-g'",
"in",
"args",
":",
"# Return args without any -g",
"return",
"[",
"x",
"for",
"x",
"in",
"args",
"if",
"x",
"!=",
"'-g'",
"]",
"else",
":",
"# No -g, add one",
"return",
"args",
"+",
"[",
"'-g'",
"]"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang/utils/check_cfc/check_cfc.py#L111-L119 | ||
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/algorithms/sfm/OpenSfM/opensfm/io.py | python | imread | (filename, grayscale=False, unchanged=False) | return image | Load image as an array ignoring EXIF orientation. | Load image as an array ignoring EXIF orientation. | [
"Load",
"image",
"as",
"an",
"array",
"ignoring",
"EXIF",
"orientation",
"."
] | def imread(filename, grayscale=False, unchanged=False):
"""Load image as an array ignoring EXIF orientation."""
if context.OPENCV3:
if grayscale:
flags = cv2.IMREAD_GRAYSCALE
elif unchanged:
flags = cv2.IMREAD_UNCHANGED
else:
flags = cv2.IMREAD_COLOR
try:
flags |= cv2.IMREAD_IGNORE_ORIENTATION
except AttributeError:
logger.warning(
"OpenCV version {} does not support loading images without "
"rotating them according to EXIF. Please upgrade OpenCV to "
"version 3.2 or newer.".format(cv2.__version__))
else:
if grayscale:
flags = cv2.CV_LOAD_IMAGE_GRAYSCALE
elif unchanged:
flags = cv2.CV_LOAD_IMAGE_UNCHANGED
else:
flags = cv2.CV_LOAD_IMAGE_COLOR
image = cv2.imread(filename, flags)
if image is None:
raise IOError("Unable to load image {}".format(filename))
if len(image.shape) == 3:
image[:,:,:3] = image[:, :, [2,1,0]] # Turn BGR to RGB (or BGRA to RGBA)
return image | [
"def",
"imread",
"(",
"filename",
",",
"grayscale",
"=",
"False",
",",
"unchanged",
"=",
"False",
")",
":",
"if",
"context",
".",
"OPENCV3",
":",
"if",
"grayscale",
":",
"flags",
"=",
"cv2",
".",
"IMREAD_GRAYSCALE",
"elif",
"unchanged",
":",
"flags",
"=",
"cv2",
".",
"IMREAD_UNCHANGED",
"else",
":",
"flags",
"=",
"cv2",
".",
"IMREAD_COLOR",
"try",
":",
"flags",
"|=",
"cv2",
".",
"IMREAD_IGNORE_ORIENTATION",
"except",
"AttributeError",
":",
"logger",
".",
"warning",
"(",
"\"OpenCV version {} does not support loading images without \"",
"\"rotating them according to EXIF. Please upgrade OpenCV to \"",
"\"version 3.2 or newer.\"",
".",
"format",
"(",
"cv2",
".",
"__version__",
")",
")",
"else",
":",
"if",
"grayscale",
":",
"flags",
"=",
"cv2",
".",
"CV_LOAD_IMAGE_GRAYSCALE",
"elif",
"unchanged",
":",
"flags",
"=",
"cv2",
".",
"CV_LOAD_IMAGE_UNCHANGED",
"else",
":",
"flags",
"=",
"cv2",
".",
"CV_LOAD_IMAGE_COLOR",
"image",
"=",
"cv2",
".",
"imread",
"(",
"filename",
",",
"flags",
")",
"if",
"image",
"is",
"None",
":",
"raise",
"IOError",
"(",
"\"Unable to load image {}\"",
".",
"format",
"(",
"filename",
")",
")",
"if",
"len",
"(",
"image",
".",
"shape",
")",
"==",
"3",
":",
"image",
"[",
":",
",",
":",
",",
":",
"3",
"]",
"=",
"image",
"[",
":",
",",
":",
",",
"[",
"2",
",",
"1",
",",
"0",
"]",
"]",
"# Turn BGR to RGB (or BGRA to RGBA)",
"return",
"image"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/io.py#L577-L609 | |
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/agents/ppo/algorithm.py | python | PPOAlgorithm._define_end_episode | (self, agent_indices) | Implement the branch of end_episode() entered during training. | Implement the branch of end_episode() entered during training. | [
"Implement",
"the",
"branch",
"of",
"end_episode",
"()",
"entered",
"during",
"training",
"."
] | def _define_end_episode(self, agent_indices):
"""Implement the branch of end_episode() entered during training."""
episodes, length = self._episodes.data(agent_indices)
space_left = self._config.update_every - self._memory_index
use_episodes = tf.range(tf.minimum(tf.shape(agent_indices)[0], space_left))
episodes = [tf.gather(elem, use_episodes) for elem in episodes]
append = self._memory.replace(episodes, tf.gather(length, use_episodes),
use_episodes + self._memory_index)
with tf.control_dependencies([append]):
inc_index = self._memory_index.assign_add(tf.shape(use_episodes)[0])
with tf.control_dependencies([inc_index]):
memory_full = self._memory_index >= self._config.update_every
return tf.cond(memory_full, self._training, str) | [
"def",
"_define_end_episode",
"(",
"self",
",",
"agent_indices",
")",
":",
"episodes",
",",
"length",
"=",
"self",
".",
"_episodes",
".",
"data",
"(",
"agent_indices",
")",
"space_left",
"=",
"self",
".",
"_config",
".",
"update_every",
"-",
"self",
".",
"_memory_index",
"use_episodes",
"=",
"tf",
".",
"range",
"(",
"tf",
".",
"minimum",
"(",
"tf",
".",
"shape",
"(",
"agent_indices",
")",
"[",
"0",
"]",
",",
"space_left",
")",
")",
"episodes",
"=",
"[",
"tf",
".",
"gather",
"(",
"elem",
",",
"use_episodes",
")",
"for",
"elem",
"in",
"episodes",
"]",
"append",
"=",
"self",
".",
"_memory",
".",
"replace",
"(",
"episodes",
",",
"tf",
".",
"gather",
"(",
"length",
",",
"use_episodes",
")",
",",
"use_episodes",
"+",
"self",
".",
"_memory_index",
")",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"append",
"]",
")",
":",
"inc_index",
"=",
"self",
".",
"_memory_index",
".",
"assign_add",
"(",
"tf",
".",
"shape",
"(",
"use_episodes",
")",
"[",
"0",
"]",
")",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"inc_index",
"]",
")",
":",
"memory_full",
"=",
"self",
".",
"_memory_index",
">=",
"self",
".",
"_config",
".",
"update_every",
"return",
"tf",
".",
"cond",
"(",
"memory_full",
",",
"self",
".",
"_training",
",",
"str",
")"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/ppo/algorithm.py#L231-L243 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/imaplib.py | python | IMAP4.logout | (self) | return typ, dat | Shutdown connection to server.
(typ, [data]) = <instance>.logout()
Returns server 'BYE' response. | Shutdown connection to server. | [
"Shutdown",
"connection",
"to",
"server",
"."
] | def logout(self):
"""Shutdown connection to server.
(typ, [data]) = <instance>.logout()
Returns server 'BYE' response.
"""
self.state = 'LOGOUT'
try: typ, dat = self._simple_command('LOGOUT')
except: typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]]
self.shutdown()
if 'BYE' in self.untagged_responses:
return 'BYE', self.untagged_responses['BYE']
return typ, dat | [
"def",
"logout",
"(",
"self",
")",
":",
"self",
".",
"state",
"=",
"'LOGOUT'",
"try",
":",
"typ",
",",
"dat",
"=",
"self",
".",
"_simple_command",
"(",
"'LOGOUT'",
")",
"except",
":",
"typ",
",",
"dat",
"=",
"'NO'",
",",
"[",
"'%s: %s'",
"%",
"sys",
".",
"exc_info",
"(",
")",
"[",
":",
"2",
"]",
"]",
"self",
".",
"shutdown",
"(",
")",
"if",
"'BYE'",
"in",
"self",
".",
"untagged_responses",
":",
"return",
"'BYE'",
",",
"self",
".",
"untagged_responses",
"[",
"'BYE'",
"]",
"return",
"typ",
",",
"dat"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/imaplib.py#L527-L540 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/ma/core.py | python | _MaskedBinaryOperation.reduce | (self, target, axis=0, dtype=None) | return masked_tr | Reduce `target` along the given `axis`. | Reduce `target` along the given `axis`. | [
"Reduce",
"target",
"along",
"the",
"given",
"axis",
"."
] | def reduce(self, target, axis=0, dtype=None):
"""
Reduce `target` along the given `axis`.
"""
tclass = get_masked_subclass(target)
m = getmask(target)
t = filled(target, self.filly)
if t.shape == ():
t = t.reshape(1)
if m is not nomask:
m = make_mask(m, copy=True)
m.shape = (1,)
if m is nomask:
tr = self.f.reduce(t, axis)
mr = nomask
else:
tr = self.f.reduce(t, axis, dtype=dtype or t.dtype)
mr = umath.logical_and.reduce(m, axis)
if not tr.shape:
if mr:
return masked
else:
return tr
masked_tr = tr.view(tclass)
masked_tr._mask = mr
return masked_tr | [
"def",
"reduce",
"(",
"self",
",",
"target",
",",
"axis",
"=",
"0",
",",
"dtype",
"=",
"None",
")",
":",
"tclass",
"=",
"get_masked_subclass",
"(",
"target",
")",
"m",
"=",
"getmask",
"(",
"target",
")",
"t",
"=",
"filled",
"(",
"target",
",",
"self",
".",
"filly",
")",
"if",
"t",
".",
"shape",
"==",
"(",
")",
":",
"t",
"=",
"t",
".",
"reshape",
"(",
"1",
")",
"if",
"m",
"is",
"not",
"nomask",
":",
"m",
"=",
"make_mask",
"(",
"m",
",",
"copy",
"=",
"True",
")",
"m",
".",
"shape",
"=",
"(",
"1",
",",
")",
"if",
"m",
"is",
"nomask",
":",
"tr",
"=",
"self",
".",
"f",
".",
"reduce",
"(",
"t",
",",
"axis",
")",
"mr",
"=",
"nomask",
"else",
":",
"tr",
"=",
"self",
".",
"f",
".",
"reduce",
"(",
"t",
",",
"axis",
",",
"dtype",
"=",
"dtype",
"or",
"t",
".",
"dtype",
")",
"mr",
"=",
"umath",
".",
"logical_and",
".",
"reduce",
"(",
"m",
",",
"axis",
")",
"if",
"not",
"tr",
".",
"shape",
":",
"if",
"mr",
":",
"return",
"masked",
"else",
":",
"return",
"tr",
"masked_tr",
"=",
"tr",
".",
"view",
"(",
"tclass",
")",
"masked_tr",
".",
"_mask",
"=",
"mr",
"return",
"masked_tr"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/core.py#L1052-L1080 | |
infinit/elle | a8154593c42743f45b9df09daf62b44630c24a02 | drake/src/drake/__init__.py | python | BaseNode.__lt__ | (self, rhs) | return self.name_absolute() < rhs.name_absolute() | Arbitrary global order on nodes, to enable
sorting/indexing. | Arbitrary global order on nodes, to enable
sorting/indexing. | [
"Arbitrary",
"global",
"order",
"on",
"nodes",
"to",
"enable",
"sorting",
"/",
"indexing",
"."
] | def __lt__(self, rhs):
"""Arbitrary global order on nodes, to enable
sorting/indexing."""
return self.name_absolute() < rhs.name_absolute() | [
"def",
"__lt__",
"(",
"self",
",",
"rhs",
")",
":",
"return",
"self",
".",
"name_absolute",
"(",
")",
"<",
"rhs",
".",
"name_absolute",
"(",
")"
] | https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/__init__.py#L1592-L1595 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/numpy/multiarray.py | python | log1p | (x, out=None, **kwargs) | return _mx_nd_np.log1p(x, out=out, **kwargs) | Return the natural logarithm of one plus the input array, element-wise.
Calculates ``log(1 + x)``.
Parameters
----------
x : ndarray or scalar
Input array.
out : ndarray or None
A location into which the result is stored. If provided, it
must have a shape that the inputs fill into. If not provided
or None, a freshly-allocated array is returned. The dtype of the
output and input must be the same.
Returns
-------
y : ndarray or scalar
Natural logarithm of 1 + x, element-wise. This is a scalar
if x is a scalar.
Notes
-----
For real-valued input, `log1p` is accurate also for `x` so small
that `1 + x == 1` in floating-point accuracy.
Logarithm is a multivalued function: for each `x` there is an infinite
number of `z` such that `exp(z) = 1 + x`. The convention is to return
the `z` whose imaginary part lies in `[-pi, pi]`.
For real-valued input data types, `log1p` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
cannot support complex-valued input.
Examples
--------
>>> np.log1p(1e-99)
1e-99
>>> a = np.array([3, 4, 5])
>>> np.log1p(a)
array([1.3862944, 1.609438 , 1.7917595]) | Return the natural logarithm of one plus the input array, element-wise.
Calculates ``log(1 + x)``. | [
"Return",
"the",
"natural",
"logarithm",
"of",
"one",
"plus",
"the",
"input",
"array",
"element",
"-",
"wise",
".",
"Calculates",
"log",
"(",
"1",
"+",
"x",
")",
"."
] | def log1p(x, out=None, **kwargs):
"""
Return the natural logarithm of one plus the input array, element-wise.
Calculates ``log(1 + x)``.
Parameters
----------
x : ndarray or scalar
Input array.
out : ndarray or None
A location into which the result is stored. If provided, it
must have a shape that the inputs fill into. If not provided
or None, a freshly-allocated array is returned. The dtype of the
output and input must be the same.
Returns
-------
y : ndarray or scalar
Natural logarithm of 1 + x, element-wise. This is a scalar
if x is a scalar.
Notes
-----
For real-valued input, `log1p` is accurate also for `x` so small
that `1 + x == 1` in floating-point accuracy.
Logarithm is a multivalued function: for each `x` there is an infinite
number of `z` such that `exp(z) = 1 + x`. The convention is to return
the `z` whose imaginary part lies in `[-pi, pi]`.
For real-valued input data types, `log1p` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
cannot support complex-valued input.
Examples
--------
>>> np.log1p(1e-99)
1e-99
>>> a = np.array([3, 4, 5])
>>> np.log1p(a)
array([1.3862944, 1.609438 , 1.7917595])
"""
return _mx_nd_np.log1p(x, out=out, **kwargs) | [
"def",
"log1p",
"(",
"x",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_mx_nd_np",
".",
"log1p",
"(",
"x",
",",
"out",
"=",
"out",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L4958-L4999 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/inspector_protocol/jinja2/filters.py | python | do_max | (environment, value, case_sensitive=False, attribute=None) | return _min_or_max(environment, value, max, case_sensitive, attribute) | Return the largest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|max }}
-> 3
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute. | Return the largest item from the sequence. | [
"Return",
"the",
"largest",
"item",
"from",
"the",
"sequence",
"."
] | def do_max(environment, value, case_sensitive=False, attribute=None):
"""Return the largest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|max }}
-> 3
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute.
"""
return _min_or_max(environment, value, max, case_sensitive, attribute) | [
"def",
"do_max",
"(",
"environment",
",",
"value",
",",
"case_sensitive",
"=",
"False",
",",
"attribute",
"=",
"None",
")",
":",
"return",
"_min_or_max",
"(",
"environment",
",",
"value",
",",
"max",
",",
"case_sensitive",
",",
"attribute",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/filters.py#L341-L352 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/multiprocessing/context.py | python | BaseContext.Lock | (self) | return Lock(ctx=self.get_context()) | Returns a non-recursive lock object | Returns a non-recursive lock object | [
"Returns",
"a",
"non",
"-",
"recursive",
"lock",
"object"
] | def Lock(self):
'''Returns a non-recursive lock object'''
from .synchronize import Lock
return Lock(ctx=self.get_context()) | [
"def",
"Lock",
"(",
"self",
")",
":",
"from",
".",
"synchronize",
"import",
"Lock",
"return",
"Lock",
"(",
"ctx",
"=",
"self",
".",
"get_context",
"(",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/multiprocessing/context.py#L65-L68 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/constraints/constraint.py | python | Constraint.is_dcp | (self, dpp: bool = False) | Checks whether the constraint is DCP.
Returns
-------
bool
True if the constraint is DCP, False otherwise. | Checks whether the constraint is DCP. | [
"Checks",
"whether",
"the",
"constraint",
"is",
"DCP",
"."
] | def is_dcp(self, dpp: bool = False) -> bool:
"""Checks whether the constraint is DCP.
Returns
-------
bool
True if the constraint is DCP, False otherwise.
"""
raise NotImplementedError() | [
"def",
"is_dcp",
"(",
"self",
",",
"dpp",
":",
"bool",
"=",
"False",
")",
"->",
"bool",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/constraints/constraint.py#L94-L102 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Window.GetWindowStyleFlag | (*args, **kwargs) | return _core_.Window_GetWindowStyleFlag(*args, **kwargs) | GetWindowStyleFlag(self) -> long
Gets the window style that was passed to the constructor or Create
method. | GetWindowStyleFlag(self) -> long | [
"GetWindowStyleFlag",
"(",
"self",
")",
"-",
">",
"long"
] | def GetWindowStyleFlag(*args, **kwargs):
"""
GetWindowStyleFlag(self) -> long
Gets the window style that was passed to the constructor or Create
method.
"""
return _core_.Window_GetWindowStyleFlag(*args, **kwargs) | [
"def",
"GetWindowStyleFlag",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_GetWindowStyleFlag",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L10027-L10034 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | ThirdParty/cinema/paraview/tpl/cinema_python/database/store.py | python | Store.metadata | (self) | return self.__metadata | Auxiliary data about the store itself. An example is hints that help
the viewer app know how to interpret this particular store. | Auxiliary data about the store itself. An example is hints that help
the viewer app know how to interpret this particular store. | [
"Auxiliary",
"data",
"about",
"the",
"store",
"itself",
".",
"An",
"example",
"is",
"hints",
"that",
"help",
"the",
"viewer",
"app",
"know",
"how",
"to",
"interpret",
"this",
"particular",
"store",
"."
] | def metadata(self):
"""
Auxiliary data about the store itself. An example is hints that help
the viewer app know how to interpret this particular store.
"""
return self.__metadata | [
"def",
"metadata",
"(",
"self",
")",
":",
"return",
"self",
".",
"__metadata"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/database/store.py#L275-L280 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/third_party/Python/module/pexpect-2.4/screen.py | python | screen.erase_screen | (self) | Erases the screen with the background color. | Erases the screen with the background color. | [
"Erases",
"the",
"screen",
"with",
"the",
"background",
"color",
"."
] | def erase_screen(self): # <ESC>[2J
"""Erases the screen with the background color."""
self.fill() | [
"def",
"erase_screen",
"(",
"self",
")",
":",
"# <ESC>[2J",
"self",
".",
"fill",
"(",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/screen.py#L326-L329 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Script/Main.py | python | _scons_user_warning | (e) | Handle user warnings. Print out a message and a description of
the warning, along with the line number and routine where it occured.
The file and line number will be the deepest stack frame that is
not part of SCons itself. | Handle user warnings. Print out a message and a description of
the warning, along with the line number and routine where it occured.
The file and line number will be the deepest stack frame that is
not part of SCons itself. | [
"Handle",
"user",
"warnings",
".",
"Print",
"out",
"a",
"message",
"and",
"a",
"description",
"of",
"the",
"warning",
"along",
"with",
"the",
"line",
"number",
"and",
"routine",
"where",
"it",
"occured",
".",
"The",
"file",
"and",
"line",
"number",
"will",
"be",
"the",
"deepest",
"stack",
"frame",
"that",
"is",
"not",
"part",
"of",
"SCons",
"itself",
"."
] | def _scons_user_warning(e):
"""Handle user warnings. Print out a message and a description of
the warning, along with the line number and routine where it occured.
The file and line number will be the deepest stack frame that is
not part of SCons itself.
"""
etype, value, tb = sys.exc_info()
filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extract_tb(tb))
sys.stderr.write("\nscons: warning: %s\n" % e)
sys.stderr.write('File "%s", line %d, in %s\n' % (filename, lineno, routine)) | [
"def",
"_scons_user_warning",
"(",
"e",
")",
":",
"etype",
",",
"value",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"filename",
",",
"lineno",
",",
"routine",
",",
"dummy",
"=",
"find_deepest_user_frame",
"(",
"traceback",
".",
"extract_tb",
"(",
"tb",
")",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\nscons: warning: %s\\n\"",
"%",
"e",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"'File \"%s\", line %d, in %s\\n'",
"%",
"(",
"filename",
",",
"lineno",
",",
"routine",
")",
")"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Script/Main.py#L585-L594 | ||
fasiondog/hikyuu | 842751aa25283f9fdafc6f560ea262f79e67a307 | hikyuu/hub.py | python | remove_hub | (name) | 删除指定的仓库
:param str name: 仓库名称 | 删除指定的仓库 | [
"删除指定的仓库"
] | def remove_hub(name):
"""删除指定的仓库
:param str name: 仓库名称
"""
HubManager().remove_hub(name) | [
"def",
"remove_hub",
"(",
"name",
")",
":",
"HubManager",
"(",
")",
".",
"remove_hub",
"(",
"name",
")"
] | https://github.com/fasiondog/hikyuu/blob/842751aa25283f9fdafc6f560ea262f79e67a307/hikyuu/hub.py#L531-L536 | ||
HyeonwooNoh/caffe | d9e8494a2832d67b25dee37194c7bcb9d52d0e42 | scripts/cpp_lint.py | python | CheckForBadCharacters | (filename, lines, error) | Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | Logs an error for each line containing bad characters. | [
"Logs",
"an",
"error",
"for",
"each",
"line",
"containing",
"bad",
"characters",
"."
] | def CheckForBadCharacters(filename, lines, error):
"""Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
for linenum, line in enumerate(lines):
if u'\ufffd' in line:
error(filename, linenum, 'readability/utf8', 5,
'Line contains invalid UTF-8 (or Unicode replacement character).')
if '\0' in line:
error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') | [
"def",
"CheckForBadCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"for",
"linenum",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"u'\\ufffd'",
"in",
"line",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/utf8'",
",",
"5",
",",
"'Line contains invalid UTF-8 (or Unicode replacement character).'",
")",
"if",
"'\\0'",
"in",
"line",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/nul'",
",",
"5",
",",
"'Line contains NUL byte.'",
")"
] | https://github.com/HyeonwooNoh/caffe/blob/d9e8494a2832d67b25dee37194c7bcb9d52d0e42/scripts/cpp_lint.py#L1483-L1505 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/credentials.py | python | CredentialResolver.load_credentials | (self) | return None | Goes through the credentials chain, returning the first ``Credentials``
that could be loaded. | Goes through the credentials chain, returning the first ``Credentials``
that could be loaded. | [
"Goes",
"through",
"the",
"credentials",
"chain",
"returning",
"the",
"first",
"Credentials",
"that",
"could",
"be",
"loaded",
"."
] | def load_credentials(self):
"""
Goes through the credentials chain, returning the first ``Credentials``
that could be loaded.
"""
# First provider to return a non-None response wins.
for provider in self.providers:
logger.debug("Looking for credentials via: %s", provider.METHOD)
creds = provider.load()
if creds is not None:
return creds
# If we got here, no credentials could be found.
# This feels like it should be an exception, but historically, ``None``
# is returned.
#
# +1
# -js
return None | [
"def",
"load_credentials",
"(",
"self",
")",
":",
"# First provider to return a non-None response wins.",
"for",
"provider",
"in",
"self",
".",
"providers",
":",
"logger",
".",
"debug",
"(",
"\"Looking for credentials via: %s\"",
",",
"provider",
".",
"METHOD",
")",
"creds",
"=",
"provider",
".",
"load",
"(",
")",
"if",
"creds",
"is",
"not",
"None",
":",
"return",
"creds",
"# If we got here, no credentials could be found.",
"# This feels like it should be an exception, but historically, ``None``",
"# is returned.",
"#",
"# +1",
"# -js",
"return",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/credentials.py#L1634-L1652 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/framework/errors.py | python | OutOfRangeError.__init__ | (self, node_def, op, message) | Creates an `OutOfRangeError`. | Creates an `OutOfRangeError`. | [
"Creates",
"an",
"OutOfRangeError",
"."
] | def __init__(self, node_def, op, message):
"""Creates an `OutOfRangeError`."""
super(OutOfRangeError, self).__init__(node_def, op, message,
OUT_OF_RANGE) | [
"def",
"__init__",
"(",
"self",
",",
"node_def",
",",
"op",
",",
"message",
")",
":",
"super",
"(",
"OutOfRangeError",
",",
"self",
")",
".",
"__init__",
"(",
"node_def",
",",
"op",
",",
"message",
",",
"OUT_OF_RANGE",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/errors.py#L345-L348 | ||
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/clang/bindings/python/clang/cindex.py | python | Cursor.get_bitfield_width | (self) | return conf.lib.clang_getFieldDeclBitWidth(self) | Retrieve the width of a bitfield. | Retrieve the width of a bitfield. | [
"Retrieve",
"the",
"width",
"of",
"a",
"bitfield",
"."
] | def get_bitfield_width(self):
"""
Retrieve the width of a bitfield.
"""
return conf.lib.clang_getFieldDeclBitWidth(self) | [
"def",
"get_bitfield_width",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getFieldDeclBitWidth",
"(",
"self",
")"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/bindings/python/clang/cindex.py#L1881-L1885 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Tools/Scripts/analyze_dxp.py | python | render_common_pairs | (profile=None) | return ''.join(seq()) | Renders the most common opcode pairs to a string in order of
descending frequency.
The result is a series of lines of the form:
# of occurrences: ('1st opname', '2nd opname') | Renders the most common opcode pairs to a string in order of
descending frequency. | [
"Renders",
"the",
"most",
"common",
"opcode",
"pairs",
"to",
"a",
"string",
"in",
"order",
"of",
"descending",
"frequency",
"."
] | def render_common_pairs(profile=None):
"""Renders the most common opcode pairs to a string in order of
descending frequency.
The result is a series of lines of the form:
# of occurrences: ('1st opname', '2nd opname')
"""
if profile is None:
profile = snapshot_profile()
def seq():
for _, ops, count in common_pairs(profile):
yield "%s: %s\n" % (count, ops)
return ''.join(seq()) | [
"def",
"render_common_pairs",
"(",
"profile",
"=",
"None",
")",
":",
"if",
"profile",
"is",
"None",
":",
"profile",
"=",
"snapshot_profile",
"(",
")",
"def",
"seq",
"(",
")",
":",
"for",
"_",
",",
"ops",
",",
"count",
"in",
"common_pairs",
"(",
"profile",
")",
":",
"yield",
"\"%s: %s\\n\"",
"%",
"(",
"count",
",",
"ops",
")",
"return",
"''",
".",
"join",
"(",
"seq",
"(",
")",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Tools/Scripts/analyze_dxp.py#L117-L130 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | _cnfmerge | (cnfs) | Internal function. | Internal function. | [
"Internal",
"function",
"."
] | def _cnfmerge(cnfs):
"""Internal function."""
if type(cnfs) is DictionaryType:
return cnfs
elif type(cnfs) in (NoneType, StringType):
return cnfs
else:
cnf = {}
for c in _flatten(cnfs):
try:
cnf.update(c)
except (AttributeError, TypeError), msg:
print "_cnfmerge: fallback due to:", msg
for k, v in c.items():
cnf[k] = v
return cnf | [
"def",
"_cnfmerge",
"(",
"cnfs",
")",
":",
"if",
"type",
"(",
"cnfs",
")",
"is",
"DictionaryType",
":",
"return",
"cnfs",
"elif",
"type",
"(",
"cnfs",
")",
"in",
"(",
"NoneType",
",",
"StringType",
")",
":",
"return",
"cnfs",
"else",
":",
"cnf",
"=",
"{",
"}",
"for",
"c",
"in",
"_flatten",
"(",
"cnfs",
")",
":",
"try",
":",
"cnf",
".",
"update",
"(",
"c",
")",
"except",
"(",
"AttributeError",
",",
"TypeError",
")",
",",
"msg",
":",
"print",
"\"_cnfmerge: fallback due to:\"",
",",
"msg",
"for",
"k",
",",
"v",
"in",
"c",
".",
"items",
"(",
")",
":",
"cnf",
"[",
"k",
"]",
"=",
"v",
"return",
"cnf"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L109-L124 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/scripts.py | python | ScriptMaker.make_multiple | (self, specifications, options=None) | return filenames | Take a list of specifications and make scripts from them,
:param specifications: A list of specifications.
:return: A list of all absolute pathnames written to, | Take a list of specifications and make scripts from them,
:param specifications: A list of specifications.
:return: A list of all absolute pathnames written to, | [
"Take",
"a",
"list",
"of",
"specifications",
"and",
"make",
"scripts",
"from",
"them",
":",
"param",
"specifications",
":",
"A",
"list",
"of",
"specifications",
".",
":",
"return",
":",
"A",
"list",
"of",
"all",
"absolute",
"pathnames",
"written",
"to"
] | def make_multiple(self, specifications, options=None):
"""
Take a list of specifications and make scripts from them,
:param specifications: A list of specifications.
:return: A list of all absolute pathnames written to,
"""
filenames = []
for specification in specifications:
filenames.extend(self.make(specification, options))
return filenames | [
"def",
"make_multiple",
"(",
"self",
",",
"specifications",
",",
"options",
"=",
"None",
")",
":",
"filenames",
"=",
"[",
"]",
"for",
"specification",
"in",
"specifications",
":",
"filenames",
".",
"extend",
"(",
"self",
".",
"make",
"(",
"specification",
",",
"options",
")",
")",
"return",
"filenames"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/scripts.py#L326-L335 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/dist.py | python | Distribution._move_install_requirements_markers | (self) | Move requirements in `install_requires` that are using environment
markers `extras_require`. | Move requirements in `install_requires` that are using environment
markers `extras_require`. | [
"Move",
"requirements",
"in",
"install_requires",
"that",
"are",
"using",
"environment",
"markers",
"extras_require",
"."
] | def _move_install_requirements_markers(self):
"""
Move requirements in `install_requires` that are using environment
markers `extras_require`.
"""
# divide the install_requires into two sets, simple ones still
# handled by install_requires and more complex ones handled
# by extras_require.
def is_simple_req(req):
return not req.marker
spec_inst_reqs = getattr(self, 'install_requires', None) or ()
inst_reqs = list(pkg_resources.parse_requirements(spec_inst_reqs))
simple_reqs = filter(is_simple_req, inst_reqs)
complex_reqs = filterfalse(is_simple_req, inst_reqs)
self.install_requires = list(map(str, simple_reqs))
for r in complex_reqs:
self._tmp_extras_require[':' + str(r.marker)].append(r)
self.extras_require = dict(
(k, [str(r) for r in map(self._clean_req, v)])
for k, v in self._tmp_extras_require.items()
) | [
"def",
"_move_install_requirements_markers",
"(",
"self",
")",
":",
"# divide the install_requires into two sets, simple ones still",
"# handled by install_requires and more complex ones handled",
"# by extras_require.",
"def",
"is_simple_req",
"(",
"req",
")",
":",
"return",
"not",
"req",
".",
"marker",
"spec_inst_reqs",
"=",
"getattr",
"(",
"self",
",",
"'install_requires'",
",",
"None",
")",
"or",
"(",
")",
"inst_reqs",
"=",
"list",
"(",
"pkg_resources",
".",
"parse_requirements",
"(",
"spec_inst_reqs",
")",
")",
"simple_reqs",
"=",
"filter",
"(",
"is_simple_req",
",",
"inst_reqs",
")",
"complex_reqs",
"=",
"filterfalse",
"(",
"is_simple_req",
",",
"inst_reqs",
")",
"self",
".",
"install_requires",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"simple_reqs",
")",
")",
"for",
"r",
"in",
"complex_reqs",
":",
"self",
".",
"_tmp_extras_require",
"[",
"':'",
"+",
"str",
"(",
"r",
".",
"marker",
")",
"]",
".",
"append",
"(",
"r",
")",
"self",
".",
"extras_require",
"=",
"dict",
"(",
"(",
"k",
",",
"[",
"str",
"(",
"r",
")",
"for",
"r",
"in",
"map",
"(",
"self",
".",
"_clean_req",
",",
"v",
")",
"]",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_tmp_extras_require",
".",
"items",
"(",
")",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/dist.py#L528-L552 | ||
jiaxiang-wu/quantized-cnn | 4d020e17026df90e40111d219e3eb74e0afb1588 | cpplint.py | python | FileInfo.Extension | (self) | return self.Split()[2] | File extension - text following the final period. | File extension - text following the final period. | [
"File",
"extension",
"-",
"text",
"following",
"the",
"final",
"period",
"."
] | def Extension(self):
"""File extension - text following the final period."""
return self.Split()[2] | [
"def",
"Extension",
"(",
"self",
")",
":",
"return",
"self",
".",
"Split",
"(",
")",
"[",
"2",
"]"
] | https://github.com/jiaxiang-wu/quantized-cnn/blob/4d020e17026df90e40111d219e3eb74e0afb1588/cpplint.py#L1051-L1053 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py | python | Bits._append | (self, bs) | Append a bitstring to the current bitstring. | Append a bitstring to the current bitstring. | [
"Append",
"a",
"bitstring",
"to",
"the",
"current",
"bitstring",
"."
] | def _append(self, bs):
"""Append a bitstring to the current bitstring."""
self._datastore._appendstore(bs._datastore) | [
"def",
"_append",
"(",
"self",
",",
"bs",
")",
":",
"self",
".",
"_datastore",
".",
"_appendstore",
"(",
"bs",
".",
"_datastore",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L2014-L2016 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/pexpect/pexpect.py | python | spawn.expect_list | (self, pattern_list, timeout=-1, searchwindowsize=-1) | return self.expect_loop(searcher_re(pattern_list),
timeout, searchwindowsize) | This takes a list of compiled regular expressions and returns the
index into the pattern_list that matched the child output. The list may
also contain EOF or TIMEOUT(which are not compiled regular
expressions). This method is similar to the expect() method except that
expect_list() does not recompile the pattern list on every call. This
may help if you are trying to optimize for speed, otherwise just use
the expect() method. This is called by expect(). If timeout==-1 then
the self.timeout value is used. If searchwindowsize==-1 then the
self.searchwindowsize value is used. | This takes a list of compiled regular expressions and returns the
index into the pattern_list that matched the child output. The list may
also contain EOF or TIMEOUT(which are not compiled regular
expressions). This method is similar to the expect() method except that
expect_list() does not recompile the pattern list on every call. This
may help if you are trying to optimize for speed, otherwise just use
the expect() method. This is called by expect(). If timeout==-1 then
the self.timeout value is used. If searchwindowsize==-1 then the
self.searchwindowsize value is used. | [
"This",
"takes",
"a",
"list",
"of",
"compiled",
"regular",
"expressions",
"and",
"returns",
"the",
"index",
"into",
"the",
"pattern_list",
"that",
"matched",
"the",
"child",
"output",
".",
"The",
"list",
"may",
"also",
"contain",
"EOF",
"or",
"TIMEOUT",
"(",
"which",
"are",
"not",
"compiled",
"regular",
"expressions",
")",
".",
"This",
"method",
"is",
"similar",
"to",
"the",
"expect",
"()",
"method",
"except",
"that",
"expect_list",
"()",
"does",
"not",
"recompile",
"the",
"pattern",
"list",
"on",
"every",
"call",
".",
"This",
"may",
"help",
"if",
"you",
"are",
"trying",
"to",
"optimize",
"for",
"speed",
"otherwise",
"just",
"use",
"the",
"expect",
"()",
"method",
".",
"This",
"is",
"called",
"by",
"expect",
"()",
".",
"If",
"timeout",
"==",
"-",
"1",
"then",
"the",
"self",
".",
"timeout",
"value",
"is",
"used",
".",
"If",
"searchwindowsize",
"==",
"-",
"1",
"then",
"the",
"self",
".",
"searchwindowsize",
"value",
"is",
"used",
"."
] | def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1):
"""This takes a list of compiled regular expressions and returns the
index into the pattern_list that matched the child output. The list may
also contain EOF or TIMEOUT(which are not compiled regular
expressions). This method is similar to the expect() method except that
expect_list() does not recompile the pattern list on every call. This
may help if you are trying to optimize for speed, otherwise just use
the expect() method. This is called by expect(). If timeout==-1 then
the self.timeout value is used. If searchwindowsize==-1 then the
self.searchwindowsize value is used. """
return self.expect_loop(searcher_re(pattern_list),
timeout, searchwindowsize) | [
"def",
"expect_list",
"(",
"self",
",",
"pattern_list",
",",
"timeout",
"=",
"-",
"1",
",",
"searchwindowsize",
"=",
"-",
"1",
")",
":",
"return",
"self",
".",
"expect_loop",
"(",
"searcher_re",
"(",
"pattern_list",
")",
",",
"timeout",
",",
"searchwindowsize",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/pexpect/pexpect.py#L1388-L1401 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/mfg/games/linear_quadratic.py | python | Observer.string_from | (self, state, player) | return state.to_string() | Observation of `state` from the PoV of `player`, as a string. | Observation of `state` from the PoV of `player`, as a string. | [
"Observation",
"of",
"state",
"from",
"the",
"PoV",
"of",
"player",
"as",
"a",
"string",
"."
] | def string_from(self, state, player):
"""Observation of `state` from the PoV of `player`, as a string."""
del player
return state.to_string() | [
"def",
"string_from",
"(",
"self",
",",
"state",
",",
"player",
")",
":",
"del",
"player",
"return",
"state",
".",
"to_string",
"(",
")"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/mfg/games/linear_quadratic.py#L387-L390 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/imports.py | python | TomboyHandler.set_links_to_nodes | (self, dad) | After the node import, set the links to nodes on the new tree | After the node import, set the links to nodes on the new tree | [
"After",
"the",
"node",
"import",
"set",
"the",
"links",
"to",
"nodes",
"on",
"the",
"new",
"tree"
] | def set_links_to_nodes(self, dad):
"""After the node import, set the links to nodes on the new tree"""
for link_to_node in self.links_to_node_list:
node_dest = dad.get_tree_iter_from_node_name(link_to_node['name_dest'])
node_source = dad.get_tree_iter_from_node_name(link_to_node['node_source'])
if not node_dest:
#print "node_dest not found"
continue
if not node_source:
#print "node_source not found"
continue
source_buffer = dad.get_textbuffer_from_tree_iter(node_source)
if source_buffer.get_char_count() < link_to_node['char_end']:
continue
property_value = cons.LINK_TYPE_NODE + cons.CHAR_SPACE + str(dad.treestore[node_dest][3])
source_buffer.apply_tag_by_name(dad.apply_tag_exist_or_create(cons.TAG_LINK, property_value),
source_buffer.get_iter_at_offset(link_to_node['char_start']),
source_buffer.get_iter_at_offset(link_to_node['char_end'])) | [
"def",
"set_links_to_nodes",
"(",
"self",
",",
"dad",
")",
":",
"for",
"link_to_node",
"in",
"self",
".",
"links_to_node_list",
":",
"node_dest",
"=",
"dad",
".",
"get_tree_iter_from_node_name",
"(",
"link_to_node",
"[",
"'name_dest'",
"]",
")",
"node_source",
"=",
"dad",
".",
"get_tree_iter_from_node_name",
"(",
"link_to_node",
"[",
"'node_source'",
"]",
")",
"if",
"not",
"node_dest",
":",
"#print \"node_dest not found\"",
"continue",
"if",
"not",
"node_source",
":",
"#print \"node_source not found\"",
"continue",
"source_buffer",
"=",
"dad",
".",
"get_textbuffer_from_tree_iter",
"(",
"node_source",
")",
"if",
"source_buffer",
".",
"get_char_count",
"(",
")",
"<",
"link_to_node",
"[",
"'char_end'",
"]",
":",
"continue",
"property_value",
"=",
"cons",
".",
"LINK_TYPE_NODE",
"+",
"cons",
".",
"CHAR_SPACE",
"+",
"str",
"(",
"dad",
".",
"treestore",
"[",
"node_dest",
"]",
"[",
"3",
"]",
")",
"source_buffer",
".",
"apply_tag_by_name",
"(",
"dad",
".",
"apply_tag_exist_or_create",
"(",
"cons",
".",
"TAG_LINK",
",",
"property_value",
")",
",",
"source_buffer",
".",
"get_iter_at_offset",
"(",
"link_to_node",
"[",
"'char_start'",
"]",
")",
",",
"source_buffer",
".",
"get_iter_at_offset",
"(",
"link_to_node",
"[",
"'char_end'",
"]",
")",
")"
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/imports.py#L1338-L1355 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | demo/Ticker.py | python | TestPanel.SetTickDirection | (self, dir) | Sets tick direction, updates label | Sets tick direction, updates label | [
"Sets",
"tick",
"direction",
"updates",
"label"
] | def SetTickDirection(self, dir):
"""Sets tick direction, updates label"""
self.ticker.SetDirection(dir)
self.dirl.SetLabel("Direction: %s"%(self.ticker.GetDirection())) | [
"def",
"SetTickDirection",
"(",
"self",
",",
"dir",
")",
":",
"self",
".",
"ticker",
".",
"SetDirection",
"(",
"dir",
")",
"self",
".",
"dirl",
".",
"SetLabel",
"(",
"\"Direction: %s\"",
"%",
"(",
"self",
".",
"ticker",
".",
"GetDirection",
"(",
")",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/demo/Ticker.py#L99-L102 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/externals/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/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/externals/six.py#L74-L77 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/sources_list.py | python | SourcesListLoader.get_rosdeps | (self, resource_name, implicit=True) | Always raises as SourceListLoader defines no concrete resources with rosdeps.
:raises: :exc:`rospkg.ResourceNotFound` | Always raises as SourceListLoader defines no concrete resources with rosdeps. | [
"Always",
"raises",
"as",
"SourceListLoader",
"defines",
"no",
"concrete",
"resources",
"with",
"rosdeps",
"."
] | def get_rosdeps(self, resource_name, implicit=True):
"""
Always raises as SourceListLoader defines no concrete resources with rosdeps.
:raises: :exc:`rospkg.ResourceNotFound`
"""
raise rospkg.ResourceNotFound(resource_name) | [
"def",
"get_rosdeps",
"(",
"self",
",",
"resource_name",
",",
"implicit",
"=",
"True",
")",
":",
"raise",
"rospkg",
".",
"ResourceNotFound",
"(",
"resource_name",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/sources_list.py#L657-L663 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/messages.py | python | Message.__ne__ | (self, other) | return not self.__eq__(other) | Not equals operator.
Does field by field comparison with other message. For
non-equality, must be different type or any value of a field must be
non-equal to the same field in the other instance.
Messages not required to be initialized for comparison.
Args:
other: Other message to compare with. | Not equals operator. | [
"Not",
"equals",
"operator",
"."
] | def __ne__(self, other):
"""Not equals operator.
Does field by field comparison with other message. For
non-equality, must be different type or any value of a field must be
non-equal to the same field in the other instance.
Messages not required to be initialized for comparison.
Args:
other: Other message to compare with.
"""
return not self.__eq__(other) | [
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
":",
"return",
"not",
"self",
".",
"__eq__",
"(",
"other",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/messages.py#L1033-L1045 | |
bayandin/chromedriver | d40a2092b50f2fca817221eeb5ea093e0e642c10 | log_replay/client_replay.py | python | _ParserWithUndo.GetNext | (self) | return self._parser.GetNext() | Get the next client command or response in the log.
Returns:
LogEntry object representing the next command or response in the log. | Get the next client command or response in the log. | [
"Get",
"the",
"next",
"client",
"command",
"or",
"response",
"in",
"the",
"log",
"."
] | def GetNext(self):
"""Get the next client command or response in the log.
Returns:
LogEntry object representing the next command or response in the log.
"""
if self._saved_log_entry is not None:
log_entry = self._saved_log_entry
self._saved_log_entry = None
return log_entry
return self._parser.GetNext() | [
"def",
"GetNext",
"(",
"self",
")",
":",
"if",
"self",
".",
"_saved_log_entry",
"is",
"not",
"None",
":",
"log_entry",
"=",
"self",
".",
"_saved_log_entry",
"self",
".",
"_saved_log_entry",
"=",
"None",
"return",
"log_entry",
"return",
"self",
".",
"_parser",
".",
"GetNext",
"(",
")"
] | https://github.com/bayandin/chromedriver/blob/d40a2092b50f2fca817221eeb5ea093e0e642c10/log_replay/client_replay.py#L552-L562 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/jinja2/lexer.py | python | Lexer.tokeniter | (self, source, name, filename=None, state=None) | This method tokenizes the text and returns the tokens in a
generator. Use this method if you just want to tokenize a template. | This method tokenizes the text and returns the tokens in a
generator. Use this method if you just want to tokenize a template. | [
"This",
"method",
"tokenizes",
"the",
"text",
"and",
"returns",
"the",
"tokens",
"in",
"a",
"generator",
".",
"Use",
"this",
"method",
"if",
"you",
"just",
"want",
"to",
"tokenize",
"a",
"template",
"."
] | def tokeniter(self, source, name, filename=None, state=None):
"""This method tokenizes the text and returns the tokens in a
generator. Use this method if you just want to tokenize a template.
"""
source = text_type(source)
lines = source.splitlines()
if self.keep_trailing_newline and source:
for newline in ('\r\n', '\r', '\n'):
if source.endswith(newline):
lines.append('')
break
source = '\n'.join(lines)
pos = 0
lineno = 1
stack = ['root']
if state is not None and state != 'root':
assert state in ('variable', 'block'), 'invalid state'
stack.append(state + '_begin')
else:
state = 'root'
statetokens = self.rules[stack[-1]]
source_length = len(source)
balancing_stack = []
while 1:
# tokenizer loop
for regex, tokens, new_state in statetokens:
m = regex.match(source, pos)
# if no match we try again with the next rule
if m is None:
continue
# we only match blocks and variables if braces / parentheses
# are balanced. continue parsing with the lower rule which
# is the operator rule. do this only if the end tags look
# like operators
if balancing_stack and \
tokens in ('variable_end', 'block_end',
'linestatement_end'):
continue
# tuples support more options
if isinstance(tokens, tuple):
for idx, token in enumerate(tokens):
# failure group
if token.__class__ is Failure:
raise token(lineno, filename)
# bygroup is a bit more complex, in that case we
# yield for the current token the first named
# group that matched
elif token == '#bygroup':
for key, value in iteritems(m.groupdict()):
if value is not None:
yield lineno, key, value
lineno += value.count('\n')
break
else:
raise RuntimeError('%r wanted to resolve '
'the token dynamically'
' but no group matched'
% regex)
# normal group
else:
data = m.group(idx + 1)
if data or token not in ignore_if_empty:
yield lineno, token, data
lineno += data.count('\n')
# strings as token just are yielded as it.
else:
data = m.group()
# update brace/parentheses balance
if tokens == 'operator':
if data == '{':
balancing_stack.append('}')
elif data == '(':
balancing_stack.append(')')
elif data == '[':
balancing_stack.append(']')
elif data in ('}', ')', ']'):
if not balancing_stack:
raise TemplateSyntaxError('unexpected \'%s\'' %
data, lineno, name,
filename)
expected_op = balancing_stack.pop()
if expected_op != data:
raise TemplateSyntaxError('unexpected \'%s\', '
'expected \'%s\'' %
(data, expected_op),
lineno, name,
filename)
# yield items
if data or tokens not in ignore_if_empty:
yield lineno, tokens, data
lineno += data.count('\n')
# fetch new position into new variable so that we can check
# if there is a internal parsing error which would result
# in an infinite loop
pos2 = m.end()
# handle state changes
if new_state is not None:
# remove the uppermost state
if new_state == '#pop':
stack.pop()
# resolve the new state by group checking
elif new_state == '#bygroup':
for key, value in iteritems(m.groupdict()):
if value is not None:
stack.append(key)
break
else:
raise RuntimeError('%r wanted to resolve the '
'new state dynamically but'
' no group matched' %
regex)
# direct state name given
else:
stack.append(new_state)
statetokens = self.rules[stack[-1]]
# we are still at the same position and no stack change.
# this means a loop without break condition, avoid that and
# raise error
elif pos2 == pos:
raise RuntimeError('%r yielded empty string without '
'stack change' % regex)
# publish new function and start again
pos = pos2
break
# if loop terminated without break we haven't found a single match
# either we are at the end of the file or we have a problem
else:
# end of text
if pos >= source_length:
return
# something went wrong
raise TemplateSyntaxError('unexpected char %r at %d' %
(source[pos], pos), lineno,
name, filename) | [
"def",
"tokeniter",
"(",
"self",
",",
"source",
",",
"name",
",",
"filename",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"source",
"=",
"text_type",
"(",
"source",
")",
"lines",
"=",
"source",
".",
"splitlines",
"(",
")",
"if",
"self",
".",
"keep_trailing_newline",
"and",
"source",
":",
"for",
"newline",
"in",
"(",
"'\\r\\n'",
",",
"'\\r'",
",",
"'\\n'",
")",
":",
"if",
"source",
".",
"endswith",
"(",
"newline",
")",
":",
"lines",
".",
"append",
"(",
"''",
")",
"break",
"source",
"=",
"'\\n'",
".",
"join",
"(",
"lines",
")",
"pos",
"=",
"0",
"lineno",
"=",
"1",
"stack",
"=",
"[",
"'root'",
"]",
"if",
"state",
"is",
"not",
"None",
"and",
"state",
"!=",
"'root'",
":",
"assert",
"state",
"in",
"(",
"'variable'",
",",
"'block'",
")",
",",
"'invalid state'",
"stack",
".",
"append",
"(",
"state",
"+",
"'_begin'",
")",
"else",
":",
"state",
"=",
"'root'",
"statetokens",
"=",
"self",
".",
"rules",
"[",
"stack",
"[",
"-",
"1",
"]",
"]",
"source_length",
"=",
"len",
"(",
"source",
")",
"balancing_stack",
"=",
"[",
"]",
"while",
"1",
":",
"# tokenizer loop",
"for",
"regex",
",",
"tokens",
",",
"new_state",
"in",
"statetokens",
":",
"m",
"=",
"regex",
".",
"match",
"(",
"source",
",",
"pos",
")",
"# if no match we try again with the next rule",
"if",
"m",
"is",
"None",
":",
"continue",
"# we only match blocks and variables if braces / parentheses",
"# are balanced. continue parsing with the lower rule which",
"# is the operator rule. do this only if the end tags look",
"# like operators",
"if",
"balancing_stack",
"and",
"tokens",
"in",
"(",
"'variable_end'",
",",
"'block_end'",
",",
"'linestatement_end'",
")",
":",
"continue",
"# tuples support more options",
"if",
"isinstance",
"(",
"tokens",
",",
"tuple",
")",
":",
"for",
"idx",
",",
"token",
"in",
"enumerate",
"(",
"tokens",
")",
":",
"# failure group",
"if",
"token",
".",
"__class__",
"is",
"Failure",
":",
"raise",
"token",
"(",
"lineno",
",",
"filename",
")",
"# bygroup is a bit more complex, in that case we",
"# yield for the current token the first named",
"# group that matched",
"elif",
"token",
"==",
"'#bygroup'",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"m",
".",
"groupdict",
"(",
")",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"yield",
"lineno",
",",
"key",
",",
"value",
"lineno",
"+=",
"value",
".",
"count",
"(",
"'\\n'",
")",
"break",
"else",
":",
"raise",
"RuntimeError",
"(",
"'%r wanted to resolve '",
"'the token dynamically'",
"' but no group matched'",
"%",
"regex",
")",
"# normal group",
"else",
":",
"data",
"=",
"m",
".",
"group",
"(",
"idx",
"+",
"1",
")",
"if",
"data",
"or",
"token",
"not",
"in",
"ignore_if_empty",
":",
"yield",
"lineno",
",",
"token",
",",
"data",
"lineno",
"+=",
"data",
".",
"count",
"(",
"'\\n'",
")",
"# strings as token just are yielded as it.",
"else",
":",
"data",
"=",
"m",
".",
"group",
"(",
")",
"# update brace/parentheses balance",
"if",
"tokens",
"==",
"'operator'",
":",
"if",
"data",
"==",
"'{'",
":",
"balancing_stack",
".",
"append",
"(",
"'}'",
")",
"elif",
"data",
"==",
"'('",
":",
"balancing_stack",
".",
"append",
"(",
"')'",
")",
"elif",
"data",
"==",
"'['",
":",
"balancing_stack",
".",
"append",
"(",
"']'",
")",
"elif",
"data",
"in",
"(",
"'}'",
",",
"')'",
",",
"']'",
")",
":",
"if",
"not",
"balancing_stack",
":",
"raise",
"TemplateSyntaxError",
"(",
"'unexpected \\'%s\\''",
"%",
"data",
",",
"lineno",
",",
"name",
",",
"filename",
")",
"expected_op",
"=",
"balancing_stack",
".",
"pop",
"(",
")",
"if",
"expected_op",
"!=",
"data",
":",
"raise",
"TemplateSyntaxError",
"(",
"'unexpected \\'%s\\', '",
"'expected \\'%s\\''",
"%",
"(",
"data",
",",
"expected_op",
")",
",",
"lineno",
",",
"name",
",",
"filename",
")",
"# yield items",
"if",
"data",
"or",
"tokens",
"not",
"in",
"ignore_if_empty",
":",
"yield",
"lineno",
",",
"tokens",
",",
"data",
"lineno",
"+=",
"data",
".",
"count",
"(",
"'\\n'",
")",
"# fetch new position into new variable so that we can check",
"# if there is a internal parsing error which would result",
"# in an infinite loop",
"pos2",
"=",
"m",
".",
"end",
"(",
")",
"# handle state changes",
"if",
"new_state",
"is",
"not",
"None",
":",
"# remove the uppermost state",
"if",
"new_state",
"==",
"'#pop'",
":",
"stack",
".",
"pop",
"(",
")",
"# resolve the new state by group checking",
"elif",
"new_state",
"==",
"'#bygroup'",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"m",
".",
"groupdict",
"(",
")",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"stack",
".",
"append",
"(",
"key",
")",
"break",
"else",
":",
"raise",
"RuntimeError",
"(",
"'%r wanted to resolve the '",
"'new state dynamically but'",
"' no group matched'",
"%",
"regex",
")",
"# direct state name given",
"else",
":",
"stack",
".",
"append",
"(",
"new_state",
")",
"statetokens",
"=",
"self",
".",
"rules",
"[",
"stack",
"[",
"-",
"1",
"]",
"]",
"# we are still at the same position and no stack change.",
"# this means a loop without break condition, avoid that and",
"# raise error",
"elif",
"pos2",
"==",
"pos",
":",
"raise",
"RuntimeError",
"(",
"'%r yielded empty string without '",
"'stack change'",
"%",
"regex",
")",
"# publish new function and start again",
"pos",
"=",
"pos2",
"break",
"# if loop terminated without break we haven't found a single match",
"# either we are at the end of the file or we have a problem",
"else",
":",
"# end of text",
"if",
"pos",
">=",
"source_length",
":",
"return",
"# something went wrong",
"raise",
"TemplateSyntaxError",
"(",
"'unexpected char %r at %d'",
"%",
"(",
"source",
"[",
"pos",
"]",
",",
"pos",
")",
",",
"lineno",
",",
"name",
",",
"filename",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/lexer.py#L593-L733 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | Log_GetActiveTarget | (*args) | return _misc_.Log_GetActiveTarget(*args) | Log_GetActiveTarget() -> Log | Log_GetActiveTarget() -> Log | [
"Log_GetActiveTarget",
"()",
"-",
">",
"Log"
] | def Log_GetActiveTarget(*args):
"""Log_GetActiveTarget() -> Log"""
return _misc_.Log_GetActiveTarget(*args) | [
"def",
"Log_GetActiveTarget",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"Log_GetActiveTarget",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1664-L1666 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/shutil.py | python | copystat | (src, dst) | Copy all stat info (mode bits, atime, mtime, flags) from src to dst | Copy all stat info (mode bits, atime, mtime, flags) from src to dst | [
"Copy",
"all",
"stat",
"info",
"(",
"mode",
"bits",
"atime",
"mtime",
"flags",
")",
"from",
"src",
"to",
"dst"
] | def copystat(src, dst):
"""Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
if hasattr(os, 'utime'):
os.utime(dst, (st.st_atime, st.st_mtime))
if hasattr(os, 'chmod'):
os.chmod(dst, mode)
if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
try:
os.chflags(dst, st.st_flags)
except OSError as why:
if (not hasattr(errno, 'EOPNOTSUPP') or
why.errno != errno.EOPNOTSUPP):
raise | [
"def",
"copystat",
"(",
"src",
",",
"dst",
")",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"src",
")",
"mode",
"=",
"stat",
".",
"S_IMODE",
"(",
"st",
".",
"st_mode",
")",
"if",
"hasattr",
"(",
"os",
",",
"'utime'",
")",
":",
"os",
".",
"utime",
"(",
"dst",
",",
"(",
"st",
".",
"st_atime",
",",
"st",
".",
"st_mtime",
")",
")",
"if",
"hasattr",
"(",
"os",
",",
"'chmod'",
")",
":",
"os",
".",
"chmod",
"(",
"dst",
",",
"mode",
")",
"if",
"hasattr",
"(",
"os",
",",
"'chflags'",
")",
"and",
"hasattr",
"(",
"st",
",",
"'st_flags'",
")",
":",
"try",
":",
"os",
".",
"chflags",
"(",
"dst",
",",
"st",
".",
"st_flags",
")",
"except",
"OSError",
"as",
"why",
":",
"if",
"(",
"not",
"hasattr",
"(",
"errno",
",",
"'EOPNOTSUPP'",
")",
"or",
"why",
".",
"errno",
"!=",
"errno",
".",
"EOPNOTSUPP",
")",
":",
"raise"
] | 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/_backport/shutil.py#L114-L128 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/polynomial/hermite_e.py | python | hermeadd | (c1, c2) | return pu._add(c1, c2) | Add one Hermite series to another.
Returns the sum of two Hermite series `c1` + `c2`. The arguments
are sequences of coefficients ordered from lowest order term to
highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Array representing the Hermite series of their sum.
See Also
--------
hermesub, hermemulx, hermemul, hermediv, hermepow
Notes
-----
Unlike multiplication, division, etc., the sum of two Hermite series
is a Hermite series (without having to "reproject" the result onto
the basis set) so addition, just like that of "standard" polynomials,
is simply "component-wise."
Examples
--------
>>> from numpy.polynomial.hermite_e import hermeadd
>>> hermeadd([1, 2, 3], [1, 2, 3, 4])
array([2., 4., 6., 4.]) | Add one Hermite series to another. | [
"Add",
"one",
"Hermite",
"series",
"to",
"another",
"."
] | def hermeadd(c1, c2):
"""
Add one Hermite series to another.
Returns the sum of two Hermite series `c1` + `c2`. The arguments
are sequences of coefficients ordered from lowest order term to
highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Array representing the Hermite series of their sum.
See Also
--------
hermesub, hermemulx, hermemul, hermediv, hermepow
Notes
-----
Unlike multiplication, division, etc., the sum of two Hermite series
is a Hermite series (without having to "reproject" the result onto
the basis set) so addition, just like that of "standard" polynomials,
is simply "component-wise."
Examples
--------
>>> from numpy.polynomial.hermite_e import hermeadd
>>> hermeadd([1, 2, 3], [1, 2, 3, 4])
array([2., 4., 6., 4.])
"""
return pu._add(c1, c2) | [
"def",
"hermeadd",
"(",
"c1",
",",
"c2",
")",
":",
"return",
"pu",
".",
"_add",
"(",
"c1",
",",
"c2",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/hermite_e.py#L312-L349 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/nll_loss.py | python | _nll_loss_tbe | () | return | NLLLoss TBE register | NLLLoss TBE register | [
"NLLLoss",
"TBE",
"register"
] | def _nll_loss_tbe():
"""NLLLoss TBE register"""
return | [
"def",
"_nll_loss_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/nll_loss.py#L39-L41 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/beanstalk/layer1.py | python | Layer1.describe_environments | (self, application_name=None, version_label=None,
environment_ids=None, environment_names=None,
include_deleted=None,
included_deleted_back_to=None) | return self._get_response('DescribeEnvironments', params) | Returns descriptions for existing environments.
:type application_name: string
:param application_name: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to include only those that are associated
with this application.
:type version_label: string
:param version_label: If specified, AWS Elastic Beanstalk restricts the
returned descriptions to include only those that are associated
with this application version.
:type environment_ids: list
:param environment_ids: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to include only those that have the
specified IDs.
:type environment_names: list
:param environment_names: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to include only those that have the
specified names.
:type include_deleted: boolean
:param include_deleted: Indicates whether to include deleted
environments: true: Environments that have been deleted after
IncludedDeletedBackTo are displayed. false: Do not include deleted
environments.
:type included_deleted_back_to: timestamp
:param included_deleted_back_to: If specified when IncludeDeleted is
set to true, then environments deleted after this date are
displayed. | Returns descriptions for existing environments. | [
"Returns",
"descriptions",
"for",
"existing",
"environments",
"."
] | def describe_environments(self, application_name=None, version_label=None,
environment_ids=None, environment_names=None,
include_deleted=None,
included_deleted_back_to=None):
"""Returns descriptions for existing environments.
:type application_name: string
:param application_name: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to include only those that are associated
with this application.
:type version_label: string
:param version_label: If specified, AWS Elastic Beanstalk restricts the
returned descriptions to include only those that are associated
with this application version.
:type environment_ids: list
:param environment_ids: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to include only those that have the
specified IDs.
:type environment_names: list
:param environment_names: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to include only those that have the
specified names.
:type include_deleted: boolean
:param include_deleted: Indicates whether to include deleted
environments: true: Environments that have been deleted after
IncludedDeletedBackTo are displayed. false: Do not include deleted
environments.
:type included_deleted_back_to: timestamp
:param included_deleted_back_to: If specified when IncludeDeleted is
set to true, then environments deleted after this date are
displayed.
"""
params = {}
if application_name:
params['ApplicationName'] = application_name
if version_label:
params['VersionLabel'] = version_label
if environment_ids:
self.build_list_params(params, environment_ids,
'EnvironmentIds.member')
if environment_names:
self.build_list_params(params, environment_names,
'EnvironmentNames.member')
if include_deleted:
params['IncludeDeleted'] = self._encode_bool(include_deleted)
if included_deleted_back_to:
params['IncludedDeletedBackTo'] = included_deleted_back_to
return self._get_response('DescribeEnvironments', params) | [
"def",
"describe_environments",
"(",
"self",
",",
"application_name",
"=",
"None",
",",
"version_label",
"=",
"None",
",",
"environment_ids",
"=",
"None",
",",
"environment_names",
"=",
"None",
",",
"include_deleted",
"=",
"None",
",",
"included_deleted_back_to",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"application_name",
":",
"params",
"[",
"'ApplicationName'",
"]",
"=",
"application_name",
"if",
"version_label",
":",
"params",
"[",
"'VersionLabel'",
"]",
"=",
"version_label",
"if",
"environment_ids",
":",
"self",
".",
"build_list_params",
"(",
"params",
",",
"environment_ids",
",",
"'EnvironmentIds.member'",
")",
"if",
"environment_names",
":",
"self",
".",
"build_list_params",
"(",
"params",
",",
"environment_names",
",",
"'EnvironmentNames.member'",
")",
"if",
"include_deleted",
":",
"params",
"[",
"'IncludeDeleted'",
"]",
"=",
"self",
".",
"_encode_bool",
"(",
"include_deleted",
")",
"if",
"included_deleted_back_to",
":",
"params",
"[",
"'IncludedDeletedBackTo'",
"]",
"=",
"included_deleted_back_to",
"return",
"self",
".",
"_get_response",
"(",
"'DescribeEnvironments'",
",",
"params",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/beanstalk/layer1.py#L617-L669 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/req/constructors.py | python | parse_editable | (editable_req) | return package_name, url, set() | Parses an editable requirement into:
- a requirement name
- an URL
- extras
- editable options
Accepted requirements:
svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir
.[some_extra] | Parses an editable requirement into:
- a requirement name
- an URL
- extras
- editable options
Accepted requirements:
svn+http://blahblah | [
"Parses",
"an",
"editable",
"requirement",
"into",
":",
"-",
"a",
"requirement",
"name",
"-",
"an",
"URL",
"-",
"extras",
"-",
"editable",
"options",
"Accepted",
"requirements",
":",
"svn",
"+",
"http",
":",
"//",
"blahblah"
] | def parse_editable(editable_req):
# type: (str) -> Tuple[Optional[str], str, Set[str]]
"""Parses an editable requirement into:
- a requirement name
- an URL
- extras
- editable options
Accepted requirements:
svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir
.[some_extra]
"""
url = editable_req
# If a file path is specified with extras, strip off the extras.
url_no_extras, extras = _strip_extras(url)
if os.path.isdir(url_no_extras):
if not os.path.exists(os.path.join(url_no_extras, 'setup.py')):
msg = (
'File "setup.py" not found. Directory cannot be installed '
'in editable mode: {}'.format(os.path.abspath(url_no_extras))
)
pyproject_path = make_pyproject_path(url_no_extras)
if os.path.isfile(pyproject_path):
msg += (
'\n(A "pyproject.toml" file was found, but editable '
'mode currently requires a setup.py based build.)'
)
raise InstallationError(msg)
# Treating it as code that has already been checked out
url_no_extras = path_to_url(url_no_extras)
if url_no_extras.lower().startswith('file:'):
package_name = Link(url_no_extras).egg_fragment
if extras:
return (
package_name,
url_no_extras,
Requirement("placeholder" + extras.lower()).extras,
)
else:
return package_name, url_no_extras, set()
for version_control in vcs:
if url.lower().startswith(f'{version_control}:'):
url = f'{version_control}+{url}'
break
link = Link(url)
if not link.is_vcs:
backends = ", ".join(vcs.all_schemes)
raise InstallationError(
f'{editable_req} is not a valid editable requirement. '
f'It should either be a path to a local project or a VCS URL '
f'(beginning with {backends}).'
)
package_name = link.egg_fragment
if not package_name:
raise InstallationError(
"Could not detect requirement name for '{}', please specify one "
"with #egg=your_package_name".format(editable_req)
)
return package_name, url, set() | [
"def",
"parse_editable",
"(",
"editable_req",
")",
":",
"# type: (str) -> Tuple[Optional[str], str, Set[str]]",
"url",
"=",
"editable_req",
"# If a file path is specified with extras, strip off the extras.",
"url_no_extras",
",",
"extras",
"=",
"_strip_extras",
"(",
"url",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"url_no_extras",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"url_no_extras",
",",
"'setup.py'",
")",
")",
":",
"msg",
"=",
"(",
"'File \"setup.py\" not found. Directory cannot be installed '",
"'in editable mode: {}'",
".",
"format",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"url_no_extras",
")",
")",
")",
"pyproject_path",
"=",
"make_pyproject_path",
"(",
"url_no_extras",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"pyproject_path",
")",
":",
"msg",
"+=",
"(",
"'\\n(A \"pyproject.toml\" file was found, but editable '",
"'mode currently requires a setup.py based build.)'",
")",
"raise",
"InstallationError",
"(",
"msg",
")",
"# Treating it as code that has already been checked out",
"url_no_extras",
"=",
"path_to_url",
"(",
"url_no_extras",
")",
"if",
"url_no_extras",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'file:'",
")",
":",
"package_name",
"=",
"Link",
"(",
"url_no_extras",
")",
".",
"egg_fragment",
"if",
"extras",
":",
"return",
"(",
"package_name",
",",
"url_no_extras",
",",
"Requirement",
"(",
"\"placeholder\"",
"+",
"extras",
".",
"lower",
"(",
")",
")",
".",
"extras",
",",
")",
"else",
":",
"return",
"package_name",
",",
"url_no_extras",
",",
"set",
"(",
")",
"for",
"version_control",
"in",
"vcs",
":",
"if",
"url",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"f'{version_control}:'",
")",
":",
"url",
"=",
"f'{version_control}+{url}'",
"break",
"link",
"=",
"Link",
"(",
"url",
")",
"if",
"not",
"link",
".",
"is_vcs",
":",
"backends",
"=",
"\", \"",
".",
"join",
"(",
"vcs",
".",
"all_schemes",
")",
"raise",
"InstallationError",
"(",
"f'{editable_req} is not a valid editable requirement. '",
"f'It should either be a path to a local project or a VCS URL '",
"f'(beginning with {backends}).'",
")",
"package_name",
"=",
"link",
".",
"egg_fragment",
"if",
"not",
"package_name",
":",
"raise",
"InstallationError",
"(",
"\"Could not detect requirement name for '{}', please specify one \"",
"\"with #egg=your_package_name\"",
".",
"format",
"(",
"editable_req",
")",
")",
"return",
"package_name",
",",
"url",
",",
"set",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/req/constructors.py#L67-L133 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pyedbglib/serialport/wincdc.py | python | CDC.iter_keys_as_str | (self, key) | Iterate over subkeys of a key returning subkey as string | Iterate over subkeys of a key returning subkey as string | [
"Iterate",
"over",
"subkeys",
"of",
"a",
"key",
"returning",
"subkey",
"as",
"string"
] | def iter_keys_as_str(self, key):
"""
Iterate over subkeys of a key returning subkey as string
"""
for i in range(winreg.QueryInfoKey(key)[0]):
yield winreg.EnumKey(key, i) | [
"def",
"iter_keys_as_str",
"(",
"self",
",",
"key",
")",
":",
"for",
"i",
"in",
"range",
"(",
"winreg",
".",
"QueryInfoKey",
"(",
"key",
")",
"[",
"0",
"]",
")",
":",
"yield",
"winreg",
".",
"EnumKey",
"(",
"key",
",",
"i",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/serialport/wincdc.py#L41-L46 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/driver.py | python | Event.query | (self) | Returns True if all work before the most recent record has completed;
otherwise, returns False. | Returns True if all work before the most recent record has completed;
otherwise, returns False. | [
"Returns",
"True",
"if",
"all",
"work",
"before",
"the",
"most",
"recent",
"record",
"has",
"completed",
";",
"otherwise",
"returns",
"False",
"."
] | def query(self):
"""
Returns True if all work before the most recent record has completed;
otherwise, returns False.
"""
try:
driver.cuEventQuery(self.handle)
except CudaAPIError as e:
if e.code == enums.CUDA_ERROR_NOT_READY:
return False
else:
raise
else:
return True | [
"def",
"query",
"(",
"self",
")",
":",
"try",
":",
"driver",
".",
"cuEventQuery",
"(",
"self",
".",
"handle",
")",
"except",
"CudaAPIError",
"as",
"e",
":",
"if",
"e",
".",
"code",
"==",
"enums",
".",
"CUDA_ERROR_NOT_READY",
":",
"return",
"False",
"else",
":",
"raise",
"else",
":",
"return",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/cudadrv/driver.py#L1440-L1453 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.FormatRange | (*args, **kwargs) | return _stc.StyledTextCtrl_FormatRange(*args, **kwargs) | FormatRange(self, bool doDraw, int startPos, int endPos, DC draw, DC target,
Rect renderRect, Rect pageRect) -> int
On Windows, will draw the document into a display context such as a printer. | FormatRange(self, bool doDraw, int startPos, int endPos, DC draw, DC target,
Rect renderRect, Rect pageRect) -> int | [
"FormatRange",
"(",
"self",
"bool",
"doDraw",
"int",
"startPos",
"int",
"endPos",
"DC",
"draw",
"DC",
"target",
"Rect",
"renderRect",
"Rect",
"pageRect",
")",
"-",
">",
"int"
] | def FormatRange(*args, **kwargs):
"""
FormatRange(self, bool doDraw, int startPos, int endPos, DC draw, DC target,
Rect renderRect, Rect pageRect) -> int
On Windows, will draw the document into a display context such as a printer.
"""
return _stc.StyledTextCtrl_FormatRange(*args, **kwargs) | [
"def",
"FormatRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_FormatRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L3504-L3511 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | llvm/utils/benchmark/tools/gbench/report.py | python | generate_difference_report | (json1, json2, use_color=True) | return output_strs | Calculate and report the difference between each test of two benchmarks
runs specified as 'json1' and 'json2'. | Calculate and report the difference between each test of two benchmarks
runs specified as 'json1' and 'json2'. | [
"Calculate",
"and",
"report",
"the",
"difference",
"between",
"each",
"test",
"of",
"two",
"benchmarks",
"runs",
"specified",
"as",
"json1",
"and",
"json2",
"."
] | def generate_difference_report(json1, json2, use_color=True):
"""
Calculate and report the difference between each test of two benchmarks
runs specified as 'json1' and 'json2'.
"""
first_col_width = find_longest_name(json1['benchmarks'])
def find_test(name):
for b in json2['benchmarks']:
if b['name'] == name:
return b
return None
first_col_width = max(first_col_width, len('Benchmark'))
first_line = "{:<{}s}Time CPU Time Old Time New CPU Old CPU New".format(
'Benchmark', 12 + first_col_width)
output_strs = [first_line, '-' * len(first_line)]
gen = (bn for bn in json1['benchmarks'] if 'real_time' in bn and 'cpu_time' in bn)
for bn in gen:
other_bench = find_test(bn['name'])
if not other_bench:
continue
if bn['time_unit'] != other_bench['time_unit']:
continue
def get_color(res):
if res > 0.05:
return BC_FAIL
elif res > -0.07:
return BC_WHITE
else:
return BC_CYAN
fmt_str = "{}{:<{}s}{endc}{}{:+16.4f}{endc}{}{:+16.4f}{endc}{:14.0f}{:14.0f}{endc}{:14.0f}{:14.0f}"
tres = calculate_change(bn['real_time'], other_bench['real_time'])
cpures = calculate_change(bn['cpu_time'], other_bench['cpu_time'])
output_strs += [color_format(use_color, fmt_str,
BC_HEADER, bn['name'], first_col_width,
get_color(tres), tres, get_color(cpures), cpures,
bn['real_time'], other_bench['real_time'],
bn['cpu_time'], other_bench['cpu_time'],
endc=BC_ENDC)]
return output_strs | [
"def",
"generate_difference_report",
"(",
"json1",
",",
"json2",
",",
"use_color",
"=",
"True",
")",
":",
"first_col_width",
"=",
"find_longest_name",
"(",
"json1",
"[",
"'benchmarks'",
"]",
")",
"def",
"find_test",
"(",
"name",
")",
":",
"for",
"b",
"in",
"json2",
"[",
"'benchmarks'",
"]",
":",
"if",
"b",
"[",
"'name'",
"]",
"==",
"name",
":",
"return",
"b",
"return",
"None",
"first_col_width",
"=",
"max",
"(",
"first_col_width",
",",
"len",
"(",
"'Benchmark'",
")",
")",
"first_line",
"=",
"\"{:<{}s}Time CPU Time Old Time New CPU Old CPU New\"",
".",
"format",
"(",
"'Benchmark'",
",",
"12",
"+",
"first_col_width",
")",
"output_strs",
"=",
"[",
"first_line",
",",
"'-'",
"*",
"len",
"(",
"first_line",
")",
"]",
"gen",
"=",
"(",
"bn",
"for",
"bn",
"in",
"json1",
"[",
"'benchmarks'",
"]",
"if",
"'real_time'",
"in",
"bn",
"and",
"'cpu_time'",
"in",
"bn",
")",
"for",
"bn",
"in",
"gen",
":",
"other_bench",
"=",
"find_test",
"(",
"bn",
"[",
"'name'",
"]",
")",
"if",
"not",
"other_bench",
":",
"continue",
"if",
"bn",
"[",
"'time_unit'",
"]",
"!=",
"other_bench",
"[",
"'time_unit'",
"]",
":",
"continue",
"def",
"get_color",
"(",
"res",
")",
":",
"if",
"res",
">",
"0.05",
":",
"return",
"BC_FAIL",
"elif",
"res",
">",
"-",
"0.07",
":",
"return",
"BC_WHITE",
"else",
":",
"return",
"BC_CYAN",
"fmt_str",
"=",
"\"{}{:<{}s}{endc}{}{:+16.4f}{endc}{}{:+16.4f}{endc}{:14.0f}{:14.0f}{endc}{:14.0f}{:14.0f}\"",
"tres",
"=",
"calculate_change",
"(",
"bn",
"[",
"'real_time'",
"]",
",",
"other_bench",
"[",
"'real_time'",
"]",
")",
"cpures",
"=",
"calculate_change",
"(",
"bn",
"[",
"'cpu_time'",
"]",
",",
"other_bench",
"[",
"'cpu_time'",
"]",
")",
"output_strs",
"+=",
"[",
"color_format",
"(",
"use_color",
",",
"fmt_str",
",",
"BC_HEADER",
",",
"bn",
"[",
"'name'",
"]",
",",
"first_col_width",
",",
"get_color",
"(",
"tres",
")",
",",
"tres",
",",
"get_color",
"(",
"cpures",
")",
",",
"cpures",
",",
"bn",
"[",
"'real_time'",
"]",
",",
"other_bench",
"[",
"'real_time'",
"]",
",",
"bn",
"[",
"'cpu_time'",
"]",
",",
"other_bench",
"[",
"'cpu_time'",
"]",
",",
"endc",
"=",
"BC_ENDC",
")",
"]",
"return",
"output_strs"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/llvm/utils/benchmark/tools/gbench/report.py#L87-L128 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py | python | RandomShuffleQueue.__init__ | (self, capacity, min_after_dequeue, dtypes, shapes=None,
names=None, seed=None, shared_name=None,
name="random_shuffle_queue") | Create a queue that dequeues elements in a random order.
A `RandomShuffleQueue` has bounded capacity; supports multiple
concurrent producers and consumers; and provides exactly-once
delivery.
A `RandomShuffleQueue` holds a list of up to `capacity`
elements. Each element is a fixed-length tuple of tensors whose
dtypes are described by `dtypes`, and whose shapes are optionally
described by the `shapes` argument.
If the `shapes` argument is specified, each component of a queue
element must have the respective fixed shape. If it is
unspecified, different queue elements may have different shapes,
but the use of `dequeue_many` is disallowed.
The `min_after_dequeue` argument allows the caller to specify a
minimum number of elements that will remain in the queue after a
`dequeue` or `dequeue_many` operation completes, to ensure a
minimum level of mixing of elements. This invariant is maintained
by blocking those operations until sufficient elements have been
enqueued. The `min_after_dequeue` argument is ignored after the
queue has been closed.
Args:
capacity: An integer. The upper bound on the number of elements
that may be stored in this queue.
min_after_dequeue: An integer (described above).
dtypes: A list of `DType` objects. The length of `dtypes` must equal
the number of tensors in each queue element.
shapes: (Optional.) A list of fully-defined `TensorShape` objects
with the same length as `dtypes`, or `None`.
names: (Optional.) A list of string naming the components in the queue
with the same length as `dtypes`, or `None`. If specified the dequeue
methods return a dictionary with the names as keys.
seed: A Python integer. Used to create a random seed. See
[`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
for behavior.
shared_name: (Optional.) If non-empty, this queue will be shared under
the given name across multiple sessions.
name: Optional name for the queue operation. | Create a queue that dequeues elements in a random order. | [
"Create",
"a",
"queue",
"that",
"dequeues",
"elements",
"in",
"a",
"random",
"order",
"."
] | def __init__(self, capacity, min_after_dequeue, dtypes, shapes=None,
names=None, seed=None, shared_name=None,
name="random_shuffle_queue"):
"""Create a queue that dequeues elements in a random order.
A `RandomShuffleQueue` has bounded capacity; supports multiple
concurrent producers and consumers; and provides exactly-once
delivery.
A `RandomShuffleQueue` holds a list of up to `capacity`
elements. Each element is a fixed-length tuple of tensors whose
dtypes are described by `dtypes`, and whose shapes are optionally
described by the `shapes` argument.
If the `shapes` argument is specified, each component of a queue
element must have the respective fixed shape. If it is
unspecified, different queue elements may have different shapes,
but the use of `dequeue_many` is disallowed.
The `min_after_dequeue` argument allows the caller to specify a
minimum number of elements that will remain in the queue after a
`dequeue` or `dequeue_many` operation completes, to ensure a
minimum level of mixing of elements. This invariant is maintained
by blocking those operations until sufficient elements have been
enqueued. The `min_after_dequeue` argument is ignored after the
queue has been closed.
Args:
capacity: An integer. The upper bound on the number of elements
that may be stored in this queue.
min_after_dequeue: An integer (described above).
dtypes: A list of `DType` objects. The length of `dtypes` must equal
the number of tensors in each queue element.
shapes: (Optional.) A list of fully-defined `TensorShape` objects
with the same length as `dtypes`, or `None`.
names: (Optional.) A list of string naming the components in the queue
with the same length as `dtypes`, or `None`. If specified the dequeue
methods return a dictionary with the names as keys.
seed: A Python integer. Used to create a random seed. See
[`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
for behavior.
shared_name: (Optional.) If non-empty, this queue will be shared under
the given name across multiple sessions.
name: Optional name for the queue operation.
"""
dtypes = _as_type_list(dtypes)
shapes = _as_shape_list(shapes, dtypes)
names = _as_name_list(names, dtypes)
# If shared_name is provided and an op seed was not provided, we must ensure
# that we use the same seed for all queues with the same shared_name.
if shared_name is not None and seed is None:
seed = hash(shared_name)
seed1, seed2 = random_seed.get_seed(seed)
queue_ref = gen_data_flow_ops._random_shuffle_queue(
component_types=dtypes, shapes=shapes, capacity=capacity,
min_after_dequeue=min_after_dequeue, seed=seed1, seed2=seed2,
shared_name=shared_name, name=name)
super(RandomShuffleQueue, self).__init__(dtypes, shapes, names, queue_ref) | [
"def",
"__init__",
"(",
"self",
",",
"capacity",
",",
"min_after_dequeue",
",",
"dtypes",
",",
"shapes",
"=",
"None",
",",
"names",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"shared_name",
"=",
"None",
",",
"name",
"=",
"\"random_shuffle_queue\"",
")",
":",
"dtypes",
"=",
"_as_type_list",
"(",
"dtypes",
")",
"shapes",
"=",
"_as_shape_list",
"(",
"shapes",
",",
"dtypes",
")",
"names",
"=",
"_as_name_list",
"(",
"names",
",",
"dtypes",
")",
"# If shared_name is provided and an op seed was not provided, we must ensure",
"# that we use the same seed for all queues with the same shared_name.",
"if",
"shared_name",
"is",
"not",
"None",
"and",
"seed",
"is",
"None",
":",
"seed",
"=",
"hash",
"(",
"shared_name",
")",
"seed1",
",",
"seed2",
"=",
"random_seed",
".",
"get_seed",
"(",
"seed",
")",
"queue_ref",
"=",
"gen_data_flow_ops",
".",
"_random_shuffle_queue",
"(",
"component_types",
"=",
"dtypes",
",",
"shapes",
"=",
"shapes",
",",
"capacity",
"=",
"capacity",
",",
"min_after_dequeue",
"=",
"min_after_dequeue",
",",
"seed",
"=",
"seed1",
",",
"seed2",
"=",
"seed2",
",",
"shared_name",
"=",
"shared_name",
",",
"name",
"=",
"name",
")",
"super",
"(",
"RandomShuffleQueue",
",",
"self",
")",
".",
"__init__",
"(",
"dtypes",
",",
"shapes",
",",
"names",
",",
"queue_ref",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py#L536-L594 | ||
eric612/MobileNet-YOLO | 69b4441cb3ec8d553fbdef788ad033e246f901bd | scripts/cpp_lint.py | python | CheckAccess | (filename, clean_lines, linenum, nesting_state, error) | Checks for improper use of DISALLOW* macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks for improper use of DISALLOW* macros. | [
"Checks",
"for",
"improper",
"use",
"of",
"DISALLOW",
"*",
"macros",
"."
] | def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
"""Checks for improper use of DISALLOW* macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum] # get rid of comments and strings
matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
r'DISALLOW_EVIL_CONSTRUCTORS|'
r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
if not matched:
return
if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
if nesting_state.stack[-1].access != 'private':
error(filename, linenum, 'readability/constructors', 3,
'%s must be in the private: section' % matched.group(1))
else:
# Found DISALLOW* macro outside a class declaration, or perhaps it
# was used inside a function when it should have been part of the
# class declaration. We could issue a warning here, but it
# probably resulted in a compiler error already.
pass | [
"def",
"CheckAccess",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# get rid of comments and strings",
"matched",
"=",
"Match",
"(",
"(",
"r'\\s*(DISALLOW_COPY_AND_ASSIGN|'",
"r'DISALLOW_EVIL_CONSTRUCTORS|'",
"r'DISALLOW_IMPLICIT_CONSTRUCTORS)'",
")",
",",
"line",
")",
"if",
"not",
"matched",
":",
"return",
"if",
"nesting_state",
".",
"stack",
"and",
"isinstance",
"(",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_ClassInfo",
")",
":",
"if",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"access",
"!=",
"'private'",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/constructors'",
",",
"3",
",",
"'%s must be in the private: section'",
"%",
"matched",
".",
"group",
"(",
"1",
")",
")",
"else",
":",
"# Found DISALLOW* macro outside a class declaration, or perhaps it",
"# was used inside a function when it should have been part of the",
"# class declaration. We could issue a warning here, but it",
"# probably resulted in a compiler error already.",
"pass"
] | https://github.com/eric612/MobileNet-YOLO/blob/69b4441cb3ec8d553fbdef788ad033e246f901bd/scripts/cpp_lint.py#L2490-L2518 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/metadata.py | python | LegacyMetadata.is_field | (self, name) | return name in _ALL_FIELDS | return True if name is a valid metadata key | return True if name is a valid metadata key | [
"return",
"True",
"if",
"name",
"is",
"a",
"valid",
"metadata",
"key"
] | def is_field(self, name):
"""return True if name is a valid metadata key"""
name = self._convert_name(name)
return name in _ALL_FIELDS | [
"def",
"is_field",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"_convert_name",
"(",
"name",
")",
"return",
"name",
"in",
"_ALL_FIELDS"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/metadata.py#L321-L324 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/dataview.py | python | DataViewModel.HasValue | (*args, **kwargs) | return _dataview.DataViewModel_HasValue(*args, **kwargs) | HasValue(self, DataViewItem item, unsigned int col) -> bool
return true if the given item has a value to display in the given
column: this is always true except for container items which by
default only show their label in the first column (but see
HasContainerColumns()) | HasValue(self, DataViewItem item, unsigned int col) -> bool | [
"HasValue",
"(",
"self",
"DataViewItem",
"item",
"unsigned",
"int",
"col",
")",
"-",
">",
"bool"
] | def HasValue(*args, **kwargs):
"""
HasValue(self, DataViewItem item, unsigned int col) -> bool
return true if the given item has a value to display in the given
column: this is always true except for container items which by
default only show their label in the first column (but see
HasContainerColumns())
"""
return _dataview.DataViewModel_HasValue(*args, **kwargs) | [
"def",
"HasValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewModel_HasValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L482-L491 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/gen_keyboard_overlay_data/gen_keyboard_overlay_data.py | python | UniqueBehaviors | (hotkey_data) | return sorted(set((behavior, description) for (behavior, _, description)
in hotkey_data),
cmp=lambda x, y: cmp(ToMessageName(x[0]), ToMessageName(y[0]))) | Retrieves a sorted list of unique behaviors from |hotkey_data|. | Retrieves a sorted list of unique behaviors from |hotkey_data|. | [
"Retrieves",
"a",
"sorted",
"list",
"of",
"unique",
"behaviors",
"from",
"|hotkey_data|",
"."
] | def UniqueBehaviors(hotkey_data):
"""Retrieves a sorted list of unique behaviors from |hotkey_data|."""
return sorted(set((behavior, description) for (behavior, _, description)
in hotkey_data),
cmp=lambda x, y: cmp(ToMessageName(x[0]), ToMessageName(y[0]))) | [
"def",
"UniqueBehaviors",
"(",
"hotkey_data",
")",
":",
"return",
"sorted",
"(",
"set",
"(",
"(",
"behavior",
",",
"description",
")",
"for",
"(",
"behavior",
",",
"_",
",",
"description",
")",
"in",
"hotkey_data",
")",
",",
"cmp",
"=",
"lambda",
"x",
",",
"y",
":",
"cmp",
"(",
"ToMessageName",
"(",
"x",
"[",
"0",
"]",
")",
",",
"ToMessageName",
"(",
"y",
"[",
"0",
"]",
")",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/gen_keyboard_overlay_data/gen_keyboard_overlay_data.py#L398-L402 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | CalculateVariables | (default_variables, params) | Calculate additional variables for use in the build (called by gyp). | Calculate additional variables for use in the build (called by gyp). | [
"Calculate",
"additional",
"variables",
"for",
"use",
"in",
"the",
"build",
"(",
"called",
"by",
"gyp",
")",
"."
] | def CalculateVariables(default_variables, params):
"""Calculate additional variables for use in the build (called by gyp)."""
global generator_additional_non_configuration_keys
global generator_additional_path_sections
flavor = gyp.common.GetFlavor(params)
if flavor == "mac":
default_variables.setdefault("OS", "mac")
default_variables.setdefault("SHARED_LIB_SUFFIX", ".dylib")
default_variables.setdefault(
"SHARED_LIB_DIR", generator_default_variables["PRODUCT_DIR"]
)
default_variables.setdefault(
"LIB_DIR", generator_default_variables["PRODUCT_DIR"]
)
# Copy additional generator configuration data from Xcode, which is shared
# by the Mac Ninja generator.
import gyp.generator.xcode as xcode_generator
generator_additional_non_configuration_keys = getattr(
xcode_generator, "generator_additional_non_configuration_keys", []
)
generator_additional_path_sections = getattr(
xcode_generator, "generator_additional_path_sections", []
)
global generator_extra_sources_for_rules
generator_extra_sources_for_rules = getattr(
xcode_generator, "generator_extra_sources_for_rules", []
)
elif flavor == "win":
exts = gyp.MSVSUtil.TARGET_TYPE_EXT
default_variables.setdefault("OS", "win")
default_variables["EXECUTABLE_SUFFIX"] = "." + exts["executable"]
default_variables["STATIC_LIB_PREFIX"] = ""
default_variables["STATIC_LIB_SUFFIX"] = "." + exts["static_library"]
default_variables["SHARED_LIB_PREFIX"] = ""
default_variables["SHARED_LIB_SUFFIX"] = "." + exts["shared_library"]
# Copy additional generator configuration data from VS, which is shared
# by the Windows Ninja generator.
import gyp.generator.msvs as msvs_generator
generator_additional_non_configuration_keys = getattr(
msvs_generator, "generator_additional_non_configuration_keys", []
)
generator_additional_path_sections = getattr(
msvs_generator, "generator_additional_path_sections", []
)
gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)
else:
operating_system = flavor
if flavor == "android":
operating_system = "linux" # Keep this legacy behavior for now.
default_variables.setdefault("OS", operating_system)
default_variables.setdefault("SHARED_LIB_SUFFIX", ".so")
default_variables.setdefault(
"SHARED_LIB_DIR", os.path.join("$!PRODUCT_DIR", "lib")
)
default_variables.setdefault("LIB_DIR", os.path.join("$!PRODUCT_DIR", "obj")) | [
"def",
"CalculateVariables",
"(",
"default_variables",
",",
"params",
")",
":",
"global",
"generator_additional_non_configuration_keys",
"global",
"generator_additional_path_sections",
"flavor",
"=",
"gyp",
".",
"common",
".",
"GetFlavor",
"(",
"params",
")",
"if",
"flavor",
"==",
"\"mac\"",
":",
"default_variables",
".",
"setdefault",
"(",
"\"OS\"",
",",
"\"mac\"",
")",
"default_variables",
".",
"setdefault",
"(",
"\"SHARED_LIB_SUFFIX\"",
",",
"\".dylib\"",
")",
"default_variables",
".",
"setdefault",
"(",
"\"SHARED_LIB_DIR\"",
",",
"generator_default_variables",
"[",
"\"PRODUCT_DIR\"",
"]",
")",
"default_variables",
".",
"setdefault",
"(",
"\"LIB_DIR\"",
",",
"generator_default_variables",
"[",
"\"PRODUCT_DIR\"",
"]",
")",
"# Copy additional generator configuration data from Xcode, which is shared",
"# by the Mac Ninja generator.",
"import",
"gyp",
".",
"generator",
".",
"xcode",
"as",
"xcode_generator",
"generator_additional_non_configuration_keys",
"=",
"getattr",
"(",
"xcode_generator",
",",
"\"generator_additional_non_configuration_keys\"",
",",
"[",
"]",
")",
"generator_additional_path_sections",
"=",
"getattr",
"(",
"xcode_generator",
",",
"\"generator_additional_path_sections\"",
",",
"[",
"]",
")",
"global",
"generator_extra_sources_for_rules",
"generator_extra_sources_for_rules",
"=",
"getattr",
"(",
"xcode_generator",
",",
"\"generator_extra_sources_for_rules\"",
",",
"[",
"]",
")",
"elif",
"flavor",
"==",
"\"win\"",
":",
"exts",
"=",
"gyp",
".",
"MSVSUtil",
".",
"TARGET_TYPE_EXT",
"default_variables",
".",
"setdefault",
"(",
"\"OS\"",
",",
"\"win\"",
")",
"default_variables",
"[",
"\"EXECUTABLE_SUFFIX\"",
"]",
"=",
"\".\"",
"+",
"exts",
"[",
"\"executable\"",
"]",
"default_variables",
"[",
"\"STATIC_LIB_PREFIX\"",
"]",
"=",
"\"\"",
"default_variables",
"[",
"\"STATIC_LIB_SUFFIX\"",
"]",
"=",
"\".\"",
"+",
"exts",
"[",
"\"static_library\"",
"]",
"default_variables",
"[",
"\"SHARED_LIB_PREFIX\"",
"]",
"=",
"\"\"",
"default_variables",
"[",
"\"SHARED_LIB_SUFFIX\"",
"]",
"=",
"\".\"",
"+",
"exts",
"[",
"\"shared_library\"",
"]",
"# Copy additional generator configuration data from VS, which is shared",
"# by the Windows Ninja generator.",
"import",
"gyp",
".",
"generator",
".",
"msvs",
"as",
"msvs_generator",
"generator_additional_non_configuration_keys",
"=",
"getattr",
"(",
"msvs_generator",
",",
"\"generator_additional_non_configuration_keys\"",
",",
"[",
"]",
")",
"generator_additional_path_sections",
"=",
"getattr",
"(",
"msvs_generator",
",",
"\"generator_additional_path_sections\"",
",",
"[",
"]",
")",
"gyp",
".",
"msvs_emulation",
".",
"CalculateCommonVariables",
"(",
"default_variables",
",",
"params",
")",
"else",
":",
"operating_system",
"=",
"flavor",
"if",
"flavor",
"==",
"\"android\"",
":",
"operating_system",
"=",
"\"linux\"",
"# Keep this legacy behavior for now.",
"default_variables",
".",
"setdefault",
"(",
"\"OS\"",
",",
"operating_system",
")",
"default_variables",
".",
"setdefault",
"(",
"\"SHARED_LIB_SUFFIX\"",
",",
"\".so\"",
")",
"default_variables",
".",
"setdefault",
"(",
"\"SHARED_LIB_DIR\"",
",",
"os",
".",
"path",
".",
"join",
"(",
"\"$!PRODUCT_DIR\"",
",",
"\"lib\"",
")",
")",
"default_variables",
".",
"setdefault",
"(",
"\"LIB_DIR\"",
",",
"os",
".",
"path",
".",
"join",
"(",
"\"$!PRODUCT_DIR\"",
",",
"\"obj\"",
")",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L1985-L2044 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.